grix-connector 3.9.0 → 3.9.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.
@@ -8,7 +8,7 @@ Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBi
8
8
 
9
9
  Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(s,i,n,a,r)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r)},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),forceCompleteInternalEvent:(s,i)=>{this.pool.eventComplete(s,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(s,i)=>{this.bindingStore.setAgyConversationId(s,i)},getAgentProfile:()=>this.agentProfile},t=s=>{const i=this.bindingStore.get(s);return{cwd:i?.cwd,modelId:this.resolveSessionModelId(s),conversationId:i?.agyConversationId}};return new U({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},o,t)}createAcpAdapter(e){const o=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(r,d,c,l,h,m,v)=>{this.finalizeThinking(r,d),this.sendStreamChunkByRuntimeConfig(r,d,c,l,h,m,v)},sendFinalStreamChunkReliable:async(r,d,c,l)=>{if(this.finalizeThinking(r,d),this.resolveEventRuntimeConfig(r).responseDelivery==="single_message"&&r){this.bufferStreamChunk(r,d,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:r,session_id:d,delta_content:"",chunk_seq:c,is_finish:!0,...l?{client_msg_id:l}:{}})}catch(m){u.warn("bridge",`[acp] sendFinalStreamChunkReliable ACK failed event=${r}: ${m}`)}u.info("bridge",`[acp] sendFinalStreamChunkReliable done event=${r} seq=${c}`)},sendEventResult:(r,d,c)=>{this.sendEventResultWithCleanup(r,d,c)},sendEventAck:(r,d)=>{this.aibotHandle.sendEventAck({event_id:r,session_id:d,received_at:Date.now()})},agentInvoke:async(r,d,c)=>this.platformInvoke(r,d,c),sendLocalActionResult:(r,d,c,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:r,status:d,...c!==void 0?{result:c}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}})},sendRawEventEnvelope:(r,d,c)=>{this.sendAcpRawEventEnvelope(r,d,c)},sendToolUse:(r,d,c,l)=>{if(o){this.sendAcpRawEventEnvelope(r,d,{type:"tool_use",payload:{tool_name:c,tool_input:l??""}});return}this.sendToolExecutionCard(r,d,$(c,l))},sendToolResult:(r,d,c,l)=>{this.sendToolExecutionCard(r,d,y(c,l))},sendThinking:(r,d,c)=>{this.sendThinkingByRuntimeConfig(r,d,c)},sendRunError:(r,d,c)=>{this.sendStreamChunkByRuntimeConfig(r,d,`
10
10
 
11
- Error: ${c}`,1,!1)},sendPermissionCard:r=>{if(u.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:r.eventId,sessionId:r.sessionId,toolCallId:r.toolCallId,toolName:r.toolName,toolTitle:r.toolTitle}),o){this.sendAcpRawEventEnvelope(r.eventId,r.sessionId,{type:"permission_request",payload:{tool_call_id:r.toolCallId,tool_name:r.toolName,tool_title:r.toolTitle,options:r.options}}),u.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:r.eventId,toolCallId:r.toolCallId});return}const d=`perm_${H()}`,c={event_id:r.eventId,session_id:r.sessionId,client_msg_id:d,msg_type:1,content:r.toolTitle?`Permission required: ${r.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:r.toolCallId,approvalSlug:r.toolName},grix:{execApproval:{approval_command_id:r.toolCallId,command:r.toolTitle||r.toolName,host:"acp"}}},agent_api_origin:!0}};u.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:r.eventId,sessionId:r.sessionId,clientMsgId:d,toolCallId:r.toolCallId,contentLength:c.content.length});try{this.aibotHandle.sendMsg(c),u.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:r.eventId,clientMsgId:d})}catch(l){u.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:r.eventId,clientMsgId:d,error:l instanceof Error?l.message:String(l)})}},sendAuthNotification:(r,d)=>{r&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendUpdateBindingCard:(r,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:r=>{try{this.aibotHandle.sendSkillsUpdate({skills:r})}catch(d){}},onContextWindowUpdated:r=>{this.cachedAcpContextWindow=r,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in r?r.usedPercentage.toFixed(1):(r.used/r.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l={context_window:"usedPercentage"in r?{usedPercentage:r.usedPercentage,remainingPercentage:100-r.usedPercentage}:r};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),l.provider_quota=this.cachedProviderQuota;const h=this.providerQuotaToRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:l})}},sendMcpFrame:r=>{this.aibotHandle.sendMcpFrame(e,r)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:n,initialMode:a}=Ne({sessionBinding:s,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&n&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,n),(n||a)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${n??"<none>"} mode=${a??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:a,acpInitialModel:n,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Be(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new V;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{u.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const a=this.pool.getSlot(t.session_id);a?.adapter instanceof A&&a.adapter.getSessionBindings().delete(t.session_id);const r=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(r);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){u.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){u.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){u.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){u.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){u.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{u.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{u.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)u.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?u.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const a of o)if(a.adapter.onAgentProfileChanged)try{a.adapter.onAgentProfileChanged(),t++}catch(r){u.warn(this.name,`onAgentProfileChanged failed for session=${a.sessionId}: ${r}`)}const s=o.filter(a=>a.adapter instanceof T),i=s.filter(a=>{if(a.state!=="ready")return!1;const r=a.adapter.getStatus();return!r.busy&&!r.backgroundBusy}),n=s.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const a of i)this.pool.removeSlot(a.sessionId).catch(r=>{u.warn(this.name,`removeSlot failed during ${e}: ${r}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,a=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:a,title:a,summary:a,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?je(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Je({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),a=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${H()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(a.cmd!=="send_ack"){const d=a.payload??{},c=String(d.msg??a.cmd);throw new Error(`media message send failed: ${c}`)}const r=a.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:r.msg_id!=null?String(r.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,a){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,a),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
11
+ Error: ${c}`,1,!1)},sendPermissionCard:r=>{if(u.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:r.eventId,sessionId:r.sessionId,toolCallId:r.toolCallId,toolName:r.toolName,toolTitle:r.toolTitle}),o){this.sendAcpRawEventEnvelope(r.eventId,r.sessionId,{type:"permission_request",payload:{tool_call_id:r.toolCallId,tool_name:r.toolName,tool_title:r.toolTitle,options:r.options}}),u.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:r.eventId,toolCallId:r.toolCallId});return}const d=`perm_${H()}`,c={event_id:r.eventId,session_id:r.sessionId,client_msg_id:d,msg_type:1,content:r.toolTitle?`Permission required: ${r.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:r.toolCallId,approvalSlug:r.toolName},grix:{execApproval:{approval_command_id:r.toolCallId,command:r.toolTitle||r.toolName,host:"acp"}}},agent_api_origin:!0}};u.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:r.eventId,sessionId:r.sessionId,clientMsgId:d,toolCallId:r.toolCallId,contentLength:c.content.length});try{this.aibotHandle.sendMsg(c),u.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:r.eventId,clientMsgId:d})}catch(l){u.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:r.eventId,clientMsgId:d,error:l instanceof Error?l.message:String(l)})}},sendAuthNotification:(r,d)=>{r&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendAgentMessage:(r,d)=>{r&&d&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d})},sendUpdateBindingCard:(r,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:r=>{try{this.aibotHandle.sendSkillsUpdate({skills:r})}catch(d){}},onContextWindowUpdated:r=>{this.cachedAcpContextWindow=r,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in r?r.usedPercentage.toFixed(1):(r.used/r.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l={context_window:"usedPercentage"in r?{usedPercentage:r.usedPercentage,remainingPercentage:100-r.usedPercentage}:r};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),l.provider_quota=this.cachedProviderQuota;const h=this.providerQuotaToRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:l})}},sendMcpFrame:r=>{this.aibotHandle.sendMcpFrame(e,r)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:n,initialMode:a}=Ne({sessionBinding:s,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&n&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,n),(n||a)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${n??"<none>"} mode=${a??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:a,acpInitialModel:n,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Be(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new V;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{u.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const a=this.pool.getSlot(t.session_id);a?.adapter instanceof A&&a.adapter.getSessionBindings().delete(t.session_id);const r=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(r);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){u.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){u.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){u.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){u.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){u.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{u.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{u.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)u.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?u.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const a of o)if(a.adapter.onAgentProfileChanged)try{a.adapter.onAgentProfileChanged(),t++}catch(r){u.warn(this.name,`onAgentProfileChanged failed for session=${a.sessionId}: ${r}`)}const s=o.filter(a=>a.adapter instanceof T),i=s.filter(a=>{if(a.state!=="ready")return!1;const r=a.adapter.getStatus();return!r.busy&&!r.backgroundBusy}),n=s.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const a of i)this.pool.removeSlot(a.sessionId).catch(r=>{u.warn(this.name,`removeSlot failed during ${e}: ${r}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,a=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:a,title:a,summary:a,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?je(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Je({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),a=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${H()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(a.cmd!=="send_ack"){const d=a.payload??{},c=String(d.msg??a.cmd);throw new Error(`media message send failed: ${c}`)}const r=a.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:r.msg_id!=null?String(r.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,a){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,a),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
12
12
 
13
13
  Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,s){this.sendCtrl.sendEventResult(e,o,t,s);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.maybeQueryProviderQuota().catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const a=this.config.adapterType??"acp";if(n>O){u.error(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${O} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${O} outcome=restarting err=${s}`);const r=this.pool.drainQueuedForSession(t);r.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${r.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(a,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of r){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:this.buildAcpRawEventFallbackText(t),extra:{channel_data:{acp:{raw_event:t}},agent_api_origin:!0}})}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=et(e.extra);if(t.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:t.error,updated_at:Date.now()});return}const s=t.patch,i=Ue(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const r=i.args.trim();if(!r){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=P.resolve(r);if(!(await M(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${P.resolve(r)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${r}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const r=this.bindingStore.get(e.session_id);if(r?.cwd)try{await M(r.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${r.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(q(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const r=this.bindingStore.get(e.session_id)?.cwd??"";r&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:r,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(ut.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,s));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(_=>_.name===c||_.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const _=await m.execCommand(c,l.trim(),e.session_id);_.status==="options"&&_.data&&this.handleExecCommandOptions(e.session_id,c,_.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:_.status==="failed"?"failed":"responded",msg:_.message,updated_at:Date.now()})}catch(_){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_ instanceof Error?_.message:String(_),updated_at:Date.now()})}return}}}const a=this.buildInboundEvent(e,s);try{this.captureEventRuntimeConfig(a),await this.pool.deliverInboundEvent(a)}catch(r){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.inflightEvents.delete(e.event_id),this.restartCount.delete(e.event_id),this.eventSessionIndex.delete(e.event_id),r instanceof Fe)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r.message,updated_at:Date.now()});else throw r}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${r.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${a}\``,quoted_message_id:o.msg_id})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(a,r)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:a,...r,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof A?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),q(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){if(await this.resolveCwdForBinding(r.cwd)!==a){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){const d=await this.resolveCwdForBinding(r.cwd);if(d!==a){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",a={};if(o==="model"){a.available_models=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.model_id=r.id)}else if(o==="mode"){a.available_modes=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.mode_id=r.id)}else a[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:a})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=ee(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(a=>a.id===i)&&(i=s);const n=te();return{model_id:i,currentModelId:i,available_models:t.map(a=>({id:a.id,displayName:a.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=B(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),a={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},r=this.pool.getSlot(e),d=r?.adapter instanceof T?r.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(a.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(a.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!a.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(a.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return a.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(a.rate_limits)}`),a}providerQuotaToCodexRateLimits(e){const o=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit"),s=i=>i||null;if(o||t){const i={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};let n=0,a=0,r=0,d=0;return o&&(i.primary={usedPercent:o.usedPercent,windowMinutes:300,resetsAt:s(o.resetsAt)},n=o.usedPercent,a=300),t&&(i.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:s(t.resetsAt)},r=t.usedPercent,d=10080),{rateLimits:i,primaryPercent:n,secondaryPercent:r,primaryWindowMin:a,secondaryWindowMin:d}}if(e.balance){const i=e.balance,n=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:n,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()},primaryPercent:n,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}return null}providerQuotaToRateLimits(e){const o=i=>{if(!i)return 0;const n=Date.parse(i);return Number.isFinite(n)?Math.floor(n/1e3):0},t=e.tiers.find(i=>i.name==="five_hour"),s=e.tiers.find(i=>i.name==="weekly_limit");if(t||s)return{...t?{fiveHour:{usedPercentage:t.usedPercent,resetsAt:o(t.resetsAt)}}:{},...s?{sevenDay:{usedPercentage:s.usedPercent,resetsAt:o(s.resetsAt)}}:{},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};if(e.balance){const i=e.balance;return{credit:{remaining:i.remaining,total:i.total,used:i.used,unit:i.unit,resetsAt:i.resetsAt?o(i.resetsAt):0},planName:e.planName,sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()}}return null}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=P.resolve(o);let s;try{s=await M(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const a=new Error(`Specified path does not exist: ${t}`);throw a.cwdErrorCode=g.invalidCwd,a}if(n==="EACCES"||n==="EPERM"){const a=new Error("Specified path is not accessible.");throw a.cwdErrorCode=g.invalidCwd,a}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await G(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}reportSessionSkills(e){const o=ne(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,s=o==="kiro"?t:t||process.cwd();let i;try{i=se({mode:o,projectDir:s})}catch{return}if(i.length===0)return;const n=JSON.stringify(i.map(a=>`${a.source}:${a.name}`));if(n!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=n;try{this.aibotHandle.sendSkillsUpdate({skills:i})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(!e||!this.reasonixTitleScan)return;const o=ve(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=P.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,r]of this.bindingStore.entries())if(this.resolveAgentSessionId(r)===t){i=r.cwd??"";break}}if(!i){const r=new Error(`agent session not found: ${t}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}const a=this.normalizePathForCompare(i);if(a&&s&&a!==s){const r=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.threadId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(d.createdAt).toISOString()}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionPath);const c=i.get(d.sessionPath);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionPath}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="cursor"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":r.slice(0,8)+"\u2026");n.push(` Title: ${m}`),n.push(` AIBot: ${r}`),c&&n.push(` Agent: ${c}`),n.push(` CWD: ${d.cwd??"-"}`),n.push(` State: ${h}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(r=>r==="---").length}):
14
14
  ${n.join(`
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1,2 +1,2 @@
1
- import{readFileSync as y,writeFileSync as z,mkdirSync as N,rmdirSync as x,statSync as C}from"node:fs";import{homedir as I}from"node:os";import{join as b}from"node:path";function D(o){const e=o.toLowerCase();return e.includes("open.bigmodel.cn")||e.includes("bigmodel.cn")||e.includes("api.z.ai")?{id:"zhipu",label:"Zhipu GLM"}:e.includes("api.kimi.com")?{id:"kimi",label:"Kimi"}:e.includes("api.minimaxi.com")?{id:"minimax_cn",label:"MiniMax"}:e.includes("api.minimax.io")?{id:"minimax_en",label:"MiniMax"}:e.includes("api.deepseek.com")?{id:"deepseek",label:"DeepSeek"}:e.includes("api.stepfun.ai")||e.includes("api.stepfun.com")?{id:"stepfun",label:"StepFun"}:e.includes("api.siliconflow.cn")?{id:"siliconflow_cn",label:"SiliconFlow"}:e.includes("api.siliconflow.com")?{id:"siliconflow_en",label:"SiliconFlow"}:e.includes("openrouter.ai")?{id:"openrouter",label:"OpenRouter"}:e.includes("api.novita.ai")?{id:"novita",label:"Novita AI"}:null}const f=1e4;function d(o,e,i){return{provider:o,providerLabel:e,planName:null,tiers:[],balance:null,success:!1,error:i}}function p(o){if(typeof o=="number")return o;if(typeof o=="string"){const e=Number(o);return Number.isFinite(e)?e:null}return null}function w(o){if(!Number.isFinite(o)||o<=0)return null;try{return new Date(o).toISOString()}catch{return null}}function S(o){if(typeof o=="string")return o;if(typeof o=="number"){const e=o<1e12?o*1e3:o;return w(e)}return null}function $(o){const e=o||b(I(),".kimi"),i=300*1e3;let t;try{const r=b(e,"config.toml"),n=y(r,"utf8"),s=n.indexOf('[providers."managed:kimi-code"]');if(s>=0){const c=n.indexOf(`
2
- [`,s+1),u=(c>=0?n.slice(s,c):n.slice(s)).match(/^\s*base_url\s*=\s*"([^"]+)"/m);u&&(t=u[1].trim())}}catch{}let a;try{const r=b(e,"credentials","kimi-code.json"),n=JSON.parse(y(r,"utf8")),s=typeof n.access_token=="string"?n.access_token.trim():"",c=typeof n.expires_at=="number"?n.expires_at:null;s&&(!c||Date.now()<c*1e3-i)&&(a=s)}catch{}return{baseUrl:t,apiKey:a}}const F="17e5f671-d194-4dfb-9706-5516cb48c098";function q(){return(process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||"https://auth.kimi.com").replace(/\/+$/,"")}const Y=30*1e3;async function ne(o){const e=$(o);if(e.apiKey)return e;const i=await Z(o);return{baseUrl:e.baseUrl,apiKey:i}}async function Z(o){const e=o||b(I(),".kimi"),i=b(e,"credentials","kimi-code.json");let t;try{t=JSON.parse(y(i,"utf8"))}catch{return}const a=typeof t.refresh_token=="string"?t.refresh_token.trim():"";if(!a)return;const r=b(e,"credentials","kimi-code.lock.lock");if(V(r))try{const n=$(o);if(n.apiKey)return n.apiKey;let s="";try{s=y(b(e,"device_id"),"utf8").trim()}catch{}const c=await fetch(`${q()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...s?{"X-Msh-Device-Id":s}:{}},body:new URLSearchParams({client_id:F,grant_type:"refresh_token",refresh_token:a}),signal:AbortSignal.timeout(8e3)}),l=await c.json().catch(()=>({})),u=typeof l.access_token=="string"?l.access_token:"";if(c.status!==200||!u)return $(o).apiKey;const m=Number(l.expires_in),h={access_token:u,refresh_token:typeof l.refresh_token=="string"&&l.refresh_token?l.refresh_token:a,expires_at:Math.floor(Date.now()/1e3)+(Number.isFinite(m)&&m>0?m:900),scope:typeof l.scope=="string"&&l.scope?l.scope:t.scope??"kimi-code",token_type:typeof l.token_type=="string"&&l.token_type?l.token_type:"Bearer",expires_in:Number.isFinite(m)&&m>0?m:900};return z(i,JSON.stringify(h),{mode:384}),u}catch{return}finally{try{x(r)}catch{}}}function V(o){try{return N(o),!0}catch{}try{const e=C(o);return Date.now()-e.mtimeMs<Y?!1:(x(o),N(o),!0)}catch{return!1}}async function E(o){const e="zhipu",i="Zhipu GLM";try{const t=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",{method:"GET",headers:{Authorization:o,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const c=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${c.slice(0,200)}`)}const a=await t.json();if(a.success===!1)return d(e,i,`API error: ${a.msg??"Unknown error"}`);const r=a.data;if(!r)return d(e,i,"Missing data field");const n=typeof r.level=="string"?r.level:null,s=M(r);return{provider:e,providerLabel:i,planName:n,tiers:s,balance:null,success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}function M(o){const e=Array.isArray(o.limits)?o.limits:[],i=[];for(const a of e){if(String(a.type??"").toUpperCase()!=="TOKENS_LIMIT")continue;const n=p(a.percentage)??0,s=typeof a.nextResetTime=="number"?a.nextResetTime:Number.MAX_SAFE_INTEGER,c=s===Number.MAX_SAFE_INTEGER?null:w(s);i.push({percentage:n,resetMs:s,resetIso:c})}i.sort((a,r)=>a.resetMs-r.resetMs);const t=[];if(i.length>0){const a=i[0];t.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}return t}async function L(o){const e="kimi",i="Kimi";try{const t=await fetch("https://api.kimi.com/coding/v1/usages",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const c=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${c.slice(0,200)}`)}const a=await t.json(),r=[],n=Array.isArray(a.limits)?a.limits:[];for(const c of n){const l=c.detail;if(!l)continue;const u=p(l.limit)??1,m=p(l.remaining)??0,h=S(l.resetTime),_=Math.max(0,u-m);r.push({name:"five_hour",label:"5h limit",usedPercent:u>0?Math.round(_/u*1e4)/100:0,resetsAt:h})}const s=a.usage;if(s){const c=p(s.limit)??1,l=p(s.remaining)??0,u=S(s.resetTime),m=Math.max(0,c-l);r.push({name:"weekly_limit",label:"Weekly limit",usedPercent:c>0?Math.round(m/c*1e4)/100:0,resetsAt:u})}return{provider:e,providerLabel:i,planName:null,tiers:r,balance:null,success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function v(o,e){const i=e?"minimax_cn":"minimax_en",t="MiniMax",a=e?"api.minimaxi.com":"api.minimax.io";try{const r=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(f)});if(r.status===401||r.status===403)return d(i,t,`Authentication failed (HTTP ${r.status})`);if(!r.ok){const m=await r.text().catch(()=>"");return d(i,t,`API error (HTTP ${r.status}): ${m.slice(0,200)}`)}const n=await r.json(),s=n.base_resp;if(s&&typeof s.status_code=="number"&&s.status_code!==0)return d(i,t,`API error (code ${s.status_code}): ${s.status_msg??"Unknown"}`);const c=[],u=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(u){const m=p(u.current_interval_total_count)??0,h=p(u.current_interval_usage_count)??0,_=typeof u.end_time=="number"?u.end_time:null;m>0&&c.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(h/m*1e4)/100,resetsAt:_!==null?w(_):null});const g=p(u.current_weekly_total_count)??0,H=p(u.current_weekly_usage_count)??0,P=typeof u.weekly_end_time=="number"?u.weekly_end_time:null;g>0&&c.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(H/g*1e4)/100,resetsAt:P!==null?w(P):null})}return{provider:i,providerLabel:t,planName:null,tiers:c,balance:null,success:!0,error:null}}catch(r){return d(i,t,`Network error: ${r instanceof Error?r.message:String(r)}`)}}async function j(o){const e="deepseek",i="DeepSeek";try{const t=await fetch("https://api.deepseek.com/user/balance",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const u=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${u.slice(0,200)}`)}const a=await t.json(),r=a.is_available===!0,s=(Array.isArray(a.balance_infos)?a.balance_infos:[])[0];if(!s)return d(e,i,"No balance info returned");const c=String(s.currency??"CNY"),l=p(s.total_balance);return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:l??0,total:null,used:null,unit:c},success:!0,error:r?null:"Insufficient balance"}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function O(o){const e="stepfun",i="StepFun";try{const t=await fetch("https://api.stepfun.com/v1/accounts",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const n=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${n.slice(0,200)}`)}const a=await t.json(),r=p(a.balance)??0;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:r,total:null,used:null,unit:"CNY"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function k(o,e){const i=e?"siliconflow_cn":"siliconflow_en",t=e?"SiliconFlow":"SiliconFlow (EN)",a=e?"api.siliconflow.cn":"api.siliconflow.com",r=e?"CNY":"USD";try{const n=await fetch(`https://${a}/v1/user/info`,{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(n.status===401||n.status===403)return d(i,t,`Authentication failed (HTTP ${n.status})`);if(!n.ok){const u=await n.text().catch(()=>"");return d(i,t,`API error (HTTP ${n.status}): ${u.slice(0,200)}`)}const c=(await n.json()).data;if(!c)return d(i,t,"Missing data field");const l=p(c.totalBalance)??0;return{provider:i,providerLabel:t,planName:null,tiers:[],balance:{remaining:l,total:null,used:null,unit:r},success:!0,error:null}}catch(n){return d(i,t,`Network error: ${n instanceof Error?n.message:String(n)}`)}}async function R(o){const e="openrouter",i="OpenRouter";try{const t=await fetch("https://openrouter.ai/api/v1/credits",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const l=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${l.slice(0,200)}`)}const a=await t.json(),r=a.data??a,n=p(r.total_credits)??0,s=p(r.total_usage)??0,c=n-s;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:c,total:n,used:s,unit:"USD"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function U(o){const e="novita",i="Novita AI";try{const t=await fetch("https://api.novita.ai/v3/user/balance",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const n=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${n.slice(0,200)}`)}const a=await t.json(),r=(p(a.availableBalance)??0)/1e4;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:r,total:null,used:null,unit:"USD"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}const A=new Map,X=300*1e3;async function J(o,e){const i=`${e.slice(0,8)}@${o}`,t=A.get(i);if(t&&Date.now()-t.timestamp<=X){const n=await G(t.providerId,o,e);if(n)return n;A.delete(i)}else t&&A.delete(i);const a=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],r=await Promise.allSettled(a.map(n=>G(n,o,e)));for(let n=0;n<r.length;n++){const s=r[n];if(s.status==="fulfilled"&&s.value?.success)return A.set(i,{providerId:a[n],timestamp:Date.now()}),s.value}return null}const T=new Map,K=300*1e3;async function W(o){const e=o.slice(0,8),i=T.get(e);if(i&&Date.now()-i.timestamp<=K){const r=[i.providerId],n=await Promise.allSettled(r.map(s=>B(s,o)));for(const s of n)if(s.status==="fulfilled"&&s.value?.success)return s.value;T.delete(e)}else i&&T.delete(e);const t=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],a=await Promise.allSettled(t.map(r=>B(r,o)));for(let r=0;r<a.length;r++){const n=a[r];if(n.status==="fulfilled"&&n.value?.success)return T.set(e,{providerId:t[r],timestamp:Date.now()}),n.value}return null}async function B(o,e){try{switch(o){case"zhipu":return E(e);case"kimi":return L(e);case"minimax_cn":return v(e,!0);case"minimax_en":return v(e,!1);case"deepseek":return j(e);case"stepfun":return O(e);case"siliconflow_cn":return k(e,!0);case"siliconflow_en":return k(e,!1);case"openrouter":return R(e);case"novita":return U(e)}}catch{return null}}async function G(o,e,i){const t=e.replace(/\/+$/,""),a={Authorization:"Bearer ${apiKey}",Accept:"application/json"};try{switch(o){case"zhipu":{const r=await fetch("${origin}/api/monitor/usage/quota/limit",{method:"GET",headers:{...a,Authorization:i,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json();if(n.success===!1)return null;const s=n.data;if(!s)return null;const c=typeof s.level=="string"?s.level:null,l=M(s);return{provider:"zhipu",providerLabel:"Zhipu GLM",planName:c,tiers:l,balance:null,success:!0,error:null}}case"deepseek":{const r=await fetch("${origin}/user/balance",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.is_available===!0,l=(Array.isArray(n.balance_infos)?n.balance_infos:[])[0];if(!l)return null;const u=String(l.currency??"CNY"),m=p(l.total_balance);return{provider:"deepseek",providerLabel:"DeepSeek",planName:null,tiers:[],balance:{remaining:m??0,total:null,used:null,unit:u},success:!0,error:s?null:"Insufficient balance"}}case"kimi":{const r=await fetch("${origin}/coding/v1/usages",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=[],c=Array.isArray(n.limits)?n.limits:[];for(const l of c){const u=l.detail;if(!u)continue;const m=p(u.limit)??1,h=p(u.remaining)??0,_=S(u.resetTime),g=Math.max(0,m-h);s.push({name:"five_hour",label:"5h limit",usedPercent:m>0?Math.round(g/m*1e4)/100:0,resetsAt:_})}return{provider:"kimi",providerLabel:"Kimi",planName:null,tiers:s,balance:null,success:!0,error:null}}case"openrouter":{const r=await fetch("${origin}/api/v1/credits",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.data??n,c=p(s.total_credits)??0,l=p(s.total_usage)??0,u=c-l;return{provider:"openrouter",providerLabel:"OpenRouter",planName:null,tiers:[],balance:{remaining:u,total:c,used:l,unit:"USD"},success:!0,error:null}}case"stepfun":{const r=await fetch("${origin}/v1/accounts",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=p(n.balance)??0;return{provider:"stepfun",providerLabel:"StepFun",planName:null,tiers:[],balance:{remaining:s,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"minimax_cn":{const r=await fetch("${origin}/v1/api/openplatform/coding_plan/remains",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.base_resp;if(s&&typeof s.status_code=="number"&&s.status_code!==0)return null;const l=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(!l)return null;const u=[],m=p(l.current_interval_total_count)??0,h=p(l.current_interval_usage_count)??0;return m>0&&u.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(h/m*1e4)/100,resetsAt:null}),{provider:"minimax_cn",providerLabel:"MiniMax",planName:null,tiers:u,balance:null,success:!0,error:null}}case"siliconflow_cn":{const r=await fetch("${origin}/v1/user/info",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const s=(await r.json()).data;if(!s)return null;const c=p(s.totalBalance)??0;return{provider:"siliconflow_cn",providerLabel:"SiliconFlow",planName:null,tiers:[],balance:{remaining:c,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"novita":{const r=await fetch("${origin}/v3/user/balance",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=(p(n.availableBalance)??0)/1e4;return{provider:"novita",providerLabel:"Novita AI",planName:null,tiers:[],balance:{remaining:s,total:null,used:null,unit:"USD"},success:!0,error:null}}default:return null}}catch{return null}}async function re(o,e){if(!e.trim())return{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:"API key is empty"};const i=D(o);if(i)switch(i.id){case"zhipu":return E(e);case"kimi":return L(e);case"minimax_cn":return v(e,!0);case"minimax_en":return v(e,!1);case"deepseek":return j(e);case"stepfun":return O(e);case"siliconflow_cn":return k(e,!0);case"siliconflow_en":return k(e,!1);case"openrouter":return R(e);case"novita":return U(e)}const t=await J(o,e);if(t)return t;const a=await W(e);return a||{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:`Could not identify provider for base URL: ${o}`}}export{D as detectProvider,re as queryProviderQuota,$ as readKimiProviderSettings,ne as resolveKimiProviderSettings};
1
+ import{readFileSync as y,writeFileSync as D,mkdirSync as N,rmdirSync as x,statSync as G}from"node:fs";import{homedir as z}from"node:os";import{join as _}from"node:path";function F(o){const e=o.toLowerCase();return e.includes("open.bigmodel.cn")||e.includes("bigmodel.cn")||e.includes("api.z.ai")?{id:"zhipu",label:"Zhipu GLM"}:e.includes("api.kimi.com")?{id:"kimi",label:"Kimi"}:e.includes("api.minimaxi.com")?{id:"minimax_cn",label:"MiniMax"}:e.includes("api.minimax.io")?{id:"minimax_en",label:"MiniMax"}:e.includes("api.deepseek.com")?{id:"deepseek",label:"DeepSeek"}:e.includes("api.stepfun.ai")||e.includes("api.stepfun.com")?{id:"stepfun",label:"StepFun"}:e.includes("api.siliconflow.cn")?{id:"siliconflow_cn",label:"SiliconFlow"}:e.includes("api.siliconflow.com")?{id:"siliconflow_en",label:"SiliconFlow"}:e.includes("openrouter.ai")?{id:"openrouter",label:"OpenRouter"}:e.includes("api.novita.ai")?{id:"novita",label:"Novita AI"}:null}const f=1e4;function d(o,e,i){return{provider:o,providerLabel:e,planName:null,tiers:[],balance:null,success:!1,error:i}}function m(o){if(typeof o=="number")return o;if(typeof o=="string"){const e=Number(o);return Number.isFinite(e)?e:null}return null}function v(o){if(!Number.isFinite(o)||o<=0)return null;try{return new Date(o).toISOString()}catch{return null}}function S(o){if(typeof o=="string")return o;if(typeof o=="number"){const e=o<1e12?o*1e3:o;return v(e)}return null}function I(){return(process.env.KIMI_CODE_HOME||"").trim()||_(z(),".kimi-code")}function $(o){const e=o||I(),i=300*1e3;let t;try{const r=_(e,"config.toml"),n=y(r,"utf8"),s=n.indexOf('[providers."managed:kimi-code"]');if(s>=0){const c=n.indexOf(`
2
+ [`,s+1),u=(c>=0?n.slice(s,c):n.slice(s)).match(/^\s*base_url\s*=\s*"([^"]+)"/m);u&&(t=u[1].trim())}}catch{}let a;try{const r=_(e,"credentials","kimi-code.json"),n=JSON.parse(y(r,"utf8")),s=typeof n.access_token=="string"?n.access_token.trim():"",c=typeof n.expires_at=="number"?n.expires_at:null;s&&(!c||Date.now()<c*1e3-i)&&(a=s)}catch{}return{baseUrl:t,apiKey:a}}const q="17e5f671-d194-4dfb-9706-5516cb48c098";function Y(){return(process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||"https://auth.kimi.com").replace(/\/+$/,"")}const Z=30*1e3;async function re(o){const e=$(o);if(e.apiKey)return e;const i=await K(o);return{baseUrl:e.baseUrl,apiKey:i}}async function K(o){const e=o||I(),i=_(e,"credentials","kimi-code.json");let t;try{t=JSON.parse(y(i,"utf8"))}catch{return}const a=typeof t.refresh_token=="string"?t.refresh_token.trim():"";if(!a)return;const r=_(e,"credentials","kimi-code.lock.lock");if(V(r))try{const n=$(o);if(n.apiKey)return n.apiKey;let s="";try{s=y(_(e,"device_id"),"utf8").trim()}catch{}const c=await fetch(`${Y()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...s?{"X-Msh-Device-Id":s}:{}},body:new URLSearchParams({client_id:q,grant_type:"refresh_token",refresh_token:a}),signal:AbortSignal.timeout(8e3)}),l=await c.json().catch(()=>({})),u=typeof l.access_token=="string"?l.access_token:"";if(c.status!==200||!u)return $(o).apiKey;const p=Number(l.expires_in),h={access_token:u,refresh_token:typeof l.refresh_token=="string"&&l.refresh_token?l.refresh_token:a,expires_at:Math.floor(Date.now()/1e3)+(Number.isFinite(p)&&p>0?p:900),scope:typeof l.scope=="string"&&l.scope?l.scope:t.scope??"kimi-code",token_type:typeof l.token_type=="string"&&l.token_type?l.token_type:"Bearer",expires_in:Number.isFinite(p)&&p>0?p:900};return D(i,JSON.stringify(h),{mode:384}),u}catch{return}finally{try{x(r)}catch{}}}function V(o){try{return N(o),!0}catch{}try{const e=G(o);return Date.now()-e.mtimeMs<Z?!1:(x(o),N(o),!0)}catch{return!1}}async function E(o){const e="zhipu",i="Zhipu GLM";try{const t=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",{method:"GET",headers:{Authorization:o,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const c=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${c.slice(0,200)}`)}const a=await t.json();if(a.success===!1)return d(e,i,`API error: ${a.msg??"Unknown error"}`);const r=a.data;if(!r)return d(e,i,"Missing data field");const n=typeof r.level=="string"?r.level:null,s=M(r);return{provider:e,providerLabel:i,planName:n,tiers:s,balance:null,success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}function M(o){const e=Array.isArray(o.limits)?o.limits:[],i=[];for(const a of e){if(String(a.type??"").toUpperCase()!=="TOKENS_LIMIT")continue;const n=m(a.percentage)??0,s=typeof a.nextResetTime=="number"?a.nextResetTime:Number.MAX_SAFE_INTEGER,c=s===Number.MAX_SAFE_INTEGER?null:v(s);i.push({percentage:n,resetMs:s,resetIso:c})}i.sort((a,r)=>a.resetMs-r.resetMs);const t=[];if(i.length>0){const a=i[0];t.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}return t}async function L(o){const e="kimi",i="Kimi";try{const t=await fetch("https://api.kimi.com/coding/v1/usages",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const c=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${c.slice(0,200)}`)}const a=await t.json(),r=[],n=Array.isArray(a.limits)?a.limits:[];for(const c of n){const l=c.detail;if(!l)continue;const u=m(l.limit)??1,p=m(l.remaining)??0,h=S(l.resetTime),b=Math.max(0,u-p);r.push({name:"five_hour",label:"5h limit",usedPercent:u>0?Math.round(b/u*1e4)/100:0,resetsAt:h})}const s=a.usage;if(s){const c=m(s.limit)??1,l=m(s.remaining)??0,u=S(s.resetTime),p=Math.max(0,c-l);r.push({name:"weekly_limit",label:"Weekly limit",usedPercent:c>0?Math.round(p/c*1e4)/100:0,resetsAt:u})}return{provider:e,providerLabel:i,planName:null,tiers:r,balance:null,success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function w(o,e){const i=e?"minimax_cn":"minimax_en",t="MiniMax",a=e?"api.minimaxi.com":"api.minimax.io";try{const r=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(f)});if(r.status===401||r.status===403)return d(i,t,`Authentication failed (HTTP ${r.status})`);if(!r.ok){const p=await r.text().catch(()=>"");return d(i,t,`API error (HTTP ${r.status}): ${p.slice(0,200)}`)}const n=await r.json(),s=n.base_resp;if(s&&typeof s.status_code=="number"&&s.status_code!==0)return d(i,t,`API error (code ${s.status_code}): ${s.status_msg??"Unknown"}`);const c=[],u=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(u){const p=m(u.current_interval_total_count)??0,h=m(u.current_interval_usage_count)??0,b=typeof u.end_time=="number"?u.end_time:null;p>0&&c.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(h/p*1e4)/100,resetsAt:b!==null?v(b):null});const g=m(u.current_weekly_total_count)??0,C=m(u.current_weekly_usage_count)??0,P=typeof u.weekly_end_time=="number"?u.weekly_end_time:null;g>0&&c.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(C/g*1e4)/100,resetsAt:P!==null?v(P):null})}return{provider:i,providerLabel:t,planName:null,tiers:c,balance:null,success:!0,error:null}}catch(r){return d(i,t,`Network error: ${r instanceof Error?r.message:String(r)}`)}}async function j(o){const e="deepseek",i="DeepSeek";try{const t=await fetch("https://api.deepseek.com/user/balance",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const u=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${u.slice(0,200)}`)}const a=await t.json(),r=a.is_available===!0,s=(Array.isArray(a.balance_infos)?a.balance_infos:[])[0];if(!s)return d(e,i,"No balance info returned");const c=String(s.currency??"CNY"),l=m(s.total_balance);return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:l??0,total:null,used:null,unit:c},success:!0,error:r?null:"Insufficient balance"}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function O(o){const e="stepfun",i="StepFun";try{const t=await fetch("https://api.stepfun.com/v1/accounts",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const n=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${n.slice(0,200)}`)}const a=await t.json(),r=m(a.balance)??0;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:r,total:null,used:null,unit:"CNY"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function k(o,e){const i=e?"siliconflow_cn":"siliconflow_en",t=e?"SiliconFlow":"SiliconFlow (EN)",a=e?"api.siliconflow.cn":"api.siliconflow.com",r=e?"CNY":"USD";try{const n=await fetch(`https://${a}/v1/user/info`,{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(n.status===401||n.status===403)return d(i,t,`Authentication failed (HTTP ${n.status})`);if(!n.ok){const u=await n.text().catch(()=>"");return d(i,t,`API error (HTTP ${n.status}): ${u.slice(0,200)}`)}const c=(await n.json()).data;if(!c)return d(i,t,"Missing data field");const l=m(c.totalBalance)??0;return{provider:i,providerLabel:t,planName:null,tiers:[],balance:{remaining:l,total:null,used:null,unit:r},success:!0,error:null}}catch(n){return d(i,t,`Network error: ${n instanceof Error?n.message:String(n)}`)}}async function H(o){const e="openrouter",i="OpenRouter";try{const t=await fetch("https://openrouter.ai/api/v1/credits",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const l=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${l.slice(0,200)}`)}const a=await t.json(),r=a.data??a,n=m(r.total_credits)??0,s=m(r.total_usage)??0,c=n-s;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:c,total:n,used:s,unit:"USD"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}async function R(o){const e="novita",i="Novita AI";try{const t=await fetch("https://api.novita.ai/v3/user/balance",{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:AbortSignal.timeout(f)});if(t.status===401||t.status===403)return d(e,i,`Authentication failed (HTTP ${t.status})`);if(!t.ok){const n=await t.text().catch(()=>"");return d(e,i,`API error (HTTP ${t.status}): ${n.slice(0,200)}`)}const a=await t.json(),r=(m(a.availableBalance)??0)/1e4;return{provider:e,providerLabel:i,planName:null,tiers:[],balance:{remaining:r,total:null,used:null,unit:"USD"},success:!0,error:null}}catch(t){return d(e,i,`Network error: ${t instanceof Error?t.message:String(t)}`)}}const A=new Map,X=300*1e3;async function J(o,e){const i=`${e.slice(0,8)}@${o}`,t=A.get(i);if(t&&Date.now()-t.timestamp<=X){const n=await B(t.providerId,o,e);if(n)return n;A.delete(i)}else t&&A.delete(i);const a=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],r=await Promise.allSettled(a.map(n=>B(n,o,e)));for(let n=0;n<r.length;n++){const s=r[n];if(s.status==="fulfilled"&&s.value?.success)return A.set(i,{providerId:a[n],timestamp:Date.now()}),s.value}return null}const T=new Map,W=300*1e3;async function Q(o){const e=o.slice(0,8),i=T.get(e);if(i&&Date.now()-i.timestamp<=W){const r=[i.providerId],n=await Promise.allSettled(r.map(s=>U(s,o)));for(const s of n)if(s.status==="fulfilled"&&s.value?.success)return s.value;T.delete(e)}else i&&T.delete(e);const t=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],a=await Promise.allSettled(t.map(r=>U(r,o)));for(let r=0;r<a.length;r++){const n=a[r];if(n.status==="fulfilled"&&n.value?.success)return T.set(e,{providerId:t[r],timestamp:Date.now()}),n.value}return null}async function U(o,e){try{switch(o){case"zhipu":return E(e);case"kimi":return L(e);case"minimax_cn":return w(e,!0);case"minimax_en":return w(e,!1);case"deepseek":return j(e);case"stepfun":return O(e);case"siliconflow_cn":return k(e,!0);case"siliconflow_en":return k(e,!1);case"openrouter":return H(e);case"novita":return R(e)}}catch{return null}}async function B(o,e,i){const t=e.replace(/\/+$/,""),a={Authorization:"Bearer ${apiKey}",Accept:"application/json"};try{switch(o){case"zhipu":{const r=await fetch("${origin}/api/monitor/usage/quota/limit",{method:"GET",headers:{...a,Authorization:i,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json();if(n.success===!1)return null;const s=n.data;if(!s)return null;const c=typeof s.level=="string"?s.level:null,l=M(s);return{provider:"zhipu",providerLabel:"Zhipu GLM",planName:c,tiers:l,balance:null,success:!0,error:null}}case"deepseek":{const r=await fetch("${origin}/user/balance",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.is_available===!0,l=(Array.isArray(n.balance_infos)?n.balance_infos:[])[0];if(!l)return null;const u=String(l.currency??"CNY"),p=m(l.total_balance);return{provider:"deepseek",providerLabel:"DeepSeek",planName:null,tiers:[],balance:{remaining:p??0,total:null,used:null,unit:u},success:!0,error:s?null:"Insufficient balance"}}case"kimi":{const r=await fetch("${origin}/coding/v1/usages",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=[],c=Array.isArray(n.limits)?n.limits:[];for(const l of c){const u=l.detail;if(!u)continue;const p=m(u.limit)??1,h=m(u.remaining)??0,b=S(u.resetTime),g=Math.max(0,p-h);s.push({name:"five_hour",label:"5h limit",usedPercent:p>0?Math.round(g/p*1e4)/100:0,resetsAt:b})}return{provider:"kimi",providerLabel:"Kimi",planName:null,tiers:s,balance:null,success:!0,error:null}}case"openrouter":{const r=await fetch("${origin}/api/v1/credits",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.data??n,c=m(s.total_credits)??0,l=m(s.total_usage)??0,u=c-l;return{provider:"openrouter",providerLabel:"OpenRouter",planName:null,tiers:[],balance:{remaining:u,total:c,used:l,unit:"USD"},success:!0,error:null}}case"stepfun":{const r=await fetch("${origin}/v1/accounts",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=m(n.balance)??0;return{provider:"stepfun",providerLabel:"StepFun",planName:null,tiers:[],balance:{remaining:s,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"minimax_cn":{const r=await fetch("${origin}/v1/api/openplatform/coding_plan/remains",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=n.base_resp;if(s&&typeof s.status_code=="number"&&s.status_code!==0)return null;const l=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(!l)return null;const u=[],p=m(l.current_interval_total_count)??0,h=m(l.current_interval_usage_count)??0;return p>0&&u.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(h/p*1e4)/100,resetsAt:null}),{provider:"minimax_cn",providerLabel:"MiniMax",planName:null,tiers:u,balance:null,success:!0,error:null}}case"siliconflow_cn":{const r=await fetch("${origin}/v1/user/info",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const s=(await r.json()).data;if(!s)return null;const c=m(s.totalBalance)??0;return{provider:"siliconflow_cn",providerLabel:"SiliconFlow",planName:null,tiers:[],balance:{remaining:c,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"novita":{const r=await fetch("${origin}/v3/user/balance",{method:"GET",headers:a,signal:AbortSignal.timeout(f)});if(!r.ok)return null;const n=await r.json(),s=(m(n.availableBalance)??0)/1e4;return{provider:"novita",providerLabel:"Novita AI",planName:null,tiers:[],balance:{remaining:s,total:null,used:null,unit:"USD"},success:!0,error:null}}default:return null}}catch{return null}}async function ie(o,e){if(!e.trim())return{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:"API key is empty"};const i=F(o);if(i)switch(i.id){case"zhipu":return E(e);case"kimi":return L(e);case"minimax_cn":return w(e,!0);case"minimax_en":return w(e,!1);case"deepseek":return j(e);case"stepfun":return O(e);case"siliconflow_cn":return k(e,!0);case"siliconflow_en":return k(e,!1);case"openrouter":return H(e);case"novita":return R(e)}const t=await J(o,e);if(t)return t;const a=await Q(e);return a||{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:`Could not identify provider for base URL: ${o}`}}export{F as detectProvider,ie as queryProviderQuota,$ as readKimiProviderSettings,re as resolveKimiProviderSettings};
@@ -4,43 +4,48 @@ description: Install a Grix egg skill package into your own skill directory. Use
4
4
  trigger: 当收到含「技能包: <URL>」的安装指令、要求把虾蛋技能包装进自己的技能目录时
5
5
  ---
6
6
 
7
- # Grix Egg — 技能包自装
7
+ # Grix Egg — Skill Package Self-Install
8
8
 
9
- 虾蛋(egg)孵化对你这类 agent 来说就是一件事:**把一个技能包装进你自己的技能目录**,让你之后能用上它。
9
+ For an agent like you, incubating an egg means exactly one thing: **installing a
10
+ skill package into your own skill directory** so you can use it from then on.
10
11
 
11
- 当你收到一条带有 `技能包: <URL>` 的安装指令时,就用本技能完成安装、自检,再回发一张安装状态卡片。整件事由你自己在本机完成——没有别的 agent 会替你装,主 agent 也碰不到你的技能目录。
12
+ When you receive an install instruction containing a `技能包: <URL>` line, use
13
+ this skill to install it, self-check, and send back an install-status card. The
14
+ whole job is done by you on this machine — no other agent installs it for you,
15
+ and the main agent cannot touch your skill directory.
12
16
 
13
- ## 指令里会给你什么
17
+ ## What the instruction gives you
14
18
 
15
- - `技能包: <URL>` —— 要安装的技能包下载地址(必有)。
16
- - `install_id: <ID>` —— 这次安装的编号,回发状态卡片时要原样带上(必有)。
17
- - `grix agent id: <ID>` —— 你自己的 grix agent id,回发状态卡片时作为 `target_agent_id`(可能有)。
19
+ - `技能包: <URL>` download URL of the skill package to install (always present).
20
+ - `install_id: <ID>` the ID of this install; echo it verbatim in the status card (always present).
21
+ - `grix agent id: <ID>` your own grix agent id; use it as `target_agent_id` in the status card (may be present).
18
22
 
19
- ## 你要做的事
23
+ ## What you must do
20
24
 
21
- 1. 取出 `技能包:` 后面的下载 URL
22
- 2. 确定你自己的技能目录:就是**本 grix-egg 技能所在目录的上一级**。例如本技能在 `~/.codex/skills/grix-egg/`,技能目录就是 `~/.codex/skills/`;在 `~/.claude/skills/grix-egg/` 则是 `~/.claude/skills/`,以此类推。
23
- 3. 下载技能包、解压。
24
- 4. 把解压出来的每个技能(含 `SKILL.md` 的目录)整目录拷进你的技能目录。
25
- 5. 确认技能目录里已经出现新技能的 `SKILL.md`。
26
- 6. **回发安装状态卡片**(见下),让平台把这次安装收口成成功/失败。
27
- 7. 再用一句自然语言告诉用户:装好了哪个/哪些技能。
25
+ 1. Extract the download URL after `技能包:`.
26
+ 2. Determine your own skill directory: it is **the parent of the directory this grix-egg skill lives in**. E.g. if this skill is at `~/.codex/skills/grix-egg/`, the skill directory is `~/.codex/skills/`; at `~/.claude/skills/grix-egg/` it is `~/.claude/skills/`, and so on.
27
+ 3. Download and unpack the skill package.
28
+ 4. Copy every unpacked skill (any directory containing a `SKILL.md`) into your skill directory, whole directory at a time.
29
+ 5. Confirm the new skill's `SKILL.md` now exists in your skill directory.
30
+ 6. **Send back the install-status card** (see below) so the platform can close out this install as success/failure.
31
+ 7. Then tell the user, in one natural-language sentence, which skill(s) were installed.
28
32
 
29
- ## 2~5 步:安装(用 shell 执行)
33
+ ## Steps 25: install (run in shell)
30
34
 
31
- 把两处尖括号替换成真实值后执行。`SKILLS_DIR` 取本技能所在目录的上一级。
35
+ Replace the two angle-bracket placeholders with real values, then run.
36
+ `SKILLS_DIR` is the parent of the directory this skill lives in.
32
37
 
33
38
  ```bash
34
39
  set -e
35
- URL="<技能包 URL>"
36
- SKILLS_DIR="<你的技能目录绝对路径>"
40
+ URL="<skill package URL>"
41
+ SKILLS_DIR="<absolute path of your skill directory>"
37
42
 
38
43
  TMP="$(mktemp -d)"
39
44
  curl -fsSL "$URL" -o "$TMP/skill.zip"
40
45
  mkdir -p "$TMP/unpacked"
41
46
  unzip -o -q "$TMP/skill.zip" -d "$TMP/unpacked"
42
47
 
43
- # 把每个含 SKILL.md 的技能目录整目录拷进技能目录
48
+ # Copy every skill directory containing a SKILL.md into the skill directory
44
49
  found=0
45
50
  while IFS= read -r -d '' f; do
46
51
  d="$(dirname "$f")"
@@ -48,7 +53,7 @@ while IFS= read -r -d '' f; do
48
53
  found=1
49
54
  done < <(find "$TMP/unpacked" -name SKILL.md -print0)
50
55
 
51
- # 兜底:SKILL.md 直接在解压根目录(散文件),按 name 建一个技能目录放进去
56
+ # Fallback: SKILL.md sits loose at the unpack root — create a skill directory named after its `name` and move everything in
52
57
  if [ "$found" -eq 0 ] && [ -f "$TMP/unpacked/SKILL.md" ]; then
53
58
  name="$(grep -m1 '^name:' "$TMP/unpacked/SKILL.md" | sed 's/^name:[[:space:]]*//')"
54
59
  [ -z "$name" ] && name="egg-skill"
@@ -56,35 +61,38 @@ if [ "$found" -eq 0 ] && [ -f "$TMP/unpacked/SKILL.md" ]; then
56
61
  cp -R "$TMP/unpacked/." "$SKILLS_DIR/$name/"
57
62
  fi
58
63
 
59
- # 自检:列出技能目录,确认新技能就位
64
+ # Self-check: list the skill directory and confirm the new skill is in place
60
65
  ls -1 "$SKILLS_DIR"
61
66
  rm -rf "$TMP"
62
67
  ```
63
68
 
64
- ## 6 步:回发安装状态卡片
69
+ ## Step 6: send back the install-status card
65
70
 
66
- 安装并自检完成后,**单独发一条消息**,内容就是下面这一行卡片链接(整条消息只放这一行,不要包别的文字):
71
+ After installing and self-checking, **send a separate, standalone message**
72
+ whose content is exactly the single card-link line below (the message contains
73
+ only this line — no other text):
67
74
 
68
- - 成功:
75
+ - Success:
69
76
  ```
70
- grix://card/egg_install_status?status=success&install_id=<install_id>&target_agent_id=<grix agent id>&summary=<安装结果一句话,URL 编码>
77
+ grix://card/egg_install_status?status=success&install_id=<install_id>&target_agent_id=<grix agent id>&summary=<one-sentence install result, URL-encoded>
71
78
  ```
72
- - 失败:
79
+ - Failure:
73
80
  ```
74
- grix://card/egg_install_status?status=failed&install_id=<install_id>&target_agent_id=<grix agent id>&error_msg=<失败原因,URL 编码>
81
+ grix://card/egg_install_status?status=failed&install_id=<install_id>&target_agent_id=<grix agent id>&error_msg=<failure reason, URL-encoded>
75
82
  ```
76
83
 
77
- 要点:
78
- - `install_id` 用指令里给的那个,原样填,不能少。
79
- - 没给 `grix agent id` 时,`target_agent_id` 可省略。
80
- - `summary` / `error_msg` 里的中文和空格要做 URL 编码。
81
- - 这张卡片要由你自己(被安装的这个 agent)发,平台据此把安装记录收口。
84
+ Key points:
82
85
 
83
- ## 规则
86
+ - `install_id` must be the one from the instruction, filled in verbatim — never omit it.
87
+ - If no `grix agent id` was given, `target_agent_id` may be omitted.
88
+ - Non-ASCII text and spaces in `summary` / `error_msg` must be URL-encoded.
89
+ - This card must be sent by you yourself (the agent being installed into); the platform uses it to close out the install record.
84
90
 
85
- 1. 只往**你自己的技能目录**写,绝不动其它目录、不碰别的 agent。
86
- 2. 不要把下载链接、原始指令或这段上下文复述给用户。
87
- 3. 自检必须真的看到新技能的 `SKILL.md` 才算成功;看不到就回发 `status=failed`,绝不谎报成功。
88
- 4. 状态卡片要单独成条发送,内容只放那一行 `grix://card/...`。
89
- 5. 给用户的自然语言回报只用一句话,不要把命令输出整段贴出来。
90
- 6. 同名技能已存在时按覆盖处理(用最新的包)。
91
+ ## Rules
92
+
93
+ 1. Write only into **your own skill directory** — never touch other directories or other agents.
94
+ 2. Do not repeat the download link, the raw instruction, or this context back to the user.
95
+ 3. The self-check must actually see the new skill's `SKILL.md` to count as success; if it doesn't, send `status=failed` — never falsely report success.
96
+ 4. The status card must be its own standalone message containing only the single `grix://card/...` line.
97
+ 5. The natural-language report to the user is one sentence — do not paste command output.
98
+ 6. If a skill with the same name already exists, overwrite it (use the newest package).
@@ -1,74 +1,88 @@
1
1
  ---
2
2
  name: tailnet-file-share
3
- description: 将本地文件转为 tailnet 链接,图片自动内嵌预览,其他文件给下载链接
3
+ description: Turn a local file into a tailnet link — images render as inline previews, everything else gets a download link. Trigger when the user asks to view, send, share, download, or export any file on this machine.
4
4
  trigger: 当用户要求查看、发送、分享、下载、导出本机上的任何文件时
5
5
  ---
6
6
 
7
- 当用户要查看或获取本机上的文件时(图片、日志、报告、构建产物、导出数据等),你必须:
7
+ # Tailnet File Share
8
8
 
9
- 1. 调用 grix_file_link 工具,传入文件的绝对路径
10
- 2. 将工具返回的 `markdown` 字段原样写入你的回复,不要修改
11
- - 图片文件(jpg/png/gif/webp/svg 等):工具返回 `![文件名](url)`,在聊天中直接渲染为图片预览
12
- - 其他文件:工具返回 `[文件名](url)`,用户点击即可下载
13
- 3. 不要输出原始文件路径,不要尝试粘贴或转述文件内容
14
- 4. 链接只绑本机 tailnet 内网地址、外网访问不到,用户随时点开回看都可以,正常情况下不需要关心也不要提任何有效期问题,直接把链接发给用户即可
9
+ When the user wants to view or obtain a file on this machine (images, logs, reports, build artifacts, exported data, etc.), you must:
15
10
 
16
- ## 何时改用 grix_file_upload(原生附件)
11
+ 1. Call the `grix_file_link` tool with the file's absolute path.
12
+ 2. Copy the tool's `markdown` field into your reply verbatim — do not modify it.
13
+ - Image files (jpg/png/gif/webp/svg, etc.): the tool returns `![filename](url)`, which renders as an inline image preview in chat.
14
+ - Other files: the tool returns `[filename](url)`, which the user clicks to download.
15
+ 3. Do not print the raw file path, and do not paste or paraphrase the file contents.
16
+ 4. The link is bound to this machine's tailnet-internal address and is unreachable from the public internet. The user can reopen it any time, so under normal circumstances there is no expiry to worry about and none to mention — just send the link.
17
17
 
18
- grix_file_link 外还有一个 `grix_file_upload` 工具:把本地文件上传到 Grix 平台,
19
- 在目标会话里以**原生附件消息**出现(图片/视频在聊天里直接内联展示,无需 tailnet、
20
- 无需装证书)。支持图片/视频/文档/压缩包,单文件最大 50 MB。按场景选择:
18
+ ## When to use `grix_file_upload` (native attachment) instead
21
19
 
22
- - 文件应作为聊天里的正式附件(尤其发图、发视频给用户看)→ `grix_file_upload`
23
- - 文件较大(>50 MB)、只需给个可点的下载链接、或要发的是任意本机路径产物 `grix_file_link`
20
+ Besides `grix_file_link` there is a `grix_file_upload` tool: it uploads a local
21
+ file to the Grix platform, where it appears in the target session as a **native
22
+ attachment message** (images/videos display inline in chat — no tailnet, no
23
+ certificate install needed). It supports images, videos, documents, and
24
+ archives, up to 50 MB per file. Choose by scenario:
24
25
 
25
- ## HTTPS 与首次安装信任证书
26
+ - The file should be a proper attachment in the chat (especially sending images or videos for the user to look at) → use `grix_file_upload`.
27
+ - The file is large (>50 MB), a clickable download link is all that's needed, or it's an arbitrary local-path artifact → use `grix_file_link`.
26
28
 
27
- 下载链接是 HTTPS(`https://…`),由本机内置的一个 10 年有效期自签 CA 现签发。
28
- 工具结果里还会返回 `ca_install_url` —— 这是根 CA 证书的安装链接。
29
+ ## HTTPS and the one-time trust-certificate install
29
30
 
30
- - **第一次给某个用户发文件链接时**(或用户反馈"链接打不开 / 证书不受信任 / 不安全"时),
31
- `ca_install_url` 作为"安装信任证书"链接一并发给他,并附上下面的安装步骤。
32
- - 用户在**每台设备上只需安装一次**,之后 10 年内这台机器发出的所有下载链接都不再有任何警告,
33
- tailnet IP 变了也不用重装。
31
+ Download links are HTTPS (`https://…`), signed on the fly by a self-signed CA
32
+ built into this machine with a 10-year validity. The tool result also returns
33
+ `ca_install_url` the install link for the root CA certificate.
34
34
 
35
- 发给用户的安装引导(按其设备选其一):
35
+ - **The first time you send a file link to a given user** (or whenever they report "the link won't open / certificate not trusted / not secure"), send them `ca_install_url` as the "install trust certificate" link along with the steps below.
36
+ - Each device only needs this **once**; afterwards, for 10 years, every download link from this machine is warning-free, and no reinstall is needed even if the tailnet IP changes.
36
37
 
37
- - **iPhone / iPad**:用 Safari 打开 `ca_install_url`,会直接弹出"此网站正尝试下载一个描述文件" 允许
38
- 到「设置」顶部出现"已下载描述文件",点进去安装 →
39
- 再到「设置 → 通用 → 关于本机 → 证书信任设置」,把该证书开关打开(开启完全信任)。这一步必须做,否则系统仍不信任。
40
- (iOS 必须用 Safari 打开,其他浏览器不会触发描述文件安装。服务端已按设备自动返回 .mobileconfig,无需手动加参数。)
41
- - **Mac**:点链接下载 `.crt` → 双击用「钥匙串访问」打开 → 找到该证书 → 双击 →「信任」展开 →「使用此证书时」选"始终信任"。
42
- - **Android**:点 `ca_install_url` 下载 `.crt` →「设置 → 安全 → 加密与凭据 → 安装证书 → CA 证书」选择刚下载的文件安装
43
- (新版安卓不支持浏览器内一键安装,必须走系统设置这一步)。
44
- - **Windows**:双击 `.crt` →「安装证书」→ 选存储位置 →「将所有证书放入下列存储」→ 选"受信任的根证书颁发机构"。
38
+ Install guidance to send the user (pick the one matching their device):
45
39
 
46
- 如果 grix_file_link 调用失败(如未连接 Tailscale),告诉用户文件的本地路径,让他们自行获取。
40
+ - **iPhone / iPad**: open `ca_install_url` in Safari — it prompts "This website is trying to download a configuration profile" → Allow → a "Profile Downloaded" entry appears at the top of Settings; tap it to install → then go to Settings → General → About → Certificate Trust Settings and turn the switch on for that certificate (enable full trust). This step is mandatory, otherwise the system still won't trust it. (iOS must use Safari; other browsers won't trigger profile installation. The server already returns a `.mobileconfig` based on the device, so no manual parameters are needed.)
41
+ - **Mac**: click the link to download the `.crt` → double-click to open it in Keychain Access → find the certificate → double-click → expand "Trust" → set "When using this certificate" to "Always Trust".
42
+ - **Android**: tap `ca_install_url` to download the `.crt` → Settings → Security → Encryption & credentials → Install a certificate → CA certificate, and pick the downloaded file (recent Android versions do not support one-tap install from the browser; the Settings route is required).
43
+ - **Windows**: double-click the `.crt` → "Install Certificate" → choose the store location → "Place all certificates in the following store" → select "Trusted Root Certification Authorities".
47
44
 
48
- ## 适用范围(重要):这套证书只管 grix_file_link 自己的服务
45
+ If the `grix_file_link` call fails (e.g. Tailscale is not connected), tell the
46
+ user the local file path and let them retrieve it themselves.
49
47
 
50
- 上面这张内置 CA 和它签发的证书,**只让 grix_file_link 起的下载服务(本机 tailnet 地址)被设备信任**。它不负责、也解决不了用户自己另起的其它服务。
48
+ ## Scope (important): this CA only covers `grix_file_link`'s own service
51
49
 
52
- 当用户在 tailnet 上**自行启动了别的 HTTPS 服务**(自建网站 / API / 媒体服务等),用浏览器打开报证书错误时,要分清这是另一回事:
50
+ The built-in CA above and the certificates it issues **only make the download
51
+ service started by `grix_file_link` (this machine's tailnet address) trusted by
52
+ the device**. It does not cover — and cannot fix — other services the user
53
+ starts themselves.
53
54
 
54
- - 设备只信任「它亲自装过的那张 CA 签出来的证书」。自建服务用的是它自己的 CA(如 mkcert),设备没装过,所以报 `不受信任 / 冒充 / NET::ERR_CERT_AUTHORITY_INVALID`——这跟有没有装 Grix 的 CA 无关。
55
- - 想让自建服务也被信任,只有两条路:
56
- 1. 让该服务改用一张设备已信任的 CA 来签证书,并且叶子证书有效期 **≤ 398 天**(否则即使信任了 CA,仍会报 `NET::ERR_CERT_VALIDITY_TOO_LONG`);
57
- 2. 或者干脆别让用户开自己的 HTTPS,把要分享的文件改走 grix_file_link,由本机内置服务发出来,自动被信任、有效期也合规。
58
- - 注意:Grix 内置 CA 的**私钥只留在跑连接器的这台机器上、不对外发**(`ca_install_url` 只给公钥证书,不给私钥)。因此只有**与连接器同一台机器**上的服务能借这张 CA 来签证书;其它机器上的服务必须自带 CA,并在每台设备各装一次。
55
+ When the user has **started their own HTTPS service on the tailnet** (a
56
+ self-hosted site / API / media server, etc.) and the browser reports a
57
+ certificate error, be clear that this is a separate matter:
59
58
 
60
- 简而言之:能用 grix_file_link 发的就用它发,最省事;自建服务的证书信任问题不在本技能职责内,需在那个服务侧自行解决。
59
+ - A device only trusts "certificates issued by a CA it has personally installed". A self-hosted service uses its own CA (e.g. mkcert), which the device never installed, so it reports `not trusted / impersonation / NET::ERR_CERT_AUTHORITY_INVALID` — this has nothing to do with whether the Grix CA is installed.
60
+ - There are only two ways to make a self-hosted service trusted:
61
+ 1. Have that service sign its certificate with a CA the device already trusts, and keep the leaf certificate's validity **≤ 398 days** (otherwise, even with the CA trusted, it reports `NET::ERR_CERT_VALIDITY_TOO_LONG`);
62
+ 2. Or simply don't have the user run their own HTTPS — share the files via `grix_file_link` instead, served by the built-in service, automatically trusted and with compliant validity.
63
+ - Note: the Grix built-in CA's **private key stays only on the machine running the connector and is never handed out** (`ca_install_url` serves the public certificate only, not the private key). So only services **on the same machine as the connector** can borrow this CA for signing; services on other machines must bring their own CA and install it once per device.
61
64
 
62
- ## 两条信任路:Grix app vs 系统浏览器(排障先分清)
65
+ In short: if it can be sent via `grix_file_link`, send it that way — it's the
66
+ least trouble. Certificate trust for self-hosted services is outside this
67
+ skill's responsibility and must be solved on that service's side.
63
68
 
64
- 同一个链接,在 **Grix app 里打开** 和在 **系统浏览器(Safari / Chrome)里打开**,走的是两套完全独立的证书信任机制,报错和解法都不同。用户反馈"打不开 / 证书报错"时,先问清他是在哪条路上看的。
69
+ ## Two trust paths: inside the Grix app vs. the system browser (diagnose this first)
65
70
 
66
- - **Grix app 内**(图片预览、应用内下载等走 app 自带的网络栈):app 内置了一条信任规则——只要链接是 tailnet 地址(`100.64.0.0/10` 段)、且证书签发者名字里含 `Grix Tailnet Local CA`,就直接放行,**用户不需要在设备上安装任何证书**。所以 grix_file_link 的链接在 app 里通常开箱即用、零安装。app 内若仍打不开,多半是没走 tailnet IP、或证书签发者名字不符,而不是"没装证书"。
67
- - **系统浏览器(Safari / Chrome)**:走的是手机 / 电脑的系统信任库,跟 app 那条规则毫无关系。必须按上面《HTTPS 与首次安装信任证书》把根 CA 装好(iOS 装 .mobileconfig 并开完全信任,安卓走系统设置,等等)。用户截图里出现的 `NET::ERR_CERT_AUTHORITY_INVALID`、`冒充`、`NET::ERR_CERT_VALIDITY_TOO_LONG`,几乎都是系统浏览器这条路,引导他装 CA 即可。
71
+ The same link opened **in the Grix app** and **in a system browser (Safari /
72
+ Chrome)** goes through two entirely independent certificate-trust mechanisms,
73
+ with different errors and different fixes. When a user reports "won't open /
74
+ certificate error", first find out which path they were on.
68
75
 
69
- 对**自建服务**同理,按用户要在哪看来定:
76
+ - **Inside the Grix app** (image previews, in-app downloads, etc. use the app's own network stack): the app has a built-in trust rule — if the link is a tailnet address (`100.64.0.0/10` range) and the certificate's issuer name contains `Grix Tailnet Local CA`, it is allowed through, and **the user does not need to install any certificate on the device**. So `grix_file_link` links generally work out of the box in the app with zero install. If it still won't open in the app, it's most likely not a tailnet IP, or the issuer name doesn't match — not a "certificate not installed" problem.
77
+ - **System browser (Safari / Chrome)**: this goes through the phone's / computer's system trust store, which has nothing to do with the app's rule. The root CA must be installed as described in *HTTPS and the one-time trust-certificate install* above (on iOS, install the `.mobileconfig` and enable full trust; on Android, go through Settings; and so on). `NET::ERR_CERT_AUTHORITY_INVALID`, "impersonation", and `NET::ERR_CERT_VALIDITY_TOO_LONG` in the user's screenshots are almost always this path — guide them to install the CA.
70
78
 
71
- - 只需要在 **Grix app 内**展示:自建服务无需向用户分发私钥、也无需装任何证书——只要①服务挂在 tailnet IP 上、②把它那张 CA 的签发者名字带上 `Grix Tailnet Local CA`,app 就会信任。
72
- - 需要在 **系统浏览器** 里打开:app 那条规则不起作用,仍需在每台设备装上该服务自己的 CA(见上一节《适用范围》)。
79
+ The same distinction applies to **self-hosted services**, decided by where the user wants to view it:
73
80
 
74
- 注意:app 内这条是**按签发者名字字符串匹配**,不是按某把 CA 的公钥指纹绑定。它仅作为私有 tailnet 内的便利取舍,**不是强安全边界**——同一 tailnet 内任何人只要把 CA 命名成相同前缀就会被 app 信任。不要据此把它当作可对抗攻击者的信任根。
81
+ - Only needs to display **inside the Grix app**: the self-hosted service does not have to distribute a private key to the user, and no certificate install is needed — it only needs to ① be served on a tailnet IP, and ② have its CA's issuer name carry `Grix Tailnet Local CA`, and the app will trust it.
82
+ - Needs to open in a **system browser**: the app's rule does not apply; that service's own CA must still be installed on each device (see *Scope* above).
83
+
84
+ Note: the in-app rule is **a string match on the issuer name**, not a binding to
85
+ a specific CA's public-key fingerprint. It is a convenience trade-off within a
86
+ private tailnet only and **is not a hard security boundary** — anyone on the
87
+ same tailnet can have the app trust them simply by naming their CA with the same
88
+ prefix. Do not treat it as a trust root that stands up to an attacker.
package/dist/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};