grix-connector 4.2.6 → 4.2.8
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/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/codewhale/codewhale-adapter.js +2 -2
- package/dist/adapter/codewhale/codewhale-provider-config.js +2 -2
- package/dist/adapter/deepseek-harness/dsh-provider-config.js +7 -7
- package/dist/adapter/deepseek-harness/index.js +1 -1
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +2 -2
- package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.2.8.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +5 -5
- package/dist/bridge/acp-toolbar-persist.js +1 -1
- package/dist/bridge/bridge.js +5 -9
- package/dist/bridge/cli-install-flow.js +1 -0
- package/dist/bridge/connector-ops.js +1 -0
- package/dist/bridge/event-queue.js +1 -1
- package/dist/bridge/event-stop.js +1 -0
- package/dist/bridge/host-contract.js +0 -0
- package/dist/bridge/provider-quota.js +1 -0
- package/dist/bridge/rate-limits.js +1 -0
- package/dist/bridge/session-control-open.js +1 -0
- package/dist/bridge/session-control-router.js +3 -0
- package/dist/bridge/session-list.js +3 -0
- package/dist/bridge/session-usage.js +1 -0
- package/dist/bridge/skill-actions.js +1 -0
- package/dist/bridge/toolbar-meta.js +1 -0
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/persistence/session-binding-store.js +2 -2
- package/dist/core/skill-sync/sync-state.js +1 -1
- package/package.json +2 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.2.6.tgz +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readdirSync as
|
|
2
|
-
`)){const
|
|
1
|
+
import{readdirSync as x,readFileSync as j,existsSync as h,statSync as D}from"node:fs";import{dirname as S,join as s,resolve as y}from"node:path";import{homedir as L}from"node:os";import{log as F}from"../../core/log/index.js";import{findGitProjectRoot as M}from"../../core/util/git-project-root.js";const w=".grix-managed";function b(t){const e=t.trim();if(!e.startsWith("---"))return{name:"",description:""};const r=e.indexOf("---",3);if(r===-1)return{name:"",description:""};const c=e.slice(3,r).trim();let i="",o="",l;for(const p of c.split(`
|
|
2
|
+
`)){const a=p.indexOf(":");if(a===-1)continue;const d=p.slice(0,a).trim();let u=p.slice(a+1).trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),d==="name"?i=u:d==="description"?o=u:d==="trigger"&&(l=u)}return{name:i,description:o,trigger:l}}function P(t,e,r){if(!h(t))return[];const c=[];try{for(const i of x(t,{withFileTypes:!0})){const o=s(t,i.name);if(!H(i,o)||i.name.startsWith("."))continue;const l=s(o,"SKILL.md");if(h(l))try{const p=j(l,"utf-8"),a=b(p);a.name&&c.push({name:a.name,description:a.description,trigger:a.trigger,source:e,pluginName:r,filePath:l,managed:h(s(o,w))})}catch{}}}catch{}return c}function n(t,e,r){if(!h(t))return[];const c=r?.maxDepth??6,i=r?.includeHiddenDirs??!1,o=[],l=(p,a)=>{if(a>c)return;let d;try{d=x(p,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const u of d){const f=s(p,u.name);if(r?.rootMarkdownFiles&&a===0&&u.name.endsWith(".md")){if(!i&&u.name.startsWith(".")||!v(u,f))continue;try{const g=j(f,"utf-8"),m=b(g);m.name&&o.push({name:m.name,description:m.description,trigger:m.trigger,source:e,pluginName:r?.pluginName,filePath:f})}catch{}continue}if(!H(u,f)||!i&&u.name.startsWith(".")||u.name==="node_modules")continue;const k=s(f,"SKILL.md");if(h(k))try{const g=j(k,"utf-8"),m=b(g);m.name&&o.push({name:m.name,description:m.description,trigger:m.trigger,source:e,pluginName:r?.pluginName,filePath:k,managed:h(s(f,w))})}catch{}l(f,a+1)}};return l(t,0),o}function E(t){return t.map(e=>({...e,managed:!0}))}function H(t,e){if(t.isDirectory())return!0;if(!t.isSymbolicLink())return!1;try{return D(e).isDirectory()}catch{return!1}}function v(t,e){if(t.isFile())return!0;if(!t.isSymbolicLink())return!1;try{return D(e).isFile()}catch{return!1}}function N(t){const e=[],r=new Set;for(const c of t){const i=c.name.trim().toLowerCase();r.has(i)||(r.add(i),e.push(c))}return e}function R(t){const e=t.filePath?.trim();if(!e)return 0;try{const r=D(e).mtimeMs,c=D(S(e)).mtimeMs;return Math.max(r,c)}catch{return 0}}function A(t){return t.map((e,r)=>({entry:e,index:r,timeMs:R(e)})).sort((e,r)=>e.timeMs!==r.timeMs?r.timeMs-e.timeMs:e.index-r.index).map(e=>e.entry)}function I(t){const e=[],r=new Set;let c=y(t);for(;;){r.has(c)||(e.push(c),r.add(c));const i=S(c);if(i===c)break;c=i}return e}function T(t,e){const r=[s(t,".claude","settings.json")];e&&(r.push(s(e,".claude","settings.json")),r.push(s(e,".claude","settings.local.json")));const c=new Map;for(const i of r)if(h(i))try{const l=JSON.parse(j(i,"utf-8"))?.enabledPlugins;if(!l||typeof l!="object")continue;for(const[p,a]of Object.entries(l))typeof a=="boolean"&&c.set(p,a)}catch{}return c}function C(t,e){const r=s(t,".claude","plugins","installed_plugins.json");if(!h(r))return[];const c=[];try{const i=j(r,"utf-8"),l=JSON.parse(i)?.plugins;if(!l||typeof l!="object")return c;const p=T(t,e),a=e?y(e):void 0;for(const[d,u]of Object.entries(l))if(Array.isArray(u)&&p.get(d)===!0)for(const f of u){const k=f?.installPath;if(!k||!h(k))continue;if(f?.scope==="local"){const _=typeof f?.projectPath=="string"?y(f.projectPath):void 0;if(!a||_!==a)continue}const g=s(k,"skills"),m=d.split("@")[0],O=E(P(g,"plugin",m));c.push(...O)}}catch{}return c}function $(t,e){const r=(t??"").trim().toLowerCase(),c=(e??"").trim().toLowerCase();return r==="claude"?"claude":r==="codex"?"codex":r==="pi"?"pi":r==="cursor"?"cursor":r==="codewhale"?"codewhale":r==="opencode"?"opencode":r==="agy"?"gemini":r==="openhuman"?"none":r==="deepseek-harness"?"deepseek":c==="kiro"?"kiro":c==="qwen"?"qwen":c==="reasonix"?"reasonix":c==="kimi"?"kimi":c==="hermes"?"hermes":c==="copilot"?"copilot":"gemini"}function J(t){const e=[],r=t.homeDir??L();switch(t.mode){case"claude":{const i={maxDepth:0};t.projectDir&&e.push(...n(s(t.projectDir,".claude","skills"),"project",i));const o=s(r,".claude","skills");e.push(...n(o,"global",i)),e.push(...C(r,t.projectDir));break}case"codex":{const i=process.env.CODEX_HOME?.trim()||s(r,".codex"),o=t.includeSharedAgentSkills??/^(1|true|yes|on)$/i.test(process.env.GRIX_CODEX_INCLUDE_SHARED_AGENT_SKILLS??"");if(t.projectDir)for(const l of I(t.projectDir))e.push(...n(s(l,".agents","skills"),"project")),e.push(...n(s(l,".codex","skills"),"project"));o&&e.push(...n(s(r,".agents","skills"),"codex")),e.push(...n(s(i,"skills"),"codex")),e.push(...E(n(s(i,"skills",".system"),"codex")));break}case"gemini":{const i={maxDepth:0};t.projectDir&&(e.push(...n(s(t.projectDir,".gemini","skills"),"project",i)),e.push(...n(s(t.projectDir,".agents","skills"),"project",i))),e.push(...n(s(r,".gemini","skills"),"gemini",i)),e.push(...n(s(r,".agents","skills"),"gemini",i));break}case"pi":{t.projectDir&&e.push(...n(s(t.projectDir,".pi","skills"),"project")),e.push(...n(s(r,".pi","agent","skills"),"pi"));break}case"kiro":{t.projectDir&&e.push(...n(s(t.projectDir,".kiro","skills"),"project")),e.push(...n(s(r,".kiro","skills"),"kiro"));break}case"qwen":{const i={maxDepth:0};t.projectDir&&(e.push(...n(s(t.projectDir,".qwen","skills"),"project",i)),e.push(...n(s(t.projectDir,".agents","skills"),"project",i))),e.push(...n(s(r,".qwen","skills"),"global",i)),e.push(...n(s(r,".agents","skills"),"global",i));break}case"cursor":{const i={maxDepth:0};t.projectDir&&(e.push(...n(s(t.projectDir,".agents","skills"),"project",i)),e.push(...n(s(t.projectDir,".cursor","skills"),"project",i))),e.push(...n(s(r,".agents","skills"),"global",i)),e.push(...n(s(r,".cursor","skills"),"global",i));break}case"codewhale":{t.projectDir&&e.push(...n(s(t.projectDir,".codewhale","skills"),"project")),e.push(...n(s(r,".codewhale","skills"),"global"));break}case"opencode":{const i=process.env.XDG_CONFIG_HOME?.trim()||s(r,".config");t.projectDir&&(e.push(...n(s(t.projectDir,".opencode","skills"),"project")),e.push(...n(s(t.projectDir,".opencode","skill"),"project"))),e.push(...n(s(i,"opencode","skills"),"global")),e.push(...n(s(i,"opencode","skill"),"global")),e.push(...n(s(r,".claude","skills"),"global")),e.push(...n(s(r,".agents","skills"),"global"));break}case"reasonix":{e.push(...n(s(r,".reasonix","skills"),"global"));break}case"kimi":{const i=process.env.KIMI_CODE_HOME?.trim()||s(r,".kimi-code"),o={rootMarkdownFiles:!0};if(t.projectDir){const l=M(t.projectDir);e.push(...n(s(l,".kimi-code","skills"),"project",o)),e.push(...n(s(l,".agents","skills"),"project",o))}e.push(...n(s(i,"skills"),"global",o)),e.push(...n(s(r,".agents","skills"),"global",o));break}case"deepseek":{const i=t.env??process.env,o=i.DSH_HOME?.trim()||s(r,".dsh"),l=i.DSH_AGENTS_HOME?.trim()||s(r,".agents"),p={rootMarkdownFiles:!0,maxDepth:0};if(t.projectDir){const a=M(t.projectDir);e.push(...n(s(a,".dsh","skills"),"project",p)),e.push(...n(s(a,".agents","skills"),"project",p))}e.push(...n(s(o,"skills"),"global",p)),e.push(...n(s(l,"skills"),"global",p));break}case"hermes":{const i=t.env??process.env,o=i.HERMES_HOME?.trim()||i.GRIX_HERMES_HOME?.trim()||s(r,".hermes");e.push(...n(s(o,"skills"),"global"));break}case"copilot":{t.projectDir&&(e.push(...n(s(t.projectDir,".github","skills"),"project")),e.push(...n(s(t.projectDir,".claude","skills"),"project")),e.push(...n(s(t.projectDir,".agents","skills"),"project"))),e.push(...n(s(r,".copilot","skills"),"global")),e.push(...n(s(r,".agents","skills"),"global"));break}case"none":break}const c=A(N(e));return F.info("skill-scanner",`Scanned skills: mode=${t.mode} count=${c.length}`),c}export{w as MANAGED_MARKER,N as dedupeSkills,E as markManaged,b as parseSkillFrontmatter,$ as resolveSkillScanMode,n as scanSkillTree,J as scanSkills,A as sortSkillsByRecentTime};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFileSync as I}from"node:child_process";import{stat as
|
|
1
|
+
import{execFileSync as I}from"node:child_process";import{stat as M}from"node:fs/promises";import{resolveCommandPath as w,spawnCommand as A,killProcessGroup as k}from"../../core/runtime/spawn.js";import{createInterface as C}from"node:readline";import{EventEmitter as b}from"node:events";import{join as _,resolve as E}from"node:path";import{homedir as P}from"node:os";import{fileURLToPath as T}from"node:url";import{InternalApiServer as x}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as $,LEGACY_MCP_SERVER_NAMES as N}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as R}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as B}from"../../core/protocol/message-reference.js";import{IdentityInjector as D}from"../shared/identity-injector.js";import{compactToolInputForWire as L}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as j}from"../../default-skills/index.js";import{buildSimpleProbeReport as O}from"../shared/probe-util.js";import{getCachedCodeWhaleModels as U,primeCodeWhaleModels as G}from"./model-list.js";import{writeCodeWhaleGrixConfig as H}from"./codewhale-provider-config.js";import{log as o}from"../../core/log/index.js";import{SessionBindingStore as W}from"../../core/persistence/session-binding-store.js";const q=120*1e3,f=1800*1e3,F=5*1e3;function J(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class me extends b{type="codewhale";config;callbacks;alive=!1;stopped=!1;internalApi=null;deepSeekSessionId=null;activeEventId=null;activeSessionId=null;chunkSeq=0;activeClientMsgId=null;idleTimer=null;lastProgressAt=0;activeProcess=null;identity;inboundMessageIds=new R;bindingStore=null;aibotSessionId="";cwd;provider;agentName="";grixConfigPath="";lastUsage=null;currentModel=null;toolNamesById=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t,this.identity=new D("codewhale-adapter",t.getAgentProfile);const i=e.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.bindingStore=i.bindingStore instanceof W?i.bindingStore:null;const n=String(i.model??"").trim();if(n&&(this.currentModel=n),this.provider=i.provider,this.agentName=String(i.agentName??"").trim(),this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const s=this.bindingStore.getCodeWhaleThreadId(this.aibotSessionId);s&&(this.deepSeekSessionId=s)}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async start(){this.alive=!0,await this.applyGrixProviderConfig(),await this.startInternalApiAndRegisterMcp(),G(this.config.command||"codewhale"),this.notifyBindingReady(),o.info("codewhale-adapter","Ready (exec mode)")}async applyGrixProviderConfig(){if(!this.provider){this.grixConfigPath="";return}try{this.grixConfigPath=await H(this.agentName,this.provider)??"",this.grixConfigPath?o.info("codewhale-adapter",`Grix provider config written to ${this.grixConfigPath}`):o.warn("codewhale-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}catch(e){this.grixConfigPath="",o.warn("codewhale-adapter",`Failed to write Grix provider config: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1,this.stopComposing(),this.clearIdleTimer(),this.killActiveProcess(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=this.deepSeekSessionId??`ds-${Date.now()}`;return this.notifyBindingReady(),t}async resumeSession(e,t){}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.deepSeekSessionId=null,this.persistSessionId(void 0)}sendPrompt(e){const t=new y(e.adapterSessionId);return this.runMessage(e,t).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),t}async cancel(e){this.killActiveProcess()}setPermissionHandler(e){}async ping(e){if(this.stopped||!this.alive)return!1;const t=this.activeProcess;return!(t?.pid&&!J(t.pid))}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.deepSeekSessionId?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.clearIdleTimer(),this.killActiveProcess(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){if(!this.internalApi)return null;const e=E(T(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:$(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async probe(e){const t=this.getStatus();return O(this.config.command||"codewhale",{alive:t.alive,busy:t.busy,started:this.alive},e)}getUsageSnapshot(){return this.lastUsage}async startInternalApiAndRegisterMcp(){try{this.internalApi=new x,this.internalApi.setInvokeHandler(async(a,p,h,c)=>this.callbacks.agentInvoke(a,p,c)),await this.internalApi.start(0),o.info("codewhale-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t={...process.env,...this.config.env},i=typeof t.PATH=="string"?t.PATH:void 0,n=w(this.config.command||"codewhale",i);for(const a of[...N,e.name])try{I(n,["mcp","remove",a],{env:t,timeout:1e4,stdio:"ignore",windowsHide:!0})}catch{}const s=["mcp","add",e.name,"--command",e.command];for(const a of e.args)s.push("--arg",a);I(n,s,{env:t,timeout:1e4,stdio:"ignore",windowsHide:!0}),o.info("codewhale-adapter",`Registered MCP server: ${e.name}`);const d=_(P(),".codewhale","skills"),r=j(d);r.length>0&&o.info("codewhale-adapter",`Synced connector skills to ${d}: [${r.join(", ")}]`)}catch(e){o.warn("codewhale-adapter",`Failed to register MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}getSupportedCommands(){return[{name:"status",description:"Show session and working directory status"}]}async execCommand(e,t,i){return e==="status"?{status:"ok",message:`Session: ${this.deepSeekSessionId??"none"}, CWD: ${this.cwd}`,data:{sessionId:this.deepSeekSessionId,cwd:this.cwd,alive:this.alive}}:{status:"unsupported",message:`Unknown command: ${e}`}}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};switch(t){case"get_context":return this.callbacks.sendLocalActionResult(e.action_id,"ok",{sessionId:this.deepSeekSessionId,cwd:this.cwd,model:this.currentModel,model_id:this.currentModel,available_models:this.availableModelsMeta()}),{handled:!0,kind:"get_context"};case"set_model":{const n=String(i.model_id??"").trim();return n?(this.currentModel=n,this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",modelId:n,model_id:n,available_models:this.availableModelsMeta()}),o.info("codewhale-adapter",`Model set to: ${n}`),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id is required"),{handled:!0,kind:"set_model"})}default:return{handled:!1,kind:""}}}availableModelsMeta(){return U(this.config.command||"codewhale").map(e=>({id:e.id,displayName:e.displayName}))}deliverInboundEvent(e){if(this.activeEventId){o.info("codewhale-adapter",`Event ${e.event_id}: rejected, busy with ${this.activeEventId}`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}const t=this.inboundMessageIds.inject(e.session_id,e.content,e.msg_id);this.startNewMessage(e,t)}deliverStopEvent(e,t){this.activeEventId===e&&(this.killActiveProcess(),this.callbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActive())}startNewMessage(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,this.chunkSeq=0,this.activeClientMsgId=`ds-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.beginAuditCapture(e),this.startComposing();const i={adapterSessionId:this.deepSeekSessionId??"",text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(s=>({senderId:s.sender_id??"unknown",content:s.content})):void 0},n=new y(this.deepSeekSessionId??"");this.runMessage(i,n,e.event_id,e.session_id).catch(s=>{o.error("codewhale-adapter",`Message failed: ${s}`),this.callbacks.sendEventResult(e.event_id,"failed",s instanceof Error?s.message:String(s)),this.clearActive()}),this.resetIdleTimer(e.event_id)}buildExecArgs(e){const t=[];this.grixConfigPath&&t.push("--config",this.grixConfigPath);const i=[...this.config.args??[]];return t.push("exec"),i.includes("--output-format")||t.push("--output-format","stream-json"),t.push(...i),this.currentModel&&t.push("--model",this.currentModel),this.deepSeekSessionId&&t.push("--resume",this.deepSeekSessionId),t.push("--",e),t}async runMessage(e,t,i,n){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const c=e.contextMessages.map(l=>`[${l.senderId??"unknown"}]: ${l.content}`).join(`
|
|
2
2
|
`);s=B(s,`[Conversation context]
|
|
3
|
-
${c}`)}s=this.identity.injectOnce(n??e.adapterSessionId,s);const d=this.config.command||"codewhale",r=this.buildExecArgs(s),a={...process.env,...this.config.env},p=w(d,typeof a.PATH=="string"?a.PATH:void 0);o.info("codewhale-adapter",`Spawning: ${p} ${r.slice(0,5).join(" ")}...`);try{if(!(await
|
|
3
|
+
${c}`)}s=this.identity.injectOnce(n??e.adapterSessionId,s);const d=this.config.command||"codewhale",r=this.buildExecArgs(s),a={...process.env,...this.config.env},p=w(d,typeof a.PATH=="string"?a.PATH:void 0);o.info("codewhale-adapter",`Spawning: ${p} ${r.slice(0,5).join(" ")}...`);try{if(!(await M(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):c}const h=A(p,r,{cwd:this.cwd,env:a}).process;return this.activeProcess=h,h.stderr?.on("data",c=>{const l=c.toString().trim();l&&o.info("codewhale-adapter",`[codewhale stderr] ${l}`)}),new Promise((c,l)=>{let m=!1,v="";const S=()=>{this.activeProcess=null};h.on("error",u=>{m||(m=!0,S(),l(u))}),h.on("exit",u=>{if(v.trim()&&this.handleOutputLine(v.trim(),i),v="",m){S();return}if(m=!0,S(),u!==0&&i&&this.activeEventId===i){l(new Error(`codewhale exec exited with code ${u}`));return}t.emitDone({status:"completed"}),c()}),C({input:h.stdout}).on("line",u=>{u.trim()&&this.handleOutputLine(u.trim(),i)}),h.stdin?.end()})}handleOutputLine(e,t){let i;try{i=JSON.parse(e)}catch{o.error("codewhale-adapter",`Invalid JSON: ${e.slice(0,200)}`);return}switch(t&&this.captureAuditEvent(t,e,i),i.type){case"content":{const s=i.content;s&&t&&this.activeEventId===t&&this.activeSessionId&&(this.chunkSeq++,this.callbacks.sendStreamChunk(t,this.activeSessionId,s,this.chunkSeq,!1,this.activeClientMsgId??void 0),this.startComposing(),this.resetIdleTimer(t));break}case"session_capture":{const s=i.content;s&&(this.deepSeekSessionId=s,this.persistSessionId(s),o.info("codewhale-adapter",`Session captured: ${s}`));break}case"metadata":{const s=i.meta;if(s){o.info("codewhale-adapter",`Metadata: model=${s.model}, tokens_in=${s.input_tokens}, tokens_out=${s.output_tokens}`);const d=Number(s.input_tokens??0),r=Number(s.output_tokens??0);if(d>0||r>0){const a=this.lastUsage;this.lastUsage={sampledAt:new Date().toISOString(),turns:(a?.turns??0)+1,total:{input:(a?.total.input??0)+d,output:(a?.total.output??0)+r}}}}break}case"tool_use":{const s=typeof i.name=="string"?i.name.trim():"",d=typeof i.id=="string"?i.id.trim():"",r=L(i.input);s&&t&&this.activeEventId===t&&this.activeSessionId&&(d&&this.toolNamesById.set(d,s),o.info("codewhale-adapter",`Tool use: ${s}`),this.callbacks.sendToolUse(t,this.activeSessionId,s,r),this.resetIdleTimer(t));break}case"tool_result":{const s=typeof i.id=="string"?i.id.trim():"",r=(typeof i.name=="string"?i.name.trim():"")||(s?this.toolNamesById.get(s):void 0)||"tool";s&&this.toolNamesById.delete(s);const a=typeof i.status=="string"?i.status.trim().toLowerCase():"",p=a==="failed"||a==="failure"||a==="error";t&&this.activeEventId===t&&this.activeSessionId&&(p&&this.callbacks.sendToolResult(t,this.activeSessionId,r,"(failed)"),this.resetIdleTimer(t));break}case"done":{this.handleMessageCompleted(t);break}default:break}}handleMessageCompleted(e){if(this.stopComposing(),e&&this.activeEventId===e){const t=this.activeSessionId??"",i=this.activeClientMsgId??void 0;t&&(this.chunkSeq++,this.callbacks.sendStreamChunk(e,t,"",this.chunkSeq,!0,i)),this.callbacks.sendEventResult(e,"responded"),this.clearActive()}}killActiveProcess(){const e=this.activeProcess;this.activeProcess=null,e?.pid&&(k(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{k(e,"SIGKILL")}catch{}},5e3).unref())}notifyBindingReady(){if(!this.aibotSessionId||!this.cwd)return;const e=this.availableModelsMeta(),t=this.currentModel??e[0]?.id??"";this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd,{model_id:t,available_models:e})}persistSessionId(e){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodeWhaleThreadId(this.aibotSessionId,e)}startComposing(){}stopComposing(){}resetIdleTimer(e){this.lastProgressAt=Date.now(),this.armIdleTimer(e)}armIdleTimer(e){this.clearIdleTimer();const t=this.lastProgressAt+f-Date.now(),i=Math.max(0,Math.min(q,t));this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e)},i)}async onIdleTimeout(e){if(this.activeEventId!==e)return;if(Date.now()-this.lastProgressAt>=f){this.failIdleRun(e,`liveness budget exhausted after ${f/6e4}min`);return}let i=!1;try{i=await this.ping(F)}catch{i=!1}if(this.activeEventId===e){if(i){o.info("codewhale-adapter",`Idle timer: process alive, extending until liveness cap (${f/6e4}min): ${e}`),this.armIdleTimer(e);return}this.failIdleRun(e,"process not alive")}}failIdleRun(e,t){this.activeEventId===e&&(o.error("codewhale-adapter",`Idle timeout (${t}): ${e}`),this.killActiveProcess(),this.callbacks.sendEventResult(e,"failed",`idle timeout: ${t}`),this.clearActive(),this.emit("stuck"))}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearActive(){const e=this.activeEventId;e&&this.snapshotAuditBoundary(e),this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.chunkSeq=0,this.activeClientMsgId=null,this.toolNamesById.clear(),this.lastProgressAt=0,this.clearIdleTimer(),e&&this.emit("eventDone",e)}beginAuditCapture(e){!e.audit?.enabled||this.auditCaptures.has(e.event_id)||this.auditCaptures.set(e.event_id,{events:[]})}captureAuditEvent(e,t,i){const n=this.auditCaptures.get(e);n&&n.events.push({sequence:n.events.length,observedAt:new Date().toISOString(),rawLine:t,event:structuredClone(i)})}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e);t&&(this.completedAuditBoundaries.set(e,{adapterType:"codewhale",providerSessionId:this.deepSeekSessionId??void 0,codeWhaleEvidence:{events:t.events}}),this.auditCaptures.delete(e))}}class y extends b{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("codewhale-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}export{me as CodeWhaleAdapter};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mkdir as
|
|
2
|
-
`);return await
|
|
1
|
+
import{mkdir as l,writeFile as s}from"node:fs/promises";import{homedir as m}from"node:os";import{join as a}from"node:path";import{PROVIDER_ENV_SPECS as u}from"../../core/config/provider-env.js";const d="openai",c=u.codewhale?.apiKey;function p(e){return(e??"default").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function _(e){return a(m(),".grix","runtime","native-provider",p(e),"codewhale")}async function v(e,r){const i=r.baseUrl?.trim(),o=r.model?.trim();if(!i||!o)return;if(!c)throw new Error("codewhale provider env spec declares no api key variable; refusing to write an unbound relay route");const t=_(e),n=a(t,"config.toml"),f=[`provider = ${JSON.stringify(d)}`,`default_text_model = ${JSON.stringify(o)}`,'auth_mode = "api_key"',"",`[providers.${d}]`,`base_url = ${JSON.stringify(i)}`,`api_key_env = ${JSON.stringify(c)}`,""].join(`
|
|
2
|
+
`);return await l(t,{recursive:!0}),await s(n,f,{encoding:"utf8",mode:384}),n}export{_ as codewhaleGrixConfigDir,v as writeCodeWhaleGrixConfig};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{mkdir as
|
|
2
|
-
`:""}function
|
|
3
|
-
${m(c,
|
|
4
|
-
${m(
|
|
5
|
-
`)}return`${" ".repeat(
|
|
6
|
-
`);const r=
|
|
1
|
+
import{mkdir as F,readFile as Y,writeFile as x}from"node:fs/promises";import{join as $}from"node:path";import{log as S}from"../../core/log/index.js";import{DEFAULT_DSH_MODELS as M}from"./toolbar-state.js";const Q="grix",g="GRIX_PROVIDER_API_KEY",N="settings.yaml",_=".credentials.yaml",O="dsh-provider",W="llm-pi-ai",k=new Map;function A(t,e){const r=(k.get(t)??Promise.resolve()).then(e,e);return k.set(t,r.catch(()=>{})),r}function f(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}class p extends Error{code="yaml_incomplete";constructor(e){super(e),this.name="IncompleteYamlError"}}async function w(t){try{return f(V(await Y(t,"utf8")))}catch(e){if(e.code==="ENOENT")return{};throw e}}async function Z(t){const e=$(t,_);return A(e,async()=>f((await w(e)).refs))}const T=1;function P(t){t.version===void 0&&(t.version=T);const e=f(t.refs);return t.refs=e,e}const K=Object.freeze({thinkingFormat:"deepseek",supportsDeveloperRole:!1,maxTokensField:"max_tokens"}),C=Object.freeze({off:null,high:"high",max:"max"});function L(t){const e=t.baseUrl?.trim(),r=t.model?.trim();if(!e||!r)return;const o=()=>({...C}),n=new Map;n.set(r,{id:r,name:r,contextWindow:1e6,reasoningEfforts:o()});for(const s of M)n.has(s.id)||n.set(s.id,{id:s.id,name:s.displayName,contextWindow:s.contextWindow,reasoningEfforts:o()});return{displayName:"Grix",apiKeyEnv:g,api:"openai-completions",baseURL:e,compat:{...K},models:[...n.values()]}}function R(t){return f(t).apiKeyEnv===g}function U(t,e){const r=f(t);if(r.displayName!==e.displayName||r.apiKeyEnv!==e.apiKeyEnv||r.api!==e.api||r.baseURL!==e.baseURL||!G(r.compat,e.compat))return!1;const o=Array.isArray(e.models)?e.models:[],n=Array.isArray(r.models)?r.models:[];if(o.length!==n.length)return!1;const s=new Map(n.map(i=>[String(i.id??""),i]));return o.every(i=>{const c=s.get(String(i.id??""));return!!c&&c.name===i.name&&Number(c.contextWindow)===Number(i.contextWindow)&&G(c.reasoningEfforts,i.reasoningEfforts)})}function G(t,e){const r=f(t),o=f(e),n=new Set([...Object.keys(r),...Object.keys(o)]);for(const s of n)if((r[s]??null)!==(o[s]??null))return!1;return!0}function tt(t){return!!t&&!!L(t)&&!!t.apiKey?.trim()}async function et(t,e,r){const o=L(r),n=r.apiKey?.trim();if(!o||!n||!e.trim())return"skipped";const s=$(t,N),i=$(t,_);return A(s,async()=>{let c,a;try{c=await w(s),a=await w(i)}catch(y){if(y instanceof p)return S.warn(O,`Refusing to rewrite incomplete DSH YAML: ${y.message}`),"skipped";throw y}const l=f(c[W]),d=f(l.providers),u=d[e];if(u!==void 0&&!R(u))return"skipped";const h=P(a);return R(u)&&U(u,o)&&h[g]===n?"unchanged":(d[e]=o,l.providers=d,c[W]=l,h[g]=n,await F(t,{recursive:!0,mode:448}),await x(s,b(c),{encoding:"utf8",mode:384}),await x(i,b(a),{encoding:"utf8",mode:384}),S.info(O,`Wrote Grix provider providerId=${e} baseURL=${o.baseURL} api=openai-completions apiKeyEnv=${g} path=${s}`),"written")})}async function nt(t,e){const r=$(t,N),o=$(t,_);return A(r,async()=>{let n,s;try{n=await w(r),s=await w(o)}catch(l){if(l instanceof p)return S.warn(O,`Refusing to rewrite incomplete DSH YAML: ${l.message}`),!1;throw l}const i=f(n[W]),c=f(i.providers);if(!R(c[e]))return!1;delete c[e],i.providers=c,n[W]=i;const a=P(s);return delete a[g],Object.keys(a).length===0&&delete s.refs,await x(r,b(n),{encoding:"utf8",mode:384}),await x(o,b(s),{encoding:"utf8",mode:384}),!0})}function V(t){const e=t.replace(/^\uFEFF/,"");H(e);const r=X(e,0);return f(r.value)}function H(t){const e=t.split(/\r?\n/);for(let r=0;r<e.length;r++){const o=e[r]??"";if(o.includes(" "))throw new p(`tab indent at line ${r+1}`);const n=o.trim();if(!n||n.startsWith("#"))continue;if(n==="---"||n==="..."||n.startsWith("%"))throw new p(`document marker at line ${r+1}`);if((o.length-o.trimStart().length)%2!==0)throw new p(`odd indent at line ${r+1}`);const i=n.startsWith("- ")?n.slice(2):n;if(i.startsWith("&")||i.startsWith("*")||i.startsWith("!!")||i.startsWith("|")||i.startsWith(">"))throw new p(`unsupported yaml construct at line ${r+1}`);const c=i.indexOf(":");if(!n.startsWith("- ")&&c===-1)throw new p(`non-mapping line ${r+1}`);const a=c===-1?i:i.slice(c+1).trim();if(a&&a!=="[]"&&a!=="{}"&&!(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a.startsWith("{")||a.startsWith("[")||a.startsWith("|")||a.startsWith(">")||a.startsWith("&")||a.startsWith("*")||a.startsWith("!!")))throw new p(`unsupported inline yaml at line ${r+1}`)}}function b(t){const e=m(t,0);return e?`${e}
|
|
2
|
+
`:""}function X(t,e){const r=t.split(/\r?\n/),o=[];for(let s=e;s<r.length;s++){const i=r[s]??"";if(!i.trim()||i.trimStart().startsWith("#"))continue;const c=i.length-i.trimStart().length;o.push({indent:c,content:i.trim()})}if(o.length===0)return{value:{},nextLine:r.length};const n=E(o,0,o[0].indent);if(n.next<o.length)throw new p("unconsumed yaml lines");return{value:n.value,nextLine:r.length}}function E(t,e,r){if(e>=t.length||t[e].indent<r)return{value:{},next:e};if(t[e].content.startsWith("- ")){const s=[];let i=e;for(;i<t.length&&t[i].indent===r&&t[i].content.startsWith("- ");){const c=t[i].content.slice(2),a=c.indexOf(":");if(a===-1){s.push(I(c)),i+=1;continue}const l=c.slice(0,a).trim(),d=c.slice(a+1).trim(),u=r+2;if(d){const y=E(t,i+1,u),D=f(y.value);D[l]=I(d),s.push(D),i=y.next;continue}const h=E(t,i+1,u);s.push({[l]:h.value}),i=h.next}return{value:s,next:i}}const o={};let n=e;for(;n<t.length&&t[n].indent===r&&!t[n].content.startsWith("- ");){const s=t[n].content.indexOf(":");if(s===-1)throw new p(`non-mapping entry: ${t[n].content}`);const i=t[n].content.slice(0,s).trim(),c=t[n].content.slice(s+1).trim();if(c){o[i]=I(c),n+=1;continue}const a=E(t,n+1,r+2);o[i]=a.value,n=a.next}return{value:o,next:n}}function I(t){return t==="~"||t==="null"?null:t==="true"?!0:t==="false"?!1:t==="[]"?[]:t==="{}"?{}:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\"/g,'"'):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t}function m(t,e){if(t==null)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return v(t);if(Array.isArray(t))return t.length===0?"[]":t.map(n=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const s=Object.entries(n);if(s.length===0)return`${" ".repeat(e)}- {}`;const[i,c]=s[0],l=j(c)?`${" ".repeat(e)}- ${i}: ${m(c,0)}`:`${" ".repeat(e)}- ${i}:
|
|
3
|
+
${m(c,e+4)}`,d=s.slice(1).map(([u,h])=>j(h)?`${" ".repeat(e+2)}${u}: ${m(h,0)}`:`${" ".repeat(e+2)}${u}:
|
|
4
|
+
${m(h,e+4)}`);return[l,...d].join(`
|
|
5
|
+
`)}return`${" ".repeat(e)}- ${m(n,0)}`}).join(`
|
|
6
|
+
`);const r=f(t),o=Object.keys(r);return o.length===0?"{}":o.map(n=>{const s=r[n];if(j(s))return`${" ".repeat(e)}${n}: ${m(s,0)}`;const i=m(s,e+2);return`${" ".repeat(e)}${n}:
|
|
7
7
|
${i}`}).join(`
|
|
8
|
-
`)}function
|
|
8
|
+
`)}function j(t){return t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||Array.isArray(t)&&t.length===0?!0:!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0}function v(t){return t===""||/[:#{}[\],&*!|>'"%@`]|^\s|\s$|^(?:true|false|null|~)$/i.test(t)||/^-?\d+(?:\.\d+)?$/.test(t)?JSON.stringify(t):t}export{_ as DSH_CREDENTIALS_FILE,g as DSH_GRIX_API_KEY_ENV,Q as DSH_GRIX_PROVIDER_ID,N as DSH_SETTINGS_FILE,p as IncompleteYamlError,tt as isDshGrixProviderConfigured,V as parseYamlMapping,Z as readDshCredentials,nt as removeDshGrixProvider,b as stringifyYamlMapping,et as writeDshGrixProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as o,dshRuntimeEnsureBackoffMs as s,isRetryableDshRuntimeError as t}from"./runtime-ensure.js";import{DshJsonRpcAdapter as l}from"./jsonrpc-adapter.js";import{buildDshBindingToolbarMeta as a,DEFAULT_DSH_PRESET_ID as h,DEFAULT_DSH_PRESETS as
|
|
1
|
+
import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as o,dshRuntimeEnsureBackoffMs as s,isRetryableDshRuntimeError as t}from"./runtime-ensure.js";import{DshJsonRpcAdapter as l}from"./jsonrpc-adapter.js";import{buildDshBindingToolbarMeta as a,DEFAULT_DSH_PRESET_ID as h,DEFAULT_DSH_PRESETS as n,normalizeDshModeId as d,normalizeDshReasoningEffort as m,normalizeDshThinking as f,resolveDshAgentPreset as P,resolveDshModeId as p}from"./toolbar-state.js";import{dshCatalogCachePath as E,readDshCatalogCache as g,resolveDshCatalogForToolbar as u,writeDshCatalogCache as R}from"./catalog-cache.js";import{buildDshSystemPrompt as S,describeDshSystemPrompt as T}from"./system-prompt.js";import{buildDshUserPrompt as b,extractQuotedMessageMarker as v}from"./prompt-builder.js";import{TurnCorrelator as I}from"./turn-correlator.js";import{DshJsonRpcClient as A}from"./jsonrpc-client.js";import{runDshProtocolProbe as U}from"./probe.js";import{DshBridgeInstaller as F,defaultBridgeTarball as k}from"./bridge-installer.js";import{DEFAULT_DSH_PROFILE_NAME as G,discoverDshBridgeEndpoints as L,listDshProfiles as N,resolveDshConnectorProfileDataDir as z,resolveDshHome as w,resolveDshProfileIdentity as J,resolveDshSelectedProfileName as O}from"./profile-resolver.js";import{createDshWebProfile as q}from"./profile-catalog.js";import{DSH_GRIX_PROVIDER_ID as V,isDshGrixProviderConfigured as W,readDshCredentials as j,writeDshGrixProvider as K,removeDshGrixProvider as Y}from"./dsh-provider-config.js";import{disableDshPlugin as $,enableDshPlugin as ee,isDshPluginRestartRequired as re,listDshPlugins as oe}from"./plugin-manager.js";import{listDshSkills as te}from"./skill-manager.js";export{n as DEFAULT_DSH_PRESETS,h as DEFAULT_DSH_PRESET_ID,G as DEFAULT_DSH_PROFILE_NAME,V as DSH_GRIX_PROVIDER_ID,o as DSH_RUNTIME_ENSURE_MAX_ATTEMPTS,F as DshBridgeInstaller,l as DshJsonRpcAdapter,A as DshJsonRpcClient,I as TurnCorrelator,a as buildDshBindingToolbarMeta,S as buildDshSystemPrompt,b as buildDshUserPrompt,q as createDshWebProfile,k as defaultBridgeTarball,T as describeDshSystemPrompt,$ as disableDshPlugin,L as discoverDshBridgeEndpoints,E as dshCatalogCachePath,s as dshRuntimeEnsureBackoffMs,ee as enableDshPlugin,v as extractQuotedMessageMarker,W as isDshGrixProviderConfigured,re as isDshPluginRestartRequired,t as isRetryableDshRuntimeError,oe as listDshPlugins,N as listDshProfiles,te as listDshSkills,d as normalizeDshModeId,m as normalizeDshReasoningEffort,f as normalizeDshThinking,g as readDshCatalogCache,j as readDshCredentials,Y as removeDshGrixProvider,P as resolveDshAgentPreset,u as resolveDshCatalogForToolbar,z as resolveDshConnectorProfileDataDir,w as resolveDshHome,p as resolveDshModeId,J as resolveDshProfileIdentity,O as resolveDshSelectedProfileName,U as runDshProtocolProbe,R as writeDshCatalogCache,K as writeDshGrixProvider};
|