grix-connector 3.29.2 → 3.30.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 +10 -0
- package/dist/adapter/deepseek-harness/bridge-installer.js +3 -3
- package/dist/adapter/deepseek-harness/grix-tool-bridge.js +1 -1
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +2 -2
- package/dist/adapter/deepseek-harness/process-runtime.js +1 -1
- package/dist/adapter/deepseek-harness/profile-resolver.js +1 -1
- package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
- package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -2
- package/dist/adapter/deepseek-harness/toolbar-state.js +1 -1
- package/dist/adapter/deepseek-harness/types.js +1 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-3.30.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/bridge.js +4 -4
- package/dist/core/persistence/session-binding-store.js +2 -2
- package/dist/default-skills/grix-admin/SKILL.md +71 -211
- package/dist/default-skills/grix-admin/references/api-contract.md +43 -214
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/openclaw-plugin/skills/grix-admin/SKILL.md +65 -202
- package/openclaw-plugin/skills/grix-admin/references/api-contract.md +35 -211
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-3.29.2.tgz +0 -0
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ Set `client_type` in your config to one of the values below. Each `client_type`
|
|
|
22
22
|
| `codex` | Codex (OpenAI) | codex | `codex` |
|
|
23
23
|
| `gemini` | Gemini (Google) | acp | `gemini` |
|
|
24
24
|
| `qwen` | Qwen (Alibaba) | acp | `qwen` |
|
|
25
|
+
| `deepseek` | DeepSeek Harness | deepseek-harness | `dsh` |
|
|
25
26
|
| `copilot` | GitHub Copilot | acp | `copilot` or `gh` |
|
|
26
27
|
| `kiro` | Kiro | acp | `kiro-cli` |
|
|
27
28
|
| `reasonix` | Reasonix | acp | `reasonix` |
|
|
@@ -35,6 +36,15 @@ Set `client_type` in your config to one of the values below. Each `client_type`
|
|
|
35
36
|
|
|
36
37
|
The ACP adapter (Agent Client Protocol over JSON-RPC) backs Gemini, Qwen, Copilot, Kiro and Reasonix. Hermes is an external agent maintained in a separate project — see [grix-hermes-python](https://github.com/askie/grix-hermes-python) for setup.
|
|
37
38
|
|
|
39
|
+
For DeepSeek Harness, install the official CLI and complete its login/profile setup before starting the connector:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install -g @deepseek-ai/dsh
|
|
43
|
+
dsh web
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Then set `client_type` to `deepseek`; the connector uses the configured default DeepSeek Harness profile.
|
|
47
|
+
|
|
38
48
|
You need to have the corresponding CLI tool installed locally before connecting an agent.
|
|
39
49
|
|
|
40
50
|
## Install
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{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 _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n
|
|
2
|
-
${W(a)}`),n<k&&await new Promise(
|
|
3
|
-
`,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:
|
|
1
|
+
import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{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 _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n[0]?.bridgeVersion??null,l=n[0]?.dshVersion??null,g=e?await A(e,this.options.dshHome):null;let c;return e?!w(g)||l!==null&&!w(l)?c="bridge_incompatible":d(this.identity.profileRoot)?i?i!==s||this.installedBridgeContentStale(r)?c="bridge_update_required":n.length===0||a!==i||this.runningBridgePredatesInstalledContent(n[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:g,runningDshVersion:l,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:s,runningBridgeVersion:a,endpointCount:n.length,compatibleDshVersions:H}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=await A(e,this.options.dshHome);if(!w(r))throw Object.assign(new Error(`DSH ${r??"unknown"} is outside the verified Bridge compatibility matrix (${H.join(", ")})`),{code:"bridge_incompatible"});const i=this.bridgeAsset();return j(this.identity,async()=>{await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const s=this.readInstalledBridgeVersion();if(s===i.version&&!this.installedBridgeContentStale(i))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(n,{recursive:!0,mode:448});const a=this.captureInstallBackup(n,s),l=o(n,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,l);try{if(s===i.version&&d(this.bridgePackageRoot())&&(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,l),await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const g=this.readInstalledBridgeVersion();if(g!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${g??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity)}catch(g){await this.rollbackInstall(e,n,a,s);try{u(l,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${D(g)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let s;for(let n=1;n<=k;n++)try{await h(e,i,this.options.dshHome);return}catch(a){s=a,T.warn(q,`dsh plugin add attempt ${n}/${k} failed for profile ${this.identity.profileName}
|
|
2
|
+
${W(a)}`),n<k&&await new Promise(l=>setTimeout(l,X))}throw s}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${N()}`);b(i,{recursive:!0,mode:448});const s=this.bridgePackageRoot(),n=d(s);n&&P(s,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&m(a,o(i,"package.json"));const g=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of g){const v=o(this.identity.profileRoot,c);d(v)&&m(v,o(i,c))}return B(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:n,hadPackageJson:l})}
|
|
3
|
+
`,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:l}}async rollbackInstall(e,r,i,s){const n=s?o(r,`grix-dsh-bridge-${s}.tgz`):null;if(n&&d(n)&&await h(e,["plugin","--profile",this.identity.profileName,"add",n],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}s?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(o(e.root,"package.json"),this.profilePackageJsonPath());for(const s of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const n=o(e.root,s);d(n)&&m(n,o(this.identity.profileRoot,s))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const s of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const n=r[s];n&&typeof n=="object"&&!Array.isArray(n)&&p in n&&(delete n[p],i=!0)}i&&B(e,`${JSON.stringify(r,null,2)}
|
|
4
4
|
`,{mode:384})}catch{}}discardInstallBackup(e){try{u(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(f(e,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=f(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){B(this.installedIntegrityPath(),`${e}
|
|
5
5
|
`,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=y(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?r>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E(I(this.options.tarballPath)):x()}}function de(t){if(t.readiness==="ready")return null;const e=t.identity.profileName,r=`dsh --profile ${e}`,i=t.endpointCount>0&&t.runningBridgeVersion&&t.installedBridgeVersion&&t.runningBridgeVersion!==t.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${t.runningBridgeVersion}, but ${t.installedBridgeVersion} is installed on disk. dsh does not hot-load plugin upgrades: stop the running profile process, then start it again with: ${r}`:`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. dsh does not hot-load plugins: stop the running profile process, then start it again with: ${r}`,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: ${r}`,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 ${t.installedBridgeVersion??"none"}, expected ${t.bundledBridgeVersion}${t.installedBridgeVersion===t.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:i,bridge_incompatible:`DSH / Grix Bridge versions are incompatible for profile "${e}" (dsh=${t.dshVersion??"unknown"}, running=${t.runningDshVersion??"none"}, bridge=${t.runningBridgeVersion??t.installedBridgeVersion??"none"}). Supported DSH: ${t.compatibleDshVersions.join(", ")}.`};return Object.assign(new Error(s[t.readiness]),{code:t.readiness})}function le(){return x().tarball}function x(){const t=[$(new URL("../../assets/dsh-bridge/",import.meta.url)),$(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!t)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(f(o(t,"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 r=E(o(t,e.tarball),e.bridgeVersion);if(Number(e.size)!==y(r.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!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function E(t,e){if(!d(t)||!y(t).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${t}`),{code:"bridge_asset_missing"});if(y(t).size>U)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(t)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${O("sha512").update(f(t)).digest("base64")}`;return{tarball:t,version:r,integrity:i}}async function j(t,e){const r=J(t);b(r,{recursive:!0,mode:448});const i=o(r,"install.lock");let s=V(i);if(s===null){let n=0;try{n=Number(f(i,"utf8").trim())}catch{}let a=!1;try{a=n===0&&Date.now()-y(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(n)&&n>0&&!Y(n)){try{u(i,{force:!0})}catch{}s=V(i)}}if(s===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${t.profileName}`),{code:"bridge_install_busy"});try{return B(s,`${process.pid}
|
|
6
6
|
`,"utf8"),await e()}finally{G(s);try{u(i,{force:!0})}catch{}}}function V(t){try{return C(t,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${D(e)}`),{code:"bridge_install_failed"})}}function Y(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function A(t,e){try{return(await h(t,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function h(t,e,r){try{return(await z(t,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(i){const s=i&&typeof i=="object"?i:{};throw Object.assign(new Error(D(i)),{code:"dsh_command_failed",stderr:typeof s.stderr=="string"?S(s.stderr):void 0})}}function S(t){return t.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function D(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function W(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).slice(0,8*1024)}export{ae as DshBridgeInstaller,le as defaultBridgeTarball,de as errorForDshBridgeReadiness};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{ALL_TOOLS as d}from"../../core/mcp/tools.js";const f=Object.freeze(d.map(t=>({name:t.name,description:t.description,parameters:t.inputSchema}))),p=new Set(f.map(t=>t.name));function m(t){return p.has(t)}function S(t){const e=n(t),r=n(e.context),s=[n(n(e.agent).session).id,n(e.session).id,n(e.scope).sessionId,n(n(e.scope).session).id,n(n(r.agent).session).id,n(r.session).id];for(const i of s){const o=c(i);if(o)return o}}function c(t){if(t==null)return;if(typeof t=="object"){const r=n(t),s=c(r.id??r.value);if(s)return s;const i=t.toString;if(typeof i=="function"&&i!==Object.prototype.toString){const o=String(t).trim();return o&&o!=="[object Object]"?o:void 0}return}return String(t).trim()||void 0}function n(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}export{f as DSH_BRIDGED_GRIX_TOOLS,m as isDshBridgedGrixTool,S as resolveDshToolSessionId};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new Ye(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length!==1)throw Object.assign(new Error(n.length===0?`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${p.identity.profileName}"`),{code:n.length===0?"bridge_missing":"profile_instance_ambiguous"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&m.debug(f,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=K(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
|
|
1
|
+
import{createHash as C,randomUUID as D}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as re,existsSync as L,mkdirSync as ae}from"node:fs";import{dirname as de,join as P,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as le}from"../../default-skills/index.js";import{resolveCliPath as he}from"../../core/util/cli-probe.js";import{DshWireCapture as ce}from"./audit-boundary.js";import{dsmlToolCallKey as ue,projectVisibleDsmlText as pe}from"./dsml-text-filter.js";import{mapDshSessionEvent as ge,unwrapDshSessionEvent as fe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as me}from"./process-runtime.js";import{DshProfileRuntime as ve}from"./profile-runtime.js";import{createDshWebProfile as be}from"./profile-catalog.js";import{listDshPlugins as M,resolveDshPlugin as _e,updateDshPluginIds as Se}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as Ie}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as ke,discoverDshBridgeEndpoints as Te,listDshProfiles as Pe,resolveDshConnectorProfileDataDir as we,resolveDshHome as ye,resolveDshSelectedProfileName as Ee}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as xe,prepareDshProfileBridge as Ce}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as De,isRetryableDshRuntimeError as Me}from"./runtime-ensure.js";import{runDshProtocolProbe as Re}from"./probe.js";import{buildDshSystemPrompt as Ae,describeDshSystemPrompt as He}from"./system-prompt.js";import{DshActionCoordinator as $e}from"./toolbar-actions.js";import{adoptDshProfileModels as Be,adoptLiveDshProviderSelection as Fe,buildDshToolbarMeta as qe,DEFAULT_DSH_MAX_TOKENS as Ne,DEFAULT_DSH_MODELS as je,DEFAULT_DSH_PRESETS as Le,DEFAULT_DSH_PROVIDER_ID as H,DEFAULT_DSH_REASONING_EFFORT as Ue,DEFAULT_DSH_THINKING as Oe,normalizeDshPresets as Ve,normalizeDshProviders as We,normalizeDshReasoningEffort as z,normalizeDshThinking as Q,permissionModeFor as K,resolveDshAgentPreset as X,resolveDshModeId as Ge,resolveDshProviderId as ze,retainRequestedDshProvider as Qe}from"./toolbar-state.js";import{modelsForDshProvider as Ke,resolveDshCatalogForToolbar as Xe,writeDshCatalogCache as Je}from"./catalog-cache.js";import{TurnCorrelator as Ye}from"./turn-correlator.js";import{effectiveDshReasoningEffort as Ze}from"./types.js";import{getDshSessionUsageStore as et,normalizeDshUsage as J}from"./usage.js";import{toolCallToInvoke as tt}from"../../core/mcp/tools.js";import{isEventTool as it}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as st}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as Y}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",Z=20*6e4,ee=6e4,te=9e4,ie=30*6e4;class ot extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Gt extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=Z;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 $e;activeWireStart=0;activeUsage=se();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=je;providers=[];presets=[...Le];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new ot(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_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await he(i),n=!!s;let d={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Re({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const r=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await xe({installer:r,autoStart:!1}),c=A(p);if(c)throw c;const o=Te(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"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(r){d={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:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Ye(t),this.activeUsage=se(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),n={};s?.modelId||(n.modelId=i.modelId),!s?.providerId&&i.providerId&&(n.providerId=i.providerId),s?.thinking||(n.thinking=i.thinking),s?.reasoningEffort||(n.reasoningEffort=i.reasoningEffort),Object.keys(n).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,n),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,r=Ae({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=He(r);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),o=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let a=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,o):void 0;c==="profile_bridge"&&!a&&(a={profileName:o,sessionId:dt(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,a),await this.options.bindingStore.flush()),this.runtimeSessionId=a?.sessionId??at(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(o),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=Ie({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:o,pluginIds:i.pluginIds??[],overlayId:C("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),ne=P(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ce(ne);const _=c==="embedded_jsonrpc"?new me({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:P(u,"sessions"),env:this.config.env,systemPrompt:r,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new ve({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:o,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:a?.sessionCreated===!0,lastAckCursor:a?.eventCursor??0,systemPrompt:r,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?Y(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!a||g<=a.eventCursor||(a={...a,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,a))}});this.runtime=_,this.bridgeAckCursor=a?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=We(g.providers),I=Fe({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Qe(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const E=I.providerId,F=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,q=!!this.catalogProviderId&&!!E&&E!==this.catalogProviderId;this.models=Be({current:this.models,fetched:F,providerChanged:q}),(F!==void 0||q)&&(this.catalogProviderId=E||this.catalogProviderId);const x=String(g.selectedModel??"");x&&x!==i.modelId&&(i={...i,modelId:x});const N=Ve(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,T={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(T.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(T.modelId=i.modelId),(T.providerId||T.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,T)??i.revision,await this.options.bindingStore.flush(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId,thinking:i.thinking,reasoningEffort:Ze(i)},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&a&&!a.sessionCreated&&(a={...a,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,a),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Me(s)||t===G)throw i;f.warn(m,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await rt(De(t))}throw e}onNotification(e,t){const i=nt(t);if(e==="session.event"){const s=fe(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 d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},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=ge(e);if(t.kind==="unknown"&&!ut(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=V(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?lt(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=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=pe(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let r="";l.startsWith(i.sentText)?r=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(r=l),!(!r&&!e)&&(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=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=ue(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=J(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=J(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:n,remainingTokens:Math.max(0,n-d),usedPercentage:d/n*100,remainingPercentage:Math.max(0,100-d/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=e,n=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(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 d=s==="failed"&&!!n?.trim();d&&(i.text+=`
|
|
2
2
|
|
|
3
|
-
Error: ${o}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const l=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;l&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(n,r,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,n,r,u),this.emit("eventDone",i.inbound.event_id),l?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,o,d)},async n=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(n,i.inbound.content)}`:o)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??M());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(o=>{const d=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);d.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:d})})):"unavailable"}async invokeGrixTool(e,t,i){if(!Je(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=Xe(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=Te(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=T(e,"skills"),i=ae(t);i.length>0&&m.info(f,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){m.warn(f,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(){this.intentionalRuntimeStop||this.stopped||(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active&&this.finishActive("failed","Harness runtime exited; prompt was not replayed"),this.emit("exit",1))}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const n=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),r=this.pendingApprovals.get(n);if(!r)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(r.timer),this.pendingApprovals.delete(n);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return r.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:n,decision:u?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(n){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(n)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const n=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),r=e.action_type==="dsh_install_bridge"?await n.install():await n.status();return this.runtimeReadiness=r.readiness,this.settingsErrorCode=r.readiness==="ready"?null:r.readiness,this.pushToolbarMeta(),{status:"ok",result:ot(r)}}catch(n){const r=String(n?.code??"bridge_install_failed");return this.runtimeReadiness=r,this.settingsErrorCode=r,this.pushToolbarMeta(),{status:"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);const o={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(o){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(o,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(n){const r=String(n?.code??"resource_query_failed");return{status:r==="capability_unavailable"?"unsupported":"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let n;try{n=Se(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==n?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(n,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(n):await fe({profileName:n,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),v=u.identity?.profileName??n;return this.persistSelectedProfile(v)?(await this.flushSelectedProfile(),this.finishProfileSelection(v,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===n)?this.persistSelectedProfile(n)?(await this.flushSelectedProfile(),this.finishProfileSelection(n,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const r=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(v=>v.id===r))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===r?{status:"ok",result:this.presetActionResult(r,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===r?(this.options.bindingStore.setDshAgentPreset(i,r),await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):this.options.bindingStore.setDshAgentPreset(i,r)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const n=String(t.provider_id??"").trim();if(!this.providers.some(r=>r.id===n))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:n},n!==l.providerId&&(this.models=We(this.options.dataRoot,n),this.catalogProviderId=n,this.models.some(r=>r.id===l.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const n=String(t.model_id??"").trim();if(!this.models.some(r=>r.id===n))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:n}}else{const n=String(t.mode_id??"").trim();if(n!=="approval"&&n!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:n}}if((a.providerId===void 0||a.providerId===l.providerId)&&(a.modelId===void 0||a.modelId===l.modelId)&&(a.modeId===void 0||a.modeId===l.modeId)&&this.applied?.appliedRevision===l.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,l.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??l.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}}catch(n){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(n)),errorCode:"settings_apply_failed",errorMsg:this.redactError(n)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new R({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(m.info(f,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),o=A(s);if(o)throw o;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=A(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await xe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return ke({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}currentPlugins(){try{return E(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const n=E(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(n,!1)}}const o=String(t.name??t.plugin_name??"").trim(),d=this.options.bindingStore.getDshEnabledPlugins(i);let l=o;try{const{plugin:n}=ve({...s,name:o});l=n.name}catch(n){const r=String(n?.code??"");if(e!=="dsh_disable_plugin"||r!=="plugin_not_found"||!d.includes(o))throw n}const a=be(d,l,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,a.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const c=E({...s,enabledPluginIds:a.pluginIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"skipped")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"restarted")}}catch(o){return{status:"failed",errorCode:String(o?.code??"plugin_action_failed"),errorMsg:this.redactError(o)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),o=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=we({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return Pe(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!L(t)&&L(i)&&(ne(re(t),{recursive:!0,mode:448}),oe(i,t)),Ke(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,o,d){const l=this.resolveDesiredSettings(),a=l.revision||i,p={provider_id:l.providerId,model_id:l.modelId,mode_id:l.modeId,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(p.sandbox_mode=z(l.modeId),p.approval_policy=l.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:z(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:a,settings_revision:a,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...d?{error:d}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=Ge({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ze({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){m.warn(f,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=X(this.options.provider??{});if(e){this.providers.some(o=>o.id===b)||(this.providers=[{id:b,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===H||s===b)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:b});return}this.providers=this.providers.filter(t=>t.id!==b)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,o=this.providers.some(p=>p.id===b)?b:void 0,d=Oe(s||o,this.providers),l=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=Q(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:d,modelId:l,modeId:Ue(e?.dshModeId,i?.dshModeId),agentPreset:a,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),maxTokens:t?.maxTokens??this.options.maxTokens??qe,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Be({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??J,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??Y,t=Number.isFinite(e)&&e>0?e:Y;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??Z;return Number.isFinite(e)&&e>0?e:Z}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??ee;return Number.isFinite(e)&&e>0?e:ee}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){m.info(f,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),o=t.lastRuntimeActivityAt??t.startedAt,d=Math.max(0,s-o);if(d<this.livenessFreshMs())return t.livenessExtendStartAt=s,m.info(f,`Liveness check: recent DSH activity for ${e} (quietMs=${d}), extending`),!0;const l=t.livenessExtendStartAt??o;t.livenessExtendStartAt=l;const a=s-l;return a>this.livenessMaxExtendMs()?(m.warn(f,`Liveness extension budget exhausted for ${e} (quietMs=${d}, extendMs=${a}), allowing close`),!1):(m.info(f,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${d}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&!s.isConnected()&&await s.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(m.error(f,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function Ze(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function et(h){return new Promise(e=>setTimeout(e,h))}function tt(h,e){return`grix-${D("sha256").update(h).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function it(h){return`grix-${D("sha256").update(h).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function te(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function ie(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function st(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&ie(h)==="tool-call-delta"}function ot(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required",compatibleDshVersions:h.compatibleDshVersions}}const nt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function rt(h){const e=ie(h);return nt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{Ft as DshJsonRpcAdapter};
|
|
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 l=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;l&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(o,a,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,a,u),this.emit("eventDone",i.inbound.event_id),l?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,n,d)},async o=>{await this.flushPendingFinalBridgeAck(!1),c(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??D());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const d=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);d.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:d})})):"unavailable"}async invokeGrixTool(e,t,i){if(!st(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(it(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});return this.callbacks.eventToolInvoke(e,t)}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=tt(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=ye(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=P(e,"skills"),i=le(t);i.length>0&&f.info(m,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){f.warn(m,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(){this.intentionalRuntimeStop||this.stopped||(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active&&this.finishActive("failed","Harness runtime exited; prompt was not replayed"),this.emit("exit",1))}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),a=this.pendingApprovals.get(o);if(!a)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(a.timer),this.pendingApprovals.delete(o);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return a.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:u?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(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 R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),a=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=a.readiness,this.settingsErrorCode=a.readiness==="ready"?null:a.readiness,this.pushToolbarMeta(),{status:"ok",result:ht(a)}}catch(o){const a=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=a,this.settingsErrorCode=a,this.pushToolbarMeta(),{status:"failed",errorCode:a,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);const n={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(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 a=String(o?.code??"resource_query_failed");return{status:a==="capability_unavailable"?"unsupported":"failed",errorCode:a,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=ke(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==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 u=this.options.createDshProfile?await this.options.createDshProfile(o):await be({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),v=u.identity?.profileName??o;return this.persistSelectedProfile(v)?(await this.flushSelectedProfile(),this.finishProfileSelection(v,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===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 a=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(v=>v.id===a))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=X(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===a?{status:"ok",result:this.presetActionResult(a,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===a?(this.options.bindingStore.setDshAgentPreset(i,a),await this.persistGlobalToolbarDefaults({dshAgentPreset:a}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(a,!1)}):this.options.bindingStore.setDshAgentPreset(i,a)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:a}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(a,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(a=>a.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==l.providerId&&(this.models=Ke(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(a=>a.id===l.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(a=>a.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=z(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===l.providerId)&&(r.modelId===void 0||r.modelId===l.modelId)&&(r.modeId===void 0||r.modeId===l.modeId)&&(r.thinking===void 0||r.thinking===l.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===l.reasoningEffort)&&this.applied?.appliedRevision===l.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,l.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,r)??l.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,c,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,c,"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 R({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(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=A(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=A(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await Ce({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),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 Pe({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}currentPlugins(){try{return M(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),d=this.options.bindingStore.getDshEnabledPlugins(i);let l=n;try{const{plugin:o}=_e({...s,name:n});l=o.name}catch(o){const a=String(o?.code??"");if(e!=="dsh_disable_plugin"||a!=="plugin_not_found"||!d.includes(n))throw o}const r=Se(d,l,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const c=M({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"skipped")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_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}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=Ee({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 we(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=P(this.profileDataDir(e),"session-usage.json"),i=P(this.options.dataRoot,"session-usage.json");return!L(t)&&L(i)&&(ae(de(t),{recursive:!0,mode:448}),re(i,t)),et(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,d){const l=this.resolveDesiredSettings(),r=l.revision||i,p={provider_id:l.providerId,model_id:l.modelId,mode_id:l.modeId,thinking_mode:l.thinking,reasoning_effort:l.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=K(l.modeId),p.approval_policy=l.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:K(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,...d?{error:d}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=Xe({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 Je({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=Y(this.options.provider??{});if(e){this.providers.some(n=>n.id===b)||(this.providers=[{id:b,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===H||s===b)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:b});return}this.providers=this.providers.filter(t=>t.id!==b)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(p=>p.id===b)?b:void 0,d=ze(s||n,this.providers),l=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",r=X(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:d,modelId:l,modeId:Ge(e?.dshModeId,i?.dshModeId),thinking:Q(t?.thinking)??Oe,reasoningEffort:z(t?.reasoningEffort)??Ue,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),maxTokens:t?.maxTokens??this.options.maxTokens??Ne,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,qe({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??Z,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??ee,t=Number.isFinite(e)&&e>0?e:ee;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??te;return Number.isFinite(e)&&e>0?e:te}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??ie;return Number.isFinite(e)&&e>0?e:ie}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,d=Math.max(0,s-n);if(d<this.livenessFreshMs())return t.livenessExtendStartAt=s,f.info(m,`Liveness check: recent DSH activity for ${e} (quietMs=${d}), extending`),!0;const l=t.livenessExtendStartAt??n;t.livenessExtendStartAt=l;const r=s-l;return r>this.livenessMaxExtendMs()?(f.warn(m,`Liveness extension budget exhausted for ${e} (quietMs=${d}, extendMs=${r}), allowing close`),!1):(f.info(m,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${d}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&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 nt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function rt(h){return new Promise(e=>setTimeout(e,h))}function at(h,e){return`grix-${C("sha256").update(h).digest("hex").slice(0,12)}-${e}-${D().slice(0,8)}`}function dt(h){return`grix-${C("sha256").update(h).digest("hex").slice(0,16)}-${D().slice(0,8)}`}function se(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function oe(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function lt(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&oe(h)==="tool-call-delta"}function ht(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required",compatibleDshVersions:h.compatibleDshVersions}}const ct=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function ut(h){const e=oe(h);return ct.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{Gt as DshJsonRpcAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{chmodSync as
|
|
1
|
+
import{chmodSync as m,existsSync as u,mkdirSync as E,realpathSync as f,statSync as p}from"node:fs";import{isAbsolute as l,relative as _,resolve as d}from"node:path";import{log as R}from"../../core/log/index.js";import{hasChildProcesses as D,killProcessGroup as w,resolveCommandPath as I,spawnCommand as v}from"../../core/runtime/spawn.js";import{DshJsonRpcClient as y}from"./jsonrpc-client.js";import{effectiveDshReasoningEffort as O}from"./types.js";import{permissionModeFor as x}from"./toolbar-state.js";const C="deepseek-harness-runtime",L="deepseek-harness-sdk-runtime",A=new Set(["0.0.1"]),H=15e3,k=["PATH","SystemRoot","COMSPEC","PATHEXT","WINDIR","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP","HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY","https_proxy","http_proxy","all_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS"],b=["DEEPSEEK_API_KEY","DEEPSEEK_BASE_URL"];function g(i,t){const s={};for(const e of k){const o=t?.[e]??i[e];o!==void 0&&(s[e]=o)}for(const e of b){const o=t?.[e];o!==void 0&&(s[e]=o)}return s}class X{options;process=null;client=null;stderrTail="";constructor(t){this.options=t}async start(){this.validatePaths(),E(this.options.home,{recursive:!0,mode:448}),E(this.options.sessionRoot,{recursive:!0,mode:448});try{m(this.options.home,448),m(this.options.sessionRoot,448)}catch{}const t={...g(process.env,this.options.env),HOME:this.options.home,DSH_CORDIS_CONFIG:this.options.cordisPath,DSH_HOME:this.options.home,DSH_CWD:this.options.cwd,DSH_SESSION_ROOT:this.options.sessionRoot,DSH_SYSTEM_PROMPT:this.options.systemPrompt,DSH_PERMISSION_MODE:x(this.options.settings.modeId),DSH_TELEMETRY_DISABLED:"1"},s=I(this.options.command,t.PATH),e=v(s,[this.options.cordisPath,...this.options.args??[]],{cwd:this.options.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});if(this.process=e.process,!this.process.stdout||!this.process.stdin)throw new Error("Harness stdio unavailable");this.client=new y(this.process.stdout,this.process.stdin,{maxLineBytes:this.options.maxLineBytes,capture:this.options.capture}),this.process.stderr?.setEncoding("utf8"),this.process.stderr?.on("data",h=>{this.stderrTail=M(`${this.stderrTail}${String(h)}`,t.DEEPSEEK_API_KEY).slice(-8192)});const o=new Promise((h,P)=>this.process?.once("error",P)),c=new AbortController,n=this.client.initialize({cwd:this.options.cwd,provider:"deepseek-official",model:this.options.settings.modelId,reasoningEffort:O(this.options.settings),maxTokens:this.options.settings.maxTokens},c.signal),a=S(this.options.initializeTimeoutMs??H,"Harness initialize timed out",()=>c.abort()),r=await Promise.race([n,o,a.promise]).finally(a.cancel);if(r.serverInfo?.name!==L||!A.has(r.serverInfo?.version))throw await this.terminate(),Object.assign(new Error(`incompatible Harness server ${T(r.serverInfo?.name)}@${T(r.serverInfo?.version)}`),{code:"protocol_incompatible"});return R.info(C,`initialized server=${r.serverInfo.name}@${r.serverInfo.version} env_keys=${Object.keys(t).filter(h=>h.startsWith("DSH_")||h.startsWith("DEEPSEEK_")).join(",")}`),r}async shutdown(){if(!this.process)return;const s=this.waitForExit(1e3).then(()=>!0,()=>!1),e=S(2e3,"Harness shutdown timed out");try{await Promise.race([this.client?.shutdown(),e.promise])}catch{}finally{e.cancel()}await s||await this.terminate(),this.client?.close(),this.client=null,this.process=null}async terminate(){const t=this.process;if(!t)return;const s=this.waitForExit(3e3).then(()=>!0,()=>!1);w(t,"SIGTERM"),await s||w(t,"SIGKILL"),this.client?.close(new Error("Harness runtime terminated")),this.client=null,this.process=null}async cancel(t){await this.terminate()}isConnected(){return!!this.process&&this.process.exitCode===null&&!!this.client}onExit(t){const s=this.process;return s?(s.once("exit",t),()=>s.removeListener("exit",t)):()=>{}}async hasBackgroundWork(){return this.process?.pid?D(this.process.pid,[this.process.pid]):!1}validatePaths(){const t=f(d(this.options.cwd));if(!u(t)||!p(t).isDirectory())throw new Error("bound workspace does not exist or is not a directory");if(!l(this.options.cordisPath)||!u(this.options.cordisPath)||!p(this.options.cordisPath).isFile())throw new Error("Cordis path must be an existing absolute file");const s=_(t,f(d(this.options.cordisPath)));if(s===""||!s.startsWith("..")&&!l(s))throw new Error("Cordis deployment file must be outside the user workspace");if((p(this.options.cordisPath).mode&18)!==0)throw new Error("Cordis deployment file must not be group/world writable");const e=_(t,d(this.options.sessionRoot));if(e===""||!e.startsWith("..")&&!l(e))throw new Error("DSH_SESSION_ROOT must be outside the workspace")}waitForExit(t){const s=this.process;return!s||s.exitCode!==null?Promise.resolve():new Promise((e,o)=>{const c=setTimeout(()=>{a(),o(new Error("process exit timeout"))},t),n=()=>{a(),e()},a=()=>{clearTimeout(c),s.removeListener("exit",n)};s.once("exit",n)})}}function S(i,t,s){let e;return{promise:new Promise((c,n)=>{e=setTimeout(()=>{s?.(),n(Object.assign(new Error(t),{code:"runtime_timeout"}))},i),e.unref?.()}),cancel:()=>{e&&clearTimeout(e)}}}function M(i,t){let s=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]");return t&&(s=s.split(t).join("[REDACTED]")),s}function T(i){return String(i??"unknown").replace(/[\u0000-\u001f\u007f]/g,"").slice(0,128)||"unknown"}export{X as DshProcessRuntime,g as sanitizeDshRuntimeEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as
|
|
1
|
+
import{createHash as H}from"node:crypto";import{existsSync as p,readFileSync as a,readdirSync as y,realpathSync as g,statSync as d}from"node:fs";import{homedir as P}from"node:os";import{basename as h,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as E}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(P(),".dsh");return l(t)}const s="web",D="headless";function m(e){return O(String(e??"").trim())}function A(e){const r=m(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function J(e,r){return i(l(e),"profiles",m(r))}function C(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return A(t)}catch{continue}}return s}function S(e){return e===s?"Web":e}function R(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:S(s),webApp:!0});const n=i(r,"profiles");if(!p(n)||!d(n).isDirectory())return[...t.values()];for(const o of y(n).sort()){if(o===D||o===s||o==="node_modules")continue;try{m(o)}catch{continue}const f=i(n,o);try{if(!d(f).isDirectory()||!JSON.parse(a(i(f,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:R(f,o)})}return[...t.values()]}function w(e){const r=u(e.dshHome,e.env),t=m(e.profileName?.trim()||s),n=l(r,"profiles",t),o=p(n)?g(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:N(o)}}function N(e){return H("sha256").update(l(e)).digest("hex")}function I(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function _(e){const r=I(e);if(!p(r)||!d(r).isDirectory())return[];const t=[];for(const n of y(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!F(o)||o.profileKey!==e.profileKey||!M(o.pid)||!p(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t.sort((n,o)=>b(o)-b(n)||o.instanceId.localeCompare(n.instanceId))}function W(e){const r=_(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});return r[0]}function b(e){const r=Date.parse(e.startedAt);return Number.isFinite(r)?r:0}function T(e){let r=c(E(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(p(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}h(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return w({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=g(e),t=h(r),n=c(r);return{dshHome:h(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:N(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function F(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,A as assertSelectableDshProfileName,I as bridgeDiscoveryDirectory,_ as discoverDshBridgeEndpoints,S as dshProfileDisplayName,T as inferProfileIdentityFromModule,V as listDshProfiles,m as parseDshProfileName,R as profileHasWebApp,N as profileKeyFor,J as resolveDshConnectorProfileDataDir,u as resolveDshHome,w as resolveDshProfileIdentity,C as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createHmac as H,randomUUID as
|
|
1
|
+
import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as $}from"node:fs";import{createConnection as z}from"node:net";import{isCompatibleDshVersion as C}from"./bridge-session-reliability.js";import{isDshBridgedGrixTool as G}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as q,GRIX_DSH_PROTOCOL_MAX as M,GRIX_DSH_PROTOCOL_MIN as B}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as U,selectDshBridgeEndpoint as V}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as L,normalizeDshPresets as F,normalizeDshProviders as K,resolveDshAgentPreset as X,resolveDshProviderId as J}from"./toolbar-state.js";import{effectiveDshReasoningEffort as W}from"./types.js";const Z=T(),N=5e3,E=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,l)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:l});return}this.deliverNotification(o,l)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},f(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},f(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},f(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class 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=V(t);if(e.protocolMax<B||e.protocolMin>M)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});if(!C(e.dshVersion))throw Object.assign(new Error(`DSH Profile ${e.dshVersion||"unknown"} is outside the verified Bridge compatibility matrix`),{code:"bridge_incompatible"});const c=$(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await tt(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new q(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,r)=>{const n=r&&typeof r=="object"?r:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const p=String(n.tool??"").trim(),_=n.args&&typeof n.args=="object"?n.args:{};if(!p)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!G(p))throw Object.assign(new Error(`grix tool "${p}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(p,_,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const l=T(),g=H("sha256",c).update(`${l}
|
|
2
2
|
${t.profileKey}
|
|
3
|
-
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),a=await o.call("bridge/initialize",{protocol:{min:B,max:M},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:
|
|
3
|
+
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),a=await o.call("bridge/initialize",{protocol:{min:B,max:M},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:l,proof:g}},I),R=a.profile&&typeof a.profile=="object"?a.profile:{},b=String(R.dshVersion??"");if(!C(b)||b!==e.dshVersion)throw o.close(new Error("DSH Profile version changed or is outside the verified Bridge compatibility matrix")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${b||"unknown"}`),{code:"bridge_incompatible"});const d=String(this.options.settings.providerId??"").trim(),w=this.options.managedProvider,y=!!w&&(!d||d===w.id);let m=[],P=!1;const k=y?0:this.options.catalogRefreshAttempts??4;for(let i=0;i<=k;i++){try{const r=AbortSignal.timeout(this.options.catalogTimeoutMs??E),n=await o.call("profile/listProviders",{},r),p=K(n.providers);if(P=!0,p.length>0&&(m=p),!d||m.some(_=>_.id===d)||y)break}catch{break}i<k&&await new Promise(r=>setTimeout(r,150))}const v=y&&w?w.id:P&&d&&!m.some(i=>i.id===d)?d:J(this.options.settings.providerId,m);let u;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??E),r=await o.call("profile/listModels",{provider:v},i);u=Array.isArray(r.models)?r.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const x=(u??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(u?.[0]?.id??this.options.settings.modelId);let S=[...L];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??E),r=await o.call("profile/listPresets",{},i),n=F(r.presets);n.length>0&&(S=n)}catch{}const A=X(this.options.settings.agentPreset,S);this.client=new 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:v,model:x,reasoningEffort:W(this.options.settings),maxTokens:this.options.settings.maxTokens,modeId:this.options.settings.modeId,agentPreset:A,pluginIds:this.options.settings.pluginIds??[],...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0,...this.options.managedProvider&&v===this.options.managedProvider.id?{managedProvider:this.options.managedProvider}:{}},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const D=a.serverInfo&&typeof a.serverInfo=="object"?a.serverInfo:{};return{serverInfo:{name:String(D.name??"grix-dsh-profile-bridge"),version:String(D.version??"unknown")},profile:a.profile,capabilities:a.capabilities,...u!==void 0?{models:u}:{},selectedModel:x,providers:m,selectedProvider:v,presets:S,selectedPreset:A}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function f(h,t){return h??AbortSignal.timeout(t)}function tt(h,t){return new Promise((e,c)=>{const s=z(h),o=setTimeout(()=>{l(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const l=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{l(),s.setNoDelay(!0),e(s)},I=a=>{l(),c(Object.assign(a,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{E 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}),
|
|
1
|
+
import{createWriteStream as k,existsSync as A,mkdirSync as K,readFileSync as C,renameSync as F,rmSync as H,writeFileSync as j}from"node:fs";import{join as R}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as G}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as y,profileHasWebApp as U}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",O=45e3,J=500;function W(e){return{...process.env,DSH_HOME:e}}const m=new Map,p=new Map;function $(e,r,i="coalesce"){const t=m.get(e.profileKey);if(t&&i==="coalesce")return t.promise;const o=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{m.get(e.profileKey)?.promise===o&&m.delete(e.profileKey)});return m.set(e.profileKey,{promise:o}),o}async function ce(e){return $(e.installer.identity,()=>V(e))}async function fe(e){return $(e.installer.identity,()=>Y(e))}async function Y(e){const r=e.autoInstall!==!1;let i=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(i.readiness)&&(i=await e.installer.install()),i.readiness==="ready"&&!e.reloadManaged?i:V(e)}async function V(e){const r=e.installer,i=e.autoStart!==!1,t=e.readyTimeoutMs??O;let n=await r.status();if(e.reloadManaged&&(n=await z(r,n,t),n.readiness==="ready")||n.readiness==="ready")return n;if(!i){const l=I(n);if(l)throw l;return n}if(n.readiness==="profile_restart_required"&&n.endpointCount===0)await P(r,n.identity),n=await S(g,r,t),g(n)||await N(n.identity,"bridge endpoint did not appear");else if(n.readiness==="profile_restart_required"&&n.endpointCount>0&&n.runningBridgeVersion&&n.installedBridgeVersion){const l=y(n.identity),a=u(n.identity),w=a&&l.find(s=>s.pid===a.pid),b=n.runningBridgeVersion!==n.installedBridgeVersion?"bridge upgrade":"bridge content refresh";w&&a&&f(a.pid)?(d.info(c,`restarting connector-managed profile=${n.identity.profileName} pid=${a.pid} for ${b}`),await h(n.identity,a.pid)):d.info(c,`starting connector-managed profile=${n.identity.profileName} for ${b}; external profile processes are left untouched`),await P(r,n.identity),n=await S(g,r,t),g(n)||await N(n.identity,"bridge endpoint did not appear after upgrade restart")}if(n.readiness==="ready")return Q(n),n;const o=I(n);if(o)throw o;return n}async function z(e,r,i){const t=r.identity,n=u(t);if(!n||!f(n.pid))return r;const o=y(t);if(!o.some(w=>w.pid===n.pid)&&o.length>0)return r;d.info(c,`reloading connector-managed profile=${t.profileName} pid=${n.pid} after settings write`),await h(t,n.pid),await P(e,t);const a=await S(g,e,i);return g(a)||await N(t,"bridge endpoint did not appear after settings reload"),a}function Q(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function P(e,r){const i=u(r);if(i&&f(i.pid)){if(y(r).some(x=>x.pid===i.pid)){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await h(r,i.pid)}else i&&D(r);const t=await G(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const n=X(r),o=M(r);K(o,{recursive:!0,mode:448});const l=R(o,"managed-profile.log"),a=k(l,{flags:"a",mode:384}),w=W(r.dshHome),s=q(t,n,{cwd:r.profileRoot,env:w,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!s.pid)throw a.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});s.stdout?.pipe(a,{end:!1}),s.stderr?.pipe(a,{end:!1}),s.once("exit",(E,v)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${s.pid} code=${E} signal=${v}`),p.get(r.profileKey)===s&&p.delete(r.profileKey),u(r)?.pid===s.pid&&D(r);try{a.end()}catch{}}),s.unref(),p.set(r.profileKey,s),Z(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:s.pid,startedAt:new Date().toISOString(),command:t,args:n}),d.info(c,`started connector-managed profile=${r.profileName} pid=${s.pid} args=${n.join(" ")}`)}async function N(e,r){const i=u(e);i&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${i.pid} reason=${r}`),await h(e,i.pid))}async function h(e,r){const i=p.get(e.profileKey);if(i?.pid===r){try{B(i,"SIGTERM")}catch{}p.delete(e.profileKey)}else if(f(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&f(r);)await T(100);if(f(r))try{process.kill(r,"SIGKILL")}catch{}D(e)}function X(e){return U(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function S(e,r,i){const t=Date.now()+i;let n=await r.status();for(;Date.now()<t;){if(e(n))return n;const o=u(r.identity);if(o&&!f(o.pid))throw D(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await T(J),n=await r.status()}return n}function _(e){return R(M(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(C(_(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function Z(e,r){const i=M(e);K(i,{recursive:!0,mode:448});const t=_(e),n=`${t}.${process.pid}.tmp`;j(n,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`,{mode:384}),F(n,t)}function D(e){try{H(_(e),{force:!0})}catch{}}function f(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function T(e){return new Promise(r=>setTimeout(r,e))}function le(){m.clear();for(const e of p.values())try{e.pid&&B(e,"SIGKILL")}catch{}p.clear()}function pe(e){return A(_(e))}async function ue(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ge(e,r=O){let i="failed";return await $(e.identity,async()=>(i=await ee(e,r),L(e,i==="restarted"?"ready":"profile_restart_required")),"queue"),i}async function ee(e,r){const i=e.identity,t=u(i);if(!t||!f(t.pid))return"not_managed";const n=y(i);if(n.length>0&&!n.some(o=>o.pid===t.pid))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${i.profileName} pid=${t.pid} for plugin toggle`),await h(i,t.pid),await P(e,i),(await S(g,e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return d.warn(c,`plugin-toggle restart failed profile=${i.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function g(e){return e.readiness==="ready"||e.readiness==="bridge_incompatible"}function me(e,r){return $(e.identity,async()=>(await r,L(e,"ready")))}function L(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0,compatibleDshVersions:[]}}export{ue as awaitDshProfileIdle,X as buildDshProfileBootArgs,ce as ensureDshBridgeReady,me as holdDshProfileInflightForTests,pe as managedProfileRecordExists,W as managedProfileSpawnEnv,fe as prepareDshProfileBridge,le as resetDshProfileSupervisorForTests,ge as restartManagedProfileIfOwned};
|