grix-connector 4.15.2 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/adapter/acp/acp-adapter.js +9 -9
- package/dist/adapter/claude/claude-adapter.js +18 -18
- package/dist/adapter/cursor/cursor-adapter.js +1 -1
- package/dist/adapter/deepseek-harness/bridge-installer.js +6 -6
- package/dist/adapter/deepseek-harness/bridge-session-reliability.js +1 -1
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +1 -1
- package/dist/adapter/deepseek-harness/profile-package-shadow.js +1 -0
- package/dist/adapter/deepseek-harness/profile-runtime.js +1 -1
- package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -2
- package/dist/adapter/deepseek-harness/toolbar-state.js +1 -1
- package/dist/adapter/opencode/opencode-adapter.js +4 -4
- package/dist/adapter/opencode/opencode-types.js +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.16.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -0
- package/dist/core/provider-quota/presentation.js +1 -1
- package/dist/core/provider-quota/providers.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/protocol/acp-client.js +1 -1
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.15.2.tgz +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFileSync as ee}from"node:child_process";import{createInterface as E}from"node:readline";import{EventEmitter as L}from"node:events";import{randomUUID as te}from"node:crypto";import{mkdirSync as P,readFileSync as q,writeFileSync as D,readdirSync as se,statSync as N}from"node:fs";import{join as A,resolve as ne}from"node:path";import{fileURLToPath as ie}from"node:url";import{homedir as F}from"node:os";import{GRIX_PATHS as re,log as u}from"../../core/log/index.js";import{IdentityInjector as oe}from"../shared/identity-injector.js";import{buildSimpleProbeReport as ae}from"../shared/probe-util.js";import{InternalApiServer as de}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as le,pruneLegacyMcpServerEntries as ce}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as ue}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as R}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as he}from"../../default-skills/index.js";import{spawnCommand as B,killProcessGroup as C}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as me,listLivingDescendants as fe}from"./living-descendants.js";import{SessionBindingStore as pe}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ge}from"./fetch-models.js";import{resolveCursorSpawn as x}from"./resolve-command.js";import{fetchCursorAccountUsage as Se}from"./fetch-usage.js";import{buildCursorContextWindow as ye,buildCursorContextWindowFromUsage as ve,resolveCursorContextWindowSize as _e}from"./context-window.js";const Ae=12e4,M=300*1e3,j=90*1e3,O=1800*1e3,be=8192,Q="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",U=
|
|
1
|
+
import{execFileSync as ee}from"node:child_process";import{createInterface as E}from"node:readline";import{EventEmitter as L}from"node:events";import{randomUUID as te}from"node:crypto";import{mkdirSync as P,readFileSync as q,writeFileSync as D,readdirSync as se,statSync as N}from"node:fs";import{join as A,resolve as ne}from"node:path";import{fileURLToPath as ie}from"node:url";import{homedir as F}from"node:os";import{GRIX_PATHS as re,log as u}from"../../core/log/index.js";import{IdentityInjector as oe}from"../shared/identity-injector.js";import{buildSimpleProbeReport as ae}from"../shared/probe-util.js";import{InternalApiServer as de}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as le,pruneLegacyMcpServerEntries as ce}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as ue}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as R}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as he}from"../../default-skills/index.js";import{spawnCommand as B,killProcessGroup as C}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as me,listLivingDescendants as fe}from"./living-descendants.js";import{SessionBindingStore as pe}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ge}from"./fetch-models.js";import{resolveCursorSpawn as x}from"./resolve-command.js";import{fetchCursorAccountUsage as Se}from"./fetch-usage.js";import{buildCursorContextWindow as ye,buildCursorContextWindowFromUsage as ve,resolveCursorContextWindowSize as _e}from"./context-window.js";const Ae=12e4,M=300*1e3,j=90*1e3,O=1800*1e3,be=8192,Q="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",U=600*1e3,W=90,H=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function we(d){const e=d.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):d||"tool"}function z(d){const e=String(d.call_id??d.callId??"").trim(),t=d.tool_call??d.toolCall;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=Object.keys(t);if(n.length>0){const s=n[0],r=t[s],i=r&&typeof r=="object"&&!Array.isArray(r)?r:null;return{toolName:we(s),toolInput:i?.args??i?.arguments??{},callId:e}}}return{toolName:String(d.name??d.tool_name??d.toolName??"tool").trim()||"tool",toolInput:d.args??d.tool_input??d.toolInput??{},callId:e}}function J(d){return String(d??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function G(d){const e=J(d);return e==="askquestion"||e==="askuserquestion"}function X(d){const e=J(d);return e==="createplan"||e==="exitplanmode"}function ke(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const n=t,s=String(n.label??"").trim();if(s)return s;const r=String(n.value??"").trim();if(r)return r;const i=String(n.text??"").trim();return i||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function Ce(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.title??"").trim(),n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const s=[];for(let r=0;r<n.length;r++){const i=n[r];if(!i||typeof i!="object")continue;const o=i,a=t||`Question ${r+1}`,l=String(o.header??o.id??o.question??a).trim()||a,c=String(o.prompt??o.question??"").trim();if(!c)continue;const h=ke(o.options),p=o.multiSelect===!0||o.multi_select===!0;s.push({header:l,prompt:c,...h?{options:h}:{},...p?{multi_select:!0}:{},allow_free_text:!0})}return s.length>0?s:null}function Ie(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.name??e.title??"").trim(),n=String(e.overview??"").trim(),s=String(e.plan??"").trim();if(!s&&!n&&!t)return null;const r=[];return t&&r.push(`# ${t}`),n&&r.push(n),s&&r.push(s),r.join(`
|
|
2
2
|
|
|
3
3
|
`)}function Re(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.type??"").trim().toLowerCase();if(!t)return null;switch(t){case"tool_call":{const n=String(e.subtype??"").trim().toLowerCase(),s=z(e);return G(s.toolName)||X(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(H.has(n),null)}case"error":return{type:"error",payload:{message:String(e.message??e.error??e.result??"cursor error").trim()||"cursor error"}};case"result":{const n=String(e.subtype??"").trim().toLowerCase();return e.is_error===!0||n==="error"?{type:"error",payload:{message:String(e.result??e.message??"cursor run failed").trim()||"cursor run failed"}}:null}default:return null}}function Be(d,e){if(!d||typeof d!="object"||Array.isArray(d))return"";const t=d;if(String(t.type??"")!=="assistant")return"";const n=t.model_call_id??t.modelCallId;if(n!=null&&String(n).trim()!=="")return"";const s=t.message,r=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(r))return"";const i=r.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return"";const a=o;return a.type==="text"?String(a.text??""):""}).filter(Boolean).join("");if(!i)return"";if(e){if(i===e||e.startsWith(i)&&i.length<e.length)return"";if(i.startsWith(e))return i.slice(e.length)}return i}const K=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function I(d){const e=String(d??"").trim().toLowerCase();return K.some(t=>t.id===e)?e:null}function T(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function V(d,e,t){if(t<0)return null;let n;try{n=se(d,{withFileTypes:!0})}catch{return null}for(const s of n){const r=A(d,s.name);if(s.isDirectory()){const i=V(r,e,t-1);if(i)return i}else if(s.isFile()&&s.name.endsWith(e))return r}return null}function Y(d,e){if(!d)return null;const t=e||A(F(),".cursor","projects");return V(t,`${d}.jsonl`,6)}function xe(d){const e=d.context_messages_json;if(e)try{const t=JSON.parse(e);return!Array.isArray(t)||t.length===0?void 0:t.map(n=>({senderId:String(n.sender_id??"unknown"),content:String(n.content??"")}))}catch{return}}function Me(d,e){const t=[String(d??"")],n=String(e.quoted_message_id??"").trim();n&&t.push(`[quoted_message_id] ${n}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
|
|
4
4
|
${s}`),t.filter(r=>r.length>0).join(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{execFile as V}from"node:child_process";import{createHash as N,randomUUID as O}from"node:crypto";import{closeSync as G,copyFileSync as p,cpSync as
|
|
2
|
-
${
|
|
3
|
-
`,{mode:384}),{root:
|
|
4
|
-
`,{mode:384})}catch{}}discardInstallBackup(e){try{f(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const
|
|
5
|
-
`,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const
|
|
6
|
-
`,"utf8"),await e()}finally{G(n);try{f(
|
|
1
|
+
import{execFile as V}from"node:child_process";import{createHash as N,randomUUID as O}from"node:crypto";import{closeSync as G,copyFileSync as p,cpSync as I,existsSync as d,mkdirSync as y,openSync as T,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as $}from"node:path";import{fileURLToPath as x}from"node:url";import{promisify as C}from"node:util";import{log as w}from"../../core/log/index.js";import{resolveShimInvocation as M}from"../../core/runtime/spawn.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";import{unshadowInstalledDshPackages as z}from"./profile-package-shadow.js";const U=C(V),q=2*1024*1024,u="@grix/dsh-bridge",_="deepseek-harness-bridge-installer",v=2,X=1e3;class de{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),t=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),n=t.version,s=L(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,P=e?await R(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?i?i!==n||this.installedBridgeContentStale(t)?c="bridge_update_required":s.length===0||a!==i||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:P,runningDshVersion:l,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const t=this.bridgeAsset();return j(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const i=this.readInstalledBridgeVersion();if(i===t.version&&!this.installedBridgeContentStale(t))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,i),a=o(n,`grix-dsh-bridge-${t.version}.tgz`);p(t.tarball,a);try{if(i===t.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==t.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${t.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(t.integrity),this.unshadowProfileDshPackages(e)}catch(l){try{await this.rollbackInstall(e,n,s,i)}finally{this.unshadowProfileDshPackages(e);try{f(a,{force:!0})}catch{}}throw Object.assign(new Error(`Bridge install failed: ${k(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,t){const i=["plugin","--profile",this.identity.profileName,"add",t];let n;for(let s=1;s<=v;s++)try{await g(e,i,this.options.dshHome);return}catch(a){n=a,w.warn(_,`dsh plugin add attempt ${s}/${v} failed for profile ${this.identity.profileName}
|
|
2
|
+
${W(a)}`),s<v&&await new Promise(l=>setTimeout(l,X))}throw n}unshadowProfileDshPackages(e){try{const t=z(this.identity.profileRoot,e);t.length>0&&w.info(_,`unshadowed profile DSH packages after bridge install: ${t.join(", ")}`)}catch(t){w.warn(_,`profile DSH package unshadow after install failed: ${t instanceof Error?t.message:t}`)}}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,t){const i=o(e,"rollback",`${Date.now()}-${O()}`);y(i,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&I(n,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(i,"package.json"));const P=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of P){const S=o(this.identity.profileRoot,c);d(S)&&p(S,o(i,c))}return b(o(i,"manifest.json"),`${JSON.stringify({priorVersion:t,hadBridge:s,hadPackageJson:l})}
|
|
3
|
+
`,{mode:384}),{root:i,priorVersion:t,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,t,i,n){const s=n?o(t,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}n?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const t=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(f(t,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),I(i,t,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const t=JSON.parse(h(e,"utf8"));let i=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=t[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],i=!0)}i&&b(e,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`,{mode:384})}catch{}}discardInstallBackup(e){try{f(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const t=JSON.parse(h(e,"utf8"));return typeof t.version=="string"?t.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=h(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){b(this.installedIntegrityPath(),`${e}
|
|
5
|
+
`,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const t=m(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?t>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E($(this.options.tarballPath)):H()}}function le(r){if(r.readiness==="ready")return null;const e=r.identity.profileName,t=`dsh --profile ${e}`,i=`dsh does not hot-load plugin changes: stop the running profile process, then start it again with: ${t}`;let n;r.endpointCount===0?n=`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. Start the profile with: ${t}`:r.runningBridgeVersion&&r.installedBridgeVersion&&r.runningBridgeVersion!==r.installedBridgeVersion?n=`Grix Bridge in DSH profile "${e}" is running version ${r.runningBridgeVersion}, but ${r.installedBridgeVersion} is installed on disk. ${i}`:n=`The live Grix Bridge in DSH profile "${e}" predates the Bridge content installed on disk. ${i}`;const s={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${t}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${r.installedBridgeVersion??"none"}, expected ${r.bundledBridgeVersion}${r.installedBridgeVersion===r.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:n};return Object.assign(new Error(s[r.readiness]),{code:r.readiness})}function ce(){return H().tarball}function H(){const r=[x(new URL("../../assets/dsh-bridge/",import.meta.url)),x(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!r)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(h(o(r,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const t=E(o(r,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(t.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==t.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return t}function E(r,e){if(!d(r)||!m(r).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${r}`),{code:"bridge_asset_missing"});if(m(r).size>q)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const t=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(r)?.[1];if(!t)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${N("sha512").update(h(r)).digest("base64")}`;return{tarball:r,version:t,integrity:i}}async function j(r,e){const t=J(r);y(t,{recursive:!0,mode:448});const i=o(t,"install.lock");let n=A(i);if(n===null){let s=0;try{s=Number(h(i,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!Y(s)){try{f(i,{force:!0})}catch{}n=A(i)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${r.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
|
|
6
|
+
`,"utf8"),await e()}finally{G(n);try{f(i,{force:!0})}catch{}}}function A(r){try{return T(r,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${k(e)}`),{code:"bridge_install_failed"})}}function Y(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function ge(r,e){const t=await B(r?.trim()||"dsh");return t?R(t,e):null}async function R(r,e){try{return(await g(r,["--version"],e)).trim().split(/\s+/)[0]||null}catch(t){return w.warn(_,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${r}\uFF09\uFF1A${k(t)}`),null}}async function g(r,e,t){try{const i=M(r,e);return(await U(i.command,i.args,{env:{...process.env,...t?{DSH_HOME:$(t)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:i.windowsVerbatimArguments})).stdout}catch(i){const n=i&&typeof i=="object"?i:{};throw Object.assign(new Error(k(i)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?D(n.stderr):void 0})}}function D(r){return r.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function k(r){const e=r&&typeof r=="object"?r:{};return D(String(e.stderr??e.message??r??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function W(r){const e=r&&typeof r=="object"?r:{};return D(String(e.stderr??e.message??r??"unknown error")).slice(0,8*1024)}export{de as DshBridgeInstaller,ce as defaultBridgeTarball,le as errorForDshBridgeReadiness,ge as readDshCliVersion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function o(n){const e=Number(n);return Number.isSafeInteger(e)&&e>=0?e:0}function s(n){return o(n)+1}function t(n,e){return Math.max(o(n),o(e))}function f(n,e){return n!==void 0&&o(e)+1<n}function a(n){return{nextCursor:n.nextCursor,ackCursor:n.ackCursor,buffered:[...n.buffered],bufferedBytes:n.bufferedBytes}}async function u(n){n.cancel({kind:"user"},{keepInbox:!1}),await n.whenIdle()}function c(n,e){return n.model===e.model&&n.reasoningEffort===e.reasoningEffort&&n.skillControlEnabled===e.skillControlEnabled&&n.skillsDir===e.skillsDir&&n.pluginOverlayPath===e.pluginOverlayPath&&r(n.skillIds,e.skillIds)&&r(n.pluginIds,e.pluginIds)}function r(n,e){if(n.length!==e.length)return!1;const
|
|
1
|
+
function o(n){const e=Number(n);return Number.isSafeInteger(e)&&e>=0?e:0}function s(n){return o(n)+1}function t(n,e){return Math.max(o(n),o(e))}function f(n,e){return n!==void 0&&o(e)+1<n}function a(n){return{nextCursor:n.nextCursor,ackCursor:n.ackCursor,buffered:[...n.buffered],bufferedBytes:n.bufferedBytes}}async function u(n){n.cancel({kind:"user"},{keepInbox:!1}),await n.whenIdle()}function c(n,e){return n.model===e.model&&n.provider===e.provider&&n.reasoningEffort===e.reasoningEffort&&n.skillControlEnabled===e.skillControlEnabled&&n.skillsDir===e.skillsDir&&n.pluginOverlayPath===e.pluginOverlayPath&&r(n.skillIds,e.skillIds)&&r(n.pluginIds,e.pluginIds)}function r(n,e){if(n.length!==e.length)return!1;const i=new Set(e);return n.every(l=>i.has(l))}export{u as cancelUntilIdle,a as carryReplayWindow,t as effectiveAckCursor,f as isReplayWindowExceeded,s as nextCursorAfterAck,o as normalizeCursor,c as sameDshSessionProjection};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{createHash as E,randomUUID as x}from"node:crypto";import{EventEmitter as U}from"node:events";import{copyFileSync as ce,existsSync as W,mkdirSync as ue}from"node:fs";import{dirname as pe,join as T,resolve as G}from"node:path";import{fileURLToPath as z}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ge}from"../../default-skills/index.js";import{resolveCliPath as fe}from"../../core/util/cli-probe.js";import{DshWireCapture as me}from"./audit-boundary.js";import{dsmlToolCallKey as ve,projectVisibleDsmlText as be}from"./dsml-text-filter.js";import{mapDshSessionEvent as _e,unwrapDshSessionEvent as Se}from"./event-mapper.js";import{buildDshUserPrompt as Q,extractQuotedMessageMarker as K}from"./prompt-builder.js";import{DshProcessRuntime as ke}from"./process-runtime.js";import{DshProfileRuntime as Ie}from"./profile-runtime.js";import{compareDshVersions as X}from"./dsh-version.js";import{createDshWebProfile as we}from"./profile-catalog.js";import{listDshPlugins as M,resolveDshPlugin as Te,updateDshPluginIds as Pe}from"./plugin-manager.js";import{listDshSkills as R,resolveDshSkill as ye,updateDshSkillIds as De}from"./skill-manager.js";import{prepareDshSessionPluginOverlay as Ce}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Ee,discoverDshBridgeEndpoints as xe,listDshProfiles as Me,resolveDshConnectorProfileDataDir as Re,resolveDshHome as Ae,resolveDshSelectedProfileName as He}from"./profile-resolver.js";import{DshBridgeInstaller as A,errorForDshBridgeReadiness as H,readDshCliVersion as $e}from"./bridge-installer.js";import{ensureDshBridgeReady as Be,prepareDshProfileBridge as qe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as J,dshRuntimeEnsureBackoffMs as Fe,isRetryableDshRuntimeError as Ne}from"./runtime-ensure.js";import{runDshProtocolProbe as Le}from"./probe.js";import{buildDshSystemPrompt as je,describeDshSystemPrompt as Ve}from"./system-prompt.js";import{DshActionCoordinator as Oe}from"./toolbar-actions.js";import{adoptDshProfileModels as Ue,adoptLiveDshProviderSelection as We,buildDshToolbarMeta as Ge,DEFAULT_DSH_MAX_TOKENS as ze,DEFAULT_DSH_MODELS as Qe,DEFAULT_DSH_PRESETS as Ke,DEFAULT_DSH_PROVIDER_ID as $,DEFAULT_DSH_REASONING_EFFORT as Xe,DEFAULT_DSH_THINKING as Je,normalizeDshPresets as Ye,normalizeDshProviders as Ze,normalizeDshReasoningEffort as B,normalizeDshThinking as q,permissionModeFor as Y,resolveDshAgentPreset as Z,resolveDshModeId as et,resolveDshProviderId as tt,retainRequestedDshProvider as it}from"./toolbar-state.js";import{modelsForDshProvider as st,resolveDshCatalogForToolbar as nt,writeDshCatalogCache as ot}from"./catalog-cache.js";import{TurnCorrelator as rt}from"./turn-correlator.js";import{effectiveDshReasoningEffort as at}from"./types.js";import{getDshSessionUsageStore as dt,normalizeDshUsage as ee}from"./usage.js";import{toolCallToInvoke as lt}from"../../core/mcp/tools.js";import{isEventTool as ht}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as ct}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as v,dshCredentialsLayoutFor as ut,isDshGrixProviderConfigured as te,removeDshGrixProvider as pt,writeDshGrixProvider as gt}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",ie=20*6e4,se=6e4,ne=9e4,oe=180*6e4,re="0.1.0-rc.8",ae="0.1.0-rc.8";class ft extends U{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class ai extends U{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=ie;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 Oe;activeWireStart=0;activeUsage=de();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;profileDshVersion=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Qe;providers=[];presets=[...Ke];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState==="pending"&&(this.settingsState="applied"),this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new ft(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_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}async handleExecApprovalEvent(e){const t=String(e.approval_command_id??e.approval_id??e.tool_call_id??"").trim(),i=this.pendingApprovals.get(t);return i?(clearTimeout(i.timer),this.pendingApprovals.delete(t),i.resolve(e.decision==="deny"?"rejected":"allowed-once"),{delivered:!0}):{delivered:!1,errorCode:"approval_not_found",errorMsg:"That DSH approval request is no longer pending"}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null;const t=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",t?.cwd,{provider_quota:this.providerQuota})}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await fe(i),n=!!s;let a={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await Le({command:s,args:this.config.args,cordisPath:G(this.options.cordisPath??z(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});a={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){a={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const r=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await Be({installer:r,autoStart:!1}),u=H(p);if(u)throw u;const o=xe(p.identity);if(o.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`),{code:"bridge_missing"});a={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(r){a={ok:!1,latency:null,error:this.redactError(r)}}}return{cli:{command:i,installed:n,path:s,version:null,...n?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:a.ok,latency_ms:a.latency,...a.ok?{}:{error:{code:"conversation_failed",message:a.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:a.serverName,serverVersion:a.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new rt(t),this.activeUsage=de(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=Q(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider(),await this.writeGrixProviderFile();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});const i=this.projectConnectorSkills();let s=this.resolveDesiredSettings();const n=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),a={};n?.modelId||(a.modelId=s.modelId),!n?.providerId&&s.providerId&&(a.providerId=s.providerId),n?.thinking||(a.thinking=s.thinking),n?.reasoningEffort||(a.reasoningEffort=s.reasoningEffort),Object.keys(a).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,a),await this.options.bindingStore.flush(),s=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),r=this.profileRevision,p=je({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),u=Ve(p);this.runtimeGeneration+=1;const o=this.resolveIntegrationMode(),l=this.resolveSelectedProfile();if(o==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let c=o==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,l):void 0;o==="profile_bridge"&&!c&&(c={profileName:l,sessionId:_t(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.runtimeSessionId=c?.sessionId??bt(this.options.aibotSessionId,this.runtimeGeneration);const b=this.profileDataDir(l),F=G(this.options.cordisPath??z(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),N=Ce({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,pluginIds:s.pluginIds??[],overlayId:E("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:F}),he=T(b,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new me(he);const _=o==="embedded_jsonrpc"?new ke({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:N.embeddedCordisPath??F,home:b,sessionRoot:T(b,"sessions"),skillsDir:i,env:this.config.env,systemPrompt:p,settings:s,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new Ie({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:c?.sessionCreated===!0,lastAckCursor:c?.eventCursor??0,systemPrompt:p,settings:s,skillsDir:i,pluginOverlayPath:N.bridgeOverlayPath,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,P,I)=>this.invokeGrixTool(g,P,I),onCursorAck:g=>{!c||g<=c.eventCursor||(c={...c,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c))}});this.runtime=_,this.bridgeAckCursor=c?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,k)=>this.onNotification(S,k)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let P=!1;if(o==="profile_bridge"){const S=Ze(g.providers),k=We({requestedProviderId:s.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=it(S,k.providerId,this.providers),s={...s,providerId:k.providerId},P=k.persistFallback;const D=k.providerId,j=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,V=!!this.catalogProviderId&&!!D&&D!==this.catalogProviderId;this.models=Ue({current:this.models,fetched:j,providerChanged:V}),(j!==void 0||V)&&(this.catalogProviderId=D||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==s.modelId&&(s={...s,modelId:C});const O=Ye(g.presets);O.length>0&&(this.presets=O);const y=String(g.selectedPreset??"");y&&y!==s.agentPreset&&(s={...s,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const I=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),L=(I?.revision??0)!==s.revision,w={};!L&&P&&(I?.providerId??"")!==(s.providerId??"")&&(w.providerId=s.providerId),!L&&(I?.modelId??"")!==s.modelId&&(w.modelId=s.modelId),(w.providerId||w.modelId)&&(s.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??s.revision,await this.options.bindingStore.flush(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${s.providerId} model=${s.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:s.revision,providerId:s.providerId??$,modelId:s.modelId,modeId:s.modeId,thinking:s.thinking,reasoningEffort:at(s)},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,o==="profile_bridge"&&c&&!c.sessionCreated&&(c={...c,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===s.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=r,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${u.schemaVersion} prompt_sha256=${u.sha256} prompt_length=${u.length}`),await this.persistCatalogCache(s.providerId??$),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=J;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Ne(s)||t===J)throw i;f.warn(m,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await vt(Fe(t))}throw e}onNotification(e,t){const i=mt(t);if(e==="session.event"){const s=Se(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const n=this.onSessionEvent(s);this.advanceBridgeAck(i,n);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&f.debug(m,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const a=!!this.correlator?.complete;a&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,a)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},n=String(s.childSessionId??s.sessionId??"");n&&this.capture?.addChild(n),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=_e(e);if(t.kind==="unknown"&&!Pt(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=Q(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?It(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){f.warn(m,`committed assistant text diverged event=${t.inbound.event_id}`);const i=K(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=K(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),a=be(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(a.suppressedToolCalls);const d=a.visible;this.observeVisibleTextAfterToolCall(d);let r="";d.startsWith(i.sentText)?r=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(r=d),!(!r&&!e)&&(i.repliedViaTool||(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,r,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId)),i.sentText=d)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=ve(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 n=i.arguments;try{n=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:n,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=ee(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=ee(e),i=this.resolveDesiredSettings(),s=this.models.find(a=>a.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const a=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:a,totalTokens:n,remainingTokens:Math.max(0,n-a),usedPercentage:a/n*100,remainingPercentage:Math.max(0,100-a/n*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=this.cancelRequested?"canceled":e,n=this.cancelRequested?"user canceled":t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&!i.repliedViaTool&&(s="failed",n="DeepSeek Harness ended after a tool call without returning final assistant text",f.warn(m,`${n} event=${i.inbound.event_id}`)),i.text=i.sentText;const a=s==="failed"&&!!n?.trim();a&&(i.text+=`
|
|
2
2
|
|
|
3
|
-
Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,a),()=>u(s,n,a));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,a)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??x());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const a=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);a.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:a})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ct(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ht(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,a=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return a}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=lt(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=ge(e);return t.length>0&&f.info(m,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){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 o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(o){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:wt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=Ee(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await we({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==d.providerId&&(this.models=st(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(r.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};r={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};r={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};r={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};r={modeId:o}}if((r.providerId===void 0||r.providerId===d.providerId)&&(r.modelId===void 0||r.modelId===d.modelId)&&(r.modeId===void 0||r.modeId===d.modeId)&&(r.thinking===void 0||r.thinking===d.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,r)??d.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId||r.thinking||r.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{},...r.thinking?{dshThinking:r.thinking}:{},...r.reasoningEffort?{dshReasoningEffort:r.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(f.info(m,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await qe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return M(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:R(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),a=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=Te({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!a.includes(n))throw o}const r=Pe(a,d,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${re} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),a=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=ye({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!a.includes(n))throw o}const r=De(a,d,e==="dsh_enable_skill"),p=this.options.bindingStore.setDshEnabledSkills(i,r.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledSkillIds:r.skillIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=He({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 Re(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(ue(pe(t),{recursive:!0,mode:448}),ce(i,t)),dt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,a){const d=this.resolveDesiredSettings(),r=d.revision||i,p={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:r};return e==="set_mode"&&(p.sandbox_mode=Y(d.modeId),p.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:r,settings_revision:r,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...a?{error:a}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=nt({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ot({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=Ae(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(te(this.options.provider)){await gt(e,v,this.options.provider??{},t)==="skipped"&&f.warn(m,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await pt(e,v)}catch(i){f.warn(m,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await $e(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){f.warn(m,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=ut(t);return St(t)&&f.warn(m,`dsh ${t} predates ${ae}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(te(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(p=>p.id===v)?v:void 0,a=tt(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(u=>u.id===p))??"deepseek-chat",r=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:a,modelId:d,modeId:et(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Je,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Xe,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??ze,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:kt(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Ge({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}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??ie,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??se,t=Number.isFinite(e)&&e>0?e:se;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??ne;return Number.isFinite(e)&&e>0?e:ne}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??oe;return Number.isFinite(e)&&e>0?e:oe}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){f.info(m,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,a=Math.max(0,s-n);if(a<this.livenessFreshMs())return t.livenessExtendStartAt=s,f.info(m,`Liveness check: recent DSH activity for ${e} (quietMs=${a}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const r=s-d;return r>this.livenessMaxExtendMs()?(f.warn(m,`Liveness extension budget exhausted for ${e} (quietMs=${a}, extendMs=${r}), allowing close`),!1):(f.info(m,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${a}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(f.error(m,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function mt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function vt(h){return new Promise(e=>setTimeout(e,h))}function bt(h,e){return`grix-${E("sha256").update(h).digest("hex").slice(0,12)}-${e}-${x().slice(0,8)}`}function _t(h){return`grix-${E("sha256").update(h).digest("hex").slice(0,16)}-${x().slice(0,8)}`}function de(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function St(h){const e=X(h,ae);return e!==null&&e<0}function kt(h){const e=X(h,re);return e!==null&&e<0}function le(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function It(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&le(h)==="tool-call-delta"}function wt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const Tt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function Pt(h){const e=le(h);return Tt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{ai as DshJsonRpcAdapter};
|
|
3
|
+
Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,a),()=>u(s,n,a));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,a)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??x());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const a=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);a.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:a})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ct(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ht(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,a=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return a}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=lt(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=ge(e);return t.length>0&&f.info(m,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){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 o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(o){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:wt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=Ee(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await we({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==d.providerId&&(this.models=st(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(r.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};r={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};r={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};r={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};r={modeId:o}}if((r.providerId===void 0||r.providerId===d.providerId)&&(r.modelId===void 0||r.modelId===d.modelId)&&(r.modeId===void 0||r.modeId===d.modeId)&&(r.thinking===void 0||r.thinking===d.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,r)??d.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId||r.thinking||r.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{},...r.thinking?{dshThinking:r.thinking}:{},...r.reasoningEffort?{dshReasoningEffort:r.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(f.info(m,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await qe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return M(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:R(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),a=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=Te({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!a.includes(n))throw o}const r=Pe(a,d,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${re} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),a=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=ye({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!a.includes(n))throw o}const r=De(a,d,e==="dsh_enable_skill"),p=this.options.bindingStore.setDshEnabledSkills(i,r.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledSkillIds:r.skillIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=He({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 Re(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(ue(pe(t),{recursive:!0,mode:448}),ce(i,t)),dt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,a){const d=this.resolveDesiredSettings(),r=d.revision||i,p={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:r};return e==="set_mode"&&(p.sandbox_mode=Y(d.modeId),p.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:r,settings_revision:r,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...a?{error:a}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=nt({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ot({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=Ae(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(te(this.options.provider)){await gt(e,v,this.options.provider??{},t)==="skipped"&&f.warn(m,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await pt(e,v)}catch(i){f.warn(m,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await $e(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){f.warn(m,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=ut(t);return St(t)&&f.warn(m,`dsh ${t} predates ${ae}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(te(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(p=>p.id===v)?v:void 0,a=tt(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(u=>u.id===p))??"deepseek-chat",r=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:a,modelId:d,modeId:et(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Je,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Xe,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??ze,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:kt(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Ge({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}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??ie,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??se,t=Number.isFinite(e)&&e>0?e:se;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??ne;return Number.isFinite(e)&&e>0?e:ne}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??oe;return Number.isFinite(e)&&e>0?e:oe}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){f.info(m,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,a=Math.max(0,s-n);if(a<this.livenessFreshMs())return t.livenessExtendStartAt=s,f.info(m,`Liveness check: recent DSH activity for ${e} (quietMs=${a}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const r=s-d;return r>this.livenessMaxExtendMs()?(f.warn(m,`Liveness extension budget exhausted for ${e} (quietMs=${a}, extendMs=${r}), allowing close`),!1):(f.info(m,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${a}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(f.error(m,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function mt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function vt(h){return new Promise(e=>setTimeout(e,h))}function bt(h,e){return`grix-${E("sha256").update(h).digest("hex").slice(0,12)}-${e}-${x().slice(0,8)}`}function _t(h){return`grix-${E("sha256").update(h).digest("hex").slice(0,16)}-${x().slice(0,8)}`}function de(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function St(h){const e=X(h,ae);return e!==null&&e<0}function kt(h){const e=X(h,re);return e!==null&&e<0}function le(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function It(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&le(h)==="tool-call-delta"}function wt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const Tt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session-log-deepseek/delivery-accepted","job/registered","job/settled","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function Pt(h){const e=le(h);return Tt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{ai as DshJsonRpcAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as b}from"node:module";import{cpSync as v,existsSync as m,mkdirSync as O,readdirSync as D,readFileSync as w,realpathSync as P,renameSync as _,rmSync as x,statSync as N}from"node:fs";import{dirname as A,join as c}from"node:path";function M(n,e){const s=c(n,"node_modules","@deepseek-ai");if(!m(s))return[];let t;try{t=D(s)}catch{return[]}const r=V(n),u=W(n),o=[];for(const i of t){if(!i.startsWith("dsh-"))continue;const p=c(s,i);let k;try{k=N(p)}catch{continue}if(!k.isDirectory())continue;const f=d(c(p,"package.json")),a=f?.name;if(!a?.startsWith("@deepseek-ai/dsh-")||!f?.version||r.has(a))continue;const h=q(e,a);if(!h||h===f.version)continue;const y=u.filter(l=>l.dependsOn.has(a));if(y.length===0)g(p,c(n,"node_modules",".grix-dsh-unshadowed","@deepseek-ai",i));else{const l=c(y[0].dir,"node_modules","@deepseek-ai",i);g(p,l);for(const S of y.slice(1)){const j=c(S.dir,"node_modules","@deepseek-ai",i);m(j)||v(l,j,{recursive:!0})}}o.push(a)}return o}function V(n){const e=d(c(n,"package.json")),s=new Set([...Object.keys(e?.dependencies??{}),...Object.keys(e?.optionalDependencies??{})]),t=e?.dsh?.profile?.bundles;if(Array.isArray(t))for(const r of t)typeof r=="string"&&r&&s.add(r);return s}function W(n){const e=d(c(n,"package.json")),s=[...Object.keys(e?.dependencies??{}),...Object.keys(e?.optionalDependencies??{})],t=[];for(const r of s){const u=c(n,"node_modules",...r.split("/")),o=d(c(u,"package.json"));o&&t.push({dir:u,dependsOn:new Set([...Object.keys(o.dependencies??{}),...Object.keys(o.optionalDependencies??{}),...Object.keys(o.peerDependencies??{})])})}return t}function q(n,e){try{const s=P(n),t=b(s).resolve(`${e}/package.json`);return d(t)?.version??null}catch{return null}}function d(n){try{const e=JSON.parse(w(n,"utf8"));return e&&typeof e=="object"?e:null}catch{return null}}function g(n,e){if(m(e)){x(n,{recursive:!0,force:!0});return}O(A(e),{recursive:!0}),_(n,e)}export{M as unshadowInstalledDshPackages};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{isDshBridgedGrixTool as z}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as G,GRIX_DSH_PROTOCOL_MAX as C,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as U,selectDshBridgeEndpoint as L}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as F,normalizeDshPresets as K,normalizeDshProviders as V,resolveDshAgentPreset as X,resolveDshProviderId as J}from"./toolbar-state.js";import{effectiveDshReasoningEffort as W}from"./types.js";const Z=T(),N=5e3,k=1e4,Q=6e4;class Y extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,a)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:a});return}this.deliverNotification(o,a)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},m(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},m(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},m(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class ht{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=U({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=L(t);if(e.protocolMax<M||e.protocolMin>C)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});const c=q(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await tt(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new G(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,l)=>{const n=l&&typeof l=="object"?l:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const d=String(n.tool??"").trim(),b=n.args&&typeof n.args=="object"?n.args:{};if(!d)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!z(d))throw Object.assign(new Error(`grix tool "${d}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(d,b,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const a=T(),g=H("sha256",c).update(`${a}
|
|
2
2
|
${t.profileKey}
|
|
3
|
-
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},S=String(B.dshVersion??"");if(S!==e.dshVersion)throw o.close(new Error("DSH Profile version changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${S||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,
|
|
3
|
+
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},S=String(B.dshVersion??"");if(S!==e.dshVersion)throw o.close(new Error("DSH Profile version changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${S||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,p=String(this.options.settings.providerId??"").trim();let u=[],_=!1;const x=this.options.catalogRefreshAttempts??8;for(let i=0;i<=x;i++){try{const l=AbortSignal.timeout(this.options.catalogTimeoutMs??k),n=await o.call("profile/listProviders",{},l),d=V(n.providers);if(_=!0,d.length>0&&(u=d),!p||u.some(b=>b.id===p))break}catch{break}i<x&&await new Promise(l=>setTimeout(l,150))}const w=_&&p==="grix"&&!u.some(i=>i.id===p)?p:J(p||void 0,u);let f;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listModels",{provider:w},i);f=Array.isArray(l.models)?l.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const P=(f??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(f?.[0]?.id??this.options.settings.modelId);let v=[...F];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listPresets",{},i),n=K(l.presets);n.length>0&&(v=n)}catch{}const A=X(this.options.settings.agentPreset,v);this.client=new Y(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Q);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,reasoningEffort:W(this.options.settings),...w==="codex-app-server"?{}:{maxTokens:this.options.settings.maxTokens},modeId:this.options.settings.modeId,agentPreset:A,pluginIds:this.options.settings.pluginIds??[],...E?{skillIds:y,skillIdsExplicit:!0}:{},...E&&this.options.skillsDir?{skillsDir:this.options.skillsDir}:{},...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const D=r.serverInfo&&typeof r.serverInfo=="object"?r.serverInfo:{};return{serverInfo:{name:String(D.name??"grix-dsh-profile-bridge"),version:String(D.version??"unknown")},profile:r.profile,capabilities:r.capabilities,...f!==void 0?{models:f}:{},selectedModel:P,providers:u,selectedProvider:w,presets:v,selectedPreset:A}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function m(h,t){return h??AbortSignal.timeout(t)}function tt(h,t){return new Promise((e,c)=>{const s=$(h),o=setTimeout(()=>{a(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const a=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{a(),s.setNoDelay(!0),e(s)},I=r=>{a(),c(Object.assign(r,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{k as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Q as BRIDGE_SESSION_CREATE_TIMEOUT_MS,ht as DshProfileRuntime,Y as DshProfileRuntimeClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createWriteStream as
|
|
2
|
-
`,{mode:384}),q(o,
|
|
1
|
+
import{createWriteStream as C,existsSync as U,mkdirSync as v,readFileSync as W,renameSync as q,rmSync as J,writeFileSync as z}from"node:fs";import{join as O}from"node:path";import{log as s}from"../../core/log/index.js";import{resolveCliPath as Y}from"../../core/util/cli-probe.js";import{killProcessGroup as A,spawnCommand as Q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as _,discoverDshBridgeEndpoints as m,profileHasWebApp as X}from"./profile-resolver.js";import{unshadowInstalledDshPackages as Z}from"./profile-package-shadow.js";const d="deepseek-harness-profile-supervisor",T=45e3,k=5*6e4,ee=500;function re(e){return{...process.env,DSH_HOME:e}}const w=new Map,h=new Map,y=new Map;function b(e,r,n="coalesce"){const i=w.get(e.profileKey);if(i&&n==="coalesce")return i.promise;const t=(i?i.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{w.get(e.profileKey)?.promise===t&&w.delete(e.profileKey)});return w.set(e.profileKey,{promise:t}),t}async function De(e){return b(e.installer.identity,()=>F(e))}async function Ee(e){return b(e.installer.identity,()=>ne(e))}async function ne(e){const r=e.autoInstall!==!1;let n=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(n.readiness)&&(n=await e.installer.install()),n.readiness==="ready"&&!e.reloadManaged?(B(n.identity),n):F(e)}async function F(e){const r=e.installer,n=e.autoStart!==!1,i=e.readyTimeoutMs??T,o=e.bootGraceMs??k;let t=await r.status();if(e.reloadManaged&&(t=await te(r,t,i,o)),t.readiness==="ready")return B(t.identity),t;if(!n){const a=I(t);if(a)throw a;return t}if(t.readiness==="profile_restart_required"&&(t.endpointCount>0&&await ie(t),await K(r,t.identity,o),t=await N(r,i),E(t)||await L(t.identity,o,"bridge endpoint did not appear")),t.readiness==="ready")return ae(t),t;const f=I(t);if(f)throw f;return t}async function te(e,r,n,i){const o=r.identity,t=u(o);if(!t||!p(t.pid))return r;const f=m(o);if(!f.some(M=>P(t,M))&&f.length>0)return r;s.info(d,`reloading connector-managed profile=${o.profileName} pid=${t.pid} after settings write`),await $(o,t.pid),await K(e,o,i);const g=await N(e,n);return E(g)||await L(o,i,"bridge endpoint did not appear after settings reload"),g}async function ie(e){const r=e.identity,n=u(r),i=m(r),o=e.runningBridgeVersion&&e.installedBridgeVersion&&e.runningBridgeVersion!==e.installedBridgeVersion?"bridge upgrade":"bridge content refresh";if(n&&p(n.pid)&&i.some(t=>P(n,t))){s.info(d,`restarting connector-managed profile=${r.profileName} pid=${n.pid} for ${o}`),await $(r,n.pid);return}s.info(d,`starting connector-managed profile=${r.profileName} for ${o}; external profile processes are left untouched`)}async function N(e,r){const n=await ce(E,e,r);return E(n)&&B(e.identity),n}async function L(e,r,n){const i=fe(e,r);if(i)throw s.info(d,`managed profile=${e.profileName} pid=${i.pid} still booting; left running (${n})`),oe(e,i);await se(e,n)}function oe(e,r){return Object.assign(new Error(`DSH profile "${e.profileName}" is still starting (pid ${r.pid}); a first boot installs the profile dependencies before Grix Bridge can listen. The Connector keeps it running \u2014 send the message again in a moment and it will attach automatically.`),{code:"profile_starting"})}function ae(e){s.info(d,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function K(e,r,n){const i=u(r);if(i&&p(i.pid)){if(m(r).some(R=>P(i,R))){s.info(d,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}if(G(i,n)){s.info(d,`waiting on booting connector-managed profile=${r.profileName} pid=${i.pid}`);return}s.warn(d,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await $(r,i.pid)}else i&&x(r);const o=await Y(e.command);if(!o)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});if(m(r).length===0)try{const c=Z(r.profileRoot,o);c.length>0&&s.info(d,`unshadowed profile DSH packages so official rows use the running installation: ${c.join(", ")}`)}catch(c){s.warn(d,`profile DSH package unshadow failed: ${c instanceof Error?c.message:c}`)}const t=de(r),f=_(r);v(f,{recursive:!0,mode:448});const a=O(f,"managed-profile.log"),g=C(a,{flags:"a",mode:384});g.on("error",c=>{s.warn(d,`managed profile log write failed path=${a}: ${c instanceof Error?c.message:c}`)});const M=re(r.dshHome),l=Q(o,t,{cwd:r.profileRoot,env:M,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32"}).process;if(!l.pid)throw g.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});y.set(r.profileKey,""),l.stdout?.pipe(g,{end:!1}),l.stderr?.setEncoding("utf8"),l.stderr?.on("data",c=>{const S=y.get(r.profileKey)??"";y.set(r.profileKey,`${S}${c}`.slice(-4e3))}),l.stderr?.pipe(g,{end:!1}),l.once("exit",(c,S)=>{s.warn(d,`managed profile exited profile=${r.profileName} pid=${l.pid} code=${c} signal=${S}`),h.get(r.profileKey)===l&&h.delete(r.profileKey);try{g.end()}catch{}}),l.unref(),h.set(r.profileKey,l),V(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:l.pid,startedAt:new Date().toISOString(),command:o,args:t}),s.info(d,`started connector-managed profile=${r.profileName} pid=${l.pid} args=${t.join(" ")}`)}async function se(e,r){const n=u(e);n&&(s.warn(d,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await $(e,n.pid))}async function $(e,r){const n=u(e)?.endpointPid,i=n&&n!==r&&m(e).some(a=>a.pid===n)?n:null,o=i?[r,i]:[r],t=h.get(e.profileKey);if(t?.pid===r){try{A(t,"SIGTERM")}catch{}h.delete(e.profileKey)}else for(const a of o)if(p(a))try{process.kill(a,"SIGTERM")}catch{}const f=Date.now()+5e3;for(;Date.now()<f&&o.some(p);)await H(100);for(const a of o)if(p(a))try{process.kill(a,"SIGKILL")}catch{}x(e)}function de(e){return X(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function ce(e,r,n){const i=Date.now()+n;let o=await r.status();for(;Date.now()<i;){if(e(o))return o;const t=u(r.identity);if(t&&!p(t.pid))throw x(r.identity),le(r.identity);await H(ee),o=await r.status()}return o}function D(e){return O(_(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(W(D(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function V(e,r){const n=_(e);v(n,{recursive:!0,mode:448});const i=D(e),o=`${i}.${process.pid}.tmp`;z(o,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`,{mode:384}),q(o,i)}function P(e,r){return r.pid===e.pid||r.pid===e.endpointPid}function G(e,r){const n=Date.parse(e.startedAt);return Number.isFinite(n)?Date.now()-n<r:!1}function fe(e,r){const n=u(e);return!n||!p(n.pid)||m(e).some(i=>P(n,i))?null:G(n,r)?n:null}function B(e){const r=u(e);if(!r||typeof r.endpointPid=="number"||!p(r.pid))return;const n=m(e);if(n.some(f=>f.pid===r.pid))return;const i=Date.parse(r.startedAt);if(!Number.isFinite(i))return;const o=n.filter(f=>{const a=Date.parse(f.startedAt);return Number.isFinite(a)&&a>=i});if(o.length!==1)return;const t=o[0];V(e,{...r,endpointPid:t.pid}),s.info(d,`adopted managed bridge endpoint profile=${e.profileName} wrapper=${r.pid} pid=${t.pid}`)}function x(e){try{J(D(e),{force:!0})}catch{}}function p(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function H(e){return new Promise(r=>setTimeout(r,e))}function Me(){w.clear(),y.clear();for(const e of h.values())try{e.pid&&A(e,"SIGKILL")}catch{}h.clear()}function le(e){const r=pe(y.get(e.profileKey)??""),n=`Connector-managed DSH profile "${e.profileName}" exited before Bridge became ready`+(r?`: ${r}`:"");return Object.assign(new Error(n),{code:"profile_start_failed"})}function pe(e){const r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0)return"";let n=-1;for(let o=r.length-1;o>=0;o-=1){const t=r[o];if(t.startsWith("dsh: startup failed")||t.startsWith("dsh: plugin tree failed")||t.startsWith("Error: dsh:")){n=o;break}}return(n>=0?r.slice(n,n+6):r.slice(-4)).join(" | ").replace(/\s+/g," ").slice(0,480)}function _e(e){return U(D(e))}async function Ne(e){const r=w.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function Ke(e,r=T){let n="failed";return await b(e.identity,async()=>(n=await ue(e,r),j(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function ue(e,r){const n=e.identity,i=u(n);if(!i||!p(i.pid))return"not_managed";const o=m(n);if(o.length>0&&!o.some(t=>P(i,t)))return"not_managed";try{return s.info(d,`restarting connector-managed profile=${n.profileName} pid=${i.pid} for plugin toggle`),await $(n,i.pid),await K(e,n,k),(await N(e,r)).readiness==="ready"?"restarted":"failed"}catch(t){return s.warn(d,`plugin-toggle restart failed profile=${n.profileName}: ${t instanceof Error?t.message:String(t)}`),"failed"}}function E(e){return e.readiness==="ready"}function Be(e,r){return b(e.identity,async()=>(await r,j(e,"ready")))}function j(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{Ne as awaitDshProfileIdle,de as buildDshProfileBootArgs,De as ensureDshBridgeReady,Be as holdDshProfileInflightForTests,_e as managedProfileRecordExists,re as managedProfileSpawnEnv,Ee as prepareDshProfileBridge,Me as resetDshProfileSupervisorForTests,Ke as restartManagedProfileIfOwned};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as c}from"./profile-resolver.js";const m="approval",g="enabled",u="high",E=16384,l="deepseek-official",a=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),p="standard",_=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function h(e){return e==="full_auto"||e==="approval"?e:void 0}function N(e,r){return h(e)??h(r)??m}function v(e){return e==="enabled"||e==="disabled"?e:void 0}function b(e){return e==="high"||e==="max"?e:void 0}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??i)}]:[]}):[]}function I(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i)return[];const d=Number(o.contextWindow);return[{id:i,displayName:String(o.displayName??o.name??i),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function y(e){return e.fetched!==void 0?I(e.fetched):e.providerChanged?[]:[...e.current]}function L(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i||o.broken)return[];const d=String(o.description??"").trim();return[{id:i,displayName:String(o.displayName??o.name??i),...d?{description:d}:{}}]}):[]}const D=Object.freeze([{id:s,displayName:c(s),webApp:!0}]);function T(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??c(i)),...o.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function S(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===p)?p:r[0]?.id||p}function f(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===l)?l:r[0]?.id||l}function F(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(t=>t.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:f(i||void 0,e.liveProviders),persistFallback:!0}}function R(e,r,o){const i=String(r??"").trim(),d=e.length>0?[...e]:[];if(i&&!d.some(t=>t.id===i)){const t=o.find(n=>n.id===i);t&&d.unshift(t)}return d}function M(e){const r=e.applied,o=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",d=e.providers??[],t=e.presets??_,n=f(e.desired.providerId,d),x=S(e.desired.agentPreset,t),k=r!=null||o==="pending"||o==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,thinking_mode:v(e.desired.thinking)??g,reasoning_effort:b(e.desired.reasoningEffort)??u,agent_preset_id:x,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??a],available_presets:[...t],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...k?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_thinking_mode:r?.thinking??null,applied_reasoning_effort:r?.reasoningEffort??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:o,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function q(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function w(e){const r=e.providers??[],o=f(e.providerId,r),i=[...e.models??a],d=String(e.modelId??"").trim()||i[0]?.id||a[0].id,t=e.modeId==="full_auto"?"full_auto":m;return{agent_preset_id:S(e.agentPreset,_),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[..._],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,provider_id:o,model_id:d,mode_id:t,thinking_mode:v(e.thinking)??g,reasoning_effort:b(e.reasoningEffort)??u,available_providers:[...r],available_models:i,available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}]}}export{E as DEFAULT_DSH_MAX_TOKENS,m as DEFAULT_DSH_MODE,a as DEFAULT_DSH_MODELS,_ as DEFAULT_DSH_PRESETS,p as DEFAULT_DSH_PRESET_ID,D as DEFAULT_DSH_PROFILES,l as DEFAULT_DSH_PROVIDER_ID,u as DEFAULT_DSH_REASONING_EFFORT,g as DEFAULT_DSH_THINKING,y as adoptDshProfileModels,F as adoptLiveDshProviderSelection,w as buildDshBindingToolbarMeta,M as buildDshToolbarMeta,h as normalizeDshModeId,I as normalizeDshModels,L as normalizeDshPresets,T as normalizeDshProfiles,P as normalizeDshProviders,b as normalizeDshReasoningEffort,v as normalizeDshThinking,q as permissionModeFor,S as resolveDshAgentPreset,N as resolveDshModeId,f as resolveDshProviderId,R as retainRequestedDshProvider};
|
|
1
|
+
import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as c}from"./profile-resolver.js";const m="approval",g="enabled",u="high",E=16384,l="deepseek-official",a=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),p="standard",_=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function h(e){return e==="full_auto"||e==="approval"?e:void 0}function N(e,r){return h(e)??h(r)??m}function v(e){return e==="enabled"||e==="disabled"?e:void 0}function b(e){return e==="high"||e==="max"?e:void 0}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??i)}]:[]}):[]}function I(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i)return[];const d=Number(o.contextWindow);return[{id:i,displayName:String(o.displayName??o.name??i),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function y(e){return e.fetched!==void 0?I(e.fetched):e.providerChanged?[]:[...e.current]}function L(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i||o.broken)return[];const d=String(o.description??"").trim();return[{id:i,displayName:String(o.displayName??o.name??i),...d?{description:d}:{}}]}):[]}const D=Object.freeze([{id:s,displayName:c(s),webApp:!0}]);function T(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??c(i)),...o.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function S(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===p)?p:r[0]?.id||p}function f(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===l)?l:r[0]?.id||l}function F(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(t=>t.id===r))return{providerId:r,persistFallback:!1};if(r==="grix")return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:f(i||void 0,e.liveProviders),persistFallback:!0}}function R(e,r,o){const i=String(r??"").trim(),d=e.length>0?[...e]:[];if(i&&!d.some(t=>t.id===i)){const t=o.find(n=>n.id===i);t&&d.unshift(t)}return d}function M(e){const r=e.applied,o=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",d=e.providers??[],t=e.presets??_,n=f(e.desired.providerId,d),x=S(e.desired.agentPreset,t),k=r!=null||o==="pending"||o==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,thinking_mode:v(e.desired.thinking)??g,reasoning_effort:b(e.desired.reasoningEffort)??u,agent_preset_id:x,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??a],available_presets:[...t],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...k?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_thinking_mode:r?.thinking??null,applied_reasoning_effort:r?.reasoningEffort??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:o,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function q(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function w(e){const r=e.providers??[],o=f(e.providerId,r),i=[...e.models??a],d=String(e.modelId??"").trim()||i[0]?.id||a[0].id,t=e.modeId==="full_auto"?"full_auto":m;return{agent_preset_id:S(e.agentPreset,_),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[..._],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,provider_id:o,model_id:d,mode_id:t,thinking_mode:v(e.thinking)??g,reasoning_effort:b(e.reasoningEffort)??u,available_providers:[...r],available_models:i,available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}]}}export{E as DEFAULT_DSH_MAX_TOKENS,m as DEFAULT_DSH_MODE,a as DEFAULT_DSH_MODELS,_ as DEFAULT_DSH_PRESETS,p as DEFAULT_DSH_PRESET_ID,D as DEFAULT_DSH_PROFILES,l as DEFAULT_DSH_PROVIDER_ID,u as DEFAULT_DSH_REASONING_EFFORT,g as DEFAULT_DSH_THINKING,y as adoptDshProfileModels,F as adoptLiveDshProviderSelection,w as buildDshBindingToolbarMeta,M as buildDshToolbarMeta,h as normalizeDshModeId,I as normalizeDshModels,L as normalizeDshPresets,T as normalizeDshProfiles,P as normalizeDshProviders,b as normalizeDshReasoningEffort,v as normalizeDshThinking,q as permissionModeFor,S as resolveDshAgentPreset,N as resolveDshModeId,f as resolveDshProviderId,R as retainRequestedDshProvider};
|