grix-connector 4.18.0 → 4.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/adapter/claude/claude-adapter.js +22 -22
  2. package/dist/adapter/claude/config-paths.js +1 -0
  3. package/dist/adapter/claude/model-list.js +1 -1
  4. package/dist/adapter/claude/session-history.js +2 -2
  5. package/dist/adapter/claude/session-scanner.js +1 -1
  6. package/dist/adapter/claude/skill-scanner.js +2 -2
  7. package/dist/adapter/claude/usage-parser.js +8 -8
  8. package/dist/adapter/deepseek-harness/dsh-version.js +1 -1
  9. package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
  10. package/dist/adapter/opencode/opencode-transport.js +1 -1
  11. package/dist/adapter/opencode/opencode-v2-events.js +1 -1
  12. package/dist/adapter/pi/pi-adapter.js +4 -4
  13. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
  14. package/dist/assets/dsh-bridge/manifest.json +6 -6
  15. package/dist/bridge/bridge.js +2 -2
  16. package/dist/bridge/cli-install-flow.js +1 -1
  17. package/dist/bridge/cli-install-offer.js +1 -1
  18. package/dist/bridge/local-action-session-control.js +1 -1
  19. package/dist/bridge/provider-quota.js +1 -1
  20. package/dist/bridge/session-control-open.js +1 -1
  21. package/dist/bridge/session-control-router.js +2 -2
  22. package/dist/bridge/session-list.js +2 -2
  23. package/dist/bridge/session-scan-cache.js +1 -1
  24. package/dist/bridge/session-usage.js +1 -1
  25. package/dist/bridge/skill-actions.js +1 -1
  26. package/dist/bridge/toolbar-meta.js +1 -1
  27. package/dist/core/config/index.js +1 -1
  28. package/dist/core/config/paths.js +1 -1
  29. package/dist/core/mcp/tools.js +1 -1
  30. package/dist/core/skill-sync/enable-roots.js +1 -1
  31. package/dist/core/skill-sync/library-skills.js +1 -1
  32. package/dist/core/skill-sync/skill-enable.js +1 -1
  33. package/dist/default-skills/grix-chat-state/SKILL.md +34 -2
  34. package/dist/manager.js +1 -1
  35. package/dist/mcp/stream-http/security.js +1 -1
  36. package/openclaw-plugin/audit-recorder-worker.js +52 -52
  37. package/openclaw-plugin/index.js +164 -65
  38. package/openclaw-plugin/skills/grix-chat-state/SKILL.md +33 -1
  39. package/openclaw.plugin.json +1 -0
  40. package/package.json +1 -1
  41. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.18.0.tgz +0 -0
@@ -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 +1 @@
1
- function d(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(t??"").trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),...e[4]?{prerelease:e[4]}:{}}:null}function a(t,e){const r=d(t),n=d(e);return!r||!n?null:r.major-n.major||r.minor-n.minor||r.patch-n.patch||f(r.prerelease,n.prerelease)}function f(t,e){if(t===e)return 0;if(t===void 0)return 1;if(e===void 0)return-1;const r=t.split("."),n=e.split(".");for(let s=0;s<Math.max(r.length,n.length);s+=1){const i=r[s],u=n[s];if(i===u)continue;if(i===void 0)return-1;if(u===void 0)return 1;const o=/^\d+$/.test(i),c=/^\d+$/.test(u);return o&&c?Number(i)-Number(u):o!==c?o?-1:1:i<u?-1:1}return 0}export{a as compareDshVersions,d as parseDshVersion};
1
+ function u(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(t??"").trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),...e[4]?{prerelease:e[4]}:{}}:null}function d(t,e){const r=u(t),n=u(e);return!r||!n?null:r.major-n.major||r.minor-n.minor||r.patch-n.patch||a(r.prerelease,n.prerelease)}function f(t,e){const r=u(t),n=u(e);return!r||!n?String(t??"").trim()===String(e??"").trim():r.major===n.major&&r.minor===n.minor}function a(t,e){if(t===e)return 0;if(t===void 0)return 1;if(e===void 0)return-1;const r=t.split("."),n=e.split(".");for(let s=0;s<Math.max(r.length,n.length);s+=1){const i=r[s],o=n[s];if(i===o)continue;if(i===void 0)return-1;if(o===void 0)return 1;const c=/^\d+$/.test(i),m=/^\d+$/.test(o);return c&&m?Number(i)-Number(o):c!==m?c?-1:1:i<o?-1:1}return 0}export{d as compareDshVersions,f as isSameDshVersionLine,u as parseDshVersion};
@@ -1,3 +1,3 @@
1
- import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{isDshBridgedGrixTool as z}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as G,GRIX_DSH_PROTOCOL_MAX as C,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as U,selectDshBridgeEndpoint as L}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as F,normalizeDshPresets as K,normalizeDshProviders as V,resolveDshAgentPreset as X,resolveDshProviderId as J}from"./toolbar-state.js";import{effectiveDshReasoningEffort as W}from"./types.js";const Z=T(),N=5e3,k=1e4,Q=6e4;class Y extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,a)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:a});return}this.deliverNotification(o,a)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},m(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},m(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},m(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class ht{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=U({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=L(t);if(e.protocolMax<M||e.protocolMin>C)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});const c=q(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await tt(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new G(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,l)=>{const n=l&&typeof l=="object"?l:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const d=String(n.tool??"").trim(),b=n.args&&typeof n.args=="object"?n.args:{};if(!d)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!z(d))throw Object.assign(new Error(`grix tool "${d}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(d,b,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const a=T(),g=H("sha256",c).update(`${a}
1
+ import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{isSameDshVersionLine as z}from"./dsh-version.js";import{isDshBridgedGrixTool as G}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as U,GRIX_DSH_PROTOCOL_MAX as C,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as L,selectDshBridgeEndpoint as V}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as F,normalizeDshPresets as K,normalizeDshProviders as X,resolveDshAgentPreset as J,resolveDshProviderId as W}from"./toolbar-state.js";import{effectiveDshReasoningEffort as Z}from"./types.js";const Q=T(),N=5e3,S=1e4,Y=6e4;class tt extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,a)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:a});return}this.deliverNotification(o,a)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},f(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},f(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},f(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class mt{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=L({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=V(t);if(e.protocolMax<M||e.protocolMin>C)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});const c=q(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await et(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new U(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,l)=>{const n=l&&typeof l=="object"?l:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const d=String(n.tool??"").trim(),b=n.args&&typeof n.args=="object"?n.args:{};if(!d)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!G(d))throw Object.assign(new Error(`grix tool "${d}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(d,b,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const a=T(),g=H("sha256",c).update(`${a}
2
2
  ${t.profileKey}
3
- ${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},S=String(B.dshVersion??"");if(S!==e.dshVersion)throw o.close(new Error("DSH Profile version changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${S||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,p=String(this.options.settings.providerId??"").trim();let u=[],_=!1;const x=this.options.catalogRefreshAttempts??8;for(let i=0;i<=x;i++){try{const l=AbortSignal.timeout(this.options.catalogTimeoutMs??k),n=await o.call("profile/listProviders",{},l),d=V(n.providers);if(_=!0,d.length>0&&(u=d),!p||u.some(b=>b.id===p))break}catch{break}i<x&&await new Promise(l=>setTimeout(l,150))}const w=_&&p==="grix"&&!u.some(i=>i.id===p)?p:J(p||void 0,u);let f;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listModels",{provider:w},i);f=Array.isArray(l.models)?l.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const P=(f??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(f?.[0]?.id??this.options.settings.modelId);let v=[...F];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listPresets",{},i),n=K(l.presets);n.length>0&&(v=n)}catch{}const A=X(this.options.settings.agentPreset,v);this.client=new Y(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Q);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,reasoningEffort:W(this.options.settings),...w==="codex-app-server"?{}:{maxTokens:this.options.settings.maxTokens},modeId:this.options.settings.modeId,agentPreset:A,pluginIds:this.options.settings.pluginIds??[],...E?{skillIds:y,skillIdsExplicit:!0}:{},...E&&this.options.skillsDir?{skillsDir:this.options.skillsDir}:{},...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const D=r.serverInfo&&typeof r.serverInfo=="object"?r.serverInfo:{};return{serverInfo:{name:String(D.name??"grix-dsh-profile-bridge"),version:String(D.version??"unknown")},profile:r.profile,capabilities:r.capabilities,...f!==void 0?{models:f}:{},selectedModel:P,providers:u,selectedProvider:w,presets:v,selectedPreset:A}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function m(h,t){return h??AbortSignal.timeout(t)}function tt(h,t){return new Promise((e,c)=>{const s=$(h),o=setTimeout(()=>{a(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const a=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{a(),s.setNoDelay(!0),e(s)},I=r=>{a(),c(Object.assign(r,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{k as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Q as BRIDGE_SESSION_CREATE_TIMEOUT_MS,ht as DshProfileRuntime,Y as DshProfileRuntimeClient};
3
+ ${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Q},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},k=String(B.dshVersion??"");if(!z(e.dshVersion,k))throw o.close(new Error("DSH Profile version line changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${k||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,p=String(this.options.settings.providerId??"").trim();let u=[],_=!1;const x=this.options.catalogRefreshAttempts??8;for(let i=0;i<=x;i++){try{const l=AbortSignal.timeout(this.options.catalogTimeoutMs??S),n=await o.call("profile/listProviders",{},l),d=X(n.providers);if(_=!0,d.length>0&&(u=d),!p||u.some(b=>b.id===p))break}catch{break}i<x&&await new Promise(l=>setTimeout(l,150))}const w=_&&p==="grix"&&!u.some(i=>i.id===p)?p:W(p||void 0,u);let m;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??S),l=await o.call("profile/listModels",{provider:w},i);m=Array.isArray(l.models)?l.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const P=(m??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(m?.[0]?.id??this.options.settings.modelId);let v=[...F];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??S),l=await o.call("profile/listPresets",{},i),n=K(l.presets);n.length>0&&(v=n)}catch{}const D=J(this.options.settings.agentPreset,v);this.client=new tt(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Y);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,reasoningEffort:Z(this.options.settings),...w==="codex-app-server"?{}:{maxTokens:this.options.settings.maxTokens},modeId:this.options.settings.modeId,agentPreset:D,pluginIds:this.options.settings.pluginIds??[],...E?{skillIds:y,skillIdsExplicit:!0}:{},...E&&this.options.skillsDir?{skillsDir:this.options.skillsDir}:{},...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const A=r.serverInfo&&typeof r.serverInfo=="object"?r.serverInfo:{};return{serverInfo:{name:String(A.name??"grix-dsh-profile-bridge"),version:String(A.version??"unknown")},profile:r.profile,capabilities:r.capabilities,...m!==void 0?{models:m}:{},selectedModel:P,providers:u,selectedProvider:w,presets:v,selectedPreset:D}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function f(h,t){return h??AbortSignal.timeout(t)}function et(h,t){return new Promise((e,c)=>{const s=$(h),o=setTimeout(()=>{a(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const a=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{a(),s.setNoDelay(!0),e(s)},I=r=>{a(),c(Object.assign(r,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{S as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Y as BRIDGE_SESSION_CREATE_TIMEOUT_MS,mt as DshProfileRuntime,tt as DshProfileRuntimeClient};
@@ -4,5 +4,5 @@ import{EventEmitter as I}from"node:events";import{randomUUID as P}from"node:cryp
4
4
 
5
5
  `))>=0;){const d=o.slice(0,a);if(o=o.slice(a+2),t!==this.sseGeneration||r.aborted)return;const f=this.parseSseFrame(d);for(const u of f)try{this.emit("event",u)}catch{}}}}catch{}finally{try{await e.cancel()}catch{}e.releaseLock()}if(!(this.closed||r.aborted||t!==this.sseGeneration)){this.sseConnected=!1,Date.now()-n>=5e3&&(this.reconnectAttempts=0);try{this.emit("stream-lost")}catch{}this.v2Events.clear(),this.reconnectSse(t,r)}}parseSseFrame(e){let t="";const r=[];for(const o of e.split(`
6
6
  `))o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("data:")&&r.push(o.slice(5).trimStart());if(!r.length)return[];if(t==="effect/http-api/stream/failure")throw new Error("OpenCode SSE source failure");let s;try{s=JSON.parse(r.join(`
7
- `))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){if(h(s.location)&&s.location.directory&&this.directory&&s.location.directory!==this.directory)return[];const o=s.data?.sessionID??s.data?.form?.sessionID,n=this.runWindows.get(o);return n&&!this.acceptRunEvent(s,n)?[]:this.v2Events.normalize(s).map(i=>n?{...i,runId:n.runId}:i)}if(h(s.properties)){const{properties:o,...n}=s;return[{...n,...o,type:s.type}]}return[s]}acceptRunEvent(e,t){if(t.canceled||t.signal?.aborted)return!1;const r=e.durable?.seq;if(e.type==="session.inbox.enqueued"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox admission requires durable sequence");return t.enqueuedSeq=r,!0}if(e.type==="session.inbox.delivered"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox delivery requires durable sequence");return t.deliveredSeq=r,!0}if(e.type==="session.execution.started"&&t.enqueuedSeq!==void 0&&Number.isSafeInteger(r)&&r>t.enqueuedSeq)return t.executionSeq=r,!0;const s=t.deliveredSeq??t.executionSeq;if(s===void 0||Number.isSafeInteger(r)&&r<=s)return!1;const o=/^session\.execution\.(succeeded|failed|interrupted)$/.test(e.type);if(o&&!Number.isSafeInteger(r))throw new Error("OpenCode V2 execution terminal requires durable sequence");if(t.deliveredSeq===void 0){if(e.type==="session.execution.succeeded")throw new Error("OpenCode V2 execution ended before own inbox delivery");return o}const n=e.data.assistantMessageID;return e.type==="session.step.started"&&t.messages.add(n),!(n&&!t.messages.has(n))}async reconnectSse(e,t){for(;this.reconnectAttempts<x;){const r=this.reconnectAttempts++;try{if(await b(Math.min(q*2**r,D),t),this.closed||t.aborted||e!==this.sseGeneration)return;await this.subscribeEvents(e,t);return}catch(s){if(this.closed||t.aborted||e!==this.sseGeneration)return;if(s instanceof l&&(s.status===401||s.status===403))break}}if(!this.closed&&e===this.sseGeneration)try{this.emit("stream-unavailable")}catch{}}url(e,t=""){const r=new URL(e,this.baseUrl);return t&&r.searchParams.set(this.protocol==="v2"?"location[directory]":"directory",t),r}async request(e,t,r,s){if(this.closed)throw new Error(`OpenCode REST ${e} ${t}: transport closed`);s?.signal?.throwIfAborted();const o=this.url(t,s?.scoped===!1?"":s?.directory??this.directory),n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0}),this.requests.add(n);const c=setTimeout(()=>n.abort(),s?.timeoutMs??v);let a;try{const d=await fetch(o,{method:e,headers:{...this.headers,Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:n.signal,redirect:"error"});if(a=d.status,d.status===204&&s?.response==="empty")return;const f=/^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(d.headers.get("content-type")??""),u=d.body?.getReader(),E=[];let m=0;try{if(u)for(;;){const{done:g,value:C}=await u.read();if(g||(m+=C.byteLength,m>(d.ok?y:4096)))break;E.push(C)}}finally{u&&(await u.cancel(),u.releaseLock())}const O=Buffer.concat(E).toString("utf8");let S,w=m?f?"invalid JSON response":"non-JSON response":"empty response";if(f&&m<=y)try{S=JSON.parse(O),w="JSON response"}catch{}if(!d.ok||w!=="JSON response"||s?.response==="empty"||m>y)throw new l(e,t,d.status,m>y?"response too large":d.ok&&s?.response==="empty"?"expected HTTP 204":w);return S}catch(d){throw d instanceof l?d:a!==void 0?new l(e,t,a,"response read failed or canceled"):new Error(`OpenCode REST ${e} ${t}: request failed or canceled`)}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",i),this.requests.delete(n)}}sessionPath(e){return`${this.protocol==="v2"?"/api":""}/session/${encodeURIComponent(e)}`}unwrap(e){return this.protocol==="v2"&&h(e)?e.data:e}session(e,t,r){const s=this.unwrap(e);if(!h(s)||typeof s.id!="string")throw new l(t,r,200,"invalid session JSON");return{...s,directory:s.directory??s.location?.directory??this.directory}}async createSession(e,t,r){if(this.protocol==="v2"){const s=t??this.directory;return this.session(await this.request("POST","/api/session",{...e,...s?{location:{directory:s}}:{}},{scoped:!1,signal:r}),"POST","/api/session")}return this.session(await this.request("POST","/session",e??{},{directory:t,signal:r}),"POST","/session")}async getSession(e,t,r){return this.session(await this.request("GET",this.sessionPath(e),void 0,{directory:t,scoped:this.protocol==="v1",signal:r}),"GET",this.sessionPath(e))}async deleteSession(e,t){await this.request("DELETE",this.sessionPath(e),void 0,{directory:t,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"}),this.v2Events.clearSession(e),this.runWindows.delete(e),this.inboxIDs.delete(e)}async updateSessionPermission(e,t,r,s){await this.request("PATCH",this.sessionPath(e),this.protocol==="v2"?{permissions:t.map(o=>({action:{bash:"shell",task:"subagent",write:"edit",patch:"edit"}[o.permission]??o.permission,resource:o.pattern,effect:o.action}))}:{permission:t},{directory:r,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1",signal:s})}async sendPromptAsync(e,t,r,s){const o=this.cancellations.get(e);if(o&&await o,s?.signal?.throwIfAborted(),this.admissionUncertain)throw new Error("OpenCode prompt admission unconfirmed; server must be replaced");if(this.prompts.has(e))throw new Error("OpenCode session already has a prompt admission in progress");const n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0});const c=`msg_${P().replaceAll("-","")}`,a={controller:n,admitted:!1,dispatched:!1,done:Promise.resolve()};this.prompts.set(e,a),this.protocol==="v2"&&this.inboxIDs.set(e,c),this.protocol==="v2"&&s?.runId&&(this.v2Events.clearSession(e),this.runWindows.set(e,{runId:s.runId,promptId:c,signal:s.signal,canceled:!1,messages:new Set}));const d=this.connectionGeneration;a.done=this.preparePrompt(e,t,r,c,a);try{await a.done}catch(f){throw a.dispatched&&!a.admitted&&!this.closed&&d===this.connectionGeneration&&(this.admissionUncertain=!0,this.emit("admission-uncertain")),f}finally{s?.signal?.removeEventListener("abort",i),this.prompts.get(e)===a&&this.prompts.delete(e)}}async preparePrompt(e,t,r,s,o){const n=this.sessionPath(e),i=o.controller.signal;if(this.protocol==="v1"){i.throwIfAborted(),o.dispatched=!0,await this.request("POST",`${n}/prompt_async`,t,{directory:r,response:"empty"}),o.admitted=!0;return}t.model&&await this.request("POST",`${n}/model`,{model:{providerID:t.model.providerID,id:t.model.modelID}},{scoped:!1,response:"empty",signal:i}),t.agent&&await this.request("POST",`${n}/agent`,{agent:t.agent},{scoped:!1,response:"empty",signal:i}),await this.request(t.system?"PUT":"DELETE",`/api/experimental/session/${encodeURIComponent(e)}/instructions/entries/grix_identity`,t.system?{value:t.system}:void 0,{scoped:!1,response:"empty",signal:i}),i.throwIfAborted(),o.dispatched=!0;const c=await this.request("POST",`${n}/prompt`,{id:s,text:t.parts.map(a=>a.text).join(`
7
+ `))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){s.type==="location.shutdown"&&typeof s.location?.directory=="string"&&this.mcpDirectories.delete(s.location.directory);const o=s.data?.sessionID??s.data?.form?.sessionID,n=this.runWindows.get(o);return!n&&h(s.location)&&s.location.directory&&this.directory&&s.location.directory!==this.directory?[]:n&&!this.acceptRunEvent(s,n)?[]:this.v2Events.normalize(s).map(i=>n?{...i,runId:n.runId}:i)}if(h(s.properties)){const{properties:o,...n}=s;return[{...n,...o,type:s.type}]}return[s]}acceptRunEvent(e,t){if(t.canceled||t.signal?.aborted)return!1;const r=e.durable?.seq;if(e.type==="session.inbox.enqueued"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox admission requires durable sequence");return t.enqueuedSeq=r,!0}if(e.type==="session.inbox.delivered"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox delivery requires durable sequence");return t.deliveredSeq=r,!0}if(e.type==="session.execution.started"&&t.enqueuedSeq!==void 0&&Number.isSafeInteger(r)&&r>t.enqueuedSeq)return t.executionSeq=r,!0;const s=t.deliveredSeq??t.executionSeq;if(s===void 0||Number.isSafeInteger(r)&&r<=s)return!1;const o=/^session\.execution\.(succeeded|failed|interrupted)$/.test(e.type);if(o&&!Number.isSafeInteger(r))throw new Error("OpenCode V2 execution terminal requires durable sequence");if(t.deliveredSeq===void 0){if(e.type==="session.execution.succeeded")throw new Error("OpenCode V2 execution ended before own inbox delivery");return o}const n=e.data.assistantMessageID;return e.type==="session.step.started"&&t.messages.add(n),!(n&&!t.messages.has(n))}async reconnectSse(e,t){for(;this.reconnectAttempts<x;){const r=this.reconnectAttempts++;try{if(await b(Math.min(q*2**r,D),t),this.closed||t.aborted||e!==this.sseGeneration)return;await this.subscribeEvents(e,t);return}catch(s){if(this.closed||t.aborted||e!==this.sseGeneration)return;if(s instanceof l&&(s.status===401||s.status===403))break}}if(!this.closed&&e===this.sseGeneration)try{this.emit("stream-unavailable")}catch{}}url(e,t=""){const r=new URL(e,this.baseUrl);return t&&r.searchParams.set(this.protocol==="v2"?"location[directory]":"directory",t),r}async request(e,t,r,s){if(this.closed)throw new Error(`OpenCode REST ${e} ${t}: transport closed`);s?.signal?.throwIfAborted();const o=this.url(t,s?.scoped===!1?"":s?.directory??this.directory),n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0}),this.requests.add(n);const c=setTimeout(()=>n.abort(),s?.timeoutMs??v);let a;try{const d=await fetch(o,{method:e,headers:{...this.headers,Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:n.signal,redirect:"error"});if(a=d.status,d.status===204&&s?.response==="empty")return;const f=/^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(d.headers.get("content-type")??""),u=d.body?.getReader(),E=[];let m=0;try{if(u)for(;;){const{done:g,value:C}=await u.read();if(g||(m+=C.byteLength,m>(d.ok?y:4096)))break;E.push(C)}}finally{u&&(await u.cancel(),u.releaseLock())}const O=Buffer.concat(E).toString("utf8");let S,w=m?f?"invalid JSON response":"non-JSON response":"empty response";if(f&&m<=y)try{S=JSON.parse(O),w="JSON response"}catch{}if(!d.ok||w!=="JSON response"||s?.response==="empty"||m>y)throw new l(e,t,d.status,m>y?"response too large":d.ok&&s?.response==="empty"?"expected HTTP 204":w);return S}catch(d){throw d instanceof l?d:a!==void 0?new l(e,t,a,"response read failed or canceled"):new Error(`OpenCode REST ${e} ${t}: request failed or canceled`)}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",i),this.requests.delete(n)}}sessionPath(e){return`${this.protocol==="v2"?"/api":""}/session/${encodeURIComponent(e)}`}unwrap(e){return this.protocol==="v2"&&h(e)?e.data:e}session(e,t,r){const s=this.unwrap(e);if(!h(s)||typeof s.id!="string")throw new l(t,r,200,"invalid session JSON");return{...s,directory:s.directory??s.location?.directory??this.directory}}async createSession(e,t,r){if(this.protocol==="v2"){const s=t??this.directory;return this.session(await this.request("POST","/api/session",{...e,...s?{location:{directory:s}}:{}},{scoped:!1,signal:r}),"POST","/api/session")}return this.session(await this.request("POST","/session",e??{},{directory:t,signal:r}),"POST","/session")}async getSession(e,t,r){return this.session(await this.request("GET",this.sessionPath(e),void 0,{directory:t,scoped:this.protocol==="v1",signal:r}),"GET",this.sessionPath(e))}async deleteSession(e,t){await this.request("DELETE",this.sessionPath(e),void 0,{directory:t,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"}),this.v2Events.clearSession(e),this.runWindows.delete(e),this.inboxIDs.delete(e)}async updateSessionPermission(e,t,r,s){await this.request("PATCH",this.sessionPath(e),this.protocol==="v2"?{permissions:t.map(o=>({action:{bash:"shell",task:"subagent",write:"edit",patch:"edit"}[o.permission]??o.permission,resource:o.pattern,effect:o.action}))}:{permission:t},{directory:r,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1",signal:s})}async sendPromptAsync(e,t,r,s){const o=this.cancellations.get(e);if(o&&await o,s?.signal?.throwIfAborted(),this.admissionUncertain)throw new Error("OpenCode prompt admission unconfirmed; server must be replaced");if(this.prompts.has(e))throw new Error("OpenCode session already has a prompt admission in progress");const n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0});const c=`msg_${P().replaceAll("-","")}`,a={controller:n,admitted:!1,dispatched:!1,done:Promise.resolve()};this.prompts.set(e,a),this.protocol==="v2"&&this.inboxIDs.set(e,c),this.protocol==="v2"&&s?.runId&&(this.v2Events.clearSession(e),this.runWindows.set(e,{runId:s.runId,promptId:c,signal:s.signal,canceled:!1,messages:new Set}));const d=this.connectionGeneration;a.done=this.preparePrompt(e,t,r,c,a);try{await a.done}catch(f){throw a.dispatched&&!a.admitted&&!this.closed&&d===this.connectionGeneration&&(this.admissionUncertain=!0,this.emit("admission-uncertain")),f}finally{s?.signal?.removeEventListener("abort",i),this.prompts.get(e)===a&&this.prompts.delete(e)}}async preparePrompt(e,t,r,s,o){const n=this.sessionPath(e),i=o.controller.signal;if(this.protocol==="v1"){i.throwIfAborted(),o.dispatched=!0,await this.request("POST",`${n}/prompt_async`,t,{directory:r,response:"empty"}),o.admitted=!0;return}t.model&&await this.request("POST",`${n}/model`,{model:{providerID:t.model.providerID,id:t.model.modelID}},{scoped:!1,response:"empty",signal:i}),t.agent&&await this.request("POST",`${n}/agent`,{agent:t.agent},{scoped:!1,response:"empty",signal:i}),await this.request(t.system?"PUT":"DELETE",`/api/experimental/session/${encodeURIComponent(e)}/instructions/entries/grix_identity`,t.system?{value:t.system}:void 0,{scoped:!1,response:"empty",signal:i}),i.throwIfAborted(),o.dispatched=!0;const c=await this.request("POST",`${n}/prompt`,{id:s,text:t.parts.map(a=>a.text).join(`
8
8
  `)},{scoped:!1});if(!h(c)||!h(c.data)||c.data.id!==s)throw new l("POST",`${n}/prompt`,200,"invalid inbox JSON");o.admitted=!0}async abortSession(e,t){const r=this.cancellations.get(e);if(r)return r;const s=this.prompts.get(e);s?.controller.abort();const o=this.runWindows.get(e);o&&(o.canceled=!0);const n=this.interruptAfterAdmission(e,t,s,this.inboxIDs.get(e));return this.cancellations.set(e,n),n.then(()=>{this.cancellations.get(e)===n&&this.cancellations.delete(e)},()=>{}),n}async interruptAfterAdmission(e,t,r,s){const o=this.connectionGeneration,n=()=>{if(this.closed||o!==this.connectionGeneration)throw new Error("OpenCode interrupt connection canceled")};await r?.done.catch(()=>{}),n(),this.protocol==="v2"&&s&&await this.request("DELETE",`${this.sessionPath(e)}/inbox/${encodeURIComponent(s)}`,void 0,{scoped:!1,response:"empty"}),n();const i=await this.request("POST",`${this.sessionPath(e)}/${this.protocol==="v2"?"interrupt":"abort"}`,void 0,{directory:t,scoped:this.protocol==="v1"});if(this.protocol==="v2"&&(!h(i)||typeof i.interrupted!="boolean"))throw new l("POST",`${this.sessionPath(e)}/interrupt`,200,"invalid interrupt JSON");n(),this.protocol==="v2"&&await this.request("POST",`/api/experimental/session/${encodeURIComponent(e)}/wait`,void 0,{scoped:!1,response:"empty"})}async respondPermission(e,t,r,s){await this.request("POST",this.protocol==="v2"?`${this.sessionPath(e)}/permission/${encodeURIComponent(t)}/reply`:`${this.sessionPath(e)}/permissions/${encodeURIComponent(t)}`,this.protocol==="v2"?{decision:r}:{response:r},{directory:s,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"})}async replyQuestion(e,t,r){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reply`,{answers:t},{directory:r});return}const s=this.v2Events.getForm(e);await this.request("POST",`${this.sessionPath(s.sessionID)}/form/${encodeURIComponent(e)}/reply`,{answer:this.v2Events.formAnswer(e,t)},{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async rejectQuestion(e,t){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reject`,void 0,{directory:t});return}const r=this.v2Events.getForm(e);await this.request("DELETE",`${this.sessionPath(r.sessionID)}/form/${encodeURIComponent(e)}`,void 0,{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async listProviders(e){if(this.protocol==="v1"){const s=await this.request("GET","/config/providers",void 0,{directory:e});if(!Array.isArray(s?.providers))throw new l("GET","/config/providers",200,"invalid provider JSON");return s.providers}const t=this.unwrap(await this.request("GET","/api/model",void 0,{directory:e}));if(!Array.isArray(t))throw new l("GET","/api/model",200,"invalid model list JSON");const r=new Map;for(const s of t){if(!h(s)||typeof s.id!="string"||typeof s.providerID!="string")throw new l("GET","/api/model",200,"invalid model JSON");if(s.enabled===!1)continue;const o=r.get(s.providerID)??{id:s.providerID,name:s.providerID,models:[]};o.models.push({id:s.id,name:s.name,limit:s.limit}),r.set(s.providerID,o)}return[...r.values()]}async configureMcp(e,t){this.mcp={name:e,command:t},this.mcpDirectories.clear(),await this.ensureMcpDirectory()}async ensureMcpDirectory(e){if(e?.throwIfAborted(),this.protocol!=="v2"||!this.mcp||this.mcpDirectories.has(this.directory))return;const t=this.directory,{name:r,command:s}=this.mcp;await this.request("PUT",`/api/experimental/mcp/${encodeURIComponent(r)}`,{config:{type:"local",command:s,disabled:!1}},{directory:t,response:"empty",signal:e});const o=Date.now()+1e4;for(;;){const n=this.unwrap(await this.request("GET","/api/mcp",void 0,{directory:t,signal:e})),i=Array.isArray(n)?n.find(c=>h(c)&&c.name===r):void 0;if(i?.status?.status==="connected")break;if(i?.status?.status!=="pending"||Date.now()>=o)throw new Error("OpenCode V2 MCP did not become connected");if(!this.sseController)throw new Error("OpenCode MCP setup canceled");await b(100,e??this.sseController.signal)}this.mcpDirectories.add(t)}async healthCheck(){try{if(this.closed)return!1;if(this.protocol==="v2")return T(await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3}));const e=await this.request("GET","/session",void 0,{timeoutMs:3e3});return Array.isArray(e)&&e.every(t=>h(t)&&typeof t.id=="string")}catch{return!1}}cancelConnections(){this.sseGeneration++,this.sseController?.abort(),this.sseController=null;for(const e of this.requests)e.abort();this.sseConnected=!1}disconnect(){this.connectionGeneration++,this.closed=!0,this.cancelConnections(),this.headers={},this.mcp=null,this.mcpDirectories.clear(),this.v2Events.clear();for(const e of this.prompts.values())e.controller.abort();this.prompts.clear(),this.cancellations.clear(),this.runWindows.clear(),this.inboxIDs.clear(),this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{l as OpenCodeHttpError,M as OpenCodeTransport};
@@ -1,2 +1,2 @@
1
1
  function u(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}const g=1024;class f{messages=new Map;textLengths=new Map;tools=new Map;forms=new Map;normalize(o){if(!u(o.data))throw new Error("OpenCode V2 event requires data");if([this.messages,this.textLengths,this.tools,this.forms].some(t=>t.size>g))throw new Error("OpenCode V2 event state limit exceeded");const e=o.data,r=e.sessionID;if(o.type.startsWith("session.")&&typeof r!="string")throw new Error("OpenCode V2 session event requires sessionID");let s=[];const n=e.assistantMessageID;if(/^session\.(step|text|reasoning|tool)\./.test(o.type)&&typeof n!="string")throw new Error("OpenCode V2 event requires assistantMessageID");if(/^session\.(text|reasoning)\.delta$/.test(o.type)&&typeof e.delta!="string")throw new Error("OpenCode V2 event requires text delta");const d=`${r}/${n}/${e.id}`,c=t=>{const a=this.messages.get(n),i={...a,id:n,sessionID:r,role:"assistant",time:{created:a?.time.created??e.started??o.created??Date.now()},modelID:e.model?.id??a?.modelID??"",providerID:e.model?.providerID??a?.providerID??"",...t?{tokens:t,cost:e.cost,time:{created:a?.time.created??o.created,completed:o.created}}:{}};return this.messages.set(n,i),i},p=t=>{const a=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};return{type:"message.part.updated",part:{id:d,messageID:n,sessionID:r,type:"tool",callID:e.id,tool:a.name,state:{status:t,input:a.input,raw:e.text??"",...t==="completed"?{output:Array.isArray(e.content)?e.content.map(l=>l.type==="text"?l.text:JSON.stringify(l)).join(`
2
- `):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),h=l?String(e.text??"").slice(i.length):String(e.delta??""),y=l?String(e.text??""):i+h;if(y.length>2*1024*1024)throw new Error("OpenCode V2 text limit exceeded");this.textLengths.set(a,{sessionID:r,text:y}),this.messages.has(n)||s.push({type:"message.updated",info:c()}),s.push({type:"message.part.updated",part:{type:t?"reasoning":"text",id:a,messageID:n,text:y},delta:h});break}case"session.tool.input.started":this.tools.set(d,{sessionID:r,name:e.name,input:{},started:o.created});break;case"session.tool.input.ended":{const t=this.tools.get(d);if(t)try{const a=JSON.parse(e.text);u(a)&&(t.input=a)}catch{}break}case"session.tool.called":{const t=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};t.input=u(e.input)?e.input:{},this.tools.set(d,t),s=[p("running")];break}case"session.tool.success":s=[p("completed")],this.tools.delete(d);break;case"session.tool.failed":s=[p("error")],this.tools.delete(d);break;case"permission.asked":if(typeof e.id!="string"||!Array.isArray(e.resources))throw new Error("OpenCode V2 invalid permission event");s=[{type:"permission.asked",id:e.id,sessionID:r,permission:e.action,patterns:e.resources,always:e.save??[],metadata:e.metadata??{},...e.source?.type==="tool"?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}];break;case"permission.replied":s=[{type:"permission.replied",sessionID:r,requestID:e.requestID,reply:e.reply}];break;case"form.created":{const t=e.form;if(!u(t)||typeof t.id!="string"||typeof t.sessionID!="string"||!Array.isArray(t.fields))throw new Error("OpenCode V2 invalid form event");if(this.forms.set(t.id,t),t.fields.some(i=>i.hidden||i.when?.length||!["string","multiselect","boolean","number","integer"].includes(i.type))){s=[{type:"question.unsupported",sessionID:t.sessionID,id:t.id}];break}const a=t.fields.map(i=>({header:i.title||i.key,question:i.description||i.title||i.key,options:i.type==="boolean"?[{label:"true"},{label:"false"}]:(i.options??[]).map(l=>({label:l.label,description:l.description})),multiple:i.type==="multiselect",custom:i.type!=="boolean"&&(i.custom??!i.options?.length)}));s=[{type:"question.asked",id:t.id,sessionID:t.sessionID,questions:a}];break}case"form.replied":s=[{type:"question.replied",sessionID:r,requestID:e.id,answers:[]}],this.forms.delete(e.id);break;case"form.cancelled":s=[{type:"question.rejected",sessionID:r,requestID:e.id}],this.forms.delete(e.id);break;case"location.shutdown":s=[{type:"server.instance.disposed",directory:o.location?.directory??""}];break}return s.length||(s=[{type:"opencode.v2.event"}]),s.map(t=>({...t,nativeEvent:o}))}error(o){return{type:typeof o?.type=="string"?o.type:"unknown",message:typeof o?.message=="string"?o.message:"OpenCode execution failed"}}getForm(o){const e=this.forms.get(o);if(!e)throw new Error("OpenCode V2 form is no longer pending");return e}forgetForm(o){this.forms.delete(o)}formAnswer(o,e){const r=this.getForm(o),s=Object.create(null);return r.fields.forEach((n,d)=>{const c=e[d]??[];if(!c.length){if(n.required)throw new Error("OpenCode V2 form requires an answer");return}const p=c.map(t=>n.options?.find(a=>a.label===t)?.value??t);if(n.type==="multiselect")s[n.key]=p;else if(n.type==="boolean"){if(!["true","false"].includes(p[0]))throw new Error("OpenCode V2 form requires a boolean");s[n.key]=p[0]==="true"}else if(n.type==="number"||n.type==="integer"){const t=Number(p[0]);if(!p[0].trim()||!Number.isFinite(t)||n.type==="integer"&&!Number.isInteger(t))throw new Error("OpenCode V2 form requires a number");s[n.key]=t}else if(n.type==="string")s[n.key]=p[0];else throw new Error("OpenCode V2 form field is unsupported")}),s}clearSession(o,e=!0){for(const[r,s]of this.messages)s.sessionID===o&&this.messages.delete(r);for(const[r,s]of this.textLengths)s.sessionID===o&&this.textLengths.delete(r);for(const[r,s]of this.tools)s.sessionID===o&&this.tools.delete(r);if(e)for(const[r,s]of this.forms)s.sessionID===o&&this.forms.delete(r)}clear(){this.messages.clear(),this.textLengths.clear(),this.tools.clear(),this.forms.clear()}}export{f as OpenCodeV2Events,u as isRecord};
2
+ `):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),y=l?String(e.text??"").slice(i.length):String(e.delta??""),h=l?String(e.text??""):i+y;if(h.length>2*1024*1024)throw new Error("OpenCode V2 text limit exceeded");this.textLengths.set(a,{sessionID:r,text:h}),this.messages.has(n)||s.push({type:"message.updated",info:c()}),s.push({type:"message.part.updated",part:{type:t?"reasoning":"text",id:a,messageID:n,text:h},delta:y});break}case"session.tool.input.started":this.tools.set(d,{sessionID:r,name:e.name,input:{},started:o.created});break;case"session.tool.input.ended":{const t=this.tools.get(d);if(t)try{const a=JSON.parse(e.text);u(a)&&(t.input=a)}catch{}break}case"session.tool.called":{const t=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};t.input=u(e.input)?e.input:{},this.tools.set(d,t),s=[p("running")];break}case"session.tool.success":s=[p("completed")],this.tools.delete(d);break;case"session.tool.failed":s=[p("error")],this.tools.delete(d);break;case"permission.asked":if(typeof e.id!="string"||!Array.isArray(e.resources))throw new Error("OpenCode V2 invalid permission event");s=[{type:"permission.asked",id:e.id,sessionID:r,permission:e.action,patterns:e.resources,always:e.save??[],metadata:e.metadata??{},...e.source?.type==="tool"?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}];break;case"permission.replied":s=[{type:"permission.replied",sessionID:r,requestID:e.requestID,reply:e.reply}];break;case"form.created":{const t=e.form;if(!u(t)||typeof t.id!="string"||typeof t.sessionID!="string"||!Array.isArray(t.fields))throw new Error("OpenCode V2 invalid form event");if(this.forms.set(t.id,t),t.fields.some(i=>i.hidden||i.when?.length||!["string","multiselect","boolean","number","integer"].includes(i.type))){s=[{type:"question.unsupported",sessionID:t.sessionID,id:t.id}];break}const a=t.fields.map(i=>({header:i.title||i.key,question:i.description||i.title||i.key,options:i.type==="boolean"?[{label:"true"},{label:"false"}]:(i.options??[]).map(l=>({label:l.label,description:l.description})),multiple:i.type==="multiselect",custom:i.type!=="boolean"&&(i.custom??!i.options?.length)}));s=[{type:"question.asked",id:t.id,sessionID:t.sessionID,questions:a}];break}case"form.replied":s=[{type:"question.replied",sessionID:r,requestID:e.id,answers:[]}],this.forms.delete(e.id);break;case"form.cancelled":s=[{type:"question.rejected",sessionID:r,requestID:e.id}],this.forms.delete(e.id);break;case"location.shutdown":return[]}return s.length||(s=[{type:"opencode.v2.event"}]),s.map(t=>({...t,nativeEvent:o}))}error(o){return{type:typeof o?.type=="string"?o.type:"unknown",message:typeof o?.message=="string"?o.message:"OpenCode execution failed"}}getForm(o){const e=this.forms.get(o);if(!e)throw new Error("OpenCode V2 form is no longer pending");return e}forgetForm(o){this.forms.delete(o)}formAnswer(o,e){const r=this.getForm(o),s=Object.create(null);return r.fields.forEach((n,d)=>{const c=e[d]??[];if(!c.length){if(n.required)throw new Error("OpenCode V2 form requires an answer");return}const p=c.map(t=>n.options?.find(a=>a.label===t)?.value??t);if(n.type==="multiselect")s[n.key]=p;else if(n.type==="boolean"){if(!["true","false"].includes(p[0]))throw new Error("OpenCode V2 form requires a boolean");s[n.key]=p[0]==="true"}else if(n.type==="number"||n.type==="integer"){const t=Number(p[0]);if(!p[0].trim()||!Number.isFinite(t)||n.type==="integer"&&!Number.isInteger(t))throw new Error("OpenCode V2 form requires a number");s[n.key]=t}else if(n.type==="string")s[n.key]=p[0];else throw new Error("OpenCode V2 form field is unsupported")}),s}clearSession(o,e=!0){for(const[r,s]of this.messages)s.sessionID===o&&this.messages.delete(r);for(const[r,s]of this.textLengths)s.sessionID===o&&this.textLengths.delete(r);for(const[r,s]of this.tools)s.sessionID===o&&this.tools.delete(r);if(e)for(const[r,s]of this.forms)s.sessionID===o&&this.forms.delete(r)}clear(){this.messages.clear(),this.textLengths.clear(),this.tools.clear(),this.forms.clear()}}export{f as OpenCodeV2Events,u as isRecord};
@@ -1,7 +1,7 @@
1
- import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as L,resolveWindowsExecInvocation as G,spawnCommand as j,killProcessGroup as _,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(d){return rt(d)==="omp"}function lt(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(d){const t=lt(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const b=new Map;function pt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(d){const t=b.get(d);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=G(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return b.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(d){return new Promise(t=>setTimeout(t,d))}function yt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,l=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(l?.piProviderId&&l.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const c={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(c.available_providers=p),r?.id&&(c.model_id=r.id),r?.provider&&(c.provider_id=r.provider,c.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),c),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);return p?(await this.setModelSelection(c,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${c}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
- ${r.map(c=>` ${c.provider??"unknown"}:${c.id} (${c.name??c.id})`).join(`
1
+ import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as G,resolveWindowsExecInvocation as L,spawnCommand as j,killProcessGroup as b,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(l){return rt(l)==="omp"}function lt(l){return process.platform!=="win32"?"PATH":Object.keys(l).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(l){const t=lt(l),e=String(l[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return l;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...l,[t]:e?`${n}${E}${e}`:n}):l}const _=new Map;function pt(l){const t=u(l,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(l){const t=_.get(l);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=L(l,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return _.set(l,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${l})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(l){try{return process.kill(l,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(l){return new Promise(t=>setTimeout(t,l))}function yt(l){const t=new Set,e=[];for(const i of l){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(l){if(l===void 0)return"undefined";if(l===null)return"null";if(typeof l=="string")return l.length>500?`${l.slice(0,500)}...`:l;try{const t=JSON.stringify(l);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(l)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(d.available_providers=p),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{b(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{b(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(d.length>1){const p=(await this.currentModel())?.provider?.trim();n=d.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,p=a.find(h=>h.id===d)?.id??a[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),p=s.slice(a+1);return p?(await this.setModelSelection(d,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
+ ${r.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
3
3
  `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=pt(t),s=u(N(),"grix-pi-mcp");C(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),R(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await ot(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=L(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(a=>a.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),l=it(this.agentName);if(this.provider){const a=this.isOmp(e)?"bare":"dollar";await nt(r,l,this.provider,a)?(n.includes("--provider")||n.push("--provider",l),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await st(r,l).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${l}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)});this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&!this.isOmp(e)&&(await ut(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let c={...process.env,...this.config.env};this.isOmp(e)&&(c=ht(c));const p=this.provider?.apiKey?.trim();p&&!c.GRIX_PROVIDER_API_KEY?.trim()&&(c.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=j(e,n,{env:c,cwd:h}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&at(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(a=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`)}),this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const I=a.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Z(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
4
+ `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(a,d,p,h)=>this.callbacks.agentInvoke(a,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=pt(t),s=u(N(),"grix-pi-mcp");C(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),R(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await ot(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=G(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(c=>c.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),a=it(this.agentName);if(this.provider){const c=this.isOmp(e)?"bare":"dollar";await nt(r,a,this.provider,c)?(n.includes("--provider")||n.push("--provider",a),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await st(r,a).then(c=>{c&&o.info("pi-adapter",`Removed stale Grix provider "${a}" from models.json`)}).catch(c=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${c instanceof Error?c.message:String(c)}`)});this.mcpConfigPath&&!n.some(c=>c==="--mcp-config")&&!this.isOmp(e)&&(await ut(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let d={...process.env,...this.config.env};this.isOmp(e)&&(d=ht(d));const p=this.provider?.apiKey?.trim();p&&!d.GRIX_PROVIDER_API_KEY?.trim()&&(d.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):c}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=j(e,n,{env:d,cwd:h}).process}catch(c){throw o.error("pi-adapter",`PI spawn threw: ${c}`),this.alive=!1,c}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&at(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(c=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${c instanceof Error?c.message:String(c)}`)}),this.process.on("error",c=>{o.error("pi-adapter",`Spawn error: ${c.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${c.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",c=>{o.info("pi-adapter",`PI process exited (code=${c})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${c})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",c??1)}),this.process.stderr?.on("data",c=>{const I=c.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",c=>this.handlePiEvent(c)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Z(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
5
  `);e=`${e}
6
6
 
7
7
  [Conversation context]
@@ -9,4 +9,4 @@ ${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inbou
9
9
  `);e=`${e}
10
10
 
11
11
  [Conversation context]
12
- ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),l=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${l} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} (reliable) event=${t}`)}).catch(c=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},A.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!$(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let l=0;try{l=W(t,this.descendantBaseline)}catch{l=0}if(l>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${l}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<P||s!==null&&s<P)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(Y(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-f(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&$(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{A as PiAdapter};
12
+ ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),a=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${a} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},A.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!$(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let a=0;try{a=W(t,this.descendantBaseline)}catch{a=0}if(a>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${a}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<P||s!==null&&s<P)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(Y(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-f(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&$(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{A as PiAdapter};