grix-connector 3.26.11 → 3.26.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- import{createHash as H,randomUUID as M}from"node:crypto";import{EventEmitter as B}from"node:events";import{copyFileSync as X,existsSync as $,mkdirSync as Y}from"node:fs";import{dirname as Z,join as P,resolve as q}from"node:path";import{fileURLToPath as N}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ee}from"../../default-skills/index.js";import{resolveCliPath as te}from"../../core/util/cli-probe.js";import{DshWireCapture as ie}from"./audit-boundary.js";import{dsmlToolCallKey as se,projectVisibleDsmlText as oe}from"./dsml-text-filter.js";import{mapDshSessionEvent as re,unwrapDshSessionEvent as ne}from"./event-mapper.js";import{buildDshUserPrompt as j,extractQuotedMessageMarker as U}from"./prompt-builder.js";import{DshProcessRuntime as ae}from"./process-runtime.js";import{DshProfileRuntime as de}from"./profile-runtime.js";import{createDshWebProfile as le}from"./profile-catalog.js";import{disableDshPlugin as ce,enableDshPlugin as he,isDshPluginRestartRequired as ue,listDshPlugins as L,markDshPluginRestartRequired as pe}from"./plugin-manager.js";import{assertSelectableDshProfileName as ge,discoverDshBridgeEndpoints as fe,listDshProfiles as me,resolveDshConnectorProfileDataDir as ve,resolveDshHome as _e,resolveDshProfileIdentity as F,resolveDshSelectedProfileName as be}from"./profile-resolver.js";import{DshBridgeInstaller as C,errorForDshBridgeReadiness as O}from"./bridge-installer.js";import{awaitDshProfileIdle as Se,ensureDshBridgeReady as Ie,prepareDshProfileBridge as ke,restartManagedProfileIfOwned as we}from"./profile-supervisor.js";import{runDshProtocolProbe as Pe}from"./probe.js";import{buildDshSystemPrompt as ye,describeDshSystemPrompt as De}from"./system-prompt.js";import{DshActionCoordinator as Ce}from"./toolbar-actions.js";import{adoptDshProfileModels as xe,adoptLiveDshProviderSelection as Te,buildDshToolbarMeta as Me,DEFAULT_DSH_MAX_TOKENS as Re,DEFAULT_DSH_MODE as Ee,DEFAULT_DSH_MODELS as Ae,DEFAULT_DSH_PRESETS as He,DEFAULT_DSH_PROVIDER_ID as V,DEFAULT_DSH_PROVIDERS as Be,normalizeDshPresets as $e,normalizeDshProviders as qe,permissionModeFor as W,resolveDshAgentPreset as Q,resolveDshProviderId as Ne,retainRequestedDshProvider as je}from"./toolbar-state.js";import{TurnCorrelator as Ue}from"./turn-correlator.js";import{getDshSessionUsageStore as Le,normalizeDshUsage as z}from"./usage.js";import{DSH_GRIX_PROVIDER_ID as v,buildDshManagedProvider as G}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",K=20*6e4;class Fe extends B{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class It extends B{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;activeTimeoutMs=K;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 Ce;activeWireStart=0;activeUsage=J();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;providers;presets;catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.models=i.models?.length?i.models:Ae,this.providers=[...Be],this.presets=[...He]}async start(){this.alive=!0,this.stopped=!1,this.syncGrixProvider();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&!this.options.bindingStore.getDshSettings(this.options.aibotSessionId)?.modelId&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{modelId:this.resolveDesiredSettings().modelId}),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 Fe(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 te(i),o=!!s;let l={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const a=await Pe({command:s,args:this.config.args,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});l={ok:!0,latency:a.latencyMs,serverName:a.serverName,serverVersion:a.serverVersion}}catch(a){l={ok:!1,latency:null,error:this.redactError(a)}}else{const a=Date.now();try{const d=new C({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),g=await Ie({installer:d,autoStart:!1}),p=O(g);if(p)throw p;const r=fe(g.identity);if(r.length!==1)throw Object.assign(new Error(r.length===0?`No live Grix Bridge endpoint in DSH profile "${g.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${g.identity.profileName}"`),{code:r.length===0?"bridge_missing":"profile_instance_ambiguous"});l={ok:!0,latency:Date.now()-a,serverName:"grix-dsh-profile-bridge",serverVersion:r[0].bridgeVersion}}catch(d){l={ok:!1,latency:null,error:this.redactError(d)}}}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 Ue(t),this.activeUsage=J(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{const i=this.ensureRuntimeWithRetry();this.runtimeStartPromise=i;try{await i}finally{this.runtimeStartPromise===i&&(this.runtimeStartPromise=null)}if(this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const s=j(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const o=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:s.text}]});if(!o?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(o.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(),a=this.profileRevision,d=ye({...l,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),g=De(d);this.runtimeGeneration+=1;const p=this.resolveIntegrationMode(),r=this.resolveSelectedProfile();if(p==="profile_bridge")try{const u=await this.attachSelectedProfile(),y=await this.healBridgeUpdate(u),k=O(y);if(k)throw k;this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),u}let n=p==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,r):void 0;p==="profile_bridge"&&!n&&(n={profileName:r,sessionId:We(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.runtimeSessionId=n?.sessionId??Ve(this.options.aibotSessionId,this.runtimeGeneration);const h=this.profileDataDir(r),_=P(h,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ie(_);const b=p==="embedded_jsonrpc"?new ae({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),home:h,sessionRoot:P(h,"sessions"),env:this.config.env,systemPrompt:d,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new de({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:d,settings:i,managedProvider:i.providerId===v?G(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:u=>this.handleBridgeApproval(u),onCursorAck:u=>{!n||u<=n.eventCursor||(n={...n,eventCursor:u},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n))}});this.runtime=b,this.bridgeAckCursor=n?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const u=await b.start();if(!b.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});b.client?.on("notification",(S,I)=>this.onNotification(S,I)),b.client?.on("protocolError",S=>this.onProtocolError(S)),b.onExit(()=>this.onRuntimeExit()),b.client?.activateNotifications?.();let y=!1;if(p==="profile_bridge"){const S=qe(u.providers),I=Te({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(u.selectedProvider??"")});this.providers=je(S,I.providerId,this.providers),i={...i,providerId:I.providerId},y=I.persistFallback;const x=I.providerId,R=Object.prototype.hasOwnProperty.call(u,"models")?u.models:void 0,E=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=xe({current:this.models,fetched:R,providerChanged:E}),(R!==void 0||E)&&(this.catalogProviderId=x||this.catalogProviderId);const T=String(u.selectedModel??"");T&&T!==i.modelId&&(i={...i,modelId:T});const A=$e(u.presets);A.length>0&&(this.presets=A);const D=String(u.selectedPreset??"");D&&D!==i.agentPreset&&(i={...i,agentPreset:D},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,D))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),w={};y&&(k?.providerId??"")!==(i.providerId??"")&&(w.providerId=i.providerId),(k?.modelId??"")!==i.modelId&&(w.modelId=i.modelId),(w.providerId||w.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??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??V,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=u.capabilities??null,p==="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=a,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${g.schemaVersion} prompt_sha256=${g.sha256} prompt_length=${g.length}`),this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),u}}async ensureRuntimeWithRetry(){let e;for(let t=1;t<=2;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||s==="binding_missing"||s==="protocol_incompatible"||t===2)throw i;await this.stopRuntime(!0)}throw e}onNotification(e,t){const i=Oe(t);if(e==="session.event"){const s=ne(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=re(e);if(t.kind==="unknown"&&!Ge(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=j(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=U(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=U(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),l=oe(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(l.suppressedToolCalls);const a=l.visible;this.observeVisibleTextAfterToolCall(a);let d="";a.startsWith(i.sentText)?d=a.slice(i.sentText.length):(e||t.finalizeDsml)&&(d=a),!(!d&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,d,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=a)}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=se(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=z(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=z(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 H,randomUUID as M}from"node:crypto";import{EventEmitter as B}from"node:events";import{copyFileSync as X,existsSync as $,mkdirSync as Y}from"node:fs";import{dirname as Z,join as P,resolve as q}from"node:path";import{fileURLToPath as N}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ee}from"../../default-skills/index.js";import{resolveCliPath as te}from"../../core/util/cli-probe.js";import{DshWireCapture as ie}from"./audit-boundary.js";import{dsmlToolCallKey as se,projectVisibleDsmlText as oe}from"./dsml-text-filter.js";import{mapDshSessionEvent as re,unwrapDshSessionEvent as ne}from"./event-mapper.js";import{buildDshUserPrompt as j,extractQuotedMessageMarker as U}from"./prompt-builder.js";import{DshProcessRuntime as ae}from"./process-runtime.js";import{DshProfileRuntime as de}from"./profile-runtime.js";import{createDshWebProfile as le}from"./profile-catalog.js";import{disableDshPlugin as ce,enableDshPlugin as he,isDshPluginRestartRequired as ue,listDshPlugins as L,markDshPluginRestartRequired as pe}from"./plugin-manager.js";import{assertSelectableDshProfileName as ge,discoverDshBridgeEndpoints as fe,listDshProfiles as me,resolveDshConnectorProfileDataDir as ve,resolveDshHome as _e,resolveDshProfileIdentity as F,resolveDshSelectedProfileName as be}from"./profile-resolver.js";import{DshBridgeInstaller as D,errorForDshBridgeReadiness as O}from"./bridge-installer.js";import{awaitDshProfileIdle as Se,ensureDshBridgeReady as Ie,prepareDshProfileBridge as ke,restartManagedProfileIfOwned as we}from"./profile-supervisor.js";import{runDshProtocolProbe as Pe}from"./probe.js";import{buildDshSystemPrompt as ye,describeDshSystemPrompt as Ce}from"./system-prompt.js";import{DshActionCoordinator as De}from"./toolbar-actions.js";import{adoptDshProfileModels as xe,adoptLiveDshProviderSelection as Te,buildDshToolbarMeta as Me,DEFAULT_DSH_MAX_TOKENS as Re,DEFAULT_DSH_MODE as Ee,DEFAULT_DSH_MODELS as Ae,DEFAULT_DSH_PRESETS as He,DEFAULT_DSH_PROVIDER_ID as V,normalizeDshPresets as Be,normalizeDshProviders as $e,permissionModeFor as W,resolveDshAgentPreset as Q,resolveDshProviderId as qe,retainRequestedDshProvider as Ne}from"./toolbar-state.js";import{TurnCorrelator as je}from"./turn-correlator.js";import{getDshSessionUsageStore as Ue,normalizeDshUsage as z}from"./usage.js";import{DSH_GRIX_PROVIDER_ID as v,buildDshManagedProvider as G}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",K=20*6e4;class Le extends B{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class St extends B{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;activeTimeoutMs=K;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 De;activeWireStart=0;activeUsage=J();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;providers;presets;catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.models=i.models?.length?i.models:Ae,this.providers=[],this.presets=[...He]}async start(){this.alive=!0,this.stopped=!1,this.syncGrixProvider();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&!this.options.bindingStore.getDshSettings(this.options.aibotSessionId)?.modelId&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{modelId:this.resolveDesiredSettings().modelId}),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 Le(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 te(i),o=!!s;let l={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const a=await Pe({command:s,args:this.config.args,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});l={ok:!0,latency:a.latencyMs,serverName:a.serverName,serverVersion:a.serverVersion}}catch(a){l={ok:!1,latency:null,error:this.redactError(a)}}else{const a=Date.now();try{const d=new D({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),g=await Ie({installer:d,autoStart:!1}),p=O(g);if(p)throw p;const r=fe(g.identity);if(r.length!==1)throw Object.assign(new Error(r.length===0?`No live Grix Bridge endpoint in DSH profile "${g.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${g.identity.profileName}"`),{code:r.length===0?"bridge_missing":"profile_instance_ambiguous"});l={ok:!0,latency:Date.now()-a,serverName:"grix-dsh-profile-bridge",serverVersion:r[0].bridgeVersion}}catch(d){l={ok:!1,latency:null,error:this.redactError(d)}}}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 je(t),this.activeUsage=J(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{const i=this.ensureRuntimeWithRetry();this.runtimeStartPromise=i;try{await i}finally{this.runtimeStartPromise===i&&(this.runtimeStartPromise=null)}if(this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const s=j(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const o=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:s.text}]});if(!o?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(o.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(),a=this.profileRevision,d=ye({...l,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),g=Ce(d);this.runtimeGeneration+=1;const p=this.resolveIntegrationMode(),r=this.resolveSelectedProfile();if(p==="profile_bridge")try{const u=await this.attachSelectedProfile(),y=await this.healBridgeUpdate(u),k=O(y);if(k)throw k;this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),u}let n=p==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,r):void 0;p==="profile_bridge"&&!n&&(n={profileName:r,sessionId:Ve(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.runtimeSessionId=n?.sessionId??Oe(this.options.aibotSessionId,this.runtimeGeneration);const h=this.profileDataDir(r),_=P(h,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ie(_);const b=p==="embedded_jsonrpc"?new ae({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),home:h,sessionRoot:P(h,"sessions"),env:this.config.env,systemPrompt:d,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new de({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:d,settings:i,managedProvider:i.providerId===v?G(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:u=>this.handleBridgeApproval(u),onCursorAck:u=>{!n||u<=n.eventCursor||(n={...n,eventCursor:u},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n))}});this.runtime=b,this.bridgeAckCursor=n?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const u=await b.start();if(!b.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});b.client?.on("notification",(S,I)=>this.onNotification(S,I)),b.client?.on("protocolError",S=>this.onProtocolError(S)),b.onExit(()=>this.onRuntimeExit()),b.client?.activateNotifications?.();let y=!1;if(p==="profile_bridge"){const S=$e(u.providers),I=Te({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(u.selectedProvider??"")});this.providers=Ne(S,I.providerId,this.providers),i={...i,providerId:I.providerId},y=I.persistFallback;const x=I.providerId,R=Object.prototype.hasOwnProperty.call(u,"models")?u.models:void 0,E=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=xe({current:this.models,fetched:R,providerChanged:E}),(R!==void 0||E)&&(this.catalogProviderId=x||this.catalogProviderId);const T=String(u.selectedModel??"");T&&T!==i.modelId&&(i={...i,modelId:T});const A=Be(u.presets);A.length>0&&(this.presets=A);const C=String(u.selectedPreset??"");C&&C!==i.agentPreset&&(i={...i,agentPreset:C},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,C))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),w={};y&&(k?.providerId??"")!==(i.providerId??"")&&(w.providerId=i.providerId),(k?.modelId??"")!==i.modelId&&(w.modelId=i.modelId),(w.providerId||w.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??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??V,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=u.capabilities??null,p==="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=a,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${g.schemaVersion} prompt_sha256=${g.sha256} prompt_length=${g.length}`),this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),u}}async ensureRuntimeWithRetry(){let e;for(let t=1;t<=2;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||s==="binding_missing"||s==="protocol_incompatible"||t===2)throw i;await this.stopRuntime(!0)}throw e}onNotification(e,t){const i=Fe(t);if(e==="session.event"){const s=ne(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=re(e);if(t.kind==="unknown"&&!ze(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=j(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=U(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=U(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),l=oe(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(l.suppressedToolCalls);const a=l.visible;this.observeVisibleTextAfterToolCall(a);let d="";a.startsWith(i.sentText)?d=a.slice(i.sentText.length):(e||t.finalizeDsml)&&(d=a),!(!d&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,d,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=a)}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=se(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=z(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=z(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+=`
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 a=this.personaDirty&&!!this.runtime;a&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const d=`${i.inbound.event_id}-dsh`,g=(p,r,n=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,p,r,n),this.emit("eventDone",i.inbound.event_id),a&&this.rebuildRuntime("persona_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,d).then(async()=>{await this.flushPendingFinalBridgeAck(!0),g(s,o,l)},async p=>{await this.flushPendingFinalBridgeAck(!1),g(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(p,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="pending",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 l=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);l.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:l})})):"unavailable"}projectConnectorSkills(){const e=_e(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=P(e,"skills"),i=ee(t);i.length>0&&f.info(m,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(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 h=e.action_type==="exec_approve"||e.action_type==="permission_approve";return n.resolve(h?"allowed-once":"rejected"),{status:"ok",result:{approval_id:r,decision:h?"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 C({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:Qe(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=ge(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(h){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(h)}}if(this.options.bindingStore.isDshProfileLocked(i)){const h=this.resolveSelectedProfile();return e.action_type==="create_profile"||h!==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 h=this.options.createDshProfile?await this.options.createDshProfile(r):await le({profileName:r,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),_=h.identity?.profileName??r;return this.persistSelectedProfile(_)?(await this.flushSelectedProfile(),this.finishProfileSelection(_,h.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(h){return{status:"failed",errorCode:String(h?.code??"profile_create_failed"),errorMsg:this.redactError(h)}}return this.listProfiles().some(h=>h.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(_=>_.id===n))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const h=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?h===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"}:h===n?(this.options.bindingStore.setDshAgentPreset(i,n),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!1)}):this.options.bindingStore.setDshAgentPreset(i,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 a=this.resolveDesiredSettings();let d;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"};d={providerId:r}}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"};d={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"};d={modeId:r}}if((d.providerId===void 0||d.providerId===a.providerId)&&(d.modelId===void 0||d.modelId===a.modelId)&&(d.modeId===void 0||d.modeId===a.modeId)&&this.applied?.appliedRevision===a.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,d,a.revision,"already_applied",!0)};const p=this.options.bindingStore.updateDshSettings(i,d)??a.revision;if(await this.options.bindingStore.flush(),(d.providerId||d.modelId)&&(this.options.globalConfigStore?.set(this.options.agentName,{...d.providerId?{dshProviderId:d.providerId}:{},...d.modelId?{dshModelId:d.modelId}:{}}),await this.options.globalConfigStore?.flush()),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),!this.runtime)return{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"pending",!1)};try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"applied",!0)}}catch(r){return{status:"failed",result:this.settingsActionResult(e.action_type,d,p,"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 C({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 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 ke({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 flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return me({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 L(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){try{return ue(F({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 g=L(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(g,!1)}}o&&await this.stopRuntime(!0);const l=F({dshHome:s.dshHome,profileName:s.profileName});await Se(l);const a=e==="dsh_enable_plugin"?await he({...s,name:String(t.name??t.plugin_name??"")}):await ce({...s,name:String(t.name??t.plugin_name??"")});let d="skipped";return a.changed&&(d=this.options.restartManagedProfile?await this.options.restartManagedProfile(a.identity.profileName):await we(new C({command:"dsh",dshHome:s.dshHome,profileName:a.identity.profileName})),pe(a.identity.profileKey,d!=="restarted")),o&&await this.rebuildRuntime("plugin_changed"),this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(a.plugins,a.changed,d)}}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=be({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return ve(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=P(this.profileDataDir(e),"session-usage.json"),i=P(this.options.dataRoot,"session-usage.json");return!$(t)&&$(i)&&(Y(Z(t),{recursive:!0,mode:448}),X(i,t)),Le(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 a=this.resolveDesiredSettings(),d=a.revision||i,g={provider_id:a.providerId,model_id:a.modelId,mode_id:a.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:d};return e==="set_mode"&&(g.sandbox_mode=W(a.modeId),g.approval_policy=a.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:W(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:d,settings_revision:d,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:g,...l?{error:l}:{}}}syncGrixProvider(){const e=G(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===V||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.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId,s=this.providers.some(a=>a.id===v)?v:void 0,o=Ne(i||s,this.providers),l=[e?.modelId,t?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(a=>!!a&&this.models.some(d=>d.id===a))??"deepseek-chat";return{providerId:o,modelId:l,modeId:e?.modeId??Ee,agentPreset:Q(e?.agentPreset,this.presets),maxTokens:e?.maxTokens??this.options.maxTokens??Re,revision:e?.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,Me({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??K,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="pending",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 Oe(c){const e=Number(c&&typeof c=="object"?c.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function Ve(c,e){return`grix-${H("sha256").update(c).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function We(c){return`grix-${H("sha256").update(c).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function J(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function Qe(c){return{readiness:c.readiness,profile:c.identity.profileName,dshVersion:c.dshVersion,runningDshVersion:c.runningDshVersion,installedBridgeVersion:c.installedBridgeVersion,bundledBridgeVersion:c.bundledBridgeVersion,runningBridgeVersion:c.runningBridgeVersion,endpointCount:c.endpointCount,requiresProfileRestart:c.readiness==="profile_restart_required",compatibleDshVersions:c.compatibleDshVersions}}const ze=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 Ge(c){const e=c.data?.chunk&&typeof c.data.chunk=="object"?c.data.chunk:c.data,t=String(e?.type??"");return ze.has(c.type)||c.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(t)}export{It 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 a=this.personaDirty&&!!this.runtime;a&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const d=`${i.inbound.event_id}-dsh`,g=(p,r,n=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,p,r,n),this.emit("eventDone",i.inbound.event_id),a&&this.rebuildRuntime("persona_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,d).then(async()=>{await this.flushPendingFinalBridgeAck(!0),g(s,o,l)},async p=>{await this.flushPendingFinalBridgeAck(!1),g(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(p,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="pending",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 l=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);l.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:l})})):"unavailable"}projectConnectorSkills(){const e=_e(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=P(e,"skills"),i=ee(t);i.length>0&&f.info(m,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(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 h=e.action_type==="exec_approve"||e.action_type==="permission_approve";return n.resolve(h?"allowed-once":"rejected"),{status:"ok",result:{approval_id:r,decision:h?"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 D({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:We(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=ge(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(h){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(h)}}if(this.options.bindingStore.isDshProfileLocked(i)){const h=this.resolveSelectedProfile();return e.action_type==="create_profile"||h!==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 h=this.options.createDshProfile?await this.options.createDshProfile(r):await le({profileName:r,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),_=h.identity?.profileName??r;return this.persistSelectedProfile(_)?(await this.flushSelectedProfile(),this.finishProfileSelection(_,h.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(h){return{status:"failed",errorCode:String(h?.code??"profile_create_failed"),errorMsg:this.redactError(h)}}return this.listProfiles().some(h=>h.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(_=>_.id===n))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const h=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?h===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"}:h===n?(this.options.bindingStore.setDshAgentPreset(i,n),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!1)}):this.options.bindingStore.setDshAgentPreset(i,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 a=this.resolveDesiredSettings();let d;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"};d={providerId:r}}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"};d={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"};d={modeId:r}}if((d.providerId===void 0||d.providerId===a.providerId)&&(d.modelId===void 0||d.modelId===a.modelId)&&(d.modeId===void 0||d.modeId===a.modeId)&&this.applied?.appliedRevision===a.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,d,a.revision,"already_applied",!0)};const p=this.options.bindingStore.updateDshSettings(i,d)??a.revision;if(await this.options.bindingStore.flush(),(d.providerId||d.modelId)&&(this.options.globalConfigStore?.set(this.options.agentName,{...d.providerId?{dshProviderId:d.providerId}:{},...d.modelId?{dshModelId:d.modelId}:{}}),await this.options.globalConfigStore?.flush()),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),!this.runtime)return{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"pending",!1)};try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"applied",!0)}}catch(r){return{status:"failed",result:this.settingsActionResult(e.action_type,d,p,"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 D({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 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 ke({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 flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return me({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 L(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){try{return ue(F({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 g=L(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(g,!1)}}o&&await this.stopRuntime(!0);const l=F({dshHome:s.dshHome,profileName:s.profileName});await Se(l);const a=e==="dsh_enable_plugin"?await he({...s,name:String(t.name??t.plugin_name??"")}):await ce({...s,name:String(t.name??t.plugin_name??"")});let d="skipped";return a.changed&&(d=this.options.restartManagedProfile?await this.options.restartManagedProfile(a.identity.profileName):await we(new D({command:"dsh",dshHome:s.dshHome,profileName:a.identity.profileName})),pe(a.identity.profileKey,d!=="restarted")),o&&await this.rebuildRuntime("plugin_changed"),this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(a.plugins,a.changed,d)}}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=be({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return ve(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=P(this.profileDataDir(e),"session-usage.json"),i=P(this.options.dataRoot,"session-usage.json");return!$(t)&&$(i)&&(Y(Z(t),{recursive:!0,mode:448}),X(i,t)),Ue(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 a=this.resolveDesiredSettings(),d=a.revision||i,g={provider_id:a.providerId,model_id:a.modelId,mode_id:a.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:d};return e==="set_mode"&&(g.sandbox_mode=W(a.modeId),g.approval_policy=a.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:W(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:d,settings_revision:d,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:g,...l?{error:l}:{}}}syncGrixProvider(){const e=G(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===V||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.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId,s=this.providers.some(a=>a.id===v)?v:void 0,o=qe(i||s,this.providers),l=[e?.modelId,t?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(a=>!!a&&this.models.some(d=>d.id===a))??"deepseek-chat";return{providerId:o,modelId:l,modeId:e?.modeId??Ee,agentPreset:Q(e?.agentPreset,this.presets),maxTokens:e?.maxTokens??this.options.maxTokens??Re,revision:e?.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,Me({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??K,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="pending",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 Fe(c){const e=Number(c&&typeof c=="object"?c.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function Oe(c,e){return`grix-${H("sha256").update(c).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function Ve(c){return`grix-${H("sha256").update(c).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function J(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function We(c){return{readiness:c.readiness,profile:c.identity.profileName,dshVersion:c.dshVersion,runningDshVersion:c.runningDshVersion,installedBridgeVersion:c.installedBridgeVersion,bundledBridgeVersion:c.bundledBridgeVersion,runningBridgeVersion:c.runningBridgeVersion,endpointCount:c.endpointCount,requiresProfileRestart:c.readiness==="profile_restart_required",compatibleDshVersions:c.compatibleDshVersions}}const Qe=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 ze(c){const e=c.data?.chunk&&typeof c.data.chunk=="object"?c.data.chunk:c.data,t=String(e?.type??"");return Qe.has(c.type)||c.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(t)}export{St as DshJsonRpcAdapter};
@@ -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 U,selectDshBridgeEndpoint as V}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as q,DEFAULT_DSH_PROVIDERS as G,normalizeDshPresets as L,normalizeDshProviders as F,resolveDshAgentPreset as K,resolveDshProviderId as X}from"./toolbar-state.js";const J=T(),B=5e3,b=1e4,W=6e4;class Z 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 ce{options;client=null;peer=null;socket=null;exitEmitter=new x;intentionalClose=!1;constructor(e){this.options=e}async start(){const e=U({dshHome:this.options.dshHome,profileName:this.options.profileName}),t=V(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 Q(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}
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
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:J},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,S=!!I&&(!d||d===I.id);let h=[...G],y=!1;const E=S?0:this.options.catalogRefreshAttempts??4;for(let i=0;i<=E;i++){try{const n=AbortSignal.timeout(this.options.catalogTimeoutMs??b),a=await o.call("profile/listProviders",{},n),D=F(a.providers);if(y=!0,D.length>0&&(h=D),!d||h.some(R=>R.id===d)||S)break}catch{break}i<E&&await new Promise(n=>setTimeout(n,150))}const w=S&&I?I.id:y&&d&&!h.some(i=>i.id===d)?d:X(this.options.settings.providerId,h);let m;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??b),n=await o.call("profile/listModels",{provider:w},i);m=Array.isArray(n.models)?n.models.filter(a=>!!a&&typeof a=="object"):[]}catch{}const P=(m??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(m?.[0]?.id??this.options.settings.modelId);let _=[...q];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??b),n=await o.call("profile/listPresets",{},i),a=L(n.presets);a.length>0&&(_=a)}catch{}const k=K(this.options.settings.agentPreset,_);this.client=new Z(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??W);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,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:P,providers:h,selectedProvider:w,presets:_,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 Q(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{b as BRIDGE_CATALOG_TIMEOUT_MS,B as BRIDGE_INITIALIZE_TIMEOUT_MS,W as BRIDGE_SESSION_CREATE_TIMEOUT_MS,ce as DshProfileRuntime,Z as DshProfileRuntimeClient};
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 +1 @@
1
- import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as _}from"./profile-resolver.js";const h="approval",x=16384,n="deepseek-official",c=Object.freeze([{id:n,displayName:"DeepSeek"}]),S=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),l="standard",p=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function A(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const t=r,i=String(t.id??"").trim();return i?[{id:i,displayName:String(t.displayName??t.name??i)}]:[]}):[]}function b(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const t=r,i=String(t.id??"").trim();if(!i)return[];const d=Number(t.contextWindow);return[{id:i,displayName:String(t.displayName??t.name??i),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function P(e){return e.fetched!==void 0?b(e.fetched):e.providerChanged?[]:[...e.current]}function N(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const t=r,i=String(t.id??"").trim();if(!i||t.broken)return[];const d=String(t.description??"").trim();return[{id:i,displayName:String(t.displayName??t.name??i),...d?{description:d}:{}}]}):[]}const f=Object.freeze([{id:s,displayName:_(s),webApp:!0}]);function k(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const t=r,i=String(t.id??"").trim();return i?[{id:i,displayName:String(t.displayName??t.name??_(i)),...t.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function u(e,r){const t=String(e??"").trim();return t&&r.some(i=>i.id===t)?t:r.some(i=>i.id===l)?l:r[0]?.id||l}function m(e,r){const t=String(e??"").trim();return t&&r.some(i=>i.id===t)?t:r.some(i=>i.id===n)?n:r[0]?.id||n}function y(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(o=>o.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:m(i||void 0,e.liveProviders),persistFallback:!0}}function E(e,r,t){const i=String(r??"").trim(),d=e.length>0?[...e]:[];if(i&&!d.some(o=>o.id===i)){const o=t.find(a=>a.id===i);d.unshift(o??{id:i,displayName:i})}return d.length>0?d:[...c]}function I(e){const r=e.applied,t=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",d=e.providers??c,o=e.presets??p,a=m(e.desired.providerId,d),g=u(e.desired.agentPreset,o),v=r!=null||t==="pending"||t==="failed";return{provider_id:a,model_id:e.desired.modelId,mode_id:e.desired.modeId,agent_preset_id:g,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??S],available_presets:[...o],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...v?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:t,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??f],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function L(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function R(e){return{agent_preset_id:u(e.agentPreset,p),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[...p],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??f],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0}}export{x as DEFAULT_DSH_MAX_TOKENS,h as DEFAULT_DSH_MODE,S as DEFAULT_DSH_MODELS,p as DEFAULT_DSH_PRESETS,l as DEFAULT_DSH_PRESET_ID,f as DEFAULT_DSH_PROFILES,c as DEFAULT_DSH_PROVIDERS,n as DEFAULT_DSH_PROVIDER_ID,P as adoptDshProfileModels,y as adoptLiveDshProviderSelection,R as buildDshBindingToolbarMeta,I as buildDshToolbarMeta,b as normalizeDshModels,N as normalizeDshPresets,k as normalizeDshProfiles,A as normalizeDshProviders,L as permissionModeFor,u as resolveDshAgentPreset,m as resolveDshProviderId,E as retainRequestedDshProvider};
1
+ import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as _}from"./profile-resolver.js";const h="approval",D=16384,a="deepseek-official",v=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),l="standard",p=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function x(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();return t?[{id:t,displayName:String(i.displayName??i.name??t)}]:[]}):[]}function b(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();if(!t)return[];const d=Number(i.contextWindow);return[{id:t,displayName:String(i.displayName??i.name??t),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function A(e){return e.fetched!==void 0?b(e.fetched):e.providerChanged?[]:[...e.current]}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();if(!t||i.broken)return[];const d=String(i.description??"").trim();return[{id:t,displayName:String(i.displayName??i.name??t),...d?{description:d}:{}}]}):[]}const c=Object.freeze([{id:s,displayName:_(s),webApp:!0}]);function k(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();return t?[{id:t,displayName:String(i.displayName??i.name??_(t)),...i.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function f(e,r){const i=String(e??"").trim();return i&&r.some(t=>t.id===i)?i:r.some(t=>t.id===l)?l:r[0]?.id||l}function u(e,r){const i=String(e??"").trim();return i&&r.some(t=>t.id===i)?i:r.some(t=>t.id===a)?a:r[0]?.id||a}function N(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(o=>o.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const t=String(e.liveSelectedProvider??"").trim();return{providerId:u(t||void 0,e.liveProviders),persistFallback:!0}}function y(e,r,i){const t=String(r??"").trim(),d=e.length>0?[...e]:[];if(t&&!d.some(o=>o.id===t)){const o=i.find(n=>n.id===t);o&&d.unshift(o)}return d}function I(e){const r=e.applied,i=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),t=e.runtimeReadiness??"unknown",d=e.providers??[],o=e.presets??p,n=u(e.desired.providerId,d),m=f(e.desired.agentPreset,o),g=r!=null||i==="pending"||i==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,agent_preset_id:m,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??v],available_presets:[...o],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...g?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:i,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??c],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:t,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(t)?"install_bridge":t==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:t==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function E(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function L(e){return{agent_preset_id:f(e.agentPreset,p),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[...p],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??c],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0}}export{D as DEFAULT_DSH_MAX_TOKENS,h as DEFAULT_DSH_MODE,v as DEFAULT_DSH_MODELS,p as DEFAULT_DSH_PRESETS,l as DEFAULT_DSH_PRESET_ID,c as DEFAULT_DSH_PROFILES,a as DEFAULT_DSH_PROVIDER_ID,A as adoptDshProfileModels,N as adoptLiveDshProviderSelection,L as buildDshBindingToolbarMeta,I as buildDshToolbarMeta,b as normalizeDshModels,P as normalizeDshPresets,k as normalizeDshProfiles,x as normalizeDshProviders,E as permissionModeFor,f as resolveDshAgentPreset,u as resolveDshProviderId,y as retainRequestedDshProvider};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "3.26.11",
4
- "tarball": "grix-dsh-bridge-3.26.11.tgz",
5
- "size": 11972,
3
+ "bridgeVersion": "3.26.13",
4
+ "tarball": "grix-dsh-bridge-3.26.13.tgz",
5
+ "size": 11973,
6
6
  "unpackedSize": 46345,
7
- "shasum": "65ed8f41a82ef17ee26007cc9f96c18f41489054",
8
- "integrity": "sha512-aDHIAiM6U9KzbDh++TYyWRompdswmsyv6UrbE4ot9qxFtXlkWD7fyBhkEkkVmQfWkb1lHXND+WDdX2LiOfdMwg=="
7
+ "shasum": "0df4ddbc7f0d4a0b930e0b4e86665d327eacd5a7",
8
+ "integrity": "sha512-kwC2kGPOrwTP6pi2XH1iTGgN/G5qKMaw23bjlbSovs5liwUlkmqF1qAQ/yeQ9RI9+6YnV5Ct9Zq/zv6N5LAmzQ=="
9
9
  }