grix-connector 4.18.1 → 5.0.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 (72) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/acp/acp-adapter.js +12 -12
  3. package/dist/adapter/agy/agy-adapter.js +10 -10
  4. package/dist/adapter/agy/model-list.js +2 -2
  5. package/dist/adapter/agy/quota.js +5 -5
  6. package/dist/adapter/claude/claude-adapter.js +20 -20
  7. package/dist/adapter/claude/claude-bridge-server.js +1 -0
  8. package/dist/adapter/claude/claude-tools.js +1 -0
  9. package/dist/adapter/claude/claude-worker-client.js +1 -0
  10. package/dist/adapter/claude/mcp-http-launcher.js +2 -0
  11. package/dist/adapter/claude/result-timeout.js +1 -0
  12. package/dist/adapter/cursor/cursor-adapter.js +12 -11
  13. package/dist/adapter/deepseek/deepseek-adapter.js +6 -0
  14. package/dist/adapter/deepseek/index.js +1 -0
  15. package/dist/adapter/deepseek-harness/dsh-version.js +1 -1
  16. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  17. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
  18. package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
  19. package/dist/adapter/opencode/opencode-transport.js +1 -1
  20. package/dist/adapter/opencode/opencode-v2-events.js +1 -1
  21. package/dist/adapter/pi/pi-adapter.js +6 -5
  22. package/dist/adapter/pi/pi-grix-tools-extension.js +2 -0
  23. package/dist/adapter/qwen/index.js +1 -0
  24. package/dist/adapter/qwen/qwen-adapter.js +4 -0
  25. package/dist/aibot/client.js +1 -0
  26. package/dist/aibot/index.js +1 -0
  27. package/dist/aibot/types.js +0 -0
  28. package/dist/assets/dsh-bridge/grix-dsh-bridge-5.0.0.tgz +0 -0
  29. package/dist/assets/dsh-bridge/manifest.json +6 -6
  30. package/dist/bridge/bridge.js +1 -1
  31. package/dist/bridge/cli-install-flow.js +1 -1
  32. package/dist/bridge/cli-install-offer.js +1 -1
  33. package/dist/bridge/local-action-session-control.js +1 -1
  34. package/dist/bridge/rate-limits.js +1 -1
  35. package/dist/bridge/send-controller.js +3 -3
  36. package/dist/bridge/session-control-open.js +1 -1
  37. package/dist/bridge/toolbar-meta.js +1 -1
  38. package/dist/core/access/allowlist-gate.js +1 -0
  39. package/dist/core/access/allowlist-store.js +1 -0
  40. package/dist/core/access/index.js +1 -0
  41. package/dist/core/file-ops/handler.js +1 -0
  42. package/dist/core/file-ops/list-files.js +1 -0
  43. package/dist/core/file-ops/types.js +0 -0
  44. package/dist/core/installer/registry.js +1 -1
  45. package/dist/core/mcp/tools.js +1 -1
  46. package/dist/core/util/home-env.js +1 -0
  47. package/dist/default-skills/grix-chat-state/SKILL.md +34 -2
  48. package/dist/grix.js +5 -5
  49. package/dist/log.js +3 -0
  50. package/dist/main.js +31 -0
  51. package/dist/manager.js +1 -1
  52. package/dist/mcp/stream-http/config.js +1 -0
  53. package/dist/mcp/stream-http/connection-binding.js +1 -0
  54. package/dist/mcp/stream-http/event-tool-executor.js +1 -0
  55. package/dist/mcp/stream-http/gateway.js +1 -0
  56. package/dist/mcp/stream-http/index.js +1 -0
  57. package/dist/mcp/stream-http/security.js +1 -0
  58. package/dist/mcp/stream-http/session-manager.js +1 -0
  59. package/dist/mcp/stream-http/tool-executor.js +1 -0
  60. package/dist/mcp/stream-http/tool-registry.js +1 -0
  61. package/dist/mcp/stream-http/tool-schemas.js +1 -0
  62. package/dist/protocol/acp-client.js +1 -1
  63. package/dist/session/index.js +1 -0
  64. package/dist/session/manager.js +1 -0
  65. package/dist/transport/index.js +1 -0
  66. package/dist/transport/json-rpc.js +3 -0
  67. package/openclaw-plugin/audit-recorder-worker.js +2 -1
  68. package/openclaw-plugin/index.js +99 -0
  69. package/openclaw-plugin/skills/grix-chat-state/SKILL.md +33 -1
  70. package/openclaw.plugin.json +1 -0
  71. package/package.json +1 -1
  72. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.18.1.tgz +0 -0
@@ -1 +1 @@
1
- import{EventEmitter as b}from"events";import{log as a}from"../core/log/index.js";import{AgentEventType as h}from"../types/events.js";import{mapSessionUpdate as M}from"./event-mapper.js";import{AcpTerminalHost as v,acpTerminalErrorCode as g}from"./acp-terminal.js";class m extends Error{authMethods;constructor(e){super("ACP authentication required"),this.name="AcpAuthRequiredError",this.authMethods=e}}function f(d){if(!d||typeof d!="object")return!1;const e=d;return e.code===-32e3?!0:e.code===-32603&&e.data?.details?/\b(401|token\s*expired|access\s*token)\b/i.test(e.data.details):!1}function S(d){return!d||typeof d!="object"?[{id:"oauth"}]:d.data?.authMethods??[{id:"oauth"}]}const y=new Set(["cwd","mcpServers","sessionId","additionalDirectories"]);function w(d,e){if(e)for(const[t,i]of Object.entries(e))y.has(t)||(d[t]=i)}class p extends b{acpSessionId="";alive=!1;pendingPermissions=new Map;availableModes=[];availableModels=[];currentMode="";currentModel="";listSupported=!1;loadSupported=!1;_supportsCommandsExecute=!1;_availableCommands=[];transport;terminalEnabled=!1;terminalHost=new v;settleTimer=null;static SETTLE_MS=3e3;pendingToolCallIds=new Set;settleSuppressedSince=0;static SETTLE_SUPPRESS_MAX_MS=900*1e3;constructor(){super(),this.transport=null}get sessionId(){return this.acpSessionId}get isAlive(){return this.alive}get modes(){return[...this.availableModes]}get mode(){return this.currentMode}get models(){return[...this.availableModels]}get model(){return this.currentModel}get sessionOptions(){return{modes:[...this.availableModes],currentModeId:this.currentMode,models:[...this.availableModels],currentModelId:this.currentModel}}get supportsCommandsExecute(){return this._supportsCommandsExecute}get availableCommands(){return[...this._availableCommands]}async connect(e){this.transport=e.transport,this.terminalEnabled=e.terminal===!0,this.transport.on("close",()=>{this.terminalHost.dispose(),this.alive&&(this.alive=!1,this.emit("session-lost"))}),this.transport.setHandlers((o,l)=>{o==="session/update"?this.handleSessionUpdate(l):o==="_kiro.dev/metadata"?this.handleKiroMetadata(l):o==="_kiro.dev/commands/available"?this.handleCommandsAvailable(l):o==="_kiro.dev/compaction/status"?this.emit("compactionStatus",l):o==="_kiro.dev/clear/status"&&this.emit("clearStatus",l)},(o,l,c)=>{o==="session/request_permission"?this.handlePermissionRequest(l,c):o.startsWith("terminal/")&&this.terminalEnabled?this.handleTerminalRequest(o,l,c).catch(u=>{a.warn("acp-client",`terminal response failed: ${u instanceof Error?u.message:String(u)}`)}):o.startsWith("cursor/")?this.transport.respondSuccess(l,{}).catch(()=>{}):this.transport.respondError(l,-32601,"method not implemented").catch(()=>{})});const t=await this.initialize();this.listSupported=!!t.agentCapabilities?.sessionCapabilities?.list,this.loadSupported=!!t.agentCapabilities?.loadSession;const i=t.agentCapabilities??{};this._supportsCommandsExecute=!!(i.extensions?.["_kiro.dev/commands"]||i.commands);const s=t?._meta;if(s?.modelState&&this.absorbModels(s.modelState),e.authMethod)try{await this.transport.call("authenticate",{methodId:e.authMethod})}catch(o){throw f(o)?new m(S(o)):o}const n=e.sessionId&&e.sessionId!=="__continue__";let r=!1;if(n){if(!this.loadSupported)throw new Error(`session/load not supported by agent, cannot resume session ${e.sessionId}`);try{await this.loadSession(e.sessionId,e)&&(r=!0)}catch(o){throw f(o)?new m(S(o)):o}if(!r)throw new Error(`session/load failed for session ${e.sessionId}`)}else try{await this.newSession(e)}catch(o){throw f(o)?new m(S(o)):o}e.initialMode&&await this.setLiveMode(e.initialMode).catch(()=>{}),e.initialModel&&await this.setModel(e.initialModel).catch(()=>{}),this.alive=!0}async initialize(){return await this.transport.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:this.terminalEnabled},clientInfo:{name:"grix-connector-acp",version:"0.2.0"}})}buildMcpEntries(e){return(e??[]).map(t=>{if("type"in t){const s={type:t.type,name:t.name,url:t.url};return t.headers&&(s.headers=Object.entries(t.headers).map(([n,r])=>({name:n,value:r}))),s}const i={name:t.name,command:t.command};return t.args&&(i.args=t.args),t.env&&(i.env=Object.entries(t.env).map(([s,n])=>({name:s,value:n}))),i})}async newSession(e){const t=this.buildMcpEntries(e.mcpServers),i={cwd:e.cwd||process.cwd(),mcpServers:t};e.additionalDirectories&&e.additionalDirectories.length>0&&(i.additionalDirectories=e.additionalDirectories),w(i,e.newSessionParams);const s=await this.transport.call("session/new",i);if(!s?.sessionId)throw new Error("session/new returned empty sessionId");this.acpSessionId=s.sessionId,this.absorbModes(s.modes),a.info("acp-client",`[handshake] session/new models block: ${JSON.stringify(s.models)}`),this.absorbModels(s.models),this.absorbConfigOptions(s.configOptions)}async loadSession(e,t){const i=this.buildMcpEntries(t.mcpServers),s={sessionId:e,cwd:t.cwd||process.cwd(),mcpServers:i};t.additionalDirectories&&t.additionalDirectories.length>0&&(s.additionalDirectories=t.additionalDirectories),w(s,t.newSessionParams);const n=await this.transport.call("session/load",s);return n?.sessionId?(this.acpSessionId=n.sessionId,this.absorbModes(n.modes),a.info("acp-client",`[handshake] session/load models block: ${JSON.stringify(n.models)}`),this.absorbModels(n.models),this.absorbConfigOptions(n.configOptions),!0):n&&(n.modes||n.models||n.configOptions)?(this.acpSessionId=e,this.absorbModes(n.modes),a.info("acp-client",`[handshake] session/load (compat) models block: ${JSON.stringify(n.models)}`),this.absorbModels(n.models),this.absorbConfigOptions(n.configOptions),!0):(a.info("acp-client",`[handshake] session/load returned empty result for ${e}`),this.acpSessionId=e,!0)}absorbModes(e){e?.availableModes?.length&&(this.availableModes=[...e.availableModes],e.currentModeId&&(this.currentMode=e.currentModeId))}absorbConfigOptions(e){if(Array.isArray(e))for(const t of e){const i=t,s=Array.isArray(i?.options)?i.options.filter(r=>typeof r?.value=="string"&&r.value):[];if(s.length===0)continue;const n=i.category||i.id;n==="mode"&&this.availableModes.length===0?(this.availableModes=s.map(r=>({id:r.value,name:r.name||r.value,...r.description?{description:r.description}:{}})),typeof i.currentValue=="string"&&i.currentValue&&(this.currentMode=i.currentValue),a.info("acp-client",`[handshake] absorbConfigOptions modes: count=${this.availableModes.length} ids=${JSON.stringify(this.availableModes.map(r=>r.id))} current=${i.currentValue??"<none>"}`)):n==="model"&&this.availableModels.length===0&&(this.availableModels=s.map(r=>({modelId:r.value,name:r.name||r.value})),typeof i.currentValue=="string"&&i.currentValue&&(this.currentModel=i.currentValue),a.info("acp-client",`[handshake] absorbConfigOptions models: count=${this.availableModels.length} ids=${JSON.stringify(this.availableModels.map(r=>r.modelId))} current=${i.currentValue??"<none>"}`))}}absorbModels(e){if(!e?.availableModels?.length){a.info("acp-client","[handshake] absorbModels skipped: block empty");return}this.availableModels=[...e.availableModels],a.info("acp-client",`[handshake] absorbModels: count=${this.availableModels.length} ids=${JSON.stringify(this.availableModels.map(t=>t.modelId))} current=${e.currentModelId??"<none>"}`),e.currentModelId&&(this.currentModel=e.currentModelId)}async send(e,t,i){if(!this.alive)throw new Error("session not active");if(!this.acpSessionId)throw new Error("no agent session id");const s=[{type:"text",text:e}];if(t)for(const n of t)s.push({type:"image",data:n.data.toString("base64"),mimeType:n.mimeType});this.pendingToolCallIds.clear(),this.settleSuppressedSince=0,await this.transport.call("session/prompt",{sessionId:this.acpSessionId,prompt:s,...this.currentModel?{modelId:this.currentModel}:{}}),this.scheduleSettledResult()}scheduleSettledResult(){this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{if(this.settleTimer=null,!!this.alive){if(this.pendingToolCallIds.size>0){if(this.settleSuppressedSince===0&&(this.settleSuppressedSince=Date.now()),Date.now()-this.settleSuppressedSince<p.SETTLE_SUPPRESS_MAX_MS){a.info("acp-client",`settle suppressed: ${this.pendingToolCallIds.size} pending tool call(s) for session ${this.acpSessionId}`),this.scheduleSettledResult();return}a.warn("acp-client",`settle suppression exceeded ${p.SETTLE_SUPPRESS_MAX_MS/6e4}min with ${this.pendingToolCallIds.size} pending tool call(s), emitting Result anyway`)}this.settleSuppressedSince=0,a.info("acp-client",`settle timer fired, emitting Result for session ${this.acpSessionId}`),this.emit("event",{type:h.Result,sessionId:this.acpSessionId,done:!0,synthetic:!0})}},p.SETTLE_MS),this.settleTimer.unref()}deferSettledResult(){this.scheduleSettledResult()}clearSettleTimer(){this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.settleSuppressedSince=0}dispose(){this.clearSettleTimer(),this.terminalHost.dispose(),this.alive=!1}async handleTerminalRequest(e,t,i){try{const s=await this.terminalHost.handle(e,i,this.acpSessionId);await this.transport.respondSuccess(t,s)}catch(s){await this.transport.respondError(t,g(s),s instanceof Error?s.message:String(s))}}async cancel(){if(this.acpSessionId){this.pendingToolCallIds.clear(),this.settleSuppressedSince=0;try{await this.transport.notify("session/cancel",{sessionId:this.acpSessionId})}catch{}}}async authenticate(e){await this.transport.call("authenticate",{methodId:e})}async respondPermission(e,t){const i=this.pendingPermissions.get(e);if(!i)throw new Error(`unknown permission request: ${e}`);this.pendingPermissions.delete(e);const s=this.pickPermissionOptionId(t.behavior,i.options),n=this.buildPermissionResult(t.behavior,s);await this.transport.respondSuccess(i.rpcId,n)}async respondPermissionOption(e,t){const i=this.pendingPermissions.get(e);if(!i)throw new Error(`unknown permission request: ${e}`);if(!i.options.some(s=>s.optionId===t))throw new Error(`unknown permission option: ${t}`);this.pendingPermissions.delete(e),await this.transport.respondSuccess(i.rpcId,{outcome:{outcome:"selected",optionId:t}})}async ping(e=1e4){if(!this.alive)return!1;try{const t=new AbortController,i=setTimeout(()=>t.abort(),e);return await this.transport.call("session/list",{},t.signal),clearTimeout(i),!0}catch(t){return t?.code===-32601}}async setLiveMode(e){if(!this.acpSessionId)return a.warn("acp-client",`setLiveMode("${e}") skipped: no active session`),!1;const t=this.matchAvailableMode(e);if(!t)return a.warn("acp-client",`setLiveMode("${e}") failed: mode not found in available [${this.availableModes.map(i=>i.id).join(",")}]`),!1;try{const i=new AbortController,s=setTimeout(()=>i.abort(),8e3);return await this.transport.call("session/set_mode",{sessionId:this.acpSessionId,modeId:t},i.signal),clearTimeout(s),this.currentMode=t,!0}catch(i){return a.warn("acp-client",`setLiveMode("${t}") RPC failed: ${i instanceof Error?i.message:i}`),!1}}async setModel(e){if(!this.acpSessionId)return a.warn("acp-client",`setModel("${e}") skipped: no active session`),!1;try{const t=new AbortController,i=setTimeout(()=>t.abort(),8e3);return await this.transport.call("session/set_model",{sessionId:this.acpSessionId,modelId:e},t.signal),clearTimeout(i),this.currentModel=e,!0}catch(t){return a.warn("acp-client",`setModel("${e}") RPC failed: ${t instanceof Error?t.message:t}`),!1}}handleSessionUpdate(e){this.emit("activity");const t=e?.update?.sessionUpdate,i=t==="usage_update";if(t==="tool_call"||t==="tool_call_update"){const n=e?.update??{},r=String(n.toolCallId??""),o=String(n.status??"").toLowerCase().trim();r&&(o==="completed"||o==="failed"?this.pendingToolCallIds.delete(r):t==="tool_call"&&this.pendingToolCallIds.add(r))}this.settleTimer&&!i&&this.scheduleSettledResult();const s=M(this.acpSessionId,e);for(const n of s)n.sessionId||(n.sessionId=this.acpSessionId),n.type===h.Result&&(this.pendingToolCallIds.clear(),this.settleTimer&&this.clearSettleTimer()),this.emit("event",n)}handleKiroMetadata(e){const i=e?.contextUsagePercentage;typeof i!="number"||!Number.isFinite(i)||this.emit("event",{type:h.ContextWindowUpdate,sessionId:this.acpSessionId,contextWindow:{usedPercentage:Math.min(100,Math.max(0,i))}})}handleCommandsAvailable(e){const t=e,i=Array.isArray(t?.commands)?t.commands:[];this._availableCommands=i.map(s=>({name:String(s.name??""),description:s.description?String(s.description):void 0,args:s.args?String(s.args):void 0})),this._supportsCommandsExecute=!0,this.emit("commandsAvailable",this._availableCommands)}async executeCommand(e,t,i=2e4){if(!this.alive)throw new Error("session not active");if(!this.acpSessionId)throw new Error("no agent session id");const s=new AbortController;let n=!1;const r=setTimeout(()=>{n=!0,s.abort()},i);try{const o=await this.transport.call("_kiro.dev/commands/execute",{sessionId:this.acpSessionId,command:e,...t?{args:t}:{}},s.signal);return clearTimeout(r),{status:o?.status??"ok",message:o?.message,options:o?.options,data:o?.data}}catch(o){if(clearTimeout(r),n)return{status:"failed",message:`command timed out after ${i}ms`};const l=o instanceof Error?o.message:String(o);if(o?.code===-32601)throw this._supportsCommandsExecute=!1,o;return{status:"failed",message:l}}}handlePermissionRequest(e,t){const i=t,s=i?.toolCall??{},n=String(e),r=Array.isArray(i?.options)?i.options:[];this.pendingPermissions.set(n,{rpcId:e,options:r});const o=s.title||s.kind||"permission",l=s.toolCallId||n,c=s.title||"",u={type:h.PermissionRequest,requestId:n,toolName:o,toolInput:c||l,sessionId:this.acpSessionId,permissionRequest:{requestId:n,toolCallId:l,toolName:o,toolTitle:c,options:r,rawParams:t}};this.emit("event",u)}matchAvailableMode(e){const t=e.toLowerCase();for(const i of this.availableModes)if(i.id.toLowerCase()===t||i.name.toLowerCase()===t)return i.id;return""}pickPermissionOptionId(e,t){if(t.length===0)return"";if(e==="deny"){for(const s of t)if(s.kind==="reject_once"||s.kind==="reject_always")return s.optionId;for(const s of t)if(s.kind.toLowerCase().includes("reject")||s.kind.toLowerCase().includes("deny"))return s.optionId;for(const s of t)if(s.name.toLowerCase().includes("reject")||s.name.toLowerCase().includes("deny"))return s.optionId;return t[t.length-1].optionId}const i=e==="allow-always"?"allow_always":e==="allow-once"?"allow_once":null;if(i){for(const s of t)if(s.kind===i)return s.optionId}for(const s of t)if(s.kind.toLowerCase().includes("allow"))return s.optionId;for(const s of t)if(s.name.toLowerCase().includes("allow"))return s.optionId;return t[0].optionId}buildPermissionResult(e,t){return e==="deny"?t?{outcome:{outcome:"selected",optionId:t}}:{outcome:{outcome:"cancelled"}}:t?{outcome:{outcome:"selected",optionId:t}}:{outcome:{outcome:"cancelled"}}}}export{y as ACP_NEW_SESSION_RESERVED_KEYS,m as AcpAuthRequiredError,p as AcpClient,f as isAuthRequiredError};
1
+ import{EventEmitter as S}from"events";import{log as l}from"../core/log/index.js";import{AgentEventType as p}from"../types/events.js";import{mapSessionUpdate as b}from"./event-mapper.js";import{AcpTerminalHost as M,acpTerminalErrorCode as I}from"./acp-terminal.js";class f extends Error{authMethods;constructor(e){super("ACP authentication required"),this.name="AcpAuthRequiredError",this.authMethods=e}}function g(c){if(!c||typeof c!="object")return!1;const e=c;return e.code===-32e3?!0:e.code===-32603&&e.data?.details?/\b(401|token\s*expired|access\s*token)\b/i.test(e.data.details):!1}function v(c){return!c||typeof c!="object"?[{id:"oauth"}]:c.data?.authMethods??[{id:"oauth"}]}const y=new Set(["cwd","mcpServers","sessionId","additionalDirectories"]);function w(c,e){if(e)for(const[t,i]of Object.entries(e))y.has(t)||(c[t]=i)}class m extends S{acpSessionId="";alive=!1;pendingPermissions=new Map;availableModes=[];availableModels=[];availableThoughtLevels=[];currentMode="";currentModel="";currentThoughtLevel="";thoughtLevelConfigId="";listSupported=!1;loadSupported=!1;_supportsCommandsExecute=!1;_availableCommands=[];transport;terminalEnabled=!1;terminalHost=new M;settleTimer=null;static SETTLE_MS=3e3;pendingToolCallIds=new Set;settleSuppressedSince=0;static SETTLE_SUPPRESS_MAX_MS=900*1e3;constructor(){super(),this.transport=null}get sessionId(){return this.acpSessionId}get isAlive(){return this.alive}get modes(){return[...this.availableModes]}get mode(){return this.currentMode}get models(){return[...this.availableModels]}get model(){return this.currentModel}get sessionOptions(){const e={modes:[...this.availableModes],currentModeId:this.currentMode,models:[...this.availableModels],currentModelId:this.currentModel};return(this.availableThoughtLevels.length>0||this.thoughtLevelConfigId)&&(e.thoughtLevels=[...this.availableThoughtLevels],e.currentThoughtLevelId=this.currentThoughtLevel,e.thoughtLevelConfigId=this.thoughtLevelConfigId||"thinking"),e}get hasThoughtLevel(){return this.availableThoughtLevels.length>0||!!this.thoughtLevelConfigId}get supportsCommandsExecute(){return this._supportsCommandsExecute}get availableCommands(){return[...this._availableCommands]}async connect(e){this.transport=e.transport,this.terminalEnabled=e.terminal===!0,this.transport.on("close",()=>{this.terminalHost.dispose(),this.alive&&(this.alive=!1,this.emit("session-lost"))}),this.transport.setHandlers((o,d)=>{o==="session/update"?this.handleSessionUpdate(d):o==="_kiro.dev/metadata"?this.handleKiroMetadata(d):o==="_kiro.dev/commands/available"?this.handleCommandsAvailable(d):o==="_kiro.dev/compaction/status"?this.emit("compactionStatus",d):o==="_kiro.dev/clear/status"&&this.emit("clearStatus",d)},(o,d,h)=>{o==="session/request_permission"?this.handlePermissionRequest(d,h):o.startsWith("terminal/")&&this.terminalEnabled?this.handleTerminalRequest(o,d,h).catch(u=>{l.warn("acp-client",`terminal response failed: ${u instanceof Error?u.message:String(u)}`)}):o.startsWith("cursor/")?this.transport.respondSuccess(d,{}).catch(()=>{}):this.transport.respondError(d,-32601,"method not implemented").catch(()=>{})});const t=await this.initialize();this.listSupported=!!t.agentCapabilities?.sessionCapabilities?.list,this.loadSupported=!!t.agentCapabilities?.loadSession;const i=t.agentCapabilities??{};this._supportsCommandsExecute=!!(i.extensions?.["_kiro.dev/commands"]||i.commands);const s=t?._meta;if(s?.modelState&&this.absorbModels(s.modelState),e.authMethod)try{await this.transport.call("authenticate",{methodId:e.authMethod})}catch(o){throw g(o)?new f(v(o)):o}const n=e.sessionId&&e.sessionId!=="__continue__";let a=!1;if(n){if(!this.loadSupported)throw new Error(`session/load not supported by agent, cannot resume session ${e.sessionId}`);try{await this.loadSession(e.sessionId,e)&&(a=!0)}catch(o){throw g(o)?new f(v(o)):o}if(!a)throw new Error(`session/load failed for session ${e.sessionId}`)}else try{await this.newSession(e)}catch(o){throw g(o)?new f(v(o)):o}e.initialMode&&await this.setLiveMode(e.initialMode).catch(()=>{}),e.initialModel&&await this.setModel(e.initialModel).catch(()=>{}),this.alive=!0}async initialize(){return await this.transport.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:this.terminalEnabled},clientInfo:{name:"grix-connector-acp",version:"0.2.0"}})}buildMcpEntries(e){return(e??[]).map(t=>{if("type"in t){const s={type:t.type,name:t.name,url:t.url};return t.headers&&(s.headers=Object.entries(t.headers).map(([n,a])=>({name:n,value:a}))),s}const i={name:t.name,command:t.command};return t.args&&(i.args=t.args),t.env&&(i.env=Object.entries(t.env).map(([s,n])=>({name:s,value:n}))),i})}async newSession(e){const t=this.buildMcpEntries(e.mcpServers),i={cwd:e.cwd||process.cwd(),mcpServers:t};e.additionalDirectories&&e.additionalDirectories.length>0&&(i.additionalDirectories=e.additionalDirectories),w(i,e.newSessionParams);const s=await this.transport.call("session/new",i);if(!s?.sessionId)throw new Error("session/new returned empty sessionId");this.acpSessionId=s.sessionId,this.absorbModes(s.modes),l.info("acp-client",`[handshake] session/new models block: ${JSON.stringify(s.models)}`),this.absorbModels(s.models),this.absorbConfigOptions(s.configOptions)}async loadSession(e,t){const i=this.buildMcpEntries(t.mcpServers),s={sessionId:e,cwd:t.cwd||process.cwd(),mcpServers:i};t.additionalDirectories&&t.additionalDirectories.length>0&&(s.additionalDirectories=t.additionalDirectories),w(s,t.newSessionParams);const n=await this.transport.call("session/load",s);return n?.sessionId?(this.acpSessionId=n.sessionId,this.absorbModes(n.modes),l.info("acp-client",`[handshake] session/load models block: ${JSON.stringify(n.models)}`),this.absorbModels(n.models),this.absorbConfigOptions(n.configOptions),!0):n&&(n.modes||n.models||n.configOptions)?(this.acpSessionId=e,this.absorbModes(n.modes),l.info("acp-client",`[handshake] session/load (compat) models block: ${JSON.stringify(n.models)}`),this.absorbModels(n.models),this.absorbConfigOptions(n.configOptions),!0):(l.info("acp-client",`[handshake] session/load returned empty result for ${e}`),this.acpSessionId=e,!0)}absorbModes(e){e?.availableModes?.length&&(this.availableModes=[...e.availableModes],e.currentModeId&&(this.currentMode=e.currentModeId))}absorbConfigOptions(e,t){if(!Array.isArray(e))return;const i=t?.overwrite===!0;for(const s of e){const n=s,a=Array.isArray(n?.options)?n.options.filter(r=>typeof r?.value=="string"&&r.value):[];if(a.length===0)continue;const o=typeof n?.category=="string"?n.category:"",d=typeof n?.id=="string"?n.id:"",h=o||d,u=o==="thought_level"||d==="thinking"||h==="thought_level";h==="mode"&&(i||this.availableModes.length===0)?(this.availableModes=a.map(r=>({id:r.value,name:r.name||r.value,...r.description?{description:r.description}:{}})),typeof n.currentValue=="string"&&n.currentValue&&(this.currentMode=n.currentValue),l.info("acp-client",`[configOptions] absorb modes: count=${this.availableModes.length} ids=${JSON.stringify(this.availableModes.map(r=>r.id))} current=${n.currentValue??"<none>"} overwrite=${i}`)):h==="model"&&(i||this.availableModels.length===0)?(this.availableModels=a.map(r=>({modelId:r.value,name:r.name||r.value})),typeof n.currentValue=="string"&&n.currentValue&&(this.currentModel=n.currentValue),l.info("acp-client",`[configOptions] absorb models: count=${this.availableModels.length} ids=${JSON.stringify(this.availableModels.map(r=>r.modelId))} current=${n.currentValue??"<none>"} overwrite=${i}`)):u&&(i||this.availableThoughtLevels.length===0)&&(this.thoughtLevelConfigId=d||"thinking",this.availableThoughtLevels=a.map(r=>({id:r.value,name:r.name||r.value,...r.description?{description:r.description}:{}})),typeof n.currentValue=="string"&&n.currentValue&&(this.currentThoughtLevel=n.currentValue),l.info("acp-client",`[configOptions] absorb thought_level: configId=${this.thoughtLevelConfigId} count=${this.availableThoughtLevels.length} ids=${JSON.stringify(this.availableThoughtLevels.map(r=>r.id))} current=${n.currentValue??"<none>"} overwrite=${i}`))}}absorbModels(e){if(!e?.availableModels?.length){l.info("acp-client","[handshake] absorbModels skipped: block empty");return}this.availableModels=[...e.availableModels],l.info("acp-client",`[handshake] absorbModels: count=${this.availableModels.length} ids=${JSON.stringify(this.availableModels.map(t=>t.modelId))} current=${e.currentModelId??"<none>"}`),e.currentModelId&&(this.currentModel=e.currentModelId)}async send(e,t,i){if(!this.alive)throw new Error("session not active");if(!this.acpSessionId)throw new Error("no agent session id");const s=[{type:"text",text:e}];if(t)for(const n of t)s.push({type:"image",data:n.data.toString("base64"),mimeType:n.mimeType});this.pendingToolCallIds.clear(),this.settleSuppressedSince=0,await this.transport.call("session/prompt",{sessionId:this.acpSessionId,prompt:s,...this.currentModel?{modelId:this.currentModel}:{}}),this.scheduleSettledResult()}scheduleSettledResult(){this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{if(this.settleTimer=null,!!this.alive){if(this.pendingToolCallIds.size>0){if(this.settleSuppressedSince===0&&(this.settleSuppressedSince=Date.now()),Date.now()-this.settleSuppressedSince<m.SETTLE_SUPPRESS_MAX_MS){l.info("acp-client",`settle suppressed: ${this.pendingToolCallIds.size} pending tool call(s) for session ${this.acpSessionId}`),this.scheduleSettledResult();return}l.warn("acp-client",`settle suppression exceeded ${m.SETTLE_SUPPRESS_MAX_MS/6e4}min with ${this.pendingToolCallIds.size} pending tool call(s), emitting Result anyway`)}this.settleSuppressedSince=0,l.info("acp-client",`settle timer fired, emitting Result for session ${this.acpSessionId}`),this.emit("event",{type:p.Result,sessionId:this.acpSessionId,done:!0,synthetic:!0})}},m.SETTLE_MS),this.settleTimer.unref()}deferSettledResult(){this.scheduleSettledResult()}clearSettleTimer(){this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.settleSuppressedSince=0}dispose(){this.clearSettleTimer(),this.terminalHost.dispose(),this.alive=!1}async handleTerminalRequest(e,t,i){try{const s=await this.terminalHost.handle(e,i,this.acpSessionId);await this.transport.respondSuccess(t,s)}catch(s){await this.transport.respondError(t,I(s),s instanceof Error?s.message:String(s))}}async cancel(){if(this.acpSessionId){this.pendingToolCallIds.clear(),this.settleSuppressedSince=0;try{await this.transport.notify("session/cancel",{sessionId:this.acpSessionId})}catch{}}}async authenticate(e){await this.transport.call("authenticate",{methodId:e})}async respondPermission(e,t){const i=this.pendingPermissions.get(e);if(!i)throw new Error(`unknown permission request: ${e}`);this.pendingPermissions.delete(e);const s=this.pickPermissionOptionId(t.behavior,i.options),n=this.buildPermissionResult(t.behavior,s);await this.transport.respondSuccess(i.rpcId,n)}async respondPermissionOption(e,t){const i=this.pendingPermissions.get(e);if(!i)throw new Error(`unknown permission request: ${e}`);if(!i.options.some(s=>s.optionId===t))throw new Error(`unknown permission option: ${t}`);this.pendingPermissions.delete(e),await this.transport.respondSuccess(i.rpcId,{outcome:{outcome:"selected",optionId:t}})}async ping(e=1e4){if(!this.alive)return!1;try{const t=new AbortController,i=setTimeout(()=>t.abort(),e);return await this.transport.call("session/list",{},t.signal),clearTimeout(i),!0}catch(t){return t?.code===-32601}}async setLiveMode(e){if(!this.acpSessionId)return l.warn("acp-client",`setLiveMode("${e}") skipped: no active session`),!1;const t=this.matchAvailableMode(e);if(!t)return l.warn("acp-client",`setLiveMode("${e}") failed: mode not found in available [${this.availableModes.map(i=>i.id).join(",")}]`),!1;try{const i=new AbortController,s=setTimeout(()=>i.abort(),8e3);return await this.transport.call("session/set_mode",{sessionId:this.acpSessionId,modeId:t},i.signal),clearTimeout(s),this.currentMode=t,!0}catch(i){return l.warn("acp-client",`setLiveMode("${t}") RPC failed: ${i instanceof Error?i.message:i}`),!1}}async setModel(e){if(!this.acpSessionId)return l.warn("acp-client",`setModel("${e}") skipped: no active session`),!1;try{const t=new AbortController,i=setTimeout(()=>t.abort(),8e3);return await this.transport.call("session/set_model",{sessionId:this.acpSessionId,modelId:e},t.signal),clearTimeout(i),this.currentModel=e,!0}catch(t){return l.warn("acp-client",`setModel("${e}") RPC failed: ${t instanceof Error?t.message:t}`),!1}}async setConfigOption(e,t){const i=String(e??"").trim(),s=String(t??"").trim();if(!this.acpSessionId)return l.warn("acp-client",`setConfigOption("${i}","${s}") skipped: no active session`),!1;if(!i||!s)return l.warn("acp-client","setConfigOption skipped: empty configId/value"),!1;try{const n=new AbortController,a=setTimeout(()=>n.abort(),8e3),o=await this.transport.call("session/set_config_option",{sessionId:this.acpSessionId,configId:i,value:s},n.signal);return clearTimeout(a),o?.configOptions?(this.absorbConfigOptions(o.configOptions,{overwrite:!0}),this.emit("configOptionsUpdated")):(i===this.thoughtLevelConfigId||i==="thinking")&&(this.currentThoughtLevel=s,this.thoughtLevelConfigId||(this.thoughtLevelConfigId=i)),!0}catch(n){return l.warn("acp-client",`setConfigOption("${i}","${s}") RPC failed: ${n instanceof Error?n.message:n}`),!1}}handleSessionUpdate(e){this.emit("activity");const t=e?.update?.sessionUpdate,i=t==="usage_update"||t==="config_option_update";if(t==="config_option_update"){const a=(e?.update??{}).configOptions??e?.configOptions;this.absorbConfigOptions(a,{overwrite:!0}),this.emit("configOptionsUpdated")}if(t==="tool_call"||t==="tool_call_update"){const n=e?.update??{},a=String(n.toolCallId??""),o=String(n.status??"").toLowerCase().trim();a&&(o==="completed"||o==="failed"?this.pendingToolCallIds.delete(a):t==="tool_call"&&this.pendingToolCallIds.add(a))}this.settleTimer&&!i&&this.scheduleSettledResult();const s=b(this.acpSessionId,e);for(const n of s)n.sessionId||(n.sessionId=this.acpSessionId),n.type===p.Result&&(this.pendingToolCallIds.clear(),this.settleTimer&&this.clearSettleTimer()),this.emit("event",n)}handleKiroMetadata(e){const i=e?.contextUsagePercentage;typeof i!="number"||!Number.isFinite(i)||this.emit("event",{type:p.ContextWindowUpdate,sessionId:this.acpSessionId,contextWindow:{usedPercentage:Math.min(100,Math.max(0,i))}})}handleCommandsAvailable(e){const t=e,i=Array.isArray(t?.commands)?t.commands:[];this._availableCommands=i.map(s=>({name:String(s.name??""),description:s.description?String(s.description):void 0,args:s.args?String(s.args):void 0})),this._supportsCommandsExecute=!0,this.emit("commandsAvailable",this._availableCommands)}async executeCommand(e,t,i=2e4){if(!this.alive)throw new Error("session not active");if(!this.acpSessionId)throw new Error("no agent session id");const s=new AbortController;let n=!1;const a=setTimeout(()=>{n=!0,s.abort()},i);try{const o=await this.transport.call("_kiro.dev/commands/execute",{sessionId:this.acpSessionId,command:e,...t?{args:t}:{}},s.signal);return clearTimeout(a),{status:o?.status??"ok",message:o?.message,options:o?.options,data:o?.data}}catch(o){if(clearTimeout(a),n)return{status:"failed",message:`command timed out after ${i}ms`};const d=o instanceof Error?o.message:String(o);if(o?.code===-32601)throw this._supportsCommandsExecute=!1,o;return{status:"failed",message:d}}}handlePermissionRequest(e,t){const i=t,s=i?.toolCall??{},n=String(e),a=Array.isArray(i?.options)?i.options:[];this.pendingPermissions.set(n,{rpcId:e,options:a});const o=s.title||s.kind||"permission",d=s.toolCallId||n,h=s.title||"",u={type:p.PermissionRequest,requestId:n,toolName:o,toolInput:h||d,sessionId:this.acpSessionId,permissionRequest:{requestId:n,toolCallId:d,toolName:o,toolTitle:h,options:a,rawParams:t}};this.emit("event",u)}matchAvailableMode(e){const t=e.toLowerCase();for(const i of this.availableModes)if(i.id.toLowerCase()===t||i.name.toLowerCase()===t)return i.id;return""}pickPermissionOptionId(e,t){if(t.length===0)return"";if(e==="deny"){for(const s of t)if(s.kind==="reject_once"||s.kind==="reject_always")return s.optionId;for(const s of t)if(s.kind.toLowerCase().includes("reject")||s.kind.toLowerCase().includes("deny"))return s.optionId;for(const s of t)if(s.name.toLowerCase().includes("reject")||s.name.toLowerCase().includes("deny"))return s.optionId;return t[t.length-1].optionId}const i=e==="allow-always"?"allow_always":e==="allow-once"?"allow_once":null;if(i){for(const s of t)if(s.kind===i)return s.optionId}for(const s of t)if(s.kind.toLowerCase().includes("allow"))return s.optionId;for(const s of t)if(s.name.toLowerCase().includes("allow"))return s.optionId;return t[0].optionId}buildPermissionResult(e,t){return e==="deny"?t?{outcome:{outcome:"selected",optionId:t}}:{outcome:{outcome:"cancelled"}}:t?{outcome:{outcome:"selected",optionId:t}}:{outcome:{outcome:"cancelled"}}}}export{y as ACP_NEW_SESSION_RESERVED_KEYS,f as AcpAuthRequiredError,m as AcpClient,g as isAuthRequiredError};
@@ -0,0 +1 @@
1
+ import{SessionManager as a}from"./manager.js";export{a as SessionManager};
@@ -0,0 +1 @@
1
+ import{EventEmitter as r}from"events";import{AgentProcess as c}from"../agent/process.js";import{AcpClient as l}from"../protocol/acp-client.js";class h extends r{sessions=new Map;async create(s){const e=new c,n=await e.start(s.agent),i=new l;i.on("event",a=>{this.emit("event",a)}),await i.connect({transport:n,sessionId:s.sessionId,authMethod:s.authMethod,initialMode:s.initialMode});const t=i.sessionId,o={id:t,process:e,client:i};return this.sessions.set(t,o),n.on("close",()=>{this.sessions.delete(t),this.emit("sessionClosed",t)}),this.emit("sessionCreated",t),o}get(s){return this.sessions.get(s)}list(){return[...this.sessions.values()]}async close(s){const e=this.sessions.get(s);e&&(this.sessions.delete(s),await e.process.close(),this.emit("sessionClosed",s))}async closeAll(){const s=[...this.sessions.keys()];await Promise.all(s.map(e=>this.close(e)))}get size(){return this.sessions.size}}export{h as SessionManager};
@@ -0,0 +1 @@
1
+ import{JsonRpcTransport as o}from"./json-rpc.js";export{o as JsonRpcTransport};
@@ -0,0 +1,3 @@
1
+ import{EventEmitter as p}from"events";class w extends p{nextId=1;pending=new Map;writeLock=Promise.resolve();closed=!1;_readable;_writable;_onNotify;_onRequest;constructor(t,e,r,o){super(),this._readable=t,this._writable=e,this._onNotify=r,this._onRequest=o,this.startReadLoop()}setHandlers(t,e){t&&(this._onNotify=t),e&&(this._onRequest=e)}async call(t,e,r){if(this.closed)throw new Error("transport closed");const o=this.nextId++,s=String(o),a=await new Promise((i,d)=>{if(this.pending.set(s,{resolve:i}),r){const n=()=>{this.pending.delete(s),d(new Error(`aborted: ${r.reason??"request cancelled"}`))};if(r.aborted){n();return}r.addEventListener("abort",n,{once:!0});const c=i,h=l=>{r.removeEventListener("abort",n),c(l)};this.pending.set(s,{resolve:h})}this.write({jsonrpc:"2.0",id:o,method:t,params:e??null}).catch(n=>{this.pending.delete(s),d(n)})});if(a.error){const i=new Error(a.error.message);throw i.code=a.error.code,i}return a.result}async notify(t,e){if(this.closed)throw new Error("transport closed");await this.write({jsonrpc:"2.0",method:t,params:e??null})}async respondSuccess(t,e){await this.write({jsonrpc:"2.0",id:t,result:e})}async respondError(t,e,r){await this.write({jsonrpc:"2.0",id:t,error:{code:e,message:r}})}close(){if(!this.closed){this.closed=!0;for(const[t,{resolve:e}]of this.pending)e({error:{code:-32e3,message:"transport closed"}});this.pending.clear(),this._readable.destroy(),this.emit("close")}}startReadLoop(){let t="";this._readable.on("data",e=>{t+=e.toString();const r=t.split(`
2
+ `);t=r.pop()??"";for(const o of r){const s=o.trim();s.length!==0&&this.dispatch(s)}}),this._readable.on("end",()=>{t.trim()&&this.dispatch(t.trim()),this.close()}),this._readable.on("error",e=>{this.emit("error",e),this.close()})}dispatch(t){let e;try{e=JSON.parse(t)}catch{return}if(e.id!=null&&!e.method){this.completePending(e.id,e.result,e.error);return}if(e.method&&(e.id==null||e.id===null)){this._onNotify?.(e.method,e.params);return}e.method&&e.id!=null&&this._onRequest?.(e.method,e.id,e.params)}completePending(t,e,r){const o=String(t),s=this.pending.get(o);s&&(this.pending.delete(o),s.resolve({result:e,error:r}))}async write(t){const e=this.writeLock;return this.writeLock=e.then(async()=>new Promise((r,o)=>{const s=JSON.stringify(t)+`
3
+ `;this._writable.write(s,"utf-8")?r():(this._writable.once("drain",r),this._writable.once("error",o))})),this.writeLock}}export{w as JsonRpcTransport};
@@ -7983,7 +7983,8 @@ function mapDshSessionEvent(event) {
7983
7983
  const blocks = Array.isArray(message.content) ? message.content : [];
7984
7984
  const hasToolCall = blocks.some((item) => item && typeof item === "object" && String(item.type ?? "") === "tool-call");
7985
7985
  const content = Array.isArray(message.content) ? blocks.filter((item) => item && typeof item === "object" && String(item.type ?? "") === "text").map((item) => String(item.text ?? "")).join("") : String(message.content ?? message.text ?? "");
7986
- return { kind: "text", text: content, usage: message.usage ?? data.usage, payload: { committed: true, hasToolCall } };
7986
+ const reasoning = blocks.filter((item) => item && typeof item === "object" && String(item.type ?? "") === "reasoning").map((item) => String(item.text ?? "")).join("");
7987
+ return { kind: "text", text: content, reasoning, usage: message.usage ?? data.usage, payload: { committed: true, hasToolCall } };
7987
7988
  }
7988
7989
  if (event.type === "request/context") {
7989
7990
  return {
@@ -10989,6 +10989,45 @@ var TOOLS = [
10989
10989
  properties: {}
10990
10990
  }
10991
10991
  },
10992
+ {
10993
+ name: "grix_chat_queue",
10994
+ description: "Inspect and control the task queue of a chat session. Actions: list (show queued tasks), cancel (drop a queued task), clear (drop all queued tasks), hold (pause/resume a queued task, ttl_ms clamped to 60s..30min, default 10min), edit (rewrite a queued task's content), reorder (set the desired order of queued tasks). cancel/edit/hold only apply to queued (not running) tasks. A held task at the head of the queue stalls the whole queue. reorder is a desired-order request: missing ids are ignored and newly queued tasks go to the tail. A result with confirmed=false means the command was dispatched but not yet confirmed \u2014 call list again to verify.",
10995
+ inputSchema: {
10996
+ type: "object",
10997
+ properties: {
10998
+ action: {
10999
+ type: "string",
11000
+ enum: ["list", "cancel", "clear", "hold", "edit", "reorder"],
11001
+ description: "Queue action: list, cancel, clear, hold, edit, or reorder."
11002
+ },
11003
+ session_id: { type: "string", description: "Target session ID." },
11004
+ event_id: { type: "string", description: "Queued task event ID (cancel, hold, edit)." },
11005
+ agent_id: { type: "string", description: "(Optional) Agent ID when the session has multiple agents." },
11006
+ hold: { type: "boolean", description: "hold=true pauses the task, hold=false resumes it." },
11007
+ ttl_ms: { type: "integer", description: "(Optional) Hold duration in milliseconds, clamped to 60000..1800000. Defaults to 600000 (10 minutes)." },
11008
+ content: { type: "string", description: "New task content (edit)." },
11009
+ ordered_event_ids: {
11010
+ type: "array",
11011
+ items: { type: "string" },
11012
+ description: "Desired queue order as event IDs (reorder). Must be a non-empty array."
11013
+ }
11014
+ },
11015
+ required: ["action"]
11016
+ },
11017
+ validation: {
11018
+ required: ["action"],
11019
+ properties: {
11020
+ action: { type: "string", enum: ["list", "cancel", "clear", "hold", "edit", "reorder"] },
11021
+ session_id: { type: "string" },
11022
+ event_id: { type: "string" },
11023
+ agent_id: { type: "string" },
11024
+ hold: { type: "boolean" },
11025
+ ttl_ms: { type: "integer" },
11026
+ content: { type: "string" },
11027
+ ordered_event_ids: { type: "array", items: { type: "string" } }
11028
+ }
11029
+ }
11030
+ },
10992
11031
  {
10993
11032
  name: "grix_access_control",
10994
11033
  description: "Manage sender access control: pair approval, allow/remove senders, set policy.",
@@ -11327,6 +11366,7 @@ var TOOL_SKILL_MAP = {
11327
11366
  grix_session_send: "grix-owner-relay",
11328
11367
  grix_chat_state_query: "grix-chat-state",
11329
11368
  grix_chat_state_update: "grix-chat-state",
11369
+ grix_chat_queue: "grix-chat-state",
11330
11370
  grix_status: "grix-chat-state",
11331
11371
  grix_access_control: "grix-access-control",
11332
11372
  grix_widget_visitor_ban: "grix-widget-visitor-ban",
@@ -11411,6 +11451,8 @@ function toolCallToInvoke(toolName, args) {
11411
11451
  return buildChatStateQueryInvoke(args);
11412
11452
  case "grix_chat_state_update":
11413
11453
  return buildChatStateUpdateInvoke(args);
11454
+ case "grix_chat_queue":
11455
+ return buildChatQueueInvoke(args);
11414
11456
  case "grix_access_control":
11415
11457
  return buildAccessControlInvoke(args);
11416
11458
  case "grix_widget_visitor_ban":
@@ -11632,6 +11674,58 @@ function buildChatStateUpdateInvoke(args) {
11632
11674
  if (args.reason != null) params.reason = args.reason;
11633
11675
  return { action: "chat_state_update", params };
11634
11676
  }
11677
+ var CHAT_QUEUE_ACTION_MAP = {
11678
+ list: "chat_queue_list",
11679
+ cancel: "chat_queue_cancel",
11680
+ clear: "chat_queue_clear",
11681
+ hold: "chat_queue_hold",
11682
+ edit: "chat_queue_edit",
11683
+ reorder: "chat_queue_reorder"
11684
+ };
11685
+ var CHAT_QUEUE_REQUIRED_PARAMS = {
11686
+ list: ["session_id"],
11687
+ cancel: ["session_id", "event_id"],
11688
+ clear: ["session_id"],
11689
+ hold: ["session_id", "event_id", "hold"],
11690
+ edit: ["session_id", "event_id", "content"],
11691
+ reorder: ["session_id", "ordered_event_ids"]
11692
+ };
11693
+ var CHAT_QUEUE_EXTRA_PARAMS = {
11694
+ list: ["agent_id"],
11695
+ cancel: ["event_id", "agent_id"],
11696
+ clear: ["agent_id"],
11697
+ hold: ["event_id", "hold", "ttl_ms", "agent_id"],
11698
+ edit: ["event_id", "content", "agent_id"],
11699
+ reorder: ["ordered_event_ids", "agent_id"]
11700
+ };
11701
+ function isMissingArg(value) {
11702
+ if (value === void 0 || value === null) return true;
11703
+ return typeof value === "string" && value.trim() === "";
11704
+ }
11705
+ function buildChatQueueInvoke(args) {
11706
+ const action = String(args.action ?? "");
11707
+ const invokeAction = CHAT_QUEUE_ACTION_MAP[action];
11708
+ if (!invokeAction) throw new Error(`Unknown grix_chat_queue action: ${action}`);
11709
+ for (const field of CHAT_QUEUE_REQUIRED_PARAMS[action]) {
11710
+ if (isMissingArg(args[field])) {
11711
+ throw new Error(`grix_chat_queue ${action} requires ${field}`);
11712
+ }
11713
+ }
11714
+ if (action === "reorder") {
11715
+ const ordered = args.ordered_event_ids;
11716
+ if (!Array.isArray(ordered) || ordered.length === 0) {
11717
+ throw new Error("grix_chat_queue reorder requires a non-empty ordered_event_ids array");
11718
+ }
11719
+ if (ordered.some((id) => typeof id !== "string" || id.trim() === "")) {
11720
+ throw new Error("grix_chat_queue reorder ordered_event_ids must contain only non-empty strings");
11721
+ }
11722
+ }
11723
+ const params = { session_id: args.session_id };
11724
+ for (const field of CHAT_QUEUE_EXTRA_PARAMS[action]) {
11725
+ if (args[field] != null) params[field] = args[field];
11726
+ }
11727
+ return { action: invokeAction, params };
11728
+ }
11635
11729
  function buildSkillSetInvoke(args) {
11636
11730
  return { action: "skill_set", params: { name: args.name, content: args.content }, timeoutMs: 3e4 };
11637
11731
  }
@@ -11671,6 +11765,7 @@ var PHASE1_INVOKE_ACTIONS = /* @__PURE__ */ new Set([
11671
11765
  "session_send",
11672
11766
  "chat_state_query",
11673
11767
  "chat_state_update",
11768
+ ...Object.values(CHAT_QUEUE_ACTION_MAP),
11674
11769
  "claude_access_control",
11675
11770
  "widget_visitor_ban",
11676
11771
  "webhook_create",
@@ -15241,6 +15336,9 @@ function createGrixChatStateQueryTool(api, ctx) {
15241
15336
  function createGrixChatStateUpdateTool(api, ctx) {
15242
15337
  return createGrixInvokeTool({ toolName: "grix_chat_state_update", label: "Grix Chat State Update", api, ctx });
15243
15338
  }
15339
+ function createGrixChatQueueTool(api, ctx) {
15340
+ return createGrixInvokeTool({ toolName: "grix_chat_queue", label: "Grix Chat Queue", api, ctx });
15341
+ }
15244
15342
 
15245
15343
  // src/openclaw/admin/access-control-tools.ts
15246
15344
  function createGrixAccessControlTool(api, ctx) {
@@ -15304,6 +15402,7 @@ var plugin = {
15304
15402
  api.registerTool((ctx) => createGrixSessionSendTool(api, ctx));
15305
15403
  api.registerTool((ctx) => createGrixChatStateQueryTool(api, ctx));
15306
15404
  api.registerTool((ctx) => createGrixChatStateUpdateTool(api, ctx));
15405
+ api.registerTool((ctx) => createGrixChatQueueTool(api, ctx));
15307
15406
  api.registerTool((ctx) => createGrixCallOwnerTool(api, ctx));
15308
15407
  api.registerTool((ctx) => createGrixAgentUpdateTool(api, ctx));
15309
15408
  api.registerTool((ctx) => createGrixAccessControlTool(api, ctx));
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: grix-chat-state
3
- description: Observe and manage chat task state — query the task state of all the owner's chats (`grix_chat_state_query`) and manually override one chat's state (`grix_chat_state_update`). Trigger when the user asks which chats are running/done/waiting, or wants a chat marked done/failed/idle.
3
+ description: Observe and manage chat task state and task queues — query the task state of all the owner's chats (`grix_chat_state_query`), manually override one chat's state (`grix_chat_state_update`), and inspect or control a session's queued tasks (`grix_chat_queue`). Trigger when the user asks which chats are running/done/waiting, wants a chat marked done/failed/idle, or wants queued tasks listed, cancelled, cleared, paused, edited, or reordered.
4
4
  ---
5
5
 
6
6
  # Grix Chat State
@@ -42,6 +42,38 @@ record and errors if the session has none.
42
42
  `waiting_question`, `completed`, `failed`, `idle`
43
43
  - `reason` (optional) — written to `stop_reason`
44
44
 
45
+ ## Inspect and control the task queue — `grix_chat_queue`
46
+
47
+ One tool with an `action` parameter; `session_id` is always required. Other
48
+ parameters are passed through to the backend.
49
+
50
+ | action | extra parameters | effect |
51
+ | --- | --- | --- |
52
+ | `list` | `agent_id` (optional) | List queued tasks; returns `items` |
53
+ | `cancel` | `event_id` (required), `agent_id` | Drop one queued task |
54
+ | `clear` | `agent_id` (optional) | Drop all queued tasks |
55
+ | `hold` | `event_id`, `hold` (required), `ttl_ms` (optional), `agent_id` | Pause (`hold=true`) or resume (`hold=false`) one queued task |
56
+ | `edit` | `event_id`, `content` (required), `agent_id` | Rewrite a queued task's content |
57
+ | `reorder` | `ordered_event_ids` (required, non-empty string array), `agent_id` | Set the desired queue order |
58
+
59
+ Semantics to respect:
60
+
61
+ - `cancel`, `edit`, and `hold` only work on **queued** tasks. They cannot touch
62
+ the task that is currently executing; if the user asks to change a running
63
+ task, say so instead of pretending it worked.
64
+ - A held task that reaches the head of the queue stalls the **entire** queue
65
+ until it is resumed or its TTL expires. Mention this when pausing a task near
66
+ the head.
67
+ - `ttl_ms` is clamped by the backend to 60 seconds through 30 minutes, defaults
68
+ to 10 minutes, and the hold is lifted automatically when it expires.
69
+ - `reorder` expresses a **desired order**: ids that no longer exist are ignored,
70
+ and tasks that enter the queue later go to the tail.
71
+ - A response with `confirmed: true` carries the resulting `items`. A response
72
+ with `confirmed: false, dispatched: true` means the command was sent but not
73
+ yet acknowledged — call `list` again to verify the final state before
74
+ reporting success to the owner. `list` may include `stale: true` when the
75
+ connector is offline; treat that snapshot as possibly outdated.
76
+
45
77
  ## Rules
46
78
 
47
79
  1. Never invent a `session_id`. Resolve it with `grix_query` (`session_search`)
@@ -27,6 +27,7 @@
27
27
  "grix_session_send",
28
28
  "grix_chat_state_query",
29
29
  "grix_chat_state_update",
30
+ "grix_chat_queue",
30
31
  "grix_call_owner",
31
32
  "grix_agent_update",
32
33
  "grix_access_control",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "4.18.1",
3
+ "version": "5.0.0",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",