grix-connector 3.28.0 → 3.29.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 (37) hide show
  1. package/dist/adapter/acp/acp-adapter.js +8 -8
  2. package/dist/adapter/acp/session-activity.js +1 -1
  3. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  4. package/dist/adapter/claude/claude-tools.js +1 -1
  5. package/dist/adapter/claude/claude-worker-client.js +1 -1
  6. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  7. package/dist/adapter/claude/result-timeout.js +1 -1
  8. package/dist/adapter/codex/codex-bridge.js +8 -8
  9. package/dist/adapter/deepseek-harness/dsh-provider-config.js +5 -5
  10. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  11. package/dist/adapter/deepseek-harness/grix-tool-bridge.js +1 -0
  12. package/dist/adapter/deepseek-harness/index.js +1 -1
  13. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +2 -2
  14. package/dist/adapter/deepseek-harness/plugin-manager.js +1 -2
  15. package/dist/adapter/deepseek-harness/profile-resolver.js +1 -1
  16. package/dist/adapter/deepseek-harness/profile-runtime.js +3 -3
  17. package/dist/adapter/deepseek-harness/session-plugin-overlay.js +4 -0
  18. package/dist/assets/dsh-bridge/grix-dsh-bridge-3.29.0.tgz +0 -0
  19. package/dist/assets/dsh-bridge/manifest.json +6 -6
  20. package/dist/audit/adapters/codex/codex-audit-adapter.js +1 -1
  21. package/dist/audit/adapters/deepseek-harness/deepseek-harness-audit-adapter.js +2 -2
  22. package/dist/bridge/bridge.js +7 -7
  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/persistence/session-binding-store.js +2 -2
  26. package/dist/core/util/codex-output-policy.js +1 -1
  27. package/dist/log.js +2 -2
  28. package/dist/mcp/stream-http/config.js +1 -1
  29. package/dist/mcp/stream-http/connection-binding.js +1 -1
  30. package/dist/mcp/stream-http/security.js +1 -1
  31. package/dist/mcp/stream-http/tool-executor.js +1 -1
  32. package/dist/mcp/stream-http/tool-registry.js +1 -1
  33. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  34. package/dist/protocol/acp-client.js +1 -1
  35. package/openclaw-plugin/index.js +3 -1
  36. package/package.json +2 -1
  37. package/dist/assets/dsh-bridge/grix-dsh-bridge-3.28.0.tgz +0 -0
@@ -1,3 +1,3 @@
1
- import{createHash as q,randomUUID as R}from"node:crypto";import{EventEmitter as N}from"node:events";import{copyFileSync as Z,existsSync as j,mkdirSync as ee}from"node:fs";import{dirname as te,join as k,resolve as F}from"node:path";import{fileURLToPath as U}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ie}from"../../default-skills/index.js";import{resolveCliPath as se}from"../../core/util/cli-probe.js";import{DshWireCapture as oe}from"./audit-boundary.js";import{dsmlToolCallKey as re,projectVisibleDsmlText as ne}from"./dsml-text-filter.js";import{mapDshSessionEvent as ae,unwrapDshSessionEvent as de}from"./event-mapper.js";import{buildDshUserPrompt as L,extractQuotedMessageMarker as O}from"./prompt-builder.js";import{DshProcessRuntime as le}from"./process-runtime.js";import{DshProfileRuntime as he}from"./profile-runtime.js";import{createDshWebProfile as ce}from"./profile-catalog.js";import{disableDshPlugin as ue,enableDshPlugin as pe,isDshPluginRestartRequired as ge,listDshPlugins as W,markDshPluginRestartRequired as fe}from"./plugin-manager.js";import{assertSelectableDshProfileName as me,discoverDshBridgeEndpoints as ve,listDshProfiles as be,resolveDshConnectorProfileDataDir as _e,resolveDshHome as Se,resolveDshProfileIdentity as V,resolveDshSelectedProfileName as Ie}from"./profile-resolver.js";import{DshBridgeInstaller as y,errorForDshBridgeReadiness as M}from"./bridge-installer.js";import{awaitDshProfileIdle as Pe,ensureDshBridgeReady as ke,prepareDshProfileBridge as we,restartManagedProfileIfOwned as ye}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Te}from"./probe.js";import{buildDshSystemPrompt as Re,describeDshSystemPrompt as Me}from"./system-prompt.js";import{DshActionCoordinator as xe}from"./toolbar-actions.js";import{adoptDshProfileModels as Ee,adoptLiveDshProviderSelection as Ae,buildDshToolbarMeta as He,DEFAULT_DSH_MAX_TOKENS as Be,DEFAULT_DSH_MODELS as $e,DEFAULT_DSH_PRESETS as qe,DEFAULT_DSH_PROVIDER_ID as x,normalizeDshPresets as Ne,normalizeDshProviders as je,permissionModeFor as Q,resolveDshAgentPreset as z,resolveDshModeId as Fe,resolveDshProviderId as Ue,retainRequestedDshProvider as Le}from"./toolbar-state.js";import{modelsForDshProvider as Oe,resolveDshCatalogForToolbar as We,writeDshCatalogCache as Ve}from"./catalog-cache.js";import{TurnCorrelator as Ge}from"./turn-correlator.js";import{getDshSessionUsageStore as Qe,normalizeDshUsage as K}from"./usage.js";import{DSH_GRIX_PROVIDER_ID as v,buildDshManagedProvider as J}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",X=20*6e4;class ze extends N{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Mt extends N{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;activeTimeoutMs=X;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 xe;activeWireStart=0;activeUsage=Y();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=$e;providers=[];presets=[...qe];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.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 ze(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(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");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_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_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}}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,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await se(i),o=!!s;let l={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await Te({command:s,args:this.config.args,cordisPath:F(this.options.cordisPath??U(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});l={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){l={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const a=new y({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ke({installer:a,autoStart:!1}),c=M(p);if(c)throw c;const r=ve(p.identity);if(r.length!==1)throw Object.assign(new Error(r.length===0?`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${p.identity.profileName}"`),{code:r.length===0?"bridge_missing":"profile_instance_ambiguous"});l={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:r[0].bridgeVersion}}catch(a){l={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:l.ok,latency_ms:l.latency,...l.ok?{}:{error:{code:"conversation_failed",message:l.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:l.serverName,serverVersion:l.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 Ge(t),this.activeUsage=Y(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=L(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.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();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"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const l=this.callbacks.getAgentProfile(),d=this.profileRevision,a=Re({...l,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Me(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),r=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let n=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,r):void 0;c==="profile_bridge"&&!n&&(n={profileName:r,sessionId:Ye(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.runtimeSessionId=n?.sessionId??Xe(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(r),b=k(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new oe(b);const _=c==="embedded_jsonrpc"?new le({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:F(this.options.cordisPath??U(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),home:u,sessionRoot:k(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new he({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:r,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:n?.sessionCreated===!0,lastAckCursor:n?.eventCursor??0,systemPrompt:a,settings:i,managedProvider:i.providerId===v?J(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onCursorAck:g=>{!n||g<=n.eventCursor||(n={...n,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n))}});this.runtime=_,this.bridgeAckCursor=n?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let E=!1;if(c==="profile_bridge"){const S=je(g.providers),I=Ae({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Le(S,I.providerId,this.providers),i={...i,providerId:I.providerId},E=I.persistFallback;const D=I.providerId,H=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,B=!!this.catalogProviderId&&!!D&&D!==this.catalogProviderId;this.models=Ee({current:this.models,fetched:H,providerChanged:B}),(H!==void 0||B)&&(this.catalogProviderId=D||this.catalogProviderId);const T=String(g.selectedModel??"");T&&T!==i.modelId&&(i={...i,modelId:T});const $=Ne(g.presets);$.length>0&&(this.presets=$);const w=String(g.selectedPreset??"");w&&w!==i.agentPreset&&(i={...i,agentPreset:w},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,w))}const C=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),A=(C?.revision??0)!==i.revision,P={};!A&&E&&(C?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!A&&(C?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??x,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&n&&!n.sessionCreated&&(n={...n,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=d,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??x),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}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<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;f.warn(m,`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 Je(Ce(t))}throw e}onNotification(e,t){const i=Ke(t);if(e==="session.event"){const s=de(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);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&&f.debug(m,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const l=!!this.correlator?.complete;l&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,l)}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:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),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=ae(e);if(t.kind==="unknown"&&!tt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${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")&&f.debug(m,`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=L(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?t.kind==="text"?(t.payload?.committed===!0?(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.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"?(this.sendRaw("todo_snapshot",t.payload??{},"[todo updated]"),!1):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.text+=e,this.flushVisibleText(!1)}applyCommittedText(e){const t=this.active;if(e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){f.warn(m,`committed assistant text diverged event=${t.inbound.event_id}`);const i=O(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=O(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),l=ne(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(l.suppressedToolCalls);const d=l.visible;this.observeVisibleTextAfterToolCall(d);let a="";d.startsWith(i.sentText)?a=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=d),!(!a&&!e)&&(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=re(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),f.warn(m,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,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=K(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=K(e),i=this.resolveDesiredSettings(),s=this.models.find(l=>l.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const l=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:l,totalTokens:o,remainingTokens:Math.max(0,o-l),usedPercentage:l/o*100,remainingPercentage:Math.max(0,100-l/o*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=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",f.warn(m,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const l=s==="failed"&&!!o?.trim();l&&(i.text+=`
1
+ import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;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 Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];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.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 Ye(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(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");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_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_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}}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,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length!==1)throw Object.assign(new Error(n.length===0?`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${p.identity.profileName}"`),{code:n.length===0?"bridge_missing":"profile_instance_ambiguous"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.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:d.serverName,serverVersion:d.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 Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.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();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"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}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<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`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 et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);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&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}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:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),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=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${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")&&m.debug(f,`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=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(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)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(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)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(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=l)}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=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,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=K(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=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*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=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
2
2
 
3
- Error: ${o}`,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 p=`${i.inbound.event_id}-dsh`,c=(r,n,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,r,n,u),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,o,l)},async r=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(r,i.inbound.content)}`:o)})}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){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??R());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(o=>{const l=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);l.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:l})})):"unavailable"}projectConnectorSkills(){const e=Se(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=k(e,"skills"),i=ie(t);i.length>0&&f.info(m,`Synced connector skills to ${t}: [${i.join(", ")}]`)}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){f.warn(m,`${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(){this.intentionalRuntimeStop||this.stopped||(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&&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);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 r=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),n=this.pendingApprovals.get(r);if(!n)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(n.timer),this.pendingApprovals.delete(r);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return n.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:r,decision:u?"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)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(r){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(r)}}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 r=new y({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),n=e.action_type==="dsh_install_bridge"?await r.install():await r.status();return this.runtimeReadiness=n.readiness,this.settingsErrorCode=n.readiness==="ready"?null:n.readiness,this.pushToolbarMeta(),{status:"ok",result:Ze(n)}}catch(r){const n=String(r?.code??"bridge_install_failed");return this.runtimeReadiness=n,this.settingsErrorCode=n,this.pushToolbarMeta(),{status:"failed",errorCode:n,errorMsg:this.redactError(r)}}}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);const o={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(o){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(o,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(r){const n=String(r?.code??"resource_query_failed");return{status:n==="capability_unavailable"?"unsupported":"failed",errorCode:n,errorMsg:this.redactError(r)}}}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 r;try{r=me(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==r?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(r,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(r):await ce({profileName:r,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=u.identity?.profileName??r;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===r)?this.persistSelectedProfile(r)?(await this.flushSelectedProfile(),this.finishProfileSelection(r,!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 n=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===n))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===n?{status:"ok",result:this.presetActionResult(n,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===n?(this.options.bindingStore.setDshAgentPreset(i,n),await this.persistGlobalToolbarDefaults({dshAgentPreset:n}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!1)}):this.options.bindingStore.setDshAgentPreset(i,n)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:n}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!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 r=String(t.provider_id??"").trim();if(!this.providers.some(n=>n.id===r))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:r},r!==d.providerId&&(this.models=Oe(this.options.dataRoot,r),this.catalogProviderId=r,this.models.some(n=>n.id===d.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const r=String(t.model_id??"").trim();if(!this.models.some(n=>n.id===r))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:r}}else{const r=String(t.mode_id??"").trim();if(r!=="approval"&&r!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:r}}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)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,d.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??d.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{}}),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,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}}catch(r){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(r)),errorCode:"settings_apply_failed",errorMsg:this.redactError(r)}}}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 y({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:(f.info(m,`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(),o=M(s);if(o)throw o;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=M(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await we({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,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),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 be({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),run:this.options.runDshCommand}}currentPlugins(){try{return W(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){try{return ge(V({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}).profileKey)}catch{return!1}}async executePluginAction(e,t,i){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH plugins require Profile Bridge mode"};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(),o=!!this.runtime;try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const p=W(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(p,!1)}}o&&await this.stopRuntime(!0);const l=V({dshHome:s.dshHome,profileName:s.profileName});await Pe(l);const d=e==="dsh_enable_plugin"?await pe({...s,name:String(t.name??t.plugin_name??"")}):await ue({...s,name:String(t.name??t.plugin_name??"")});let a="skipped";return d.changed&&(a=this.options.restartManagedProfile?await this.options.restartManagedProfile(d.identity.profileName):await ye(new y({command:"dsh",dshHome:s.dshHome,profileName:d.identity.profileName})),fe(d.identity.profileKey,a!=="restarted")),o&&await this.rebuildRuntime("plugin_changed"),this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(d.plugins,d.changed,a)}}catch(l){return o&&!this.runtime&&!this.stopped&&await this.rebuildRuntime("plugin_changed_failed"),{status:"failed",errorCode:String(l?.code??"plugin_action_failed"),errorMsg:this.redactError(l)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),o=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=Ie({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 _e(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=k(this.profileDataDir(e),"session-usage.json"),i=k(this.options.dataRoot,"session-usage.json");return!j(t)&&j(i)&&(ee(te(t),{recursive:!0,mode:448}),Z(i,t)),Qe(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,o,l){const d=this.resolveDesiredSettings(),a=d.revision||i,p={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(p.sandbox_mode=Q(d.modeId),p.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":"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:Q(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:a,settings_revision:a,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...l?{error:l}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=We({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 Ve({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=J(this.options.provider??{});if(e){this.providers.some(o=>o.id===v)||(this.providers=[{id:v,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===x||s===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(t=>t.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,o=this.providers.some(p=>p.id===v)?v:void 0,l=Ue(s||o,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:l,modelId:d,modeId:Fe(e?.dshModeId,i?.dshModeId),agentPreset:a,maxTokens:t?.maxTokens??this.options.maxTokens??Be,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}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,He({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(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}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??X,this.armTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||this.armTimeout(Math.min(this.activeTimeoutMs*e,60*6e4))}armTimeout(e){this.clearTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}async handlePromptTimeout(){if(!this.active)return;const e=this.active;this.clearTimeout();const t=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 t?.cancel(this.runtimeSessionId).catch(()=>{}),t&&!t.isConnected()&&await t.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==e||this.stopped)&&(this.finishActive("failed","Harness prompt timed out and the runtime was terminated"),this.emit("exit",1))}clearTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=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 Ke(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function Je(h){return new Promise(e=>setTimeout(e,h))}function Xe(h,e){return`grix-${q("sha256").update(h).digest("hex").slice(0,12)}-${e}-${R().slice(0,8)}`}function Ye(h){return`grix-${q("sha256").update(h).digest("hex").slice(0,16)}-${R().slice(0,8)}`}function Y(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function Ze(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",compatibleDshVersions:h.compatibleDshVersions}}const et=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","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 tt(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data,t=String(e?.type??"");return et.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(t)}export{Mt as DshJsonRpcAdapter};
3
+ Error: ${o}`,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 l=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;l&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(n,r,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,n,r,u),this.emit("eventDone",i.inbound.event_id),l?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,o,d)},async n=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(n,i.inbound.content)}`:o)})}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){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??M());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(o=>{const d=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);d.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:d})})):"unavailable"}async invokeGrixTool(e,t,i){if(!Je(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=Xe(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=Te(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=T(e,"skills"),i=ae(t);i.length>0&&m.info(f,`Synced connector skills to ${t}: [${i.join(", ")}]`)}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){m.warn(f,`${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(){this.intentionalRuntimeStop||this.stopped||(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&&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);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 n=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),r=this.pendingApprovals.get(n);if(!r)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(r.timer),this.pendingApprovals.delete(n);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return r.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:n,decision:u?"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)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(n){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(n)}}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 n=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),r=e.action_type==="dsh_install_bridge"?await n.install():await n.status();return this.runtimeReadiness=r.readiness,this.settingsErrorCode=r.readiness==="ready"?null:r.readiness,this.pushToolbarMeta(),{status:"ok",result:ot(r)}}catch(n){const r=String(n?.code??"bridge_install_failed");return this.runtimeReadiness=r,this.settingsErrorCode=r,this.pushToolbarMeta(),{status:"failed",errorCode:r,errorMsg:this.redactError(n)}}}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);const o={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(o){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(o,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(n){const r=String(n?.code??"resource_query_failed");return{status:r==="capability_unavailable"?"unsupported":"failed",errorCode:r,errorMsg:this.redactError(n)}}}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 n;try{n=Se(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==n?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(n,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(n):await fe({profileName:n,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),v=u.identity?.profileName??n;return this.persistSelectedProfile(v)?(await this.flushSelectedProfile(),this.finishProfileSelection(v,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===n)?this.persistSelectedProfile(n)?(await this.flushSelectedProfile(),this.finishProfileSelection(n,!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 r=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(v=>v.id===r))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===r?{status:"ok",result:this.presetActionResult(r,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===r?(this.options.bindingStore.setDshAgentPreset(i,r),await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):this.options.bindingStore.setDshAgentPreset(i,r)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!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 l=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const n=String(t.provider_id??"").trim();if(!this.providers.some(r=>r.id===n))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:n},n!==l.providerId&&(this.models=We(this.options.dataRoot,n),this.catalogProviderId=n,this.models.some(r=>r.id===l.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const n=String(t.model_id??"").trim();if(!this.models.some(r=>r.id===n))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:n}}else{const n=String(t.mode_id??"").trim();if(n!=="approval"&&n!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:n}}if((a.providerId===void 0||a.providerId===l.providerId)&&(a.modelId===void 0||a.modelId===l.modelId)&&(a.modeId===void 0||a.modeId===l.modeId)&&this.applied?.appliedRevision===l.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,l.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??l.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{}}),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,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}}catch(n){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(n)),errorCode:"settings_apply_failed",errorMsg:this.redactError(n)}}}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 R({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:(m.info(f,`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(),o=A(s);if(o)throw o;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=A(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await xe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,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),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 ke({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)}}currentPlugins(){try{return E(this.pluginCommandContext())}catch{return[]}}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 n=E(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(n,!1)}}const o=String(t.name??t.plugin_name??"").trim(),d=this.options.bindingStore.getDshEnabledPlugins(i);let l=o;try{const{plugin:n}=ve({...s,name:o});l=n.name}catch(n){const r=String(n?.code??"");if(e!=="dsh_disable_plugin"||r!=="plugin_not_found"||!d.includes(o))throw n}const a=be(d,l,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,a.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const c=E({...s,enabledPluginIds:a.pluginIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"skipped")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"restarted")}}catch(o){return{status:"failed",errorCode:String(o?.code??"plugin_action_failed"),errorMsg:this.redactError(o)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),o=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=we({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 Pe(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!L(t)&&L(i)&&(ne(re(t),{recursive:!0,mode:448}),oe(i,t)),Ke(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,o,d){const l=this.resolveDesiredSettings(),a=l.revision||i,p={provider_id:l.providerId,model_id:l.modelId,mode_id:l.modeId,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(p.sandbox_mode=z(l.modeId),p.approval_policy=l.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":"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:z(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:a,settings_revision:a,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...d?{error:d}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=Ge({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 ze({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){m.warn(f,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=X(this.options.provider??{});if(e){this.providers.some(o=>o.id===b)||(this.providers=[{id:b,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===H||s===b)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:b});return}this.providers=this.providers.filter(t=>t.id!==b)}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,o=this.providers.some(p=>p.id===b)?b:void 0,d=Oe(s||o,this.providers),l=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=Q(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:d,modelId:l,modeId:Ue(e?.dshModeId,i?.dshModeId),agentPreset:a,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),maxTokens:t?.maxTokens??this.options.maxTokens??qe,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}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,Be({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(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}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??J,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??Y,t=Number.isFinite(e)&&e>0?e:Y;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??Z;return Number.isFinite(e)&&e>0?e:Z}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??ee;return Number.isFinite(e)&&e>0?e:ee}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){m.info(f,`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(),o=t.lastRuntimeActivityAt??t.startedAt,d=Math.max(0,s-o);if(d<this.livenessFreshMs())return t.livenessExtendStartAt=s,m.info(f,`Liveness check: recent DSH activity for ${e} (quietMs=${d}), extending`),!0;const l=t.livenessExtendStartAt??o;t.livenessExtendStartAt=l;const a=s-l;return a>this.livenessMaxExtendMs()?(m.warn(f,`Liveness extension budget exhausted for ${e} (quietMs=${d}, extendMs=${a}), allowing close`),!1):(m.info(f,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${d}), 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&&!s.isConnected()&&await s.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(m.error(f,`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 Ze(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function et(h){return new Promise(e=>setTimeout(e,h))}function tt(h,e){return`grix-${D("sha256").update(h).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function it(h){return`grix-${D("sha256").update(h).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function te(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function ie(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function st(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&ie(h)==="tool-call-delta"}function ot(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",compatibleDshVersions:h.compatibleDshVersions}}const nt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","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 rt(h){const e=ie(h);return nt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{Ft as DshJsonRpcAdapter};
@@ -1,2 +1 @@
1
- import{existsSync as b,readdirSync as w,readFileSync as h,renameSync as O,statSync as p,writeFileSync as P}from"node:fs";import{join as l}from"node:path";import{resolveCliPath as R}from"../../core/util/cli-probe.js";import{runDshCommand as E}from"./profile-catalog.js";import{assertSelectableDshProfileName as B,resolveDshHome as H,resolveDshProfileIdentity as I}from"./profile-resolver.js";const M=Object.freeze(["@deepseek-ai/dsh-base","@deepseek-ai/dsh-web-app"]),q="@grix/dsh-bridge",f=new Map;function k(e){return M.includes(e)?"inbox":e===q?"grix_bridge":"user"}function _(e){if(e==="inbox")return"DeepSeek \u5185\u7F6E\u5C42\uFF0C\u4E0D\u80FD\u5F00\u5173";if(e==="grix_bridge")return"Grix Bridge \u7531\u8FDE\u63A5\u5668\u5B89\u88C5\uFF0C\u4E0D\u80FD\u5F00\u5173"}function S(e){const n=x(e),r=$(n.profileRoot),t=j(r),s=C(n.profileRoot),o=new Set([...t,...s.keys()]),d=[];for(const i of[...o].sort()){const a=s.get(i),u=k(i);if(u!=="user"||!a?.hasBundle)continue;const c=_(u);d.push({name:i,version:a.version,kind:u,enabled:t.includes(i),locked:!1,has_bundle:!0,...c?{lock_reason:c}:{}})}return d}function z(e){return f.get(e)===!0}function X(e,n){n?f.set(e,!0):f.delete(e)}function Q(){f.clear()}async function V(e){return D(e,(n,r)=>{if(r.kind!=="user")throw Object.assign(new Error(r.lock_reason||"This plugin cannot be toggled"),{code:"plugin_locked"});return n.includes(r.name)?n:[...n,r.name]})}async function Y(e){return D(e,(n,r)=>{if(r.kind!=="user")throw Object.assign(new Error(r.lock_reason||"This plugin cannot be toggled"),{code:"plugin_locked"});return n.filter(t=>t!==r.name)})}async function D(e,n){const r=x(e),t=String(e.name??"").trim();if(!t)throw Object.assign(new Error("Plugin name is required"),{code:"plugin_invalid"});const s=k(t),o=_(s);if(o)throw Object.assign(new Error(o),{code:"plugin_locked"});const d=S({...e,profileName:r.profileName}),i=d.find(m=>m.name===t);if(!i)throw Object.assign(new Error("Plugin is not installed in this Profile"),{code:"plugin_not_found"});const a=l(r.profileRoot,"package.json"),u=h(a,"utf8"),c=N(u),g=j(c),y=n(g,i);if(T(g,y))return{plugins:d,changed:!1,identity:r};G(a,{...c,dsh:{...c.dsh,profile:{...c.dsh?.profile,bundles:y}}});try{await A(e,r)}catch(m){throw P(a,u,{mode:420}),m}return{plugins:S({...e,profileName:r.profileName}),changed:!0,identity:r}}async function A(e,n){const r=e.run??E,t=e.run?e.command?.trim()||"dsh":await R(e.command?.trim()||"dsh");if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});await r(t,["--profile",n.profileName,"--dump-config"],n.dshHome)}function x(e){return I({dshHome:H(e.dshHome),profileName:B(e.profileName)})}function $(e){const n=l(e,"package.json");if(!b(n))throw Object.assign(new Error("DSH Profile package.json is missing"),{code:"profile_missing"});return N(h(n,"utf8"))}function N(e){try{const n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{throw Object.assign(new Error("DSH Profile package.json is invalid"),{code:"profile_invalid"})}}function G(e,n){const r=`${e}.${process.pid}.tmp`;P(r,`${JSON.stringify(n,null,2)}
2
- `,{mode:420}),O(r,e)}function j(e){const n=e.dsh?.profile?.bundles;if(!Array.isArray(n))return[];const r=new Set,t=[];for(const s of n){const o=String(s??"").trim();!o||r.has(o)||(r.add(o),t.push(o))}return t}function T(e,n){return e.length===n.length&&e.every((r,t)=>r===n[t])}function C(e){const n=new Map,r=l(e,"node_modules");if(!b(r)||!p(r).isDirectory())return n;for(const t of w(r)){if(t.startsWith("."))continue;const s=l(r,t);try{if(!p(s).isDirectory())continue}catch{continue}if(t.startsWith("@")){for(const o of w(s))v(l(s,o),`${t}/${o}`,n);continue}v(s,t,n)}return n}function v(e,n,r){try{if(!p(e).isDirectory())return;const t=JSON.parse(h(l(e,"package.json"),"utf8"));r.set(n,{version:String(t.version??"").trim(),hasBundle:!!(t.dsh?.bundle&&t.dsh.bundle.patch)})}catch{}}export{q as DSH_BRIDGE_PLUGIN_NAME,M as DSH_INBOX_PLUGIN_NAMES,k as classifyDshPlugin,Y as disableDshPlugin,V as enableDshPlugin,z as isDshPluginRestartRequired,S as listDshPlugins,X as markDshPluginRestartRequired,_ as pluginLockReason,Q as resetDshPluginRestartRequiredForTests};
1
+ import{existsSync as D,readdirSync as S,readFileSync as I,statSync as p}from"node:fs";import{join as a}from"node:path";import{assertSelectableDshProfileName as v,resolveDshHome as E,resolveDshProfileIdentity as O}from"./profile-resolver.js";const R=Object.freeze(["@deepseek-ai/dsh-base","@deepseek-ai/dsh-web-app"]),B="@grix/dsh-bridge",u=new Map;function h(e){return R.includes(e)?"inbox":e===B?"grix_bridge":"user"}function m(e){if(e==="inbox")return"DeepSeek \u5185\u7F6E\u5C42\uFF0C\u4E0D\u80FD\u5F00\u5173";if(e==="grix_bridge")return"Grix Bridge \u7531\u8FDE\u63A5\u5668\u5B89\u88C5\uFF0C\u4E0D\u80FD\u5F00\u5173"}function P(e){const n=y(e),i=H(n.profileRoot),t=M(i),s=new Set(t),o=new Set(b(e.enabledPluginIds??[])),r=N(n.profileRoot),c=new Set([...t,...r.keys()]),l=[];for(const d of[...c].sort()){const k=r.get(d),f=h(d);if(f!=="user"||!k?.hasBundle)continue;const g=s.has(d),w=m(f);l.push({name:d,version:k.version,kind:f,enabled:g||o.has(d),locked:g,has_bundle:!0,...g?{lock_reason:"Enabled in the DSH Profile bundles; edit DSH config to manage this plugin globally"}:w?{lock_reason:w}:{}})}return l}function z(e){return u.get(e)===!0}function F(e,n){n?u.set(e,!0):u.delete(e)}function J(){u.clear()}function b(e){const n=new Set,i=[];for(const t of e??[]){const s=String(t??"").trim();!s||n.has(s)||(n.add(s),i.push(s))}return i}function _(e){const n=y(e),i=String(e.name??"").trim();if(!i)throw Object.assign(new Error("Plugin name is required"),{code:"plugin_invalid"});const t=h(i),s=m(t);if(s)throw Object.assign(new Error(s),{code:"plugin_locked"});const r=P({...e,profileName:n.profileName}).find(c=>c.name===i);if(!r)throw Object.assign(new Error("Plugin is not installed in this Profile"),{code:"plugin_not_found"});if(r.locked)throw Object.assign(new Error(r.lock_reason??"Plugin is locked"),{code:"plugin_locked"});return{plugin:r,identity:n}}function x(e,n,i){const t=b(e),s=String(n??"").trim();if(!s)throw Object.assign(new Error("Plugin name is required"),{code:"plugin_invalid"});const o=t.includes(s);return i?o?{pluginIds:t,changed:!1}:{pluginIds:[...t,s],changed:!0}:o?{pluginIds:t.filter(r=>r!==s),changed:!0}:{pluginIds:t,changed:!1}}function U(e){const n=y(e),i=N(n.profileRoot),t=[],s=b(e.pluginIds);for(const o of s){const r=h(o),c=m(r);if(c)throw Object.assign(new Error(c),{code:"plugin_locked"});const l=i.get(o);if(!l?.hasBundle||!l.patchPath)throw Object.assign(new Error("Plugin is not installed in this Profile"),{code:"plugin_not_found"});t.push(l.patchPath)}return{identity:n,pluginIds:s,patchPaths:t}}async function W(e){const{plugin:n,identity:i}=_(e),t=x(e.enabledPluginIds??[],n.name,!0);return{plugins:P({...e,profileName:i.profileName,enabledPluginIds:t.pluginIds}),changed:t.changed,identity:i}}async function $(e){const{plugin:n,identity:i}=_(e),t=x(e.enabledPluginIds??[],n.name,!1);return{plugins:P({...e,profileName:i.profileName,enabledPluginIds:t.pluginIds}),changed:t.changed,identity:i}}function y(e){return O({dshHome:E(e.dshHome),profileName:v(e.profileName)})}function H(e){const n=a(e,"package.json");if(!D(n))throw Object.assign(new Error("DSH Profile package.json is missing"),{code:"profile_missing"});return q(I(n,"utf8"))}function q(e){try{const n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{throw Object.assign(new Error("DSH Profile package.json is invalid"),{code:"profile_invalid"})}}function M(e){const n=e.dsh?.profile?.bundles;if(!Array.isArray(n))return[];const i=new Set,t=[];for(const s of n){const o=String(s??"").trim();!o||i.has(o)||(i.add(o),t.push(o))}return t}function N(e){const n=new Map,i=a(e,"node_modules");if(!D(i)||!p(i).isDirectory())return n;for(const t of S(i)){if(t.startsWith("."))continue;const s=a(i,t);try{if(!p(s).isDirectory())continue}catch{continue}if(t.startsWith("@")){for(const o of S(s))j(a(s,o),`${t}/${o}`,n);continue}j(s,t,n)}return n}function j(e,n,i){try{if(!p(e).isDirectory())return;const t=JSON.parse(I(a(e,"package.json"),"utf8")),s=typeof t.dsh?.bundle?.patch=="string"&&t.dsh.bundle.patch.trim()?t.dsh.bundle.patch.trim():void 0;i.set(n,{version:String(t.version??"").trim(),hasBundle:!!s,...s?{patchPath:a(e,s)}:{}})}catch{}}export{B as DSH_BRIDGE_PLUGIN_NAME,R as DSH_INBOX_PLUGIN_NAMES,h as classifyDshPlugin,$ as disableDshPlugin,W as enableDshPlugin,z as isDshPluginRestartRequired,P as listDshPlugins,F as markDshPluginRestartRequired,b as normalizeDshPluginIds,m as pluginLockReason,J as resetDshPluginRestartRequiredForTests,_ as resolveDshPlugin,U as resolveDshPluginBundlePatches,x as updateDshPluginIds};
@@ -1 +1 @@
1
- import{createHash as N}from"node:crypto";import{existsSync as f,readFileSync as h,readdirSync as g,realpathSync as y,statSync as p}from"node:fs";import{homedir as H}from"node:os";import{basename as m,dirname as c,join as s,resolve as a}from"node:path";import{fileURLToPath as P}from"node:url";function d(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||s(H(),".dsh");return a(t)}const i="web",D="headless";function l(e){return A(String(e??"").trim())}function E(e){const r=l(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function L(e,r){return s(a(e),"profiles",l(r))}function G(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return E(t)}catch{continue}}return i}function S(e){return e===i?"web\uFF08\u63D2\u4EF6\u6258\u7BA1\uFF09":e}function w(e,r){if(r===i)return!0;try{const n=JSON.parse(h(s(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function J(e={}){const r=d(e.dshHome,e.env),t=new Map;t.set(i,{id:i,displayName:S(i),webApp:!0});const n=s(r,"profiles");if(!f(n)||!p(n).isDirectory())return[...t.values()];for(const o of g(n).sort()){if(o===D||o===i)continue;try{l(o)}catch{continue}const u=s(n,o);try{if(!p(u).isDirectory())continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:w(u,o)})}return[...t.values()]}function R(e){const r=d(e.dshHome,e.env),t=l(e.profileName?.trim()||i),n=a(r,"profiles",t),o=f(n)?y(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:b(o)}}function b(e){return N("sha256").update(a(e)).digest("hex")}function _(e){return s(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function I(e){const r=_(e);if(!f(r)||!p(r).isDirectory())return[];const t=[];for(const n of g(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(h(s(r,n),"utf8"));if(!O(o)||o.profileKey!==e.profileKey||!M(o.pid)||!f(o.tokenPath)||!p(o.tokenPath).isFile())continue;t.push(o)}catch{}return t}function V(e){const r=I(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});if(r.length>1)throw Object.assign(new Error(`Multiple live Grix Bridge endpoints found for DSH profile "${e.profileName}". Stop extra profile processes so only one instance remains.`),{code:"profile_instance_ambiguous"});return r[0]}function $(e){let r=c(P(e)),t;for(;c(r)!==r;){const o=s(r,"package.json");if(f(o))try{if(JSON.parse(h(o,"utf8")).dsh?.profile)return x(r)}catch{}m(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=d();return R({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||i})}function x(e){const r=y(e),t=m(r),n=c(r);return{dshHome:m(n)==="profiles"?c(n):d(),profileName:t,profileRoot:r,profileKey:b(r)}}function A(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function O(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{i as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,E as assertSelectableDshProfileName,_ as bridgeDiscoveryDirectory,I as discoverDshBridgeEndpoints,S as dshProfileDisplayName,$ as inferProfileIdentityFromModule,J as listDshProfiles,l as parseDshProfileName,w as profileHasWebApp,b as profileKeyFor,L as resolveDshConnectorProfileDataDir,d as resolveDshHome,R as resolveDshProfileIdentity,G as resolveDshSelectedProfileName,V as selectDshBridgeEndpoint};
1
+ import{createHash as N}from"node:crypto";import{existsSync as f,readFileSync as a,readdirSync as g,realpathSync as y,statSync as d}from"node:fs";import{homedir as H}from"node:os";import{basename as m,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as P}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(H(),".dsh");return l(t)}const s="web",S="headless";function h(e){return O(String(e??"").trim())}function E(e){const r=h(e);if(r===S)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function G(e,r){return i(l(e),"profiles",h(r))}function J(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return E(t)}catch{continue}}return s}function D(e){return e===s?"Web":e}function w(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:D(s),webApp:!0});const n=i(r,"profiles");if(!f(n)||!d(n).isDirectory())return[...t.values()];for(const o of g(n).sort()){if(o===S||o===s||o==="node_modules")continue;try{h(o)}catch{continue}const p=i(n,o);try{if(!d(p).isDirectory()||!JSON.parse(a(i(p,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:D(o),webApp:w(p,o)})}return[...t.values()]}function _(e){const r=u(e.dshHome,e.env),t=h(e.profileName?.trim()||s),n=l(r,"profiles",t),o=f(n)?y(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:b(o)}}function b(e){return N("sha256").update(l(e)).digest("hex")}function R(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function I(e){const r=R(e);if(!f(r)||!d(r).isDirectory())return[];const t=[];for(const n of g(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!A(o)||o.profileKey!==e.profileKey||!M(o.pid)||!f(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t}function W(e){const r=I(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});if(r.length>1)throw Object.assign(new Error(`Multiple live Grix Bridge endpoints found for DSH profile "${e.profileName}". Stop extra profile processes so only one instance remains.`),{code:"profile_instance_ambiguous"});return r[0]}function $(e){let r=c(P(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(f(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}m(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return _({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=y(e),t=m(r),n=c(r);return{dshHome:m(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:b(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function A(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,S as DSH_HEADLESS_PROFILE_NAME,E as assertSelectableDshProfileName,R as bridgeDiscoveryDirectory,I as discoverDshBridgeEndpoints,D as dshProfileDisplayName,$ as inferProfileIdentityFromModule,V as listDshProfiles,h as parseDshProfileName,w as profileHasWebApp,b as profileKeyFor,G as resolveDshConnectorProfileDataDir,u as resolveDshHome,_ as resolveDshProfileIdentity,J as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
@@ -1,3 +1,3 @@
1
- import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as x}from"node:events";import{readFileSync as j}from"node:fs";import{createConnection as $}from"node:net";import{isCompatibleDshVersion as C}from"./bridge-session-reliability.js";import{DshBridgeJsonRpcPeer as z,GRIX_DSH_PROTOCOL_MAX as O,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as q,selectDshBridgeEndpoint as G}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as U,normalizeDshPresets as V,normalizeDshProviders as L,resolveDshAgentPreset as F,resolveDshProviderId as K}from"./toolbar-state.js";const X=T(),B=5e3,_=1e4,J=6e4;class W extends x{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(e,t,r,s){super(),this.peer=e,this.sessionId=t,this.ownerId=r,this.onCursorAck=s,e.on("notification",(o,l)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:l});return}this.deliverNotification(o,l)}),e.on("protocolError",o=>this.emit("protocolError",o))}prompt(e,t){return this.peer.call("session/prompt",{sessionId:e.sessionId,ownerId:this.ownerId,contentBlocks:e.contentBlocks},t)}async shutdown(e){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},u(e,5e3))}finally{this.peer.close()}}close(e){this.peer.close(e)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const e of this.pendingNotifications.splice(0))this.deliverNotification(e.method,e.params)}}call(e,t,r){const s=t&&typeof t=="object"?t:{};return this.peer.call(e,{sessionId:this.sessionId,ownerId:this.ownerId,...s},u(r,1e4))}async ack(e,t){if(!Number.isSafeInteger(e)||e<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const r=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:e},u(t,5e3));return await this.onCursorAck?.(e),r}cancel(e){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},u(e,3e4))}setOptions(e,t){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:e.modelId,modeId:e.modeId},u(t,1e4))}deliverNotification(e,t){this.emit("notification",e,t)}}class re{options;client=null;peer=null;socket=null;exitEmitter=new x;intentionalClose=!1;constructor(e){this.options=e}async start(){const e=q({dshHome:this.options.dshHome,profileName:this.options.profileName}),t=G(e);if(t.protocolMax<M||t.protocolMin>O)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${t.protocolMin}-${t.protocolMax}`),{code:"bridge_incompatible"});if(!C(t.dshVersion))throw Object.assign(new Error(`DSH Profile ${t.dshVersion||"unknown"} is outside the verified Bridge compatibility matrix`),{code:"bridge_incompatible"});const r=j(t.tokenPath,"utf8").trim();if(!r)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await Z(t.address,this.options.connectTimeoutMs??B);this.socket=s;const o=new z(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,n)=>{if(i!=="interaction/requestApproval")throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"});const a=n&&typeof n=="object"?n:{};return{outcome:await this.options.onApproval?.(a)??"unavailable"}});const l=T(),f=H("sha256",r).update(`${l}
2
- ${e.profileKey}
3
- ${t.instanceId}`).digest("hex"),g=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??B),c=await o.call("bridge/initialize",{protocol:{min:M,max:O},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:X},profileKey:e.profileKey,requestedRole:"controller",auth:{nonce:l,proof:f}},g),N=c.profile&&typeof c.profile=="object"?c.profile:{},v=String(N.dshVersion??"");if(!C(v)||v!==t.dshVersion)throw o.close(new Error("DSH Profile version changed or is outside the verified Bridge compatibility matrix")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${t.dshVersion||"unknown"} handshake=${v||"unknown"}`),{code:"bridge_incompatible"});const d=String(this.options.settings.providerId??"").trim(),I=this.options.managedProvider,b=!!I&&(!d||d===I.id);let h=[],y=!1;const P=b?0:this.options.catalogRefreshAttempts??4;for(let i=0;i<=P;i++){try{const n=AbortSignal.timeout(this.options.catalogTimeoutMs??_),a=await o.call("profile/listProviders",{},n),D=L(a.providers);if(y=!0,D.length>0&&(h=D),!d||h.some(R=>R.id===d)||b)break}catch{break}i<P&&await new Promise(n=>setTimeout(n,150))}const w=b&&I?I.id:y&&d&&!h.some(i=>i.id===d)?d:K(this.options.settings.providerId,h);let m;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??_),n=await o.call("profile/listModels",{provider:w},i);m=Array.isArray(n.models)?n.models.filter(a=>!!a&&typeof a=="object"):[]}catch{}const E=(m??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(m?.[0]?.id??this.options.settings.modelId);let S=[...U];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??_),n=await o.call("profile/listPresets",{},i),a=V(n.presets);a.length>0&&(S=a)}catch{}const k=F(this.options.settings.agentPreset,S);this.client=new W(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??J);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:E,maxTokens:this.options.settings.maxTokens,modeId:this.options.settings.modeId,agentPreset:k,systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0,...this.options.managedProvider&&w===this.options.managedProvider.id?{managedProvider:this.options.managedProvider}:{}},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const A=c.serverInfo&&typeof c.serverInfo=="object"?c.serverInfo:{};return{serverInfo:{name:String(A.name??"grix-dsh-profile-bridge"),version:String(A.version??"unknown")},profile:c.profile,capabilities:c.capabilities,...m!==void 0?{models:m}:{},selectedModel:E,providers:h,selectedProvider:w,presets:S,selectedPreset:k}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(e){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(e){return this.exitEmitter.on("exit",e),()=>this.exitEmitter.off("exit",e)}}function u(p,e){return p??AbortSignal.timeout(e)}function Z(p,e){return new Promise((t,r)=>{const s=$(p),o=setTimeout(()=>{l(),s.destroy(),r(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},e);o.unref?.();const l=()=>{clearTimeout(o),s.off("connect",f),s.off("error",g)},f=()=>{l(),s.setNoDelay(!0),t(s)},g=c=>{l(),r(Object.assign(c,{code:"bridge_connect_failed"}))};s.once("connect",f),s.once("error",g)})}export{_ as BRIDGE_CATALOG_TIMEOUT_MS,B as BRIDGE_INITIALIZE_TIMEOUT_MS,J as BRIDGE_SESSION_CREATE_TIMEOUT_MS,re as DshProfileRuntime,W as DshProfileRuntimeClient};
1
+ import{createHmac as H,randomUUID as D}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as $}from"node:fs";import{createConnection as z}from"node:net";import{isCompatibleDshVersion as C}from"./bridge-session-reliability.js";import{isDshBridgedGrixTool as G}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as q,GRIX_DSH_PROTOCOL_MAX as M,GRIX_DSH_PROTOCOL_MIN as B}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as U,selectDshBridgeEndpoint as V}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as L,normalizeDshPresets as F,normalizeDshProviders as K,resolveDshAgentPreset as X,resolveDshProviderId as J}from"./toolbar-state.js";const W=D(),N=5e3,P=1e4,Z=6e4;class Q extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,l)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:l});return}this.deliverNotification(o,l)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},f(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},f(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},f(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class dt{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=U({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=V(t);if(e.protocolMax<B||e.protocolMin>M)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});if(!C(e.dshVersion))throw Object.assign(new Error(`DSH Profile ${e.dshVersion||"unknown"} is outside the verified Bridge compatibility matrix`),{code:"bridge_incompatible"});const c=$(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await Y(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new q(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,r)=>{const n=r&&typeof r=="object"?r:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const p=String(n.tool??"").trim(),_=n.args&&typeof n.args=="object"?n.args:{};if(!p)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!G(p))throw Object.assign(new Error(`grix tool "${p}" is not exposed to DSH`),{code:"capability_unavailable"});const R=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(p,_,R)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const l=D(),g=H("sha256",c).update(`${l}
2
+ ${t.profileKey}
3
+ ${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),a=await o.call("bridge/initialize",{protocol:{min:B,max:M},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:W},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:l,proof:g}},I),j=a.profile&&typeof a.profile=="object"?a.profile:{},b=String(j.dshVersion??"");if(!C(b)||b!==e.dshVersion)throw o.close(new Error("DSH Profile version changed or is outside the verified Bridge compatibility matrix")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${b||"unknown"}`),{code:"bridge_incompatible"});const d=String(this.options.settings.providerId??"").trim(),w=this.options.managedProvider,y=!!w&&(!d||d===w.id);let m=[],E=!1;const k=y?0:this.options.catalogRefreshAttempts??4;for(let i=0;i<=k;i++){try{const r=AbortSignal.timeout(this.options.catalogTimeoutMs??P),n=await o.call("profile/listProviders",{},r),p=K(n.providers);if(E=!0,p.length>0&&(m=p),!d||m.some(_=>_.id===d)||y)break}catch{break}i<k&&await new Promise(r=>setTimeout(r,150))}const v=y&&w?w.id:E&&d&&!m.some(i=>i.id===d)?d:J(this.options.settings.providerId,m);let u;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??P),r=await o.call("profile/listModels",{provider:v},i);u=Array.isArray(r.models)?r.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const x=(u??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(u?.[0]?.id??this.options.settings.modelId);let S=[...L];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??P),r=await o.call("profile/listPresets",{},i),n=F(r.presets);n.length>0&&(S=n)}catch{}const A=X(this.options.settings.agentPreset,S);this.client=new Q(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Z);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:v,model:x,maxTokens:this.options.settings.maxTokens,modeId:this.options.settings.modeId,agentPreset:A,pluginIds:this.options.settings.pluginIds??[],...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0,...this.options.managedProvider&&v===this.options.managedProvider.id?{managedProvider:this.options.managedProvider}:{}},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const T=a.serverInfo&&typeof a.serverInfo=="object"?a.serverInfo:{};return{serverInfo:{name:String(T.name??"grix-dsh-profile-bridge"),version:String(T.version??"unknown")},profile:a.profile,capabilities:a.capabilities,...u!==void 0?{models:u}:{},selectedModel:x,providers:m,selectedProvider:v,presets:S,selectedPreset:A}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function f(h,t){return h??AbortSignal.timeout(t)}function Y(h,t){return new Promise((e,c)=>{const s=z(h),o=setTimeout(()=>{l(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const l=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{l(),s.setNoDelay(!0),e(s)},I=a=>{l(),c(Object.assign(a,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{P as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Z as BRIDGE_SESSION_CREATE_TIMEOUT_MS,dt as DshProfileRuntime,Q as DshProfileRuntimeClient};
@@ -0,0 +1,4 @@
1
+ import{chmodSync as p,mkdirSync as m,readFileSync as h,writeFileSync as f}from"node:fs";import{dirname as g,join as n}from"node:path";import{pathToFileURL as y}from"node:url";import{normalizeDshPluginIds as P,resolveDshPluginBundlePatches as v}from"./plugin-manager.js";const I=`[]
2
+ `;function k(e){const r=P(e.pluginIds??[]);if(r.length===0)return{pluginIds:[],patchPaths:[]};const i=v({dshHome:e.dshHome,profileName:e.profileName,pluginIds:r}),t=n(i.identity.profileRoot,".grix-session-overlays",j(e.overlayId));m(t,{recursive:!0,mode:448});let o;e.baseCordisPath&&(o=n(t,"base-jsonrpc.cordis.yml"),d(o,h(e.baseCordisPath,"utf8")));const c=b(i.patchPaths),a=n(t,"empty.cordis.yml");d(a,I);const l=n(t,"bridge-agent-overlay.cordis.yml");d(l,u(a,c));let s;return o&&(s=n(t,"embedded-jsonrpc.cordis.yml"),d(s,u(o,c))),{pluginIds:i.pluginIds,patchPaths:i.patchPaths,bridgeOverlayPath:l,...s?{embeddedCordisPath:s}:{}}}function b(e){const r=[];for(const i of e){const t=h(i,"utf8").trim();!t||t==="[]"||(r.push(`# ${i}`),r.push(t))}return r.length>0?r.join(`
3
+ `):"[]"}function u(e,r){return["- id: grix-session-plugin-overlay"," name: '@deepseek-ai/cordis-plugin-include'"," config:",` path: ${JSON.stringify(y(e).href)}`," patches:",...S(r),""].join(`
4
+ `)}function S(e){const r=e.trim();return!r||r==="[]"?[" []"]:r.split(/\r?\n/).map(i=>` ${i}`)}function d(e,r){m(g(e),{recursive:!0,mode:448}),f(e,r,{mode:384});try{p(e,384)}catch{}}function j(e){return String(e??"").trim().replace(/[^a-zA-Z0-9_.-]/g,"-").slice(0,96)||"session"}export{k as prepareDshSessionPluginOverlay};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "3.28.0",
4
- "tarball": "grix-dsh-bridge-3.28.0.tgz",
5
- "size": 11972,
6
- "unpackedSize": 46341,
7
- "shasum": "d5519bce6aae7549e89ba1ba6f683a84902db497",
8
- "integrity": "sha512-jgUCA4EA2IUHkdBPkdp91I7MZUU9vYmaGtB2c0QYzztTk58aDe3J6AmJI29SRUYYfZRuNxRIO8rtgXjGVv93+A=="
3
+ "bridgeVersion": "3.29.0",
4
+ "tarball": "grix-dsh-bridge-3.29.0.tgz",
5
+ "size": 13784,
6
+ "unpackedSize": 52666,
7
+ "shasum": "1e9dbf9b08482e46ba777531668095c680f5857b",
8
+ "integrity": "sha512-mNUxDMBnizQ7lJmx5+/G1Hflo8n1NnLos/g9tSsJ2EwOGDVrWVKN6gDJZvNQ9JdkOqrGuzpg1dH5bOZEMYF8Ww=="
9
9
  }