grix-connector 4.17.0 → 4.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/agy/agy-adapter.js +8 -8
- package/dist/adapter/claude/claude-adapter.js +22 -22
- package/dist/adapter/claude/config-paths.js +1 -0
- package/dist/adapter/claude/model-list.js +1 -1
- package/dist/adapter/claude/session-history.js +2 -2
- package/dist/adapter/claude/session-scanner.js +1 -1
- package/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/claude/usage-parser.js +8 -8
- package/dist/adapter/opencode/opencode-adapter.js +1 -1
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.17.0.tgz → grix-dsh-bridge-4.18.1.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/session-control-router.js +2 -2
- package/dist/bridge/session-list.js +2 -2
- package/dist/bridge/session-scan-cache.js +1 -1
- package/dist/bridge/session-usage.js +1 -1
- package/dist/bridge/skill-actions.js +1 -1
- package/dist/bridge/toolbar-meta.js +1 -1
- package/dist/core/config/index.js +1 -1
- package/dist/core/config/paths.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -1
- package/dist/core/skill-sync/enable-roots.js +1 -1
- package/dist/core/skill-sync/library-skills.js +1 -1
- package/dist/core/skill-sync/skill-enable.js +1 -1
- package/dist/core/util/cli-probe.js +2 -2
- package/dist/grix.js +0 -0
- package/dist/manager.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +52 -52
- package/openclaw-plugin/index.js +65 -65
- package/package.json +1 -1
- package/dist/adapter/claude/claude-bridge-server.js +0 -1
- package/dist/adapter/claude/claude-tools.js +0 -1
- package/dist/adapter/claude/claude-worker-client.js +0 -1
- package/dist/adapter/claude/mcp-http-launcher.js +0 -2
- package/dist/adapter/claude/result-timeout.js +0 -1
- package/dist/adapter/deepseek/deepseek-adapter.js +0 -6
- package/dist/adapter/deepseek/index.js +0 -1
- package/dist/adapter/qwen/index.js +0 -1
- package/dist/adapter/qwen/qwen-adapter.js +0 -4
- package/dist/aibot/client.js +0 -1
- package/dist/aibot/index.js +0 -1
- package/dist/aibot/types.js +0 -0
- package/dist/core/access/allowlist-gate.js +0 -1
- package/dist/core/access/allowlist-store.js +0 -1
- package/dist/core/access/index.js +0 -1
- package/dist/core/file-ops/handler.js +0 -1
- package/dist/core/file-ops/list-files.js +0 -1
- package/dist/core/file-ops/types.js +0 -0
- package/dist/log.js +0 -3
- package/dist/main.js +0 -31
- package/dist/mcp/stream-http/config.js +0 -1
- package/dist/mcp/stream-http/connection-binding.js +0 -1
- package/dist/mcp/stream-http/event-tool-executor.js +0 -1
- package/dist/mcp/stream-http/gateway.js +0 -1
- package/dist/mcp/stream-http/index.js +0 -1
- package/dist/mcp/stream-http/security.js +0 -1
- package/dist/mcp/stream-http/session-manager.js +0 -1
- package/dist/mcp/stream-http/tool-executor.js +0 -1
- package/dist/mcp/stream-http/tool-registry.js +0 -1
- package/dist/mcp/stream-http/tool-schemas.js +0 -1
- package/dist/session/index.js +0 -1
- package/dist/session/manager.js +0 -1
- package/dist/transport/index.js +0 -1
- package/dist/transport/json-rpc.js +0 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{spawn as F}from"node:child_process";import{randomUUID as
|
|
2
|
-
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P($(),".gemini","skills"),d=z(r);d.length>0&&a.info(c,`Synced connector skills to ${r}: [${d.join(", ")}]`)}catch(t){a.warn(c,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,
|
|
1
|
+
import{spawn as F}from"node:child_process";import{randomUUID as N}from"node:crypto";import{EventEmitter as L}from"node:events";import{existsSync as b,readFileSync as I,statSync as B,mkdirSync as G,writeFileSync as K,realpathSync as Y}from"node:fs";import{homedir as $}from"node:os";import{join as P,dirname as V,resolve as Q}from"node:path";import{fileURLToPath as U}from"node:url";import{log as a}from"../../core/log/index.js";import{killProcessGroup as w}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as H,pruneLegacyMcpServerEntries as J}from"../../core/mcp/server-name.js";import{syncDefaultSkillsToDir as z}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{getAgyModelCatalog as Z,resolveAgyModelFlag as tt}from"./model-list.js";import{isGrixInternalToolName as k}from"../../core/mcp/tools.js";import{AgyStreamParser as et}from"./stream-parser.js";const c="agy-adapter";function it(g){return/^API error \(attempt \d+\):/.test(g.trim())}function st(g,t,e,s){return g===0&&it(t)&&(e.trim().length>0||s)}function nt(g){try{return process.kill(g,0),!0}catch(t){return t.code==="EPERM"}}function rt(g){try{return Y(g)}catch{return g}}const O=P($(),".gemini","antigravity-cli","log"),ot="CLI store manager shutting down",at=5e3,_=15e3,j=480*1e3,ct=["fetchAvailableModels","loadCodeAssist","token refreshed","ListExperiments","experiment refresh","Experiments refreshed","Reloading system slash commands","Slash commands unchanged","doRefreshQuota"];function lt(g,t){const e=Number(process.env[g]);return Number.isFinite(e)&&e>0?e:t}const dt="30m",D=P($(),".gemini","antigravity-cli","cache","last_conversations.json"),ht=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001agent_id\uFF08\u5F53\u524D Agent\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u5F53\u524D Turn \u7684\u6B63\u5F0F\u56DE\u7B54\u76F4\u63A5\u4F5C\u4E3A\u6700\u7EC8\u54CD\u5E94\u8F93\u51FA\uFF0C\u7531\u8FDE\u63A5\u5668\u8BFB\u53D6\u5E76\u53D1\u9001\u7ED9\u7528\u6237\u3002","\u4E0D\u8981\u4F7F\u7528 grix_message_send \u56DE\u7B54\u5F53\u524D\u5165\u7AD9\u4E8B\u4EF6\uFF1B\u5B83\u4EC5\u7528\u4E8E\u4E0E\u672C\u6B21\u56DE\u7B54\u65E0\u5173\u7684\u4E3B\u52A8\u6D88\u606F\u3002","\u8FDB\u7A0B\u5B89\u5168\uFF1A\u542F\u52A8\u4E34\u65F6\u6216\u6F14\u793A\u670D\u52A1\u65F6\u5FC5\u987B\u8BB0\u5F55\u5176 PID\uFF0C\u505C\u6B62\u65F6\u53EA\u7EC8\u6B62\u5DF2\u786E\u8BA4\u5C5E\u4E8E\u672C\u4EFB\u52A1\u7684\u8BE5 PID \u6216\u5176\u4E13\u5C5E\u8FDB\u7A0B\u7EC4\u3002","\u7981\u6B62\u4F7F\u7528 `pkill`\u3001`killall` \u6216\u5176\u4ED6\u6309\u540D\u79F0/\u547D\u4EE4\u884C\u6A21\u5F0F\u6279\u91CF\u6740\u8FDB\u7A0B\u7684\u547D\u4EE4\uFF1B\u7EDD\u4E0D\u80FD\u7EC8\u6B62 Grix MCP\u3001\u5F53\u524D agy \u6216\u5176\u7236\u8FDB\u7A0B\u3001connector \u6216\u5176\u4ED6\u65E0\u5173\u8FDB\u7A0B\u3002"].join(""),ut=new Set(["send_msg","grix_reply"]),ft=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);function W(g){try{return structuredClone(g)}catch{return}}class bt extends L{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;auditCaptures=new Map;completedAuditBoundaries=new Map;watchdogPollTimer=null;watchdogGraceTimer=null;watchdogKilledActiveProcess=!1;lastActivityAt=0;watchLogOffset=0;inactivityTimeoutMs=j;inactivityWarned=!1;inFlightToolName=null;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];systemInstructionInjectedSessions=new Set;identityInjectedSessions=new Set;constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),a.info(c,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(o,h,l,u)=>this.handleToolInvoke(o,h,u)),await this.internalApi.start(0),a.info(c,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=P($(),".gemini","config","mcp_config.json");G(V(e),{recursive:!0});let s={};try{b(e)&&(s=JSON.parse(I(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};J(i,this.internalApi.url),i[t.name]={command:t.command,args:t.args},s.mcpServers=i,K(e,`${JSON.stringify(s,null,2)}
|
|
2
|
+
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P($(),".gemini","skills"),d=z(r);d.length>0&&a.info(c,`Synced connector skills to ${r}: [${d.join(", ")}]`)}catch(t){a.warn(c,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){this.touchActivity();let i=e;ft.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const r=this.activeEventId?this.auditCaptures.get(this.activeEventId):void 0,d=r?{sequence:r.toolInvocations.length,observedAt:new Date().toISOString(),action:t,params:W(i)}:void 0;r&&d&&r.toolInvocations.push(d);try{const o=await this.callbacks.agentInvoke(t,i,s);return d&&(d.completedAt=new Date().toISOString(),d.result=W(o)),ut.has(t)&&this.activeEventId&&this.activeEventSessionId&&i.session_id===this.activeEventSessionId&&(this.activeEventSentViaTool=!0),o}catch(o){throw d&&(d.completedAt=new Date().toISOString(),d.error=o instanceof Error?o.message:String(o)),o}}async stop(){if(!this.stopped){if(this.stopped=!0,this.alive=!1,this.stopTurnWatchdog(),this.inFlightToolName=null,this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,this.activeProcess){try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId)try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}if(this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),a.info(c,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??N()}async resumeSession(t,e){}async destroySession(t){this.systemInstructionInjectedSessions.delete(t),this.identityInjectedSessions.delete(t)}onAgentProfileChanged(){this.identityInjectedSessions.clear()}sendPrompt(t){const e=new L;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;a.info(c,`cancelCurrentRun: killing process group for event ${t}`);try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","restarted by user"),this.clearActiveEvent(t),this.drainQueue()}deliverInboundEvent(t){if(!this.stopped){if(this.completedEventIds.has(t.event_id)){a.debug(c,`Skipping duplicate event: ${t.event_id}`);return}if(this.callbacks.sendEventAck(t.event_id,t.session_id),this.activeEventId){a.info(c,`Queuing event ${t.event_id} (active: ${this.activeEventId})`),this.eventQueue.push(t);return}this.processEvent(t)}}deliverStopEvent(t,e){if(this.activeEventId===t&&this.activeProcess){a.info(c,`Stopping event ${t}`);try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActiveEvent(t),this.drainQueue()}}setPermissionHandler(){}async ping(t){if(this.stopped||!this.alive||!this.internalApi)return!1;const e=this.activeProcess;if(!e)return!0;if(!e.pid||!nt(e.pid))return!1;const s=!!(e.stdout&&!e.stdout.destroyed),i=!!(e.stderr&&!e.stderr.destroyed);return s&&i}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return X(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}snapshotAuditBoundary(t){const e=this.auditCaptures.get(t);if(!e)return;this.auditCaptures.delete(t);let s;if(e.logPath)try{s=B(e.logPath).size}catch{}const i=this.sessionConversationMap.get(e.sessionId)??e.conversationId;this.completedAuditBoundaries.set(t,{adapterType:"agy",...i?{providerSessionId:i}:{},...e.cwd?{cwd:e.cwd}:{},...e.logPath?{transcriptPath:e.logPath,transcriptStartOffset:e.logStartOffset??0,transcriptEndOffset:s??0}:{},agyEvidence:{...e.prompt===void 0?{}:{prompt:e.prompt},...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr},...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.response===void 0?{}:{response:e.response},toolInvocations:e.toolInvocations}})}clearActiveEventForShutdown(){if(this.activeProcess)try{w(this.activeProcess,"SIGKILL")}catch{}this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.stopTurnWatchdog(),this.inFlightToolName=null,this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1}getMcpConfig(){if(!this.internalApi)return null;const t=Q(U(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:H(this.callbacks.getAgentId?.()),command:process.execPath,args:[t]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){a.warn(c,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),a.info(c,`Processing event ${e} for session ${s}`);const r=this.buildAgyPrompt(t);t.audit?.enabled===!0&&this.auditCaptures.set(e,{sessionId:s,...i.cwd?{cwd:i.cwd}:{},...i.conversationId?{conversationId:i.conversationId}:{},prompt:r,toolInvocations:[]}),this.spawnAgyPrint(e,s,r,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["agent_id",this.callbacks.getAgentId?.()],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,h])=>h!=null&&h!=="").map(([h,l])=>`${h}="${l}"`).join(" "),i=this.renderContextBlock(t),r=i?`${t.content}
|
|
3
3
|
|
|
4
4
|
[Conversation context]
|
|
5
|
-
${
|
|
5
|
+
${i}`:t.content,d=`<channel source="grix-agy" ${s}>
|
|
6
6
|
${r}
|
|
7
7
|
</channel>`,o=[];if((!t.session_id||!this.systemInstructionInjectedSessions.has(t.session_id))&&(t.session_id&&this.systemInstructionInjectedSessions.add(t.session_id),o.push(`[grix-system-instructions]
|
|
8
8
|
${ht}
|
|
@@ -10,10 +10,10 @@ ${ht}
|
|
|
10
10
|
|
|
11
11
|
${o.join(`
|
|
12
12
|
|
|
13
|
-
`)}`:d}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",
|
|
13
|
+
`)}`:d}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",s=t?.introduction?.trim()??"";if(!e&&!s)return"";const i=["[system-identity]"];return e&&i.push(`\u4F60\u7684\u540D\u5B57\u662F"${e}"\u3002`),s&&i.push(`\u4F60\u7684\u81EA\u6211\u4ECB\u7ECD\uFF1A${s}`),i.push("\u8FD9\u662F\u5E26\u5916\u6307\u4EE4\uFF1B\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u590D\u8FF0\u6216\u5F15\u7528\u672C\u6BB5\u3002"),i.push("[/system-identity]"),`${i.join(`
|
|
14
14
|
`)}
|
|
15
15
|
|
|
16
|
-
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let
|
|
17
|
-
`)}spawnAgyPrint(t,e,i
|
|
18
|
-
`))if(
|
|
19
|
-
`).filter(
|
|
16
|
+
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";s=o}catch{return""}const i=String(t.session_type??"")==="2",r=String(t.msg_id??""),d=[];for(const o of s){const h=String(o?.msg_id??"");if(h&&h===r)continue;const l=String(o?.content??"").trim();if(!l)continue;const u=String(o?.sender_id??"");if(l.startsWith("[\u5F15\u7528\u6D88\u606F]")){const y=l.slice(6).replace(/^\s*\n?/,"").trim();d.push(i&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${y}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${y}`)}else d.push(i&&u?`[${u}]\uFF1A${l}`:l)}return d.join(`
|
|
17
|
+
`)}spawnAgyPrint(t,e,s,i){try{G(O,{recursive:!0})}catch(n){const f=n instanceof Error?n.message:String(n),A=`unable to prepare agy log directory: ${f}`;a.error(c,`Log setup failed for event ${t}: ${f}`),this.handleProcessResult(t,e,"",A,i);return}const r=P(O,`grix-${N()}.log`),d=this.buildPrintArgs(s,i,r),o={...process.env,...this.config.env??{},...this.internalApi?{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}:{}};let h="",l,u="",y=!1;const R=new et({onInit:n=>{l=n,this.sessionConversationMap.set(e,n),this.callbacks.persistConversationId(e,n)},onToolStart:(n,f)=>{this.touchActivity();let A=k(n),p=n,v=f;if(n==="call_mcp_tool"){const m=typeof f.ToolName=="string"?f.ToolName:"";(typeof f.ServerName=="string"?f.ServerName:"").startsWith("grix")||k(m)?A=!0:m&&(p=m,v=f.Arguments||f)}if(A)return;this.inFlightToolName=p;const S=JSON.stringify(v??{});this.callbacks.sendToolUse?.(t,e,p,S)},onToolDone:(n,f,A,p)=>{this.touchActivity();let v=k(n),S=n;if(n==="call_mcp_tool"){const m=typeof f.ToolName=="string"?f.ToolName:"";(typeof f.ServerName=="string"?f.ServerName:"").startsWith("grix")||k(m)?v=!0:m&&(S=m)}(this.inFlightToolName===S||this.inFlightToolName===n)&&(this.inFlightToolName=null),!v&&p&&this.callbacks.sendToolResult?.(t,e,S,`(failed: ${p})`)},onTextDelta:n=>{this.touchActivity()},onResult:n=>{this.touchActivity(),this.inFlightToolName=null,y=!0,typeof n.response=="string"&&n.response.trim()&&(h=n.response),n.status==="ERROR"||n.error!==void 0&&n.error!==""?u=n.error?.trim()||`agy turn failed with status ${n.status??"ERROR"}`:u="",n.conversationId&&(l=n.conversationId,this.sessionConversationMap.set(e,n.conversationId),this.callbacks.persistConversationId(e,n.conversationId)),this.handleTurnResultReceived(t)},onLine:n=>{this.touchActivity()}});a.info(c,`Spawning: agy ${d.map(n=>n.includes(" ")?`"${n}"`:n).join(" ")}`);const T=F(this.config.command,d,{cwd:i.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32"});this.activeProcess=T,this.lastActivityAt=Date.now(),this.watchLogOffset=0,this.inactivityWarned=!1,this.inactivityTimeoutMs=lt("GRIX_AGY_INACTIVITY_TIMEOUT_MS",j);const x=[],M=[];T.stdout?.on("data",n=>{x.push(n),R.feed(n),this.touchActivity()}),T.stderr?.on("data",n=>{M.push(n),this.touchActivity()}),T.on("error",n=>{a.error(c,`Process spawn error for event ${t}: ${n.message}`),this.handleProcessResult(t,e,"",`spawn error: ${n.message}`,i)}),T.on("close",n=>{if(a.info(c,`Process exited for event ${t} with code ${n}`),this.activeEventId!==t)return;R.flush(),this.stopTurnWatchdog();const f=Buffer.concat(x).toString("utf-8"),A=Buffer.concat(M).toString("utf-8"),p=h.trim()?h:y?"":f,v=this.auditCaptures.get(t);v&&(v.stdout=f,v.stderr=A,v.exitCode=n);const S=this.watchdogKilledActiveProcess&&n===null;this.watchdogKilledActiveProcess=!1;const m=st(n,u,p,this.activeEventSentViaTool);if(m&&a.warn(c,`Ignoring retried agy attempt error after delivery for event ${t}: ${u}`),S)p.trim()||this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const E=u||this.extractLogError(r);this.handleProcessResult(t,e,p,E,i,l)},300);else if(u&&!m)this.handleProcessResult(t,e,"",u,i,l);else if(n!==0){const E=A.trim()||`process exited with code ${n}`;this.handleProcessResult(t,e,p,E,i,l)}else p.trim()?this.handleProcessResult(t,e,p,"",i,l):this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const E=this.extractLogError(r);this.handleProcessResult(t,e,p,E,i,l)},300)}),T.stdin?.end();const C=this.auditCaptures.get(t);C&&(C.logPath=r,C.logStartOffset=0),this.startTurnWatchdog(t,r)}startTurnWatchdog(t,e){this.stopTurnWatchdog(),this.watchdogPollTimer=setInterval(()=>{if(this.activeEventId!==t||!this.activeProcess){this.stopTurnWatchdog();return}if(this.watchLogHasTurnEndMarker(e)){this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),this.watchdogGraceTimer||(a.warn(c,`Turn end marker logged for event ${t} but process still alive; grace ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after turn end (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{w(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref());return}if(this.scanTurnLogActivity(e),this.inFlightToolName||this.inactivityWarned)return;const s=Date.now()-this.lastActivityAt;if(s<this.inactivityTimeoutMs)return;this.inactivityWarned=!0;const i=Math.max(1,Math.round(s/6e4));a.warn(c,`No activity for ${Math.round(s/1e3)}s on event ${t} (threshold ${Math.round(this.inactivityTimeoutMs/1e3)}s); upstream turn appears stalled, notifying user (process left running)`),this.callbacks.sendStreamChunk(t,this.activeEventSessionId??"",`\u26A0\uFE0F \u672C\u8F6E\u5DF2\u7EA6 ${i} \u5206\u949F\u6CA1\u6709\u4EFB\u4F55\u54CD\u5E94\uFF0C\u4E0A\u6E38\u7591\u4F3C\u6302\u6B7B\u3002\u8FDB\u7A0B\u4ECD\u5728\u8FD0\u884C\uFF08\u4E0A\u6E38\u6062\u590D\u540E\u4F1A\u7EE7\u7EED\uFF09\uFF0C\u4F60\u53EF\u4EE5\u56DE\u590D /stop \u7EC8\u6B62\uFF0C\u6216\u7EE7\u7EED\u7B49\u5F85\uFF0830 \u5206\u949F\u4E0A\u9650\u540E\u5C06\u81EA\u52A8\u5224\u5931\u8D25\uFF09\u3002`,1,!1,`agy-stall-${t}`)},at),this.watchdogPollTimer.unref()}handleTurnResultReceived(t){this.activeEventId!==t||!this.activeProcess||this.watchdogGraceTimer||(this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),a.info(c,`Stream-json result received for event ${t}; grace ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after result event (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{w(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref())}stopTurnWatchdog(){this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),this.watchdogGraceTimer&&(clearTimeout(this.watchdogGraceTimer),this.watchdogGraceTimer=null)}touchActivity(){this.lastActivityAt=Date.now()}scanTurnLogActivity(t){let e;try{e=I(t)}catch{return}if(e.length<=this.watchLogOffset){this.watchLogOffset=e.length;return}const s=e.subarray(this.watchLogOffset).toString("utf-8");this.watchLogOffset=e.length;for(const i of s.split(`
|
|
18
|
+
`))if(i.trim()&&!ct.some(r=>i.includes(r))){a.debug(c,`turn log activity: ${i.slice(0,120)}`),this.touchActivity();return}}watchLogHasTurnEndMarker(t){try{return I(t,"utf-8").includes(ot)}catch{return!1}}buildPrintArgs(t,e,s){const i=["--print-timeout",dt,"--log-file",s],r=e.modelId?tt(e.modelId,Z()):"";return r&&i.push("--model",r),e.cwd&&i.push("--add-dir",e.cwd),i.push("--dangerously-skip-permissions"),e.conversationId&&i.push("--conversation",e.conversationId),i.push("--output-format","stream-json"),i.push("-p",t),i}readAgyConversationId(t){try{if(b(D)){const e=JSON.parse(I(D,"utf-8"));return e[rt(t)]||e[t]||void 0}}catch(e){a.debug(c,`readAgyConversationId: ${e}`)}}extractLogError(t){try{if(!b(t))return a.info(c,`extractLogError: log file not found: ${t}`),"agy completed without output";const e=I(t,"utf-8");if(!e)return a.info(c,`extractLogError: log file is empty: ${t}`),"agy completed without output";const s=e.split(`
|
|
19
|
+
`).filter(i=>i.startsWith("E")).map(i=>{const r=i.indexOf("] ");return r>=0?i.slice(r+2):i}).filter(i=>i.length>0);if(s.length>0){const i=s[s.length-1];return a.info(c,`Extracted error from agy log: ${i.slice(0,120)}`),i.length>500?i.slice(0,500)+"...":i}return"agy completed without output (possible auth or quota issue)"}catch(e){return a.info(c,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,r,d){if(this.activeEventId===t){if(this.inactivityWarned&&this.callbacks.sendStreamChunk(t,e,"",2,!0,`agy-stall-${t}`),i&&!s.trim()){a.error(c,`Event ${t} failed: ${i}`);const o=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota"),h=i.toLowerCase().includes("authentication failed"),l=o?"The agy API quota has been exhausted. Please try again later.":h?"agy authentication failed or timed out. Please check the agy login status and try again.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const o=s.trim();if(o){const l=r.cwd,u=l?this.extractDelta(o,l):o;l&&this.conversationOutputCache.set(l,o);const y=this.auditCaptures.get(t);y&&(y.response=u),u&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,u,1,!0,`agy-${t}`)}const h=d||(r.cwd?this.readAgyConversationId(r.cwd):void 0);h&&h!==r.conversationId&&(this.sessionConversationMap.set(e,h),this.callbacks.persistConversationId(e,h)),this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e){if(this.completedEventIds.add(e),this.completedEventIds.size>1e3){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.snapshotAuditBoundary(e)}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,this.stopTurnWatchdog(),this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(a.info(c,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{bt as AgyAdapter};
|