grix-connector 4.17.0 → 4.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/adapter/agy/agy-adapter.js +8 -8
  2. package/dist/adapter/claude/claude-adapter.js +22 -22
  3. package/dist/adapter/claude/config-paths.js +1 -0
  4. package/dist/adapter/claude/model-list.js +1 -1
  5. package/dist/adapter/claude/session-history.js +2 -2
  6. package/dist/adapter/claude/session-scanner.js +1 -1
  7. package/dist/adapter/claude/skill-scanner.js +2 -2
  8. package/dist/adapter/claude/usage-parser.js +8 -8
  9. package/dist/adapter/opencode/opencode-adapter.js +1 -1
  10. package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.17.0.tgz → grix-dsh-bridge-4.18.1.tgz} +0 -0
  11. package/dist/assets/dsh-bridge/manifest.json +4 -4
  12. package/dist/bridge/bridge.js +2 -2
  13. package/dist/bridge/provider-quota.js +1 -1
  14. package/dist/bridge/session-control-router.js +2 -2
  15. package/dist/bridge/session-list.js +2 -2
  16. package/dist/bridge/session-scan-cache.js +1 -1
  17. package/dist/bridge/session-usage.js +1 -1
  18. package/dist/bridge/skill-actions.js +1 -1
  19. package/dist/bridge/toolbar-meta.js +1 -1
  20. package/dist/core/config/index.js +1 -1
  21. package/dist/core/config/paths.js +1 -1
  22. package/dist/core/provider-quota/index.js +1 -1
  23. package/dist/core/provider-quota/opencode-go.js +1 -1
  24. package/dist/core/skill-sync/enable-roots.js +1 -1
  25. package/dist/core/skill-sync/library-skills.js +1 -1
  26. package/dist/core/skill-sync/skill-enable.js +1 -1
  27. package/dist/core/util/cli-probe.js +2 -2
  28. package/dist/grix.js +0 -0
  29. package/dist/manager.js +1 -1
  30. package/openclaw-plugin/audit-recorder-worker.js +52 -52
  31. package/openclaw-plugin/index.js +65 -65
  32. package/package.json +1 -1
  33. package/dist/adapter/claude/claude-bridge-server.js +0 -1
  34. package/dist/adapter/claude/claude-tools.js +0 -1
  35. package/dist/adapter/claude/claude-worker-client.js +0 -1
  36. package/dist/adapter/claude/mcp-http-launcher.js +0 -2
  37. package/dist/adapter/claude/result-timeout.js +0 -1
  38. package/dist/adapter/deepseek/deepseek-adapter.js +0 -6
  39. package/dist/adapter/deepseek/index.js +0 -1
  40. package/dist/adapter/qwen/index.js +0 -1
  41. package/dist/adapter/qwen/qwen-adapter.js +0 -4
  42. package/dist/aibot/client.js +0 -1
  43. package/dist/aibot/index.js +0 -1
  44. package/dist/aibot/types.js +0 -0
  45. package/dist/core/access/allowlist-gate.js +0 -1
  46. package/dist/core/access/allowlist-store.js +0 -1
  47. package/dist/core/access/index.js +0 -1
  48. package/dist/core/file-ops/handler.js +0 -1
  49. package/dist/core/file-ops/list-files.js +0 -1
  50. package/dist/core/file-ops/types.js +0 -0
  51. package/dist/log.js +0 -3
  52. package/dist/main.js +0 -31
  53. package/dist/mcp/stream-http/config.js +0 -1
  54. package/dist/mcp/stream-http/connection-binding.js +0 -1
  55. package/dist/mcp/stream-http/event-tool-executor.js +0 -1
  56. package/dist/mcp/stream-http/gateway.js +0 -1
  57. package/dist/mcp/stream-http/index.js +0 -1
  58. package/dist/mcp/stream-http/security.js +0 -1
  59. package/dist/mcp/stream-http/session-manager.js +0 -1
  60. package/dist/mcp/stream-http/tool-executor.js +0 -1
  61. package/dist/mcp/stream-http/tool-registry.js +0 -1
  62. package/dist/mcp/stream-http/tool-schemas.js +0 -1
  63. package/dist/session/index.js +0 -1
  64. package/dist/session/manager.js +0 -1
  65. package/dist/transport/index.js +0 -1
  66. package/dist/transport/json-rpc.js +0 -3
@@ -0,0 +1 @@
1
+ import p from"node:path";import{homedir as a}from"node:os";import{expandHomePath as j}from"../../core/config/index.js";function u(e,c={}){const{platform:r=process.platform,homeDir:n=a(),pathImpl:o=p}=c,t=r==="win32"?Object.keys(e).find(l=>l.toUpperCase()==="CLAUDE_CONFIG_DIR"):"CLAUDE_CONFIG_DIR",s=(t?e[t]:void 0)?.trim(),i=s?j(s,{platform:r,homeDir:n,pathImpl:o}):o.join(n,".claude");return{dir:i,claudeJson:s?o.join(i,".claude.json"):o.join(n,".claude.json"),settings:o.join(i,"settings.json"),projectsDir:o.join(i,"projects"),skillsDir:o.join(i,"skills"),pluginsDir:o.join(i,"plugins"),credentialsJson:o.join(i,".credentials.json")}}export{u as resolveClaudeConfigPaths};
@@ -1 +1 @@
1
- import{execFileSync as N}from"node:child_process";import{readJSONFile as k}from"../../core/util/json-file.js";import{log as i}from"../../core/log/index.js";import{homedir as O}from"node:os";import{join as m}from"node:path";const A="default",g={id:A,displayName:"\u9ED8\u8BA4\uFF08CLI \u81EA\u52A8\u9009\u62E9\uFF09"};function v(e){const n=String(e??"").trim();return n===A?"":n}function _(e){return[g,...e.filter(n=>n.id!==A)]}const w=[{id:"opus",displayName:"Opus"},{id:"sonnet",displayName:"Sonnet"},{id:"haiku",displayName:"Haiku"},{id:"claude-fable-5-1",displayName:"Claude Fable 5.1"},{id:"claude-opus-5-5",displayName:"Claude Opus 5.5"},{id:"claude-sonnet-5-5",displayName:"Claude Sonnet 5.5"},{id:"claude-haiku-5-5",displayName:"Claude Haiku 5.5"},{id:"claude-opus-4-8",displayName:"Claude Opus 4.8"},{id:"claude-opus-4-7",displayName:"Claude Opus 4.7"},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6"}],u=_(w),L=3600*1e3,D=300*1e3,I="oauth-2025-04-20";let t=null,s=0;function S(){const e=m(O(),".claude");return k(m(e,"settings.json"))?.env??{}}function T(e){return!(!e?.accessToken||e.expiresAt&&Date.now()>e.expiresAt-D)}function b(){if(process.platform==="darwin")try{const e=process.env.USER||process.env.LOGNAME||"";if(!e)return null;const n=N("security",["find-generic-password","-s","Claude Code-credentials","-a",e,"-w"],{encoding:"utf-8",timeout:5e3,windowsHide:!0}).trim(),l=JSON.parse(n)?.claudeAiOauth;return T(l)?l.accessToken:(l?.accessToken&&i.info("model-list","Claude OAuth token expired, skipping keychain"),null)}catch{return null}else try{const e=m(O(),".claude",".credentials.json"),a=k(e)?.claudeAiOauth;return T(a)?a.accessToken:(a?.accessToken&&i.info("model-list","Claude OAuth token expired, skipping credentials file"),null)}catch{return null}}async function B(){if(t&&Date.now()-s<L)return t;const e=S(),n=(e.ANTHROPIC_BASE_URL??"").trim()||"https://api.anthropic.com",a=(e.ANTHROPIC_AUTH_TOKEN??"").trim(),l=(e.ANTHROPIC_API_KEY??"").trim();let d=a||l,h=!!a,C=!1;if(!d){const o=b();o&&(d=o,h=!0,C=!0,i.info("model-list","Using Claude CLI OAuth token from Keychain for model list"))}if(!d)return i.info("model-list","No API credentials found, using fallback model list"),t=u,s=Date.now(),t;try{const o=`${n.replace(/\/+$/,"")}/v1/models`,c={"anthropic-version":"2023-06-01"};h?(c.Authorization=`Bearer ${d}`,C&&(c["anthropic-beta"]=I)):c["x-api-key"]=d;const y=new AbortController,E=setTimeout(()=>y.abort(),1e4),p=await fetch(o,{headers:c,signal:y.signal});if(clearTimeout(E),!p.ok)return i.warn("model-list",`API returned ${p.status}, using fallback model list`),t=u,s=Date.now(),t;const f=(await p.json()).data;return!Array.isArray(f)||f.length===0?(i.warn("model-list","API returned empty model list, using fallback"),t=u,s=Date.now(),t):(t=_(f.map(r=>({id:r.id,displayName:r.display_name||r.name||r.id}))),s=Date.now(),i.info("model-list",`Fetched ${t.length} models from API: ${t.map(r=>r.id).join(", ")}`),t)}catch(o){return i.warn("model-list",`Failed to fetch models: ${o instanceof Error?o.message:o}, using fallback`),t=u,s=Date.now(),t}}function K(){return t??u}function R(){t=null,s=0}export{A as CLAUDE_DEFAULT_MODEL_ID,g as CLAUDE_DEFAULT_MODEL_OPTION,B as fetchAvailableModels,K as getCachedModels,S as readSettingsEnv,R as resetModelCache,v as toClaudeCliModelId};
1
+ import{execFileSync as w}from"node:child_process";import{readJSONFile as g}from"../../core/util/json-file.js";import{log as i}from"../../core/log/index.js";import{resolveClaudeConfigPaths as C}from"./config-paths.js";const y="default",I={id:y,displayName:"\u9ED8\u8BA4\uFF08CLI \u81EA\u52A8\u9009\u62E9\uFF09"};function K(e){const t=String(e??"").trim();return t===y?"":t}function E(e){return[I,...e.filter(t=>t.id!==y)]}const D=[{id:"opus",displayName:"Opus"},{id:"sonnet",displayName:"Sonnet"},{id:"haiku",displayName:"Haiku"},{id:"claude-fable-5-1",displayName:"Claude Fable 5.1"},{id:"claude-opus-5-5",displayName:"Claude Opus 5.5"},{id:"claude-sonnet-5-5",displayName:"Claude Sonnet 5.5"},{id:"claude-haiku-5-5",displayName:"Claude Haiku 5.5"},{id:"claude-opus-4-8",displayName:"Claude Opus 4.8"},{id:"claude-opus-4-7",displayName:"Claude Opus 4.7"},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6"}],c=E(D),M=3600*1e3,S=300*1e3,b="oauth-2025-04-20";let r=null,k=0,f="";function x(e=C({})){return g(e.settings)?.env??{}}function N(e){return!(!e?.accessToken||e.expiresAt&&Date.now()>e.expiresAt-S)}function U(e){if(process.platform==="darwin")try{const t=process.env.USER||process.env.LOGNAME||"";if(!t)return null;const o=w("security",["find-generic-password","-s","Claude Code-credentials","-a",t,"-w"],{encoding:"utf-8",timeout:5e3,windowsHide:!0}).trim(),a=JSON.parse(o)?.claudeAiOauth;return N(a)?a.accessToken:(a?.accessToken&&i.info("model-list","Claude OAuth token expired, skipping keychain"),null)}catch{return null}else try{const o=g(e.credentialsJson)?.claudeAiOauth;return N(o)?o.accessToken:(o?.accessToken&&i.info("model-list","Claude OAuth token expired, skipping credentials file"),null)}catch{return null}}async function R(e=C({})){if(r&&f===e.dir&&Date.now()-k<M)return r;const t=x(e),o=(t.ANTHROPIC_BASE_URL??"").trim()||"https://api.anthropic.com",p=(t.ANTHROPIC_AUTH_TOKEN??"").trim(),a=(t.ANTHROPIC_API_KEY??"").trim();let l=p||a,O=!!p,_=!1;const d=n=>(r=n,f=e.dir,k=Date.now(),n);if(!l){const n=U(e);n&&(l=n,O=!0,_=!0,i.info("model-list","Using Claude CLI OAuth token from Keychain for model list"))}if(!l)return i.info("model-list","No API credentials found, using fallback model list"),d(c);try{const n=`${o.replace(/\/+$/,"")}/v1/models`,u={"anthropic-version":"2023-06-01"};O?(u.Authorization=`Bearer ${l}`,_&&(u["anthropic-beta"]=b)):u["x-api-key"]=l;const T=new AbortController,L=setTimeout(()=>T.abort(),1e4),m=await fetch(n,{headers:u,signal:T.signal});if(clearTimeout(L),!m.ok)return i.warn("model-list",`API returned ${m.status}, using fallback model list`),d(c);const A=(await m.json()).data;if(!Array.isArray(A)||A.length===0)return i.warn("model-list","API returned empty model list, using fallback"),d(c);const h=E(A.map(s=>({id:s.id,displayName:s.display_name||s.name||s.id})));return i.info("model-list",`Fetched ${h.length} models from API: ${h.map(s=>s.id).join(", ")}`),d(h)}catch(n){return i.warn("model-list",`Failed to fetch models: ${n instanceof Error?n.message:n}, using fallback`),d(c)}}function $(e=C({})){return r&&f===e.dir?r:c}function J(){r=null,k=0,f=""}export{y as CLAUDE_DEFAULT_MODEL_ID,I as CLAUDE_DEFAULT_MODEL_OPTION,R as fetchAvailableModels,$ as getCachedModels,x as readSettingsEnv,J as resetModelCache,K as toClaudeCliModelId};
@@ -1,2 +1,2 @@
1
- import S from"node:os";import{join as _,resolve as g,sep as x}from"node:path";import{SESSION_HISTORY_ERROR_CODES as m,SessionHistoryError as h,readJsonlHistoryPage as A,registerSessionHistoryReader as j}from"../shared/session-history.js";import{encodeProjectPath as T,resolveSessionJsonlPath as E}from"./usage-parser.js";const k=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,P=new Set(["summary","custom-title","ai-title","file-history-snapshot","queue-operation"]),b=["<local-command-caveat","<command-name","<local-command-stdout"];function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function w(t){const o=t.trimStart();return b.some(s=>o.startsWith(s))}function O(t){if(typeof t=="string")return t;if(Array.isArray(t)){const o=[];for(const s of t)y(s)&&s.type==="text"&&typeof s.text=="string"&&o.push(s.text);return o.join(`
2
- `)}return t==null?"":String(t)}function R(t,o){if(t.isSidechain===!0||t.isMeta===!0)return[];const s=typeof t.type=="string"?t.type:"";if(P.has(s))return[];const a=typeof t.uuid=="string"&&t.uuid?t.uuid:o,f=typeof t.parentUuid=="string"?t.parentUuid:null,u=typeof t.timestamp=="string"?t.timestamp:"",p=y(t.message)?t.message:void 0,c=[];if(s==="user"){const i=p?.content;if(typeof i=="string")c.push({role:"user",content:i,msg_type:"text"});else if(Array.isArray(i))for(const r of i){if(!y(r))continue;const n=r;if(n.type==="text"&&typeof n.text=="string"){if(w(n.text))continue;c.push({role:"user",content:n.text,msg_type:"text"})}else if(n.type==="tool_result"){const e={};typeof n.tool_use_id=="string"&&(e.tool_use_id=n.tool_use_id),n.is_error===!0&&(e.is_error=!0),c.push({role:"tool",content:O(n.content),msg_type:"tool_result",...Object.keys(e).length>0?{extra:e}:{}})}}}else if(s==="assistant"){const i=p?.content,r=typeof p?.model=="string"?p.model:void 0;if(typeof i=="string")c.push({role:"assistant",content:i,msg_type:"text",...r?{extra:{model:r}}:{}});else if(Array.isArray(i))for(const n of i){if(!y(n))continue;const e=n;if(e.type==="text"&&typeof e.text=="string")c.push({role:"assistant",content:e.text,msg_type:"text",...r?{extra:{model:r}}:{}});else if(e.type==="thinking"&&typeof e.thinking=="string")c.push({role:"assistant",content:e.thinking,msg_type:"thinking"});else if(e.type==="tool_use"){const l={};typeof e.name=="string"&&(l.tool_name=e.name),typeof e.id=="string"&&(l.tool_use_id=e.id);let d="{}";try{d=JSON.stringify(e.input??{})}catch{}c.push({role:"assistant",content:d,msg_type:"tool_use",...Object.keys(l).length>0?{extra:l}:{}})}}}else if(s==="system")c.push({role:"system",content:String(t.content??""),msg_type:typeof t.subtype=="string"?t.subtype:"system"});else return[];return c.map((i,r)=>({native_message_id:r===0?a:`${a}#${r}`,native_parent_id:f,created_at:u,...i}))}function v(t,o){if(!k.test(t.agent_session_id))throw new h(m.invalidAgentSession,`invalid agent_session_id: ${t.agent_session_id}`);const s=o?.projectsDir??_(S.homedir(),".claude","projects"),a=o?.projectsDir?_(o.projectsDir,T(t.cwd),`${t.agent_session_id}.jsonl`):E(t.agent_session_id,t.cwd),f=g(s),u=g(a);if(u!==f&&!u.startsWith(f+x))throw new h(m.invalidAgentSession,`transcript path escapes projects dir: ${t.agent_session_id}`);return u}async function D(t,o){const s=v(t,o);return{...await A({filePath:s,cursor:t.cursor,limit:t.limit,mapLine:R,sourceLabel:"claude session transcript",logTag:"claude-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}j("claude",D);export{D as readClaudeSessionHistory};
1
+ import{join as h,resolve as _,sep as S}from"node:path";import{resolveClaudeConfigPaths as x}from"./config-paths.js";import{SESSION_HISTORY_ERROR_CODES as g,SessionHistoryError as m,readJsonlHistoryPage as A,registerSessionHistoryReader as P}from"../shared/session-history.js";import{encodeProjectPath as j,resolveSessionJsonlPath as T}from"./usage-parser.js";const E=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,k=new Set(["summary","custom-title","ai-title","file-history-snapshot","queue-operation"]),b=["<local-command-caveat","<command-name","<local-command-stdout"];function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v(t){const o=t.trimStart();return b.some(s=>o.startsWith(s))}function w(t){if(typeof t=="string")return t;if(Array.isArray(t)){const o=[];for(const s of t)p(s)&&s.type==="text"&&typeof s.text=="string"&&o.push(s.text);return o.join(`
2
+ `)}return t==null?"":String(t)}function C(t,o){if(t.isSidechain===!0||t.isMeta===!0)return[];const s=typeof t.type=="string"?t.type:"";if(k.has(s))return[];const u=typeof t.uuid=="string"&&t.uuid?t.uuid:o,y=typeof t.parentUuid=="string"?t.parentUuid:null,f=typeof t.timestamp=="string"?t.timestamp:"",a=p(t.message)?t.message:void 0,c=[];if(s==="user"){const i=a?.content;if(typeof i=="string")c.push({role:"user",content:i,msg_type:"text"});else if(Array.isArray(i))for(const r of i){if(!p(r))continue;const n=r;if(n.type==="text"&&typeof n.text=="string"){if(v(n.text))continue;c.push({role:"user",content:n.text,msg_type:"text"})}else if(n.type==="tool_result"){const e={};typeof n.tool_use_id=="string"&&(e.tool_use_id=n.tool_use_id),n.is_error===!0&&(e.is_error=!0),c.push({role:"tool",content:w(n.content),msg_type:"tool_result",...Object.keys(e).length>0?{extra:e}:{}})}}}else if(s==="assistant"){const i=a?.content,r=typeof a?.model=="string"?a.model:void 0;if(typeof i=="string")c.push({role:"assistant",content:i,msg_type:"text",...r?{extra:{model:r}}:{}});else if(Array.isArray(i))for(const n of i){if(!p(n))continue;const e=n;if(e.type==="text"&&typeof e.text=="string")c.push({role:"assistant",content:e.text,msg_type:"text",...r?{extra:{model:r}}:{}});else if(e.type==="thinking"&&typeof e.thinking=="string")c.push({role:"assistant",content:e.thinking,msg_type:"thinking"});else if(e.type==="tool_use"){const l={};typeof e.name=="string"&&(l.tool_name=e.name),typeof e.id=="string"&&(l.tool_use_id=e.id);let d="{}";try{d=JSON.stringify(e.input??{})}catch{}c.push({role:"assistant",content:d,msg_type:"tool_use",...Object.keys(l).length>0?{extra:l}:{}})}}}else if(s==="system")c.push({role:"system",content:String(t.content??""),msg_type:typeof t.subtype=="string"?t.subtype:"system"});else return[];return c.map((i,r)=>({native_message_id:r===0?u:`${u}#${r}`,native_parent_id:y,created_at:f,...i}))}function O(t,o){if(!E.test(t.agent_session_id))throw new m(g.invalidAgentSession,`invalid agent_session_id: ${t.agent_session_id}`);const s=o?.claudeConfigPaths??x({}),u=o?.projectsDir??s.projectsDir,y=o?.projectsDir?h(o.projectsDir,j(t.cwd),`${t.agent_session_id}.jsonl`):T(t.agent_session_id,t.cwd,s),f=_(u),a=_(y);if(a!==f&&!a.startsWith(f+S))throw new m(g.invalidAgentSession,`transcript path escapes projects dir: ${t.agent_session_id}`);return a}async function R(t,o){const s=O(t,o);return{...await A({filePath:s,cursor:t.cursor,limit:t.limit,mapLine:C,sourceLabel:"claude session transcript",logTag:"claude-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}P("claude",R);export{R as readClaudeSessionHistory};
@@ -1 +1 @@
1
- import{readdirSync as u,statSync as d}from"node:fs";import l from"node:path";import{homedir as p}from"node:os";import{log as h}from"../../core/log/index.js";import{readFirstLines as y}from"../../core/util/read-first-lines.js";import{makeTitle as f}from"../../core/util/session-title.js";function T(s){const t=s.trim();return t?t.startsWith("<local-command-caveat>")||t.startsWith("<local-command-stdout>")||t.startsWith("<command-name>"):!0}function m(s){if(T(s))return;const t=s.match(/<channel[^>]*>([\s\S]+?)<\/channel>/);if(t){const o=t[1].trim();if(o)return f(o)}return f(s)}function S(s){for(const t of s)try{const o=JSON.parse(t);if(o.type!=="user")continue;const i=o.message?.content;if(typeof i=="string"){const e=m(i);if(e)return e;continue}if(Array.isArray(i)){for(const e of i)if(e.type==="text"&&e.text){const r=m(e.text);if(r)return r}}}catch{}}function j(s){try{const t=d(s),o=y(s,131072);let i="",e="",r="";for(const a of o.slice(0,80))try{const n=JSON.parse(a);if(n.sessionId&&!i&&(i=n.sessionId),n.type==="custom-title"&&n.customTitle&&!n.customTitle.startsWith("grix-")&&(e=n.customTitle),n.type==="ai-title"&&n.aiTitle&&!e&&(e=n.aiTitle),n.cwd&&!r&&(r=n.cwd),i&&e&&r)break}catch{}if(!i)return null;const c=e||S(o);return{sessionId:i,cwd:r||void 0,title:c,mtimeMs:Math.round(t.mtimeMs)}}catch{return null}}function C(s=l.join(p(),".claude","projects")){const t=[];let o;try{o=u(s,{withFileTypes:!0})}catch{return t}for(const i of o){if(!i.isDirectory())continue;const e=l.join(s,i.name);let r;try{r=u(e,{withFileTypes:!0})}catch{continue}for(const c of r){if(!c.isFile()||!c.name.endsWith(".jsonl"))continue;const a=l.join(e,c.name),n=j(a);n&&t.push({sessionId:n.sessionId,cwd:n.cwd||"",title:n.title,updatedAt:n.mtimeMs,filePath:a})}}return t.sort((i,e)=>e.updatedAt-i.updatedAt),h.info("claude-session-scanner",`Scanned ${t.length} Claude sessions from ${s}`),t}export{C as scanClaudeSessions};
1
+ import{readdirSync as l,statSync as d}from"node:fs";import u from"node:path";import{resolveClaudeConfigPaths as p}from"./config-paths.js";import{log as h}from"../../core/log/index.js";import{readFirstLines as y}from"../../core/util/read-first-lines.js";import{makeTitle as f}from"../../core/util/session-title.js";function T(s){const t=s.trim();return t?t.startsWith("<local-command-caveat>")||t.startsWith("<local-command-stdout>")||t.startsWith("<command-name>"):!0}function m(s){if(T(s))return;const t=s.match(/<channel[^>]*>([\s\S]+?)<\/channel>/);if(t){const o=t[1].trim();if(o)return f(o)}return f(s)}function S(s){for(const t of s)try{const o=JSON.parse(t);if(o.type!=="user")continue;const i=o.message?.content;if(typeof i=="string"){const e=m(i);if(e)return e;continue}if(Array.isArray(i)){for(const e of i)if(e.type==="text"&&e.text){const r=m(e.text);if(r)return r}}}catch{}}function C(s){try{const t=d(s),o=y(s,131072);let i="",e="",r="";for(const a of o.slice(0,80))try{const n=JSON.parse(a);if(n.sessionId&&!i&&(i=n.sessionId),n.type==="custom-title"&&n.customTitle&&!n.customTitle.startsWith("grix-")&&(e=n.customTitle),n.type==="ai-title"&&n.aiTitle&&!e&&(e=n.aiTitle),n.cwd&&!r&&(r=n.cwd),i&&e&&r)break}catch{}if(!i)return null;const c=e||S(o);return{sessionId:i,cwd:r||void 0,title:c,mtimeMs:Math.round(t.mtimeMs)}}catch{return null}}function A(s=p({}).projectsDir){const t=[];let o;try{o=l(s,{withFileTypes:!0})}catch{return t}for(const i of o){if(!i.isDirectory())continue;const e=u.join(s,i.name);let r;try{r=l(e,{withFileTypes:!0})}catch{continue}for(const c of r){if(!c.isFile()||!c.name.endsWith(".jsonl"))continue;const a=u.join(e,c.name),n=C(a);n&&t.push({sessionId:n.sessionId,cwd:n.cwd||"",title:n.title,updatedAt:n.mtimeMs,filePath:a})}}return t.sort((i,e)=>e.updatedAt-i.updatedAt),h.info("claude-session-scanner",`Scanned ${t.length} Claude sessions from ${s}`),t}export{A as scanClaudeSessions};
@@ -1,2 +1,2 @@
1
- import{readdirSync as x,readFileSync as j,existsSync as h,statSync as D}from"node:fs";import{dirname as S,join as t,resolve as b}from"node:path";import{homedir as H}from"node:os";import{log as L}from"../../core/log/index.js";import{findGitProjectRoot as w}from"../../core/util/git-project-root.js";const M=".grix-managed";function y(r){const e=r.trim();if(!e.startsWith("---"))return{name:"",description:""};const s=e.indexOf("---",3);if(s===-1)return{name:"",description:""};const c=e.slice(3,s).trim();let n="",l="",o;for(const p of c.split(`
2
- `)){const a=p.indexOf(":");if(a===-1)continue;const m=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)),m==="name"?n=u:m==="description"?l=u:m==="trigger"&&(o=u)}return{name:n,description:l,trigger:o}}function q(r,e,s){if(!h(r))return[];const c=[];try{for(const n of x(r,{withFileTypes:!0})){const l=t(r,n.name);if(!_(n,l)||n.name.startsWith("."))continue;const o=t(l,"SKILL.md");if(h(o))try{const p=j(o,"utf-8"),a=y(p);a.name&&c.push({name:a.name,description:a.description,trigger:a.trigger,source:e,pluginName:s,filePath:o,managed:h(t(l,M))})}catch{}}}catch{}return c}function i(r,e,s){if(!h(r))return[];const c=s?.maxDepth??6,n=s?.includeHiddenDirs??!1,l=[],o=(p,a)=>{if(a>c)return;let m;try{m=x(p,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const u of m){const d=t(p,u.name);if(s?.rootMarkdownFiles&&a===0&&u.name.endsWith(".md")){if(!n&&u.name.startsWith(".")||!F(u,d))continue;try{const g=j(d,"utf-8"),f=y(g);f.name&&l.push({name:f.name,description:f.description,trigger:f.trigger,source:e,pluginName:s?.pluginName,filePath:d})}catch{}continue}if(!_(u,d)||!n&&u.name.startsWith(".")||u.name==="node_modules")continue;const k=t(d,"SKILL.md");if(h(k))try{const g=j(k,"utf-8"),f=y(g);f.name&&l.push({name:f.name,description:f.description,trigger:f.trigger,source:e,pluginName:s?.pluginName,filePath:k,managed:h(t(d,M))})}catch{}o(d,a+1)}};return o(r,0),l}function v(r){return r.map(e=>({...e,managed:!0}))}function _(r,e){if(r.isDirectory())return!0;if(!r.isSymbolicLink())return!1;try{return D(e).isDirectory()}catch{return!1}}function F(r,e){if(r.isFile())return!0;if(!r.isSymbolicLink())return!1;try{return D(e).isFile()}catch{return!1}}function P(r){const e=[],s=new Set;for(const c of r){const n=c.name.trim().toLowerCase();s.has(n)||(s.add(n),e.push(c))}return e}function I(r){const e=r.filePath?.trim();if(!e)return 0;try{const s=D(e).mtimeMs,c=D(S(e)).mtimeMs;return Math.max(s,c)}catch{return 0}}function N(r){return r.map((e,s)=>({entry:e,index:s,timeMs:I(e)})).sort((e,s)=>e.timeMs!==s.timeMs?s.timeMs-e.timeMs:e.index-s.index).map(e=>e.entry)}function A(r){const e=[],s=new Set;let c=b(r);for(;;){s.has(c)||(e.push(c),s.add(c));const n=S(c);if(n===c)break;c=n}return e}function R(r,e){const s=[t(r,".claude","settings.json")];e&&(s.push(t(e,".claude","settings.json")),s.push(t(e,".claude","settings.local.json")));const c=new Map;for(const n of s)if(h(n))try{const o=JSON.parse(j(n,"utf-8"))?.enabledPlugins;if(!o||typeof o!="object")continue;for(const[p,a]of Object.entries(o))typeof a=="boolean"&&c.set(p,a)}catch{}return c}function C(r,e){const s=t(r,".claude","plugins","installed_plugins.json");if(!h(s))return[];const c=[];try{const n=j(s,"utf-8"),o=JSON.parse(n)?.plugins;if(!o||typeof o!="object")return c;const p=R(r,e),a=e?b(e):void 0;for(const[m,u]of Object.entries(o))if(Array.isArray(u)&&p.get(m)===!0)for(const d of u){const k=d?.installPath;if(!k||!h(k))continue;if(d?.scope==="local"){const O=typeof d?.projectPath=="string"?b(d.projectPath):void 0;if(!a||O!==a)continue}const g=t(k,"skills"),f=m.split("@")[0],E=v(q(g,"plugin",f));c.push(...E)}}catch{}return c}function $(r,e){const s=(r??"").trim().toLowerCase(),c=(e??"").trim().toLowerCase();return c==="deveco"?"deveco":s==="claude"?"claude":s==="codex"?"codex":s==="pi"&&c==="omp"?"omp":s==="pi"?"pi":s==="cursor"?"cursor":s==="codewhale"?"codewhale":s==="opencode"?"opencode":s==="agy"?"gemini":s==="openhuman"?"none":s==="deepseek-harness"?"deepseek":c==="kiro"?"kiro":c==="qwen"?"qwen":c==="reasonix"?"reasonix":c==="kimi"?"kimi":c==="hermes"?"hermes":c==="copilot"?"copilot":c==="traecli"?"traecli":c==="codebuddy"?"codebuddy":c==="gemini"?"gemini":c==="grok"||c==="qwenpaw"||c==="zeroclaw"?"none":c==="qodercli"?"qodercli":c==="qoderclicn"?"qoderclicn":c==="mcode"||c==="dim"?"none":"gemini"}function J(r){const e=[],s=r.homeDir??H();switch(r.mode){case"claude":{const n={maxDepth:0};r.projectDir&&e.push(...i(t(r.projectDir,".claude","skills"),"project",n));const l=t(s,".claude","skills");e.push(...i(l,"global",n)),e.push(...C(s,r.projectDir));break}case"codex":{const n=process.env.CODEX_HOME?.trim()||t(s,".codex"),l=r.includeSharedAgentSkills??/^(1|true|yes|on)$/i.test(process.env.GRIX_CODEX_INCLUDE_SHARED_AGENT_SKILLS??"");if(r.projectDir)for(const o of A(r.projectDir))e.push(...i(t(o,".agents","skills"),"project")),e.push(...i(t(o,".codex","skills"),"project"));l&&e.push(...i(t(s,".agents","skills"),"codex")),e.push(...i(t(n,"skills"),"codex")),e.push(...v(i(t(n,"skills",".system"),"codex")));break}case"gemini":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".gemini","skills"),"project",n)),e.push(...i(t(r.projectDir,".agents","skills"),"project",n))),e.push(...i(t(s,".gemini","skills"),"gemini",n)),e.push(...i(t(s,".agents","skills"),"gemini",n));break}case"pi":{r.projectDir&&e.push(...i(t(r.projectDir,".pi","skills"),"project")),e.push(...i(t(s,".pi","agent","skills"),"pi"));break}case"kiro":{r.projectDir&&e.push(...i(t(r.projectDir,".kiro","skills"),"project")),e.push(...i(t(s,".kiro","skills"),"kiro"));break}case"qwen":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".qwen","skills"),"project",n)),e.push(...i(t(r.projectDir,".agents","skills"),"project",n))),e.push(...i(t(s,".qwen","skills"),"global",n)),e.push(...i(t(s,".agents","skills"),"global",n));break}case"cursor":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".agents","skills"),"project",n)),e.push(...i(t(r.projectDir,".cursor","skills"),"project",n))),e.push(...i(t(s,".agents","skills"),"global",n)),e.push(...i(t(s,".cursor","skills"),"global",n));break}case"codewhale":{r.projectDir&&e.push(...i(t(r.projectDir,".codewhale","skills"),"project")),e.push(...i(t(s,".codewhale","skills"),"global"));break}case"opencode":{const n=process.env.XDG_CONFIG_HOME?.trim()||t(s,".config");r.projectDir&&(e.push(...i(t(r.projectDir,".opencode","skills"),"project")),e.push(...i(t(r.projectDir,".opencode","skill"),"project"))),e.push(...i(t(n,"opencode","skills"),"global")),e.push(...i(t(n,"opencode","skill"),"global")),e.push(...i(t(s,".claude","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"deveco":{const n=process.env.XDG_CONFIG_HOME?.trim()||t(s,".config");r.projectDir&&(e.push(...i(t(r.projectDir,".deveco","skills"),"project")),e.push(...i(t(r.projectDir,".deveco","skill"),"project"))),e.push(...i(t(n,"deveco","skills"),"global")),e.push(...i(t(n,"deveco","skill"),"global")),e.push(...i(t(s,".claude","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"reasonix":{e.push(...i(t(s,".reasonix","skills"),"global"));break}case"kimi":{const n=process.env.KIMI_CODE_HOME?.trim()||t(s,".kimi-code"),l={rootMarkdownFiles:!0};if(r.projectDir){const o=w(r.projectDir);e.push(...i(t(o,".kimi-code","skills"),"project",l)),e.push(...i(t(o,".agents","skills"),"project",l))}e.push(...i(t(n,"skills"),"global",l)),e.push(...i(t(s,".agents","skills"),"global",l));break}case"deepseek":{const n=r.env??process.env,l=n.DSH_HOME?.trim()||t(s,".dsh"),o=n.DSH_AGENTS_HOME?.trim()||t(s,".agents"),p={rootMarkdownFiles:!0,maxDepth:0};if(r.projectDir){const a=w(r.projectDir);e.push(...i(t(a,".dsh","skills"),"project",p)),e.push(...i(t(a,".agents","skills"),"project",p))}e.push(...i(t(l,"skills"),"global",p)),e.push(...i(t(o,"skills"),"global",p));break}case"hermes":{const n=r.env??process.env,l=n.HERMES_HOME?.trim()||n.GRIX_HERMES_HOME?.trim()||t(s,".hermes");e.push(...i(t(l,"skills"),"global"));break}case"copilot":{r.projectDir&&(e.push(...i(t(r.projectDir,".github","skills"),"project")),e.push(...i(t(r.projectDir,".claude","skills"),"project")),e.push(...i(t(r.projectDir,".agents","skills"),"project"))),e.push(...i(t(s,".copilot","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"traecli":{r.projectDir&&e.push(...i(t(r.projectDir,".trae","skills"),"project")),e.push(...i(t(s,".trae","skills"),"global"));break}case"omp":{const l=(r.env??process.env).PI_CODING_AGENT_DIR?.trim()||t(s,".omp","agent");r.projectDir&&e.push(...i(t(r.projectDir,".omp","skills"),"project")),e.push(...i(t(l,"skills"),"omp"));break}case"codebuddy":{e.push(...i(t(s,".codebuddy","skills"),"global"));break}case"qodercli":{r.projectDir&&(e.push(...i(t(r.projectDir,".qoder","skills"),"project")),e.push(...i(t(r.projectDir,".agents","skills"),"project"))),e.push(...i(t(s,".qoder","skills"),"global"));break}case"qoderclicn":{r.projectDir&&e.push(...i(t(r.projectDir,".agents","skills"),"project")),e.push(...i(t(s,".qoder-cn","skills"),"global"));break}case"none":break}const c=N(P(e));return L.info("skill-scanner",`Scanned skills: mode=${r.mode} count=${c.length}`),c}export{M as MANAGED_MARKER,P as dedupeSkills,v as markManaged,y as parseSkillFrontmatter,$ as resolveSkillScanMode,i as scanSkillTree,J as scanSkills,N as sortSkillsByRecentTime};
1
+ import{readdirSync as x,readFileSync as j,existsSync as h,statSync as D}from"node:fs";import{dirname as S,join as t,resolve as b}from"node:path";import{homedir as H}from"node:os";import{log as P}from"../../core/log/index.js";import{findGitProjectRoot as w}from"../../core/util/git-project-root.js";import{resolveClaudeConfigPaths as L}from"./config-paths.js";const v=".grix-managed";function y(r){const e=r.trim();if(!e.startsWith("---"))return{name:"",description:""};const s=e.indexOf("---",3);if(s===-1)return{name:"",description:""};const c=e.slice(3,s).trim();let n="",l="",o;for(const p of c.split(`
2
+ `)){const a=p.indexOf(":");if(a===-1)continue;const m=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)),m==="name"?n=u:m==="description"?l=u:m==="trigger"&&(o=u)}return{name:n,description:l,trigger:o}}function q(r,e,s){if(!h(r))return[];const c=[];try{for(const n of x(r,{withFileTypes:!0})){const l=t(r,n.name);if(!_(n,l)||n.name.startsWith("."))continue;const o=t(l,"SKILL.md");if(h(o))try{const p=j(o,"utf-8"),a=y(p);a.name&&c.push({name:a.name,description:a.description,trigger:a.trigger,source:e,pluginName:s,filePath:o,managed:h(t(l,v))})}catch{}}}catch{}return c}function i(r,e,s){if(!h(r))return[];const c=s?.maxDepth??6,n=s?.includeHiddenDirs??!1,l=[],o=(p,a)=>{if(a>c)return;let m;try{m=x(p,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const u of m){const f=t(p,u.name);if(s?.rootMarkdownFiles&&a===0&&u.name.endsWith(".md")){if(!n&&u.name.startsWith(".")||!F(u,f))continue;try{const g=j(f,"utf-8"),d=y(g);d.name&&l.push({name:d.name,description:d.description,trigger:d.trigger,source:e,pluginName:s?.pluginName,filePath:f})}catch{}continue}if(!_(u,f)||!n&&u.name.startsWith(".")||u.name==="node_modules")continue;const k=t(f,"SKILL.md");if(h(k))try{const g=j(k,"utf-8"),d=y(g);d.name&&l.push({name:d.name,description:d.description,trigger:d.trigger,source:e,pluginName:s?.pluginName,filePath:k,managed:h(t(f,v))})}catch{}o(f,a+1)}};return o(r,0),l}function M(r){return r.map(e=>({...e,managed:!0}))}function _(r,e){if(r.isDirectory())return!0;if(!r.isSymbolicLink())return!1;try{return D(e).isDirectory()}catch{return!1}}function F(r,e){if(r.isFile())return!0;if(!r.isSymbolicLink())return!1;try{return D(e).isFile()}catch{return!1}}function C(r){const e=[],s=new Set;for(const c of r){const n=c.name.trim().toLowerCase();s.has(n)||(s.add(n),e.push(c))}return e}function I(r){const e=r.filePath?.trim();if(!e)return 0;try{const s=D(e).mtimeMs,c=D(S(e)).mtimeMs;return Math.max(s,c)}catch{return 0}}function N(r){return r.map((e,s)=>({entry:e,index:s,timeMs:I(e)})).sort((e,s)=>e.timeMs!==s.timeMs?s.timeMs-e.timeMs:e.index-s.index).map(e=>e.entry)}function A(r){const e=[],s=new Set;let c=b(r);for(;;){s.has(c)||(e.push(c),s.add(c));const n=S(c);if(n===c)break;c=n}return e}function R(r,e){const s=[r.settings];e&&(s.push(t(e,".claude","settings.json")),s.push(t(e,".claude","settings.local.json")));const c=new Map;for(const n of s)if(h(n))try{const o=JSON.parse(j(n,"utf-8"))?.enabledPlugins;if(!o||typeof o!="object")continue;for(const[p,a]of Object.entries(o))typeof a=="boolean"&&c.set(p,a)}catch{}return c}function G(r,e){const s=t(r.pluginsDir,"installed_plugins.json");if(!h(s))return[];const c=[];try{const n=j(s,"utf-8"),o=JSON.parse(n)?.plugins;if(!o||typeof o!="object")return c;const p=R(r,e),a=e?b(e):void 0;for(const[m,u]of Object.entries(o))if(Array.isArray(u)&&p.get(m)===!0)for(const f of u){const k=f?.installPath;if(!k||!h(k))continue;if(f?.scope==="local"){const O=typeof f?.projectPath=="string"?b(f.projectPath):void 0;if(!a||O!==a)continue}const g=t(k,"skills"),d=m.split("@")[0],E=M(q(g,"plugin",d));c.push(...E)}}catch{}return c}function z(r,e){const s=(r??"").trim().toLowerCase(),c=(e??"").trim().toLowerCase();return c==="deveco"?"deveco":s==="claude"?"claude":s==="codex"?"codex":s==="pi"&&c==="omp"?"omp":s==="pi"?"pi":s==="cursor"?"cursor":s==="codewhale"?"codewhale":s==="opencode"?"opencode":s==="agy"?"gemini":s==="openhuman"?"none":s==="deepseek-harness"?"deepseek":c==="kiro"?"kiro":c==="qwen"?"qwen":c==="reasonix"?"reasonix":c==="kimi"?"kimi":c==="hermes"?"hermes":c==="copilot"?"copilot":c==="traecli"?"traecli":c==="codebuddy"?"codebuddy":c==="gemini"?"gemini":c==="grok"||c==="qwenpaw"||c==="zeroclaw"?"none":c==="qodercli"?"qodercli":c==="qoderclicn"?"qoderclicn":c==="mcode"||c==="dim"?"none":"gemini"}function B(r){const e=[],s=r.homeDir??H();switch(r.mode){case"claude":{const n={maxDepth:0},l=r.claudeConfigPaths??L(r.env??{},{homeDir:s});r.projectDir&&e.push(...i(t(r.projectDir,".claude","skills"),"project",n)),e.push(...i(l.skillsDir,"global",n)),e.push(...G(l,r.projectDir));break}case"codex":{const n=process.env.CODEX_HOME?.trim()||t(s,".codex"),l=r.includeSharedAgentSkills??/^(1|true|yes|on)$/i.test(process.env.GRIX_CODEX_INCLUDE_SHARED_AGENT_SKILLS??"");if(r.projectDir)for(const o of A(r.projectDir))e.push(...i(t(o,".agents","skills"),"project")),e.push(...i(t(o,".codex","skills"),"project"));l&&e.push(...i(t(s,".agents","skills"),"codex")),e.push(...i(t(n,"skills"),"codex")),e.push(...M(i(t(n,"skills",".system"),"codex")));break}case"gemini":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".gemini","skills"),"project",n)),e.push(...i(t(r.projectDir,".agents","skills"),"project",n))),e.push(...i(t(s,".gemini","skills"),"gemini",n)),e.push(...i(t(s,".agents","skills"),"gemini",n));break}case"pi":{r.projectDir&&e.push(...i(t(r.projectDir,".pi","skills"),"project")),e.push(...i(t(s,".pi","agent","skills"),"pi"));break}case"kiro":{r.projectDir&&e.push(...i(t(r.projectDir,".kiro","skills"),"project")),e.push(...i(t(s,".kiro","skills"),"kiro"));break}case"qwen":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".qwen","skills"),"project",n)),e.push(...i(t(r.projectDir,".agents","skills"),"project",n))),e.push(...i(t(s,".qwen","skills"),"global",n)),e.push(...i(t(s,".agents","skills"),"global",n));break}case"cursor":{const n={maxDepth:0};r.projectDir&&(e.push(...i(t(r.projectDir,".agents","skills"),"project",n)),e.push(...i(t(r.projectDir,".cursor","skills"),"project",n))),e.push(...i(t(s,".agents","skills"),"global",n)),e.push(...i(t(s,".cursor","skills"),"global",n));break}case"codewhale":{r.projectDir&&e.push(...i(t(r.projectDir,".codewhale","skills"),"project")),e.push(...i(t(s,".codewhale","skills"),"global"));break}case"opencode":{const n=process.env.XDG_CONFIG_HOME?.trim()||t(s,".config");r.projectDir&&(e.push(...i(t(r.projectDir,".opencode","skills"),"project")),e.push(...i(t(r.projectDir,".opencode","skill"),"project"))),e.push(...i(t(n,"opencode","skills"),"global")),e.push(...i(t(n,"opencode","skill"),"global")),e.push(...i(t(s,".claude","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"deveco":{const n=process.env.XDG_CONFIG_HOME?.trim()||t(s,".config");r.projectDir&&(e.push(...i(t(r.projectDir,".deveco","skills"),"project")),e.push(...i(t(r.projectDir,".deveco","skill"),"project"))),e.push(...i(t(n,"deveco","skills"),"global")),e.push(...i(t(n,"deveco","skill"),"global")),e.push(...i(t(s,".claude","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"reasonix":{e.push(...i(t(s,".reasonix","skills"),"global"));break}case"kimi":{const n=process.env.KIMI_CODE_HOME?.trim()||t(s,".kimi-code"),l={rootMarkdownFiles:!0};if(r.projectDir){const o=w(r.projectDir);e.push(...i(t(o,".kimi-code","skills"),"project",l)),e.push(...i(t(o,".agents","skills"),"project",l))}e.push(...i(t(n,"skills"),"global",l)),e.push(...i(t(s,".agents","skills"),"global",l));break}case"deepseek":{const n=r.env??process.env,l=n.DSH_HOME?.trim()||t(s,".dsh"),o=n.DSH_AGENTS_HOME?.trim()||t(s,".agents"),p={rootMarkdownFiles:!0,maxDepth:0};if(r.projectDir){const a=w(r.projectDir);e.push(...i(t(a,".dsh","skills"),"project",p)),e.push(...i(t(a,".agents","skills"),"project",p))}e.push(...i(t(l,"skills"),"global",p)),e.push(...i(t(o,"skills"),"global",p));break}case"hermes":{const n=r.env??process.env,l=n.HERMES_HOME?.trim()||n.GRIX_HERMES_HOME?.trim()||t(s,".hermes");e.push(...i(t(l,"skills"),"global"));break}case"copilot":{r.projectDir&&(e.push(...i(t(r.projectDir,".github","skills"),"project")),e.push(...i(t(r.projectDir,".claude","skills"),"project")),e.push(...i(t(r.projectDir,".agents","skills"),"project"))),e.push(...i(t(s,".copilot","skills"),"global")),e.push(...i(t(s,".agents","skills"),"global"));break}case"traecli":{r.projectDir&&e.push(...i(t(r.projectDir,".trae","skills"),"project")),e.push(...i(t(s,".trae","skills"),"global"));break}case"omp":{const l=(r.env??process.env).PI_CODING_AGENT_DIR?.trim()||t(s,".omp","agent");r.projectDir&&e.push(...i(t(r.projectDir,".omp","skills"),"project")),e.push(...i(t(l,"skills"),"omp"));break}case"codebuddy":{e.push(...i(t(s,".codebuddy","skills"),"global"));break}case"qodercli":{r.projectDir&&(e.push(...i(t(r.projectDir,".qoder","skills"),"project")),e.push(...i(t(r.projectDir,".agents","skills"),"project"))),e.push(...i(t(s,".qoder","skills"),"global"));break}case"qoderclicn":{r.projectDir&&e.push(...i(t(r.projectDir,".agents","skills"),"project")),e.push(...i(t(s,".qoder-cn","skills"),"global"));break}case"none":break}const c=N(C(e));return P.info("skill-scanner",`Scanned skills: mode=${r.mode} count=${c.length}`),c}export{v as MANAGED_MARKER,C as dedupeSkills,M as markManaged,y as parseSkillFrontmatter,z as resolveSkillScanMode,i as scanSkillTree,B as scanSkills,N as sortSkillsByRecentTime};
@@ -1,8 +1,8 @@
1
- import{closeSync as F,createReadStream as I,existsSync as M,openSync as v,readdirSync as X,readFileSync as E,readSync as H,realpathSync as q,statSync as N}from"node:fs";import{createInterface as Q}from"node:readline";import b from"node:path";import D from"node:os";import{log as j}from"../../core/log/index.js";function V(t){let e=t;try{e=q(t)}catch{}return e.replace(/[^a-zA-Z0-9]/g,"-")}function Y(t,e){const n=b.join(D.homedir(),".claude"),s=b.join(n,"projects",V(e));return b.join(s,`${t}.jsonl`)}const Z=5e3,J=64,d=new Map;let C=0;const m=new Map;function G(t,e){for(d.delete(t),d.set(t,e);d.size>J;){const n=d.keys().next();if(n.done)break;d.delete(n.value)}}function it(t){t===void 0?(d.clear(),m.clear(),C=0):(d.delete(t),m.delete(t))}function ct(t,e){if(!(!t||!e)&&b.isAbsolute(e)&&b.basename(e)===`${t}.jsonl`&&m.get(t)!==e)for(m.delete(t),m.set(t,e);m.size>J;){const n=m.keys().next();if(n.done)break;m.delete(n.value)}}function K(t){const e=b.join(D.homedir(),".claude","projects"),n=`${t}.jsonl`;let s;try{s=X(e,{withFileTypes:!0})}catch{return null}let o=null;for(const r of s){if(!r.isDirectory())continue;const c=b.join(e,r.name,n);try{const i=N(c);if(!i.isFile()||i.size===0)continue;(!o||i.size>o.size)&&(o={path:c,size:i.size})}catch{}}return o?.path??null}function _(t,e){const n=m.get(t);if(n&&M(n))return n;const s=Y(t,e);if(M(s))return d.delete(t),s;const o=d.get(t);if(o&&M(o))return o;const r=Date.now();if(r-C<Z)return s;C=r;const c=K(t);return G(t,c),c?(j.warn("usage-parser",`Session ${t} transcript drifted off the bound cwd: reading ${c} instead of ${s}`),c):s}function P(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0}}function z(t,e){t.inputTokens+=e.input_tokens??0,t.outputTokens+=e.output_tokens??0,t.cacheReadInputTokens+=e.cache_read_input_tokens??0,t.cacheCreationInputTokens+=e.cache_creation_input_tokens??0}async function at(t,e){const n=_(t,e);j.info("usage-parser",`Parsing session usage from ${n}`);const s=new Map,o=P();let r=0;try{const i=Q({input:I(n,"utf8"),crlfDelay:1/0});for await(const u of i)if(u.trim())try{const f=JSON.parse(u);if(f.type!=="assistant")continue;const a=f.message?.usage;if(!a)continue;const l=f.message?.model??"unknown";r++,z(o,a);let p=s.get(l);p||(p={turns:0,usage:P()},s.set(l,p)),p.turns++,z(p.usage,a)}catch{}}catch(i){return i.code==="ENOENT"?(j.info("usage-parser",`Session JSONL not found: ${n}`),null):(j.error("usage-parser",`Failed to parse session usage: ${i}`),null)}return r===0?null:{models:[...s.entries()].map(([i,u])=>({model:i,turns:u.turns,total:u.usage})),total:o,turns:r}}const x=64*1024,W=9e4,tt=new Set(["No response requested."]);function L(t){return tt.has(t.trim())}function $(t){return t.isApiErrorMessage===!0}function B(t){const e=t.message;return e?.content?(Array.isArray(e.content)?e.content:[{type:"text",text:String(e.content)}]).map(s=>s).filter(s=>s.type==="text"&&s.text?.trim()).map(s=>s.text.trim()).join(`
2
- `):""}function lt(t,e,n){const s=_(t,e);try{const o=E(s);let r;n!==void 0&&n>0?r=n<o.length?o.subarray(n):Buffer.alloc(0):r=o.length>x?o.subarray(o.length-x):o;const c=r.toString("utf8").split(`
3
- `);let i;for(let u=c.length-1;u>=0;u--){const f=c[u].trim();if(!f)continue;let a;try{a=JSON.parse(f)}catch{continue}if(a.type!=="assistant")continue;const l=a.message;if($(a))return{text:"",stopReason:i!==void 0?i:l?.stop_reason??null,apiError:!0,apiErrorText:B(a)};if(!l?.content)continue;const p=Array.isArray(l.content)?l.content:[{type:"text",text:String(l.content)}],y=[];let h=0;for(const S of p){const g=S;if(!(g.type!=="text"||!g.text?.trim())){if(L(g.text)){h++;continue}y.push(g.text)}}if(y.length>0)return{text:y.join(`
4
- `),stopReason:i!==void 0?i:l.stop_reason??null};h>0&&i===void 0&&(i=l.stop_reason??null)}return i!==void 0?{text:"",stopReason:i,metaOnly:!0}:null}catch{return null}}function ut(t,e,n){const s=_(t,e),o=n>0?n:0;let r;try{const c=N(s).size;if(o>=c)return{segments:[],newOffset:o};const i=c-o,u=Buffer.alloc(i);r=v(s,"r");const f=H(r,u,0,i,o),a=u.subarray(0,f);let l=-1;for(let T=a.length-1;T>=0;T--)if(a[T]===10){l=T;break}if(l<0)return{segments:[],newOffset:o};const p=a.subarray(0,l+1),y=o+p.length,h=[];let S=!1,g="";for(const T of p.toString("utf8").split(`
5
- `)){const k=T.trim();if(!k)continue;let A;try{A=JSON.parse(k)}catch{continue}if(A.type!=="assistant")continue;if($(A)){S=!0,g=B(A)||g;continue}const R=A.message;if(!R?.content)continue;const O=Array.isArray(R.content)?R.content:[{type:"text",text:String(R.content)}];for(const U of O){const w=U;w.type!=="text"||!w.text?.trim()||L(w.text)||h.push(w.text)}}return{segments:h,newOffset:y,apiError:S,apiErrorText:g}}catch{return{segments:[],newOffset:o}}finally{if(r!==void 0)try{F(r)}catch{}}}function ft(t,e,n){const s=_(t,e);let o=null,r;try{const u=N(s);o=Date.now()-u.mtimeMs,r=E(s)}catch{return{lastStopReason:null,freshMs:null}}let c;n!==void 0&&n>0?c=n<r.length?r.subarray(n):Buffer.alloc(0):c=r.length>x?r.subarray(r.length-x):r;const i=c.toString("utf8").split(`
6
- `);for(let u=i.length-1;u>=0;u--){const f=i[u].trim();if(!f)continue;let a;try{a=JSON.parse(f)}catch{continue}if(a.type!=="assistant")continue;const l=a.message;if(l)return{lastStopReason:l.stop_reason??null,freshMs:o}}return{lastStopReason:null,freshMs:o}}function pt(t,e){const n=_(t,e);let s;try{s=E(n)}catch{return 0}const r=(s.length>x?s.subarray(s.length-x):s).toString("utf8").split(`
7
- `),c=new Set,i=new Set,u=/<task-id>\s*([^<\s]+)\s*<\/task-id>/;for(const a of r){const l=a.trim();if(!l)continue;if(l.includes("task-notification")){const h=u.exec(l);h&&i.add(h[1]);continue}let p;try{p=JSON.parse(l)}catch{continue}const y=p.toolUseResult;y&&typeof y.backgroundTaskId=="string"&&c.add(y.backgroundTaskId)}let f=0;for(const a of c)i.has(a)||f++;return f}function yt(t,e,n,s=!1){const o=_(t,e);try{const r=N(o);if(s&&Date.now()-r.mtimeMs<W)return!1;const c=E(o),u=(n>0&&n<c.length?c.subarray(n):c.length>x?c.subarray(c.length-x):c).toString("utf8").split(`
8
- `);let f=!1,a=!1;for(const l of u){const p=l.trim();if(!p)continue;let y;try{y=JSON.parse(p)}catch{continue}if(y.type==="user"){const S=y.message?.content??y.content;(Array.isArray(S)?S:[]).some(k=>typeof k=="object"&&k!==null&&k.type==="tool_result")&&(f=!0,a=!1)}else y.type==="assistant"&&f&&(a=!0)}return f&&!a}catch{return!1}}export{it as clearSessionJsonlDriftCache,pt as countPendingBackgroundTasks,V as encodeProjectPath,lt as extractLastAssistantEntry,ut as extractTextBlocksAfterOffset,yt as hasTerminalToolResultAfterOffset,ct as noteSessionJsonlPath,at as parseClaudeSessionUsage,ft as probeSessionTurnState,Y as resolveBoundSessionJsonlPath,_ as resolveSessionJsonlPath};
1
+ import{closeSync as v,createReadStream as K,existsSync as D,openSync as X,readdirSync as q,readFileSync as M,readSync as H,realpathSync as Q,statSync as N}from"node:fs";import{createInterface as V}from"node:readline";import C from"node:path";import{resolveClaudeConfigPaths as g}from"./config-paths.js";import{log as j}from"../../core/log/index.js";function Y(t){let e=t;try{e=Q(t)}catch{}return e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(t,e,n=g({})){return C.join(n.projectsDir,Y(e),`${t}.jsonl`)}const G=5e3,J=64,S=new Map,I=new Map,x=new Map;function P(t,e){return`${e.projectsDir}\0${t}`}function W(t,e){for(S.delete(t),S.set(t,e);S.size>J;){const n=S.keys().next();if(n.done)break;S.delete(n.value)}}function at(t,e=g({})){if(t===void 0){S.clear(),x.clear(),I.clear();return}const n=P(t,e);S.delete(n),x.delete(n)}function lt(t,e,n=g({})){if(!t||!e||!C.isAbsolute(e)||C.basename(e)!==`${t}.jsonl`)return;const o=P(t,n);if(x.get(o)!==e)for(x.delete(o),x.set(o,e);x.size>J;){const r=x.keys().next();if(r.done)break;x.delete(r.value)}}function tt(t,e){const n=`${t}.jsonl`;let o;try{o=q(e,{withFileTypes:!0})}catch{return null}let r=null;for(const s of o){if(!s.isDirectory())continue;const i=C.join(e,s.name,n);try{const c=N(i);if(!c.isFile()||c.size===0)continue;(!r||c.size>r.size)&&(r={path:i,size:c.size})}catch{}}return r?.path??null}function A(t,e,n=g({})){const o=P(t,n),r=x.get(o);if(r&&D(r))return r;const s=Z(t,e,n);if(D(s))return S.delete(o),s;const i=S.get(o);if(i&&D(i))return i;const c=Date.now(),l=I.get(n.projectsDir)??0;if(c-l<G)return s;I.set(n.projectsDir,c);const a=tt(t,n.projectsDir);return W(o,a),a?(j.warn("usage-parser",`Session ${t} transcript drifted off the bound cwd: reading ${a} instead of ${s}`),a):s}function z(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0}}function $(t,e){t.inputTokens+=e.input_tokens??0,t.outputTokens+=e.output_tokens??0,t.cacheReadInputTokens+=e.cache_read_input_tokens??0,t.cacheCreationInputTokens+=e.cache_creation_input_tokens??0}async function ut(t,e,n=g({})){const o=A(t,e,n);j.info("usage-parser",`Parsing session usage from ${o}`);const r=new Map,s=z();let i=0;try{const l=V({input:K(o,"utf8"),crlfDelay:1/0});for await(const a of l)if(a.trim())try{const p=JSON.parse(a);if(p.type!=="assistant")continue;const u=p.message?.usage;if(!u)continue;const f=p.message?.model??"unknown";i++,$(s,u);let y=r.get(f);y||(y={turns:0,usage:z()},r.set(f,y)),y.turns++,$(y.usage,u)}catch{}}catch(l){return l.code==="ENOENT"?(j.info("usage-parser",`Session JSONL not found: ${o}`),null):(j.error("usage-parser",`Failed to parse session usage: ${l}`),null)}return i===0?null:{models:[...r.entries()].map(([l,a])=>({model:l,turns:a.turns,total:a.usage})),total:s,turns:i}}const T=64*1024,et=9e4,nt=new Set(["No response requested."]);function L(t){return nt.has(t.trim())}function B(t){return t.isApiErrorMessage===!0}function O(t){const e=t.message;return e?.content?(Array.isArray(e.content)?e.content:[{type:"text",text:String(e.content)}]).map(o=>o).filter(o=>o.type==="text"&&o.text?.trim()).map(o=>o.text.trim()).join(`
2
+ `):""}function ft(t,e,n,o=g({})){const r=A(t,e,o);try{const s=M(r);let i;n!==void 0&&n>0?i=n<s.length?s.subarray(n):Buffer.alloc(0):i=s.length>T?s.subarray(s.length-T):s;const c=i.toString("utf8").split(`
3
+ `);let l;for(let a=c.length-1;a>=0;a--){const p=c[a].trim();if(!p)continue;let u;try{u=JSON.parse(p)}catch{continue}if(u.type!=="assistant")continue;const f=u.message;if(B(u))return{text:"",stopReason:l!==void 0?l:f?.stop_reason??null,apiError:!0,apiErrorText:O(u)};if(!f?.content)continue;const y=Array.isArray(f.content)?f.content:[{type:"text",text:String(f.content)}],d=[];let h=0;for(const b of y){const m=b;if(!(m.type!=="text"||!m.text?.trim())){if(L(m.text)){h++;continue}d.push(m.text)}}if(d.length>0)return{text:d.join(`
4
+ `),stopReason:l!==void 0?l:f.stop_reason??null};h>0&&l===void 0&&(l=f.stop_reason??null)}return l!==void 0?{text:"",stopReason:l,metaOnly:!0}:null}catch{return null}}function pt(t,e,n,o=g({})){const r=A(t,e,o),s=n>0?n:0;let i;try{const c=N(r).size;if(s>=c)return{segments:[],newOffset:s};const l=c-s,a=Buffer.alloc(l);i=X(r,"r");const p=H(i,a,0,l,s),u=a.subarray(0,p);let f=-1;for(let k=u.length-1;k>=0;k--)if(u[k]===10){f=k;break}if(f<0)return{segments:[],newOffset:s};const y=u.subarray(0,f+1),d=s+y.length,h=[];let b=!1,m="";for(const k of y.toString("utf8").split(`
5
+ `)){const _=k.trim();if(!_)continue;let R;try{R=JSON.parse(_)}catch{continue}if(R.type!=="assistant")continue;if(B(R)){b=!0,m=O(R)||m;continue}const w=R.message;if(!w?.content)continue;const U=Array.isArray(w.content)?w.content:[{type:"text",text:String(w.content)}];for(const F of U){const E=F;E.type!=="text"||!E.text?.trim()||L(E.text)||h.push(E.text)}}return{segments:h,newOffset:d,apiError:b,apiErrorText:m}}catch{return{segments:[],newOffset:s}}finally{if(i!==void 0)try{v(i)}catch{}}}function yt(t,e,n,o=g({})){const r=A(t,e,o);let s=null,i;try{const a=N(r);s=Date.now()-a.mtimeMs,i=M(r)}catch{return{lastStopReason:null,freshMs:null}}let c;n!==void 0&&n>0?c=n<i.length?i.subarray(n):Buffer.alloc(0):c=i.length>T?i.subarray(i.length-T):i;const l=c.toString("utf8").split(`
6
+ `);for(let a=l.length-1;a>=0;a--){const p=l[a].trim();if(!p)continue;let u;try{u=JSON.parse(p)}catch{continue}if(u.type!=="assistant")continue;const f=u.message;if(f)return{lastStopReason:f.stop_reason??null,freshMs:s}}return{lastStopReason:null,freshMs:s}}function dt(t,e,n=g({})){const o=A(t,e,n);let r;try{r=M(o)}catch{return 0}const i=(r.length>T?r.subarray(r.length-T):r).toString("utf8").split(`
7
+ `),c=new Set,l=new Set,a=/<task-id>\s*([^<\s]+)\s*<\/task-id>/;for(const u of i){const f=u.trim();if(!f)continue;if(f.includes("task-notification")){const h=a.exec(f);h&&l.add(h[1]);continue}let y;try{y=JSON.parse(f)}catch{continue}const d=y.toolUseResult;d&&typeof d.backgroundTaskId=="string"&&c.add(d.backgroundTaskId)}let p=0;for(const u of c)l.has(u)||p++;return p}function gt(t,e,n,o=!1,r=g({})){const s=A(t,e,r);try{const i=N(s);if(o&&Date.now()-i.mtimeMs<et)return!1;const c=M(s),a=(n>0&&n<c.length?c.subarray(n):c.length>T?c.subarray(c.length-T):c).toString("utf8").split(`
8
+ `);let p=!1,u=!1;for(const f of a){const y=f.trim();if(!y)continue;let d;try{d=JSON.parse(y)}catch{continue}if(d.type==="user"){const b=d.message?.content??d.content;(Array.isArray(b)?b:[]).some(_=>typeof _=="object"&&_!==null&&_.type==="tool_result")&&(p=!0,u=!1)}else d.type==="assistant"&&p&&(u=!0)}return p&&!u}catch{return!1}}export{at as clearSessionJsonlDriftCache,dt as countPendingBackgroundTasks,Y as encodeProjectPath,ft as extractLastAssistantEntry,pt as extractTextBlocksAfterOffset,gt as hasTerminalToolResultAfterOffset,lt as noteSessionJsonlPath,ut as parseClaudeSessionUsage,yt as probeSessionTurnState,Z as resolveBoundSessionJsonlPath,A as resolveSessionJsonlPath};
@@ -1,4 +1,4 @@
1
- import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{collapseHostedOpenCodeModels as te,normalizeOCProviderModels as se,preferredHostedOpenCodeProvider as ie}from"./opencode-types.js";import{buildOpencodeConfigContent as ne}from"./opencode-config.js";import{agentIdOf as oe}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as re,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class ae extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const de=200,ce=2e3,le=12e4,he=90*1e3,M=1800*1e3,O=3e4,k=600*1e3,pe="claude_interaction_reply",ue="set_mode",fe="set_model",me="127.0.0.1",ve=0,ge=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],Ie=[{permission:"*",pattern:"*",action:"allow"}],we=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function _(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Ue extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new re;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??me,s=this.options.port??ve,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",o=>this.handleSseEvent(o)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const n=this.getMcpConfig();await this.transport.configureMcp(n.name,[n.command,...n.args??[]]);try{await this.refreshModels()}catch(o){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${o instanceof Error?o.message:String(o)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const r of s)for(const d of se(r.models)){t.push({id:`${r.id}/${d.id}`,displayName:d.name||d.id});const c=d.limit?.context;typeof c=="number"&&c>0&&i.set(`${r.id}/${d.id}`,c)}const n=te(t,ie(this.options.model)),o=new Set(n.map(r=>r.id));for(const r of i.keys())o.has(r)||i.delete(r);n.sort((r,d)=>{const c=r.displayName.toLowerCase().localeCompare(d.displayName.toLowerCase());return c!==0?c:r.id.localeCompare(d.id)}),this.availableModels=n,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${n.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=null)}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),a.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new ae(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e),o=this.activeRun,r=this.runBarrier.then(async()=>{if(o.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,n,o)});o.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===o&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&(this.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,n,o)=>this.callbacks.agentInvoke(t,i,o)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[e]}}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ue)return this.handleSetModeAction(e);if(s===fe)return this.handleSetModelAction(e);if(s===pe){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(a.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){a.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=_(this.options.permissionPolicy);if(s)return s;if(e){const t=_(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const n=this.resolveModeId(e),o=n===v.fullAuto?Ie:we;try{await this.transport.updateSessionPermission(s,o,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${n}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=_(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};const n=this.sessionModes.get(t);this.sessionModes.set(t,i);const o=this.sessions.get(t);if(o?.ocSessionId)try{await this.applySessionPermission(t,o.ocSessionId,o.cwd)}catch(d){throw n?this.sessionModes.set(t,n):this.sessionModes.delete(t),d}const r=o?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:$.map(d=>({...d}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):o}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",n=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((o,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=ne({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(oe(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(n,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,o(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const n=this.options.bindingStore?.getAcpSessionId(e);if(n)try{return await this.transport.getSession(n,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${n} for aibot=${e}`),await this.applySessionPermission(e,n,i,s),n}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${n} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,o.id),a.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),await this.applySessionPermission(e,o.id,i,s),o.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const n=this.getSessionCwd(e),o=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=o,this.activeRun.cwd=n);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(o,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},n,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(n=>n.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const n=this.auditCaptures.get(this.activeRun.eventId);n&&n.push({sequence:n.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const n=e.part,o=e.delta;if(n.type==="text"){const r=o!==void 0?o:n.text;r&&this.acceptAssistantPartText(n.messageID,"text",r)}else n.type==="reasoning"?o&&this.acceptAssistantPartText(n.messageID,"reasoning",o):n.type==="tool"&&this.handleToolPartUpdate(n,o);break}case"message.updated":{if(!this.activeRun)break;const n=e.info;if(this.rememberMessageRole(n),n.role==="assistant"){const o=n;typeof o.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,o.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,o.providerID,o.modelID,o.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:o.providerID,model_id:o.modelID,...r??{}}),o.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(o.error)}`);const d=this.activeRun.ocSessionId;d&&o.sessionID===d&&(o.error?(this.flushTextBuffer(),this.finishRun("failed",P(o.error,o.error.type||"unknown error"))):!e.nativeEvent&&o.time?.completed&&o.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const n=P(e.error);a.error("opencode-adapter",`Session error: ${n}`),this.flushTextBuffer(),this.finishRun("failed",n);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":{const n=this.pendingPermissions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const n=this.pendingQuestions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{a.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:a.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),k);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(n=>{a.warn("opencode-adapter",`Permission response failed: ${n}`),this.onInteractionFailure(n,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(o=>{a.warn("opencode-adapter",`Orphan question reject failed: ${o}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const n=setTimeout(()=>this.onQuestionTimeout(e.id),k);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:n}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(o=>({header:o.header,prompt:o.question,...o.options.length>0?{options:o.options.map(r=>r.label)}:{},...o.multiple!==void 0?{multi_select:o.multiple}:{},...o.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+k});else{const o=e.questions.map(r=>r.question).join(`
1
+ import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{collapseHostedOpenCodeModels as te,normalizeOCProviderModels as se,preferredHostedOpenCodeProvider as ie}from"./opencode-types.js";import{buildOpencodeConfigContent as ne}from"./opencode-config.js";import{agentIdOf as oe}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as re,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class ae extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const de=200,ce=2e3,le=12e4,he=90*1e3,M=1800*1e3,O=3e4,k=600*1e3,pe="claude_interaction_reply",ue="set_mode",fe="set_model",me="127.0.0.1",ve=0,ge=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],Ie=[{permission:"*",pattern:"*",action:"allow"}],we=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function _(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Ue extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new re;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??me,s=this.options.port??ve,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",o=>this.handleSseEvent(o)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const n=this.getMcpConfig();await this.transport.configureMcp(n.name,[n.command,...n.args??[]]);try{await this.refreshModels()}catch(o){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${o instanceof Error?o.message:String(o)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const r of s)for(const d of se(r.models)){t.push({id:`${r.id}/${d.id}`,displayName:d.name||d.id});const c=d.limit?.context;typeof c=="number"&&c>0&&i.set(`${r.id}/${d.id}`,c)}const n=te(t,ie(this.options.model)),o=new Set(n.map(r=>r.id));for(const r of i.keys())o.has(r)||i.delete(r);n.sort((r,d)=>{const c=r.displayName.toLowerCase().localeCompare(d.displayName.toLowerCase());return c!==0?c:r.id.localeCompare(d.id)}),this.availableModels=n,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${n.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=null)}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),a.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new ae(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e),o=this.activeRun,r=this.runBarrier.then(async()=>{if(o.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,n,o)});o.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===o&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&(this.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,n,o)=>this.callbacks.agentInvoke(t,i,o)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[e]}}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ue)return this.handleSetModeAction(e);if(s===fe)return this.handleSetModelAction(e);if(s===pe){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(a.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){a.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=_(this.options.permissionPolicy);if(s)return s;if(e){const t=_(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const n=this.resolveModeId(e),o=n===v.fullAuto?Ie:we;try{await this.transport.updateSessionPermission(s,o,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${n}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=_(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};const n=this.sessionModes.get(t);this.sessionModes.set(t,i);const o=this.sessions.get(t);if(o?.ocSessionId)try{await this.applySessionPermission(t,o.ocSessionId,o.cwd)}catch(d){throw n?this.sessionModes.set(t,n):this.sessionModes.delete(t),d}const r=o?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:$.map(d=>({...d}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):o}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",n=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((o,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=ne({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(oe(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(n,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,o(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const n=this.options.bindingStore?.getAcpSessionId(e);if(n)try{return await this.transport.getSession(n,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${n} for aibot=${e}`),await this.applySessionPermission(e,n,i,s),n}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${n} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,o.id),a.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),await this.applySessionPermission(e,o.id,i,s),o.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const n=this.getSessionCwd(e),o=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=o,this.activeRun.cwd=n);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(o,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},n,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(n=>n.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer()),this.activeRun){const n=this.auditCaptures.get(this.activeRun.eventId);n&&n.push({sequence:n.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const n=e.part,o=e.delta;if(n.type==="text"){const r=o!==void 0?o:n.text;r&&this.acceptAssistantPartText(n.messageID,"text",r)}else n.type==="reasoning"?o&&this.acceptAssistantPartText(n.messageID,"reasoning",o):n.type==="tool"&&this.handleToolPartUpdate(n,o);break}case"message.updated":{if(!this.activeRun)break;const n=e.info;if(this.rememberMessageRole(n),n.role==="assistant"){const o=n;typeof o.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,o.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,o.providerID,o.modelID,o.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:o.providerID,model_id:o.modelID,...r??{}}),o.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(o.error)}`);const d=this.activeRun.ocSessionId;d&&o.sessionID===d&&(o.error?(this.flushTextBuffer(),this.finishRun("failed",P(o.error,o.error.type||"unknown error"))):!e.nativeEvent&&o.time?.completed&&o.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const n=P(e.error);a.error("opencode-adapter",`Session error: ${n}`),this.flushTextBuffer(),this.finishRun("failed",n);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":{const n=this.pendingPermissions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const n=this.pendingQuestions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{a.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:a.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),k);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(n=>{a.warn("opencode-adapter",`Permission response failed: ${n}`),this.onInteractionFailure(n,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(o=>{a.warn("opencode-adapter",`Orphan question reject failed: ${o}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const n=setTimeout(()=>this.onQuestionTimeout(e.id),k);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:n}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(o=>({header:o.header,prompt:o.question,...o.options.length>0?{options:o.options.map(r=>r.label)}:{},...o.multiple!==void 0?{multi_select:o.multiple}:{},...o.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+k});else{const o=e.questions.map(r=>r.question).join(`
2
2
  `);this.callbacks.sendRunError(s,t,`Agent asks: ${o}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},n=String(i.type??""),o=(c,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),c().then(()=>{this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(p=>{a.warn("opencode-adapter",`Question response failed: ${p}`),this.onInteractionFailure(p,t.eventId)}),{delivered:!0,result:l});if(n==="action"){const c=String(i.value??"");if(c==="cancel"||c==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let r=null;if(Array.isArray(e.answers))r=e.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(n==="text"){const c=String(i.value??"");c&&(r=t.questions.map((l,p)=>p===0?[c]:[]))}else if(n==="map"){const c=Array.isArray(i.entries)?i.entries:[];r=t.questions.map((l,p)=>{const u=c.find(h=>h.key===l.header||h.key===String(p+1));return u&&u.value?[u.value]:[]}),r.every(l=>l.length===0)&&c.length>0&&(r=t.questions.map((l,p)=>{const u=c[p]?.value;return u?[String(u)]:[]}))}if(!r||r.every(c=>c.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const d=r;return o(()=>this.transport.replyQuestion(t.requestId,d,t.cwd),{request_id:s,resolution:"answer"})}onInteractionFailure(e,s){this.activeRun?.eventId===s&&(this.transport.protocol==="v2"?this.finishRun("failed",e instanceof Error?e.message:"OpenCode interaction failed"):this.resetIdleTimer())}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}cancelRun(e){if(e.controller?.abort(),e.cancelTask||this.stopped)return;const s=(e.promptTask??Promise.resolve()).catch(()=>{}).then(async()=>{!this.stopped&&e.ocSessionId&&await this.transport.abortSession(e.ocSessionId,e.cwd)});e.cancelTask=s,this.runBarrier=s,s.catch(t=>{if(this.stopped)return;this.cancellationFailure=new Error("OpenCode cancellation not confirmed; replace adapter before sending more prompts"),a.warn("opencode-adapter",`OpenCode cancellation not confirmed: ${t}`),this.alive=!1,(this.activeRun?.promptTask??Promise.resolve()).catch(()=>{}).then(()=>this.stop()).then(()=>this.emit("exit",-1)).catch(()=>{})})}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null,controller:new AbortController},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(e==="responded"?t.controller?.abort():this.cancelRun(t),this.completedEvents.add(t.eventId),this.completedEvents.size>ge){const d=[...this.completedEvents].slice(-500);this.completedEvents=new Set(d)}this.snapshotAuditBoundary(t),t.flushTimer&&clearTimeout(t.flushTimer),t.flushTimer=null,this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,n=t.clientMsgId,o=e==="failed"&&!!s;o&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(d=>{const c=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${d instanceof Error?d.message:String(d)}`:s,p=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,c,l,void 0,p)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,n),this.callbacks.sendEventResult(t.eventId,e,s,void 0,o))};if(t.textBuffer){this.stopTextFlush();for(const d of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,d,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun&&this.cancelRun(this.activeRun),this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ce){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},de))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!D(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<he)return this.livenessExtendStartAt=s,a.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),s-n>M?(a.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(a.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.activeRun;this.idleTimer=setTimeout(()=>{if(this.stopped||this.activeRun!==e)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){a.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const s=this.process?.pid,i=!!(this.alive&&s&&D(s))?`liveness budget exhausted after ${M/6e4}min`:"process not alive";a.error("opencode-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${i}`),this.clearRun()),this.emit("exit",-1)},le)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
3
3
  `);s=`${s}
4
4
 
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.17.0",
4
- "tarball": "grix-dsh-bridge-4.17.0.tgz",
3
+ "bridgeVersion": "4.18.1",
4
+ "tarball": "grix-dsh-bridge-4.18.1.tgz",
5
5
  "size": 24211,
6
6
  "unpackedSize": 96662,
7
- "shasum": "464f396147e4945666a0c5705db12d4ec179560c",
8
- "integrity": "sha512-bVB9xWXQNvwpwDbW76iPQEQHfS1XK+czkRQ9PXnOM4Qmf5kTJRLFel8OaYwUpSZiCtXYV/N489YE1Nb99nY7sQ=="
7
+ "shasum": "d8c2a168ef773e4da9763f34f9bb52b40f3be892",
8
+ "integrity": "sha512-ZDgXMvdYTfStWi4OzJ0jZrpH1TqpcronvrUXo3CP0+k3DEGO/nhi6bBXMC068ms9Rw9/0ckWdUJBZJ8Ox1qs5g=="
9
9
  }