grix-connector 4.9.6 → 4.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/acp/acp-adapter.js +13 -14
- package/dist/adapter/acp/mcode-provider-config.js +2 -0
- package/dist/adapter/acp/session-activity.js +1 -1
- package/dist/adapter/acp/session-scanner.js +3 -3
- package/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +1 -1
- package/dist/adapter/opencode/opencode-adapter.js +5 -5
- package/dist/adapter/opencode/session-history.js +2 -2
- package/dist/adapter/opencode/session-scanner.js +3 -3
- package/dist/adapter/pi/omp-mcp-config.js +3 -0
- package/dist/adapter/pi/pi-adapter.js +6 -6
- package/dist/adapter/pi/pi-provider-config.js +3 -3
- package/dist/adapter/pi/session-history.js +2 -2
- package/dist/adapter/shared/identity-injector.js +2 -2
- package/dist/adapter/shared/native-provider-config.js +7 -5
- package/dist/adapter/shared/serialize-on-file.js +1 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.11.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/audit/adapters/acp/generic-acp-audit-adapter.js +2 -2
- package/dist/audit/adapters/opencode/opencode-audit-adapter.js +1 -1
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/native-provider-sweep.js +1 -1
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/session-identity.js +1 -1
- package/dist/bridge/session-list.js +3 -3
- package/dist/bridge/session-scan-cache.js +1 -1
- package/dist/bridge/session-usage.js +1 -1
- package/dist/core/config/provider-env.js +1 -1
- package/dist/core/installer/preflight.js +4 -4
- package/dist/core/installer/prereq-installer.js +3 -3
- package/dist/core/installer/registry.js +1 -1
- package/dist/core/mcp/tools.js +1 -1
- package/dist/core/persistence/session-binding-store.js +2 -2
- package/dist/core/probe/installed-clients.js +1 -1
- package/dist/core/provider-quota/providers.js +2 -2
- package/dist/core/skill-sync/enable-roots.js +1 -1
- package/dist/default-skills/grix-task-flow/SKILL.md +534 -0
- package/dist/default-skills/index.js +1 -1
- package/dist/default-skills/message-edit/SKILL.md +45 -0
- package/dist/manager.js +1 -1
- package/dist/protocol/acp-client.js +1 -1
- package/dist/types/events.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +110 -5
- package/openclaw-plugin/index.js +37 -0
- package/openclaw.plugin.json +1 -0
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.9.6.tgz +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{execFile as b}from"node:child_process";import{promisify as P}from"node:util";import{EventEmitter as I}from"node:events";import{stat as A}from"node:fs/promises";import{mkdirSync as $,writeFileSync as T,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as B}from"node:url";import{tmpdir as F,homedir as v}from"node:os";import{resolveCommandPath as D,resolveWindowsExecInvocation as N,spawnCommand as G,killProcessGroup as E,hasChildProcesses as L}from"../../core/runtime/spawn.js";import{InternalApiServer as O}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{compactToolInputForWire as q}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as z}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as K}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as X,removePiGrixProvider as J,writePiGrixProvider as Q}from"./pi-provider-config.js";const _=new Map;function Z(){const d=m(v(),".pi","agent","mcp.json");try{if(!C(d))return{};const e=JSON.parse(R(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function tt(d){const t=_.get(d);if(t!==void 0)return t;let e=!1;try{const s=P(b),i=N(d,["--help"]),{stdout:n,stderr:r}=await s(i.command,i.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return _.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class et extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const st=12e4,it=90*1e3,y=1800*1e3;function x(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const nt=500,rt=2e3,g=3,ot=500;function at(d){return new Promise(t=>setTimeout(t,d))}function dt(d){const t=new Set,e=[];for(const s of d){const i=s.provider?.trim();!i||t.has(i)||(t.add(i),e.push({id:i,display_name:i}))}return e}function u(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class w extends I{type="pi";config;callbacks;process=null;transport=new z;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new K;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new j("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=g;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<g){await at(ot);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${g} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(l=>({id:l.id,display_name:l.name??l.id,...l.provider?{provider:l.provider}:{}}))},c=dt(i);c.length>0&&(r.available_providers=c),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_id=n.provider,r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new et(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();if(!n){const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===i&&h.provider?.trim());if(l.length>1){const h=(await this.currentModel())?.provider?.trim();n=l.find(p=>p.provider?.trim()===h)?.provider?.trim()}n=n??l[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const s=t.params??{},i=(s.provider_id??s.provider??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===i);if(c.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${i}`),{handled:!0,kind:"set_provider_error"};const l=(await this.currentModel())?.id,h=c.find(p=>p.id===l)?.id??c[0].id;return await this.transport.send("set_model",{provider:i,modelId:h}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:i,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(B(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?L(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
|
-
${r.map(
|
|
3
|
-
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const
|
|
4
|
-
`):"No skills found",data:
|
|
1
|
+
import{execFile as T}from"node:child_process";import{promisify as A}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as M,writeFileSync as C,unlinkSync as R,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as B,delimiter as E}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as O,homedir as w}from"node:os";import{resolveCommandPath as N,resolveWindowsExecInvocation as L,spawnCommand as G,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{piGrixProviderId as Q,removePiGrixProvider as Z,writePiGrixProvider as tt}from"./pi-provider-config.js";import{agentIdOf as et}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as it,recordOmpMcpEntryPid as st,removeOmpMcpEntry as nt}from"./omp-mcp-config.js";function rt(d){return et(d)==="omp"}function ot(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function at(d){const t=ot(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const x=new Map;function dt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ct(d){const t=x.get(d);if(t!==void 0)return t;let e=!1;try{const i=A(T),s=L(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return x.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class lt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ht=12e4,pt=90*1e3,P=1800*1e3;function b(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,v=3,ft=500;function gt(d){return new Promise(t=>setTimeout(t,d))}function vt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class $ extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new W;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":rt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,i]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),s=e.data?.models;if(!s||s.length===0){if(t<v){await gt(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=i.data?.model,r={available_models:s.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))},l=vt(s);l.length>0&&(r.available_providers=l),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_id=n.provider,r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${s.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{R(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await nt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new lt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=i.provider?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:s}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.transport.send("set_model",{provider:s,modelId:p}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=B(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await X(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);if(!p)return{status:"failed",message:"Format: provider:model_id"};const h=await this.transport.send("set_model",{provider:c,modelId:p});return h?.success?{status:"ok",message:`Model set to ${c}:${p}`}:{status:"failed",message:`Failed to set model: ${h?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
|
+
${r.map(c=>` ${c.provider??"unknown"}:${c.id} (${c.name??c.id})`).join(`
|
|
3
|
+
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=z({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
4
|
+
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=dt(t),s=u(O(),"grix-pi-mcp");M(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),C(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await it(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=N(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(a=>a.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),l=Q(this.agentName);if(this.provider){const a=this.isOmp(e)?"bare":"dollar";await tt(r,l,this.provider,a)?(n.includes("--provider")||n.push("--provider",l),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await Z(r,l).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${l}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)});this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&!this.isOmp(e)&&(await ct(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let c={...process.env,...this.config.env};this.isOmp(e)&&(c=at(c));const p=this.provider?.apiKey?.trim();p&&!c.GRIX_PROVIDER_API_KEY?.trim()&&(c.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=G(e,n,{env:c,cwd:h}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&st(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(a=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`)}),this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const I=a.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=mt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},ut))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Y(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
|
|
5
5
|
`);e=`${e}
|
|
6
6
|
|
|
7
7
|
[Conversation context]
|
|
8
|
-
${n}`}}catch{}const
|
|
8
|
+
${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inboundMessageIds.inject(t.session_id,i,t.msg_id)}buildPromptTextFromRequest(t){let e=t.text;if(t.contextMessages&&t.contextMessages.length>0){const i=t.contextMessages.map(s=>`[context] ${s.senderId}: ${s.content}`).join(`
|
|
9
9
|
`);e=`${e}
|
|
10
10
|
|
|
11
11
|
[Conversation context]
|
|
12
|
-
${
|
|
12
|
+
${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),l=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${l} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} (reliable) event=${t}`)}).catch(c=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},$.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!b(t))return!1;const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(i<pt)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${i}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>P?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&b(t))?`liveness budget exhausted after ${P/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ht))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{$ as PiAdapter};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{mkdir as
|
|
2
|
-
`,{encoding:"utf8",mode:384}),x.info("pi-provider",`Wrote Grix provider providerId=${e} baseUrl=${o} model=${
|
|
3
|
-
`,{encoding:"utf8",mode:384}),!0)})}export{
|
|
1
|
+
import{mkdir as _,readFile as $,writeFile as l}from"node:fs/promises";import{join as m}from"node:path";import{log as x}from"../../core/log/index.js";import{serializeOnFile as u}from"../shared/serialize-on-file.js";const a="GRIX_PROVIDER_API_KEY",f=`$${a}`;function c(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function y(r){try{return c(JSON.parse(await $(r,"utf8")))}catch{return{}}}function I(r){const e=r.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-|-$/g,"");return e?`grix-${e}`:"grix"}async function b(r,e,i,n="dollar"){const o=i.baseUrl?.trim(),t=i.model?.trim();if(!o||!t)return!1;const s=m(r,"models.json");return u(s,async()=>{const p=await y(s),d=c(p.providers);return d[e]={baseUrl:o,api:"openai-completions",apiKey:n==="bare"?a:f,models:[{id:t,name:t}]},p.providers=d,await _(r,{recursive:!0}),await l(s,`${JSON.stringify(p,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384}),x.info("pi-provider",`Wrote Grix provider providerId=${e} baseUrl=${o} model=${t} api=openai-completions apiKeyEnv=${a} apiKeyRefStyle=${n} path=${s}`),!0})}async function E(r,e){const i=m(r,"models.json");return u(i,async()=>{const n=await y(i),o=c(n.providers),t=c(o[e]).apiKey;return t!==f&&t!==a?!1:(delete o[e],n.providers=o,await l(i,`${JSON.stringify(n,null,2)}
|
|
3
|
+
`,{encoding:"utf8",mode:384}),!0)})}export{I as piGrixProviderId,E as removePiGrixProvider,b as writePiGrixProvider};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isAbsolute as x,join as
|
|
2
|
-
`)}return t==null?"":String(t)}function
|
|
1
|
+
import{isAbsolute as x,join as A,resolve as u,sep as S}from"node:path";import{homedir as k}from"node:os";import{readJsonlHistoryPage as I,registerSessionHistoryReader as b,SESSION_HISTORY_ERROR_CODES as d,SessionHistoryError as _}from"../shared/session-history.js";import{resolvePiAgentDir as R}from"./session-scanner.js";function c(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v(t){if(typeof t=="string")return t;if(Array.isArray(t)){const r=[];for(const n of t)c(n)&&n.type==="text"&&typeof n.text=="string"&&r.push(n.text);return r.join(`
|
|
2
|
+
`)}return t==null?"":String(t)}function O(t,r){if((typeof t.type=="string"?t.type:"")!=="message")return[];const e=c(t.message)?t.message:void 0;if(!e)return[];const f=typeof e.role=="string"?e.role:"",y=typeof t.id=="string"&&t.id?t.id:r,m=typeof t.parentId=="string"?t.parentId:null,h=typeof t.timestamp=="string"?t.timestamp:typeof e.timestamp=="string"?e.timestamp:"",a=[];if(f==="user"){const s=e.content;if(typeof s=="string")a.push({role:"user",content:s,msg_type:"text"});else if(Array.isArray(s))for(const i of s){if(!c(i))continue;const l=i;l.type==="text"&&typeof l.text=="string"&&a.push({role:"user",content:l.text,msg_type:"text"})}}else if(f==="assistant"){const s=e.content,i=typeof e.model=="string"?e.model:void 0;if(typeof s=="string")a.push({role:"assistant",content:s,msg_type:"text",...i?{extra:{model:i}}:{}});else if(Array.isArray(s))for(const l of s){if(!c(l))continue;const o=l;if(o.type==="text"&&typeof o.text=="string")a.push({role:"assistant",content:o.text,msg_type:"text",...i?{extra:{model:i}}:{}});else if(o.type==="thinking"){const p=typeof o.thinking=="string"?o.thinking:typeof o.text=="string"?o.text:"";if(!p)continue;a.push({role:"assistant",content:p,msg_type:"thinking"})}else if(o.type==="toolCall"){const p={};typeof o.name=="string"&&(p.tool_name=o.name),typeof o.id=="string"&&(p.tool_use_id=o.id);let g="{}";try{g=JSON.stringify(o.arguments??{})}catch{}a.push({role:"assistant",content:g,msg_type:"tool_use",...Object.keys(p).length>0?{extra:p}:{}})}}}else if(f==="toolResult"){const s={};typeof e.toolCallId=="string"&&(s.tool_use_id=e.toolCallId),e.isError===!0&&(s.is_error=!0),a.push({role:"tool",content:v(e.content),msg_type:"tool_result",...Object.keys(s).length>0?{extra:s}:{}})}else return[];return a.map((s,i)=>({native_message_id:i===0?y:`${y}#${i}`,native_parent_id:m,created_at:h,...s}))}function w(t,r){const n=t.agent_session_id;if(!n||!x(n))throw new _(d.invalidAgentSession,`invalid pi agent_session_id (expect absolute session file path): ${t.agent_session_id}`);const e=u(r?.sessionsDir??A(R(k(),r?.agentEnv?.PI_CODING_AGENT_DIR),"sessions")),f=u(n);if(f!==e&&!f.startsWith(e+S))throw new _(d.invalidAgentSession,`pi session path escapes sessions dir: ${t.agent_session_id}`);return f}async function E(t,r){const n=w(t,r);return{...await I({filePath:n,cursor:t.cursor,limit:t.limit,mapLine:O,sourceLabel:"pi session transcript",logTag:"pi-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}b("pi",E);export{E as readPiSessionHistory};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{log as
|
|
2
|
-
`))}onProfileChanged(){this.injectedSessions.size>0&&(
|
|
1
|
+
import{log as c}from"../../core/log/index.js";import{insertBeforeTrailingMessageReferences as l}from"../../core/protocol/message-reference.js";const f=200,g=4e3,u=["[system-identity]","[/system-identity]"];function a(n,e){return n.replaceAll("\0","").slice(0,e)}function d(n){let e=n;for(const t of u){const s=t.replace("[","\uFF3B").replace("]","\uFF3D");e=e.split(t).join(s)}return e}class p{logTag;getProfile;injectedSessions=new Set;constructor(e,t){this.logTag=e,this.getProfile=t}injectOnce(e,t){if(!e||this.injectedSessions.has(e))return t;const s=this.getProfile?.(),o=a(d(s?.agentName?.trim()??""),f),r=a(d(s?.introduction?.trim()??""),g);if(!o&&!r)return t;this.injectedSessions.add(e);const i=["[system-identity]"];return o&&i.push(`Your name is "${o}".`),r&&i.push(`Your self-introduction: ${r}`),i.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),i.push("[/system-identity]"),c.info(this.logTag,`Injected agent identity for session=${e} name="${o}"`),l(t,i.join(`
|
|
2
|
+
`))}onProfileChanged(){this.injectedSessions.size>0&&(c.info(this.logTag,`agent profile changed; clearing ${this.injectedSessions.size} identity-injected session(s)`),this.injectedSessions.clear())}forgetSession(e){this.injectedSessions.delete(e)}markInjected(e){e&&this.injectedSessions.add(e)}}export{p as IdentityInjector};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import{mkdir as
|
|
2
|
-
`,"utf8"),await
|
|
3
|
-
`,"utf8")}async function
|
|
4
|
-
`,"utf8"),await
|
|
5
|
-
|
|
1
|
+
import{mkdir as w,readFile as O,rm as S,writeFile as m}from"node:fs/promises";import{homedir as h}from"node:os";import{join as u}from"node:path";import{isMap as E,isSeq as T,parseDocument as A,Document as v,YAMLMap as R,YAMLSeq as H}from"yaml";function x(t){const r=(t??"").trim();return(r.split(/[\\/]/).pop()||r).replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase()}async function f(t){try{const r=await O(t,"utf8"),e=JSON.parse(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function g(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const L=".grix-provider-state.json";async function k(t,r){const e=u(t,".qwen"),i=u(e,"settings.json"),o=u(e,L);if(!r.OPENAI_BASE_URL){await C(i,o);return}const n=await f(i),a=g(n.security),l=g(a.auth),s=g(n.model),c=await f(o),p={previousSelectedType:Object.keys(c).length>0?typeof c.previousSelectedType=="string"?c.previousSelectedType:null:typeof l.selectedType=="string"?l.selectedType:null,previousModelName:Object.keys(c).length>0?typeof c.previousModelName=="string"?c.previousModelName:null:typeof s.name=="string"?s.name:null,writtenModelName:r.OPENAI_MODEL??null};l.selectedType="openai",a.auth=l,n.security=a,r.OPENAI_MODEL&&(s.name=r.OPENAI_MODEL,n.model=s),await w(e,{recursive:!0}),await m(i,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf8"),await m(o,`${JSON.stringify(p,null,2)}
|
|
3
|
+
`,"utf8")}async function C(t,r){const e=await f(r);if(Object.keys(e).length===0)return!1;const i={previousSelectedType:typeof e.previousSelectedType=="string"?e.previousSelectedType:null,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null,writtenModelName:typeof e.writtenModelName=="string"?e.writtenModelName:null},o=await f(t),n=g(o.security),a=g(n.auth),l=g(o.model);let s=!1;return a.selectedType==="openai"&&(i.previousSelectedType?a.selectedType=i.previousSelectedType:delete a.selectedType,n.auth=a,o.security=n,s=!0),i.writtenModelName&&l.name===i.writtenModelName&&(i.previousModelName?l.name=i.previousModelName:delete l.name,o.model=l,s=!0),s&&await m(t,`${JSON.stringify(o,null,2)}
|
|
4
|
+
`,"utf8"),await S(r,{force:!0}),!0}const b=".grix-provider-state.json",_="grix";async function G(t,r){const e=u(t,".trae"),i=u(e,"traecli.yaml"),o=u(e,b),n=r.GRIX_TRAECLI_BASE_URL?.trim(),a=r.GRIX_TRAECLI_MODEL?.trim();if(!n||!a){await j(i,o);return}let l="";try{l=await O(i,"utf8")}catch(d){if(d.code!=="ENOENT")throw d}const s=l.trim()?A(l):new v({});if(s.errors.length>0)throw new Error(`traecli.yaml \u89E3\u6790\u5931\u8D25: ${s.errors[0].message}`);if(s.contents!=null&&!E(s.contents))throw new Error("traecli.yaml: \u9876\u5C42\u4E0D\u662F\u6620\u5C04\uFF0C\u65E0\u6CD5\u5199\u5165 models/model");let c=s.get("models",!0);if(c==null&&(c=new H,s.set("models",c)),!T(c))throw new Error("traecli.yaml: models \u4E0D\u662F\u5217\u8868");const p=new R;p.set("name",_);const N=new R;N.set("model",a),N.set("base_url",n),N.set("api_key","${GRIX_PROVIDER_API_KEY}"),p.set("open_ai",N);const I=c.items.findIndex(d=>E(d)&&d.get("name")===_);I>=0?c.set(I,p):c.add(p);let y=s.get("model",!0);if(E(y)){const d=await f(o);if(Object.keys(d).length===0){const M=y.get("name"),D={hadModelKey:!0,previousModelName:typeof M=="string"?M:null};await w(e,{recursive:!0}),await m(o,`${JSON.stringify(D,null,2)}
|
|
5
|
+
`,"utf8")}}else{const d=await f(o);if(Object.keys(d).length===0){const M={hadModelKey:y!==void 0,previousModelName:null};await w(e,{recursive:!0}),await m(o,`${JSON.stringify(M,null,2)}
|
|
6
|
+
`,"utf8")}y=new R,s.set("model",y)}y.set("name",_),await w(e,{recursive:!0}),await m(i,s.toString(),"utf8")}async function j(t,r){const e=await f(r);if(Object.keys(e).length===0)return!1;const i={hadModelKey:e.hadModelKey===!0,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null};let o="";try{o=await O(t,"utf8")}catch(a){if(a.code!=="ENOENT")throw await S(r,{force:!0}),a;return await S(r,{force:!0}),!0}const n=o.trim()?A(o):new v({});if(n.errors.length===0&&E(n.contents)){const a=n.get("models",!0);if(T(a)){const s=a.items.findIndex(c=>E(c)&&c.get("name")===_);s>=0&&a.items.splice(s,1)}const l=n.get("model",!0);E(l)&&l.get("name")===_&&(i.hadModelKey?i.previousModelName?l.set("name",i.previousModelName):l.delete("name"):n.delete("model")),await m(t,n.toString(),"utf8")}return await S(r,{force:!0}),!0}async function F(t,r){if(!r)return!1;const e=x(t);if(e==="qwen"){const i=u(r,".qwen");return C(u(i,"settings.json"),u(i,L))}if(e==="traecli"){const i=u(r,".trae");return j(u(i,"traecli.yaml"),u(i,b))}return!1}function P(t){return(t??"default").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function X(t,r){const e=t.HERMES_HOME?.trim()||t.GRIX_HERMES_HOME?.trim();if(e)return e;if(t.GRIX_HERMES_BASE_URL?.trim()&&t.HERMES_INFERENCE_MODEL?.trim()&&t.GRIX_PROVIDER_API_KEY?.trim()){const o=t.GRIX_CONNECTOR_HOME?.trim()||u(h(),".grix");return u(o,"runtime","native-provider",P(r),"hermes")}return u(h(),".hermes")}async function $(t,r){const e=t.GRIX_HERMES_BASE_URL?.trim(),i=t.HERMES_INFERENCE_MODEL?.trim(),o=t.GRIX_PROVIDER_API_KEY?.trim();if(!e||!i||!o)return;const n=X(t,r),a=["model:"," provider: grix",` default: ${JSON.stringify(i)}`,"providers:"," grix:",` api: ${JSON.stringify(e)}`,` default_model: ${JSON.stringify(i)}`," key_env: GRIX_PROVIDER_API_KEY"," name: Grix"," transport: openai_chat",""].join(`
|
|
7
|
+
`);await w(n,{recursive:!0}),await m(u(n,"config.yaml"),a,{encoding:"utf8",mode:384}),t.HERMES_HOME=n}async function U(t,r,e,i){if(!(!r||!e))switch(x(t)){case"qwen":await k(r,e);return;case"hermes":await $(e,i);return;case"traecli":await G(r,e);return;default:return}}export{x as agentIdOf,U as applyNativeProviderConfig,X as resolveHermesHomeDir,F as restoreNativeProviderConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=new Map;function t(e,n){const i=(r.get(e)??Promise.resolve()).then(n,n);return r.set(e,i.catch(()=>{})),i}export{t as serializeOnFile};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
5
|
-
"size":
|
|
6
|
-
"unpackedSize":
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
3
|
+
"bridgeVersion": "4.11.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.11.0.tgz",
|
|
5
|
+
"size": 23387,
|
|
6
|
+
"unpackedSize": 94036,
|
|
7
|
+
"shasum": "efc9f4b8fa526f45d3c26b252b17e28e5e8c622d",
|
|
8
|
+
"integrity": "sha512-uI49tFqK7SaVL4vDr/ZryjB7xOlbkvdqVlz4OErG6wYbFP+TLPBbidz/A7XAoQi8WL61RMyFP9PS2GkG3MPqFg=="
|
|
9
9
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFile as
|
|
2
|
-
`).flatMap(r=>{if(!r.trim())return[];try{const t=JSON.parse(r);return p(t)?[t]:[]}catch{return[]}})}async function X(e,n,r){const t=b(O(),".qwen","projects",r.replace(/[/\\]/g,"-"),"chats",`${n}.jsonl`);try{await L(t)}catch{return{records:[]}}const s=await J(t),c=F(s,e);if(c<0)return{records:[],sourcePath:t};const u=s.slice(c+1),i=u.findIndex(o=>o.type==="user");return{records:(i>=0?u.slice(0,i):u).flatMap((o,m)=>{if(o.type!=="assistant"||!p(o.usageMetadata))return[];const d=o.usageMetadata,v=q(d.promptTokenCount),y=q(d.candidatesTokenCount),I=q(d.cachedContentTokenCount)??0,A=q(d.thoughtsTokenCount);if(v===void 0||y===void 0)return[];const w=C(o.timestamp)??e.endedAt,h=f(o.model);return[{requestId:f(o.uuid)??`qwen-${m}`,model:h??"qwen",...h?{modelId:h}:{},endedAt:w,output:W(o,!1),thinking:W(o,!0),sourcePath:t,raw:o,inputTotal:v,outputTotal:y,uncached:Math.max(0,v-I),cacheRead:I,cacheWrite:null,reasoning:A??null,visible:A===void 0?null:Math.max(0,y-A),requestCount:1}]}),sourcePath:t}}async function Y(e,n){const r=b(O(),".gemini","tmp",V(n),"chats");try{const t=await B(r),s=e.slice(0,8),c=t.filter(i=>i.startsWith("session-")&&i.includes(s)&&(i.endsWith(".json")||i.endsWith(".jsonl")));return(await Promise.all(c.map(async i=>{const _=b(r,i);return{sourcePath:_,modifiedAt:(await L(_)).mtimeMs}}))).sort((i,_)=>_.modifiedAt-i.modifiedAt)[0]?.sourcePath}catch{return}}async function Z(e,n,r){const t=await Y(n,r);if(!t)return{records:[]};const s=t.endsWith(".jsonl")?await J(t):await(async()=>{const o=JSON.parse(await S(t,"utf8"));return Array.isArray(o)?o.filter(p):p(o)&&Array.isArray(o.messages)?o.messages.filter(p):[]})(),c=F(s,e);if(c<0)return{records:[],sourcePath:t};const u=s.slice(c+1),i=u.findIndex(o=>o.type==="user");return{records:(i>=0?u.slice(0,i):u).flatMap((o,m)=>{if(o.type!=="gemini"||!p(o.tokens))return[];const d=o.tokens,v=q(d.input),y=q(d.output),I=q(d.thoughts)??0,A=q(d.cached)??0;if(v===void 0||y===void 0)return[];const w=f(o.model);return[{requestId:f(o.id)??`gemini-${m}`,model:w??"gemini",...w?{modelId:w}:{},endedAt:C(o.timestamp)??e.endedAt,output:N(o.content),thinking:Array.isArray(o.thoughts)?o.thoughts.map(h=>p(h)?f(h.description)??"":"").join(""):void 0,sourcePath:t,raw:o,inputTotal:v,outputTotal:y+I,uncached:Math.max(0,v-A),cacheRead:A,cacheWrite:null,reasoning:I,visible:y,requestCount:1}]}),sourcePath:t}}async function j(e,n){const r=b(O(),".kiro","sessions","cli",`${n}.json`);let t;try{t=JSON.parse(await S(r,"utf8"))}catch{return{records:[]}}const s=p(t)?t:{},c=p(s.session_state)?s.session_state:{},u=p(c.conversation_metadata)?c.conversation_metadata:{},i=p(c.rts_model_state)?c.rts_model_state:{},_=p(i.model_info)?i.model_info:{};return{records:(Array.isArray(u.user_turn_metadatas)?u.user_turn_metadatas.filter(p):[]).flatMap((m,d)=>{const v=C(m.end_timestamp),y=p(m.result)?m.result:{},I=p(y.Ok)?y.Ok:{},A=q(m.input_token_count),w=q(m.output_token_count);if(!U(v,e)||A===void 0||w===void 0)return[];const h=f(_.model_id);return[{requestId:f(I.id)??`kiro-turn-${d}`,model:h??"kiro",...h?{modelId:h}:{},endedAt:v,output:N(I.content),sourcePath:r,raw:m,inputTotal:A,outputTotal:w,uncached:null,cacheRead:null,cacheWrite:null,reasoning:null,visible:null,requestCount:Math.max(1,q(m.total_request_count)??1)}]}),sourcePath:r}}async function ee(e){const n=String(e.boundary.agentType??"").toLowerCase(),r=f(e.boundary.providerSessionId),t=f(e.boundary.cwd);return r?n==="qwen"&&t?X(e,r,t):n==="gemini"&&t?Z(e,r,t):n==="kiro"?j(e,r):{records:[]}:{records:[]}}function R(e,n,r){const t=[r.role,r.sourcePath??"",r.value??""].join("\0");if(n.has(t))return n.get(t);const s=H(r);return n.set(t,s),e.push(r),s}function k(e,n){n&&!e.some(r=>r.contentId===n.contentId)&&e.push(n)}function M(e){const n=e.startedAt??e.job.startedAt,r=e.endedAt??e.job.endedAt,t=Date.parse(n),s=Date.parse(r);return{spanId:e.spanId,traceId:e.job.traceId,turnId:e.job.turnId,sessionId:e.job.sessionId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},kind:e.kind,name:e.name,sequence:e.sequence,status:e.status??"completed",startedAt:n,endedAt:r,...Number.isFinite(t)&&Number.isFinite(s)?{durationMs:Math.max(0,s-t)}:{},inputRefs:[],outputRefs:[],provider:{provider:"acp",nativeEventType:e.nativeEventType,nativeIds:Object.fromEntries(Object.entries(e.nativeIds??{}).filter(c=>typeof c[1]=="string")),...e.rawAttributes?{rawAttributes:e.rawAttributes}:{}},provenance:{source:"provider_event",accuracy:"provider_reported"}}}function te(e){const n=e.uncached!==null&&e.cacheRead!==null&&e.cacheWrite!==null;return{input:{total:e.inputTotal,uncached:e.uncached,cacheRead:e.cacheRead,cacheWrite:e.cacheWrite,other:n?0:null},output:{total:e.outputTotal,reasoning:e.reasoning,visible:e.visible},totalProcessed:e.inputTotal+e.outputTotal,requestCount:e.requestCount,accuracy:"provider_reported",completeness:n?"complete":"partial",provider:"acp",providerUsageRaw:e.raw,normalization:{adapter:"generic-acp-native-session",version:1,formula:"provider input total + provider output total; available cache/reasoning dimensions remain explicit, unavailable dimensions are null"}}}function ne(e){[...e].sort((r,t)=>r.kind==="turn"?-1:t.kind==="turn"?1:Date.parse(r.startedAt)-Date.parse(t.startedAt)||r.sequence-t.sequence).forEach((r,t)=>{r.sequence=t})}class ie{provider="acp";async collect(n){const r={events:[],usageRecords:[],sourcePaths:[],anomalies:[],gaps:[]},t=p(n.boundary.acpEvidence)?n.boundary.acpEvidence:void 0;if(t&&Array.isArray(t.events))for(const s of t.events){if(!p(s)||!p(s.event)||typeof s.sequence!="number"||typeof s.observedAt!="string"){r.anomalies.push({code:"acp_audit_event_malformed",message:"ACP evidence row is malformed"}),r.gaps.push({category:"acp_event",reason:"correlation_failed"});continue}r.events.push({sequence:s.sequence,observedAt:s.observedAt,event:s.event})}r.events.sort((s,c)=>s.sequence-c.sequence);try{const s=await ee(n);r.usageRecords=s.records,s.sourcePath&&r.sourcePaths.push(s.sourcePath)}catch(s){r.anomalies.push({code:"acp_native_usage_source_unreadable",message:s instanceof Error?s.message:String(s)})}return r}async normalize(n,r){const t=r,s=Q(n),c=[],u=[],i=new Map;let _=0;const x=f(n.boundary.agentType)??"ACP",o=`acp:${n.turnId}:turn`,m=M({job:n,spanId:o,kind:"turn",name:`${x} audited turn`,sequence:_++,status:n.outcome==="completed"?"completed":n.outcome==="cancelled"?"cancelled":"failed",nativeEventType:"acp_turn",nativeIds:{providerSessionId:f(n.boundary.providerSessionId)}});c.push(m);const d=s.inputOutput&&n.input?R(u,i,{...n.input,captureLevel:n.input.captureLevel??"runtime_exact"}):void 0;k(m.inputRefs,d),s.inputOutput&&n.finalOutput&&k(m.outputRefs,R(u,i,{...n.finalOutput,captureLevel:n.finalOutput.captureLevel??"runtime_exact"}));const v=[],y=t.usageRecords.length>0?t.usageRecords:[{requestId:`${x}-${n.turnId}`,model:x,endedAt:n.endedAt,sourcePath:"",raw:{},inputTotal:0,outputTotal:0,uncached:null,cacheRead:null,cacheWrite:null,reasoning:null,visible:null,requestCount:1}];for(const[l,a]of y.entries()){const g=M({job:n,spanId:`acp:${n.sessionId}:request:${a.requestId}`,parentSpanId:o,kind:"llm_request",name:a.model,sequence:_++,startedAt:a.startedAt??(l===0?n.startedAt:y[l-1].endedAt),endedAt:a.endedAt,nativeEventType:"native_session_usage",nativeIds:{requestId:a.requestId,providerSessionId:f(n.boundary.providerSessionId)},rawAttributes:{sourcePath:a.sourcePath,nativeUsage:a.raw}});a.modelId&&(g.modelId=a.modelId),l===0&&k(g.inputRefs,d),t.usageRecords.length>0&&(g.usage=te(a)),s.inputOutput&&a.output&&k(g.outputRefs,R(u,i,{role:"assistant_text",format:"text",value:a.output,sourcePath:a.sourcePath,captureLevel:"provider_exact"})),s.thinking&&a.thinking&&k(g.outputRefs,R(u,i,{role:"thinking",format:"text",value:a.thinking,sourcePath:a.sourcePath,captureLevel:"provider_exact"})),s.rawProviderBody&&t.usageRecords.length>0&&k(g.outputRefs,R(u,i,{role:"model_response",format:"json",value:JSON.stringify(a.raw),sourcePath:a.sourcePath,captureLevel:"provider_exact"})),c.push(g),v.push(g)}t.usageRecords.length===0&&t.gaps.push({category:"provider_usage",reason:"provider_usage_missing",detail:`${x} native session usage is unavailable`});const I=new Map,A=new Map;for(const l of t.events){const a=f(l.event.toolCallId);a&&(l.event.type==="tool_use"&&I.set(a,l),l.event.type==="tool_result"&&A.set(a,l))}if(s.tools)for(const[l,a]of I){const g=A.get(l),z=[...v].reverse().find(T=>Date.parse(T.startedAt)<=Date.parse(a.observedAt))??v[0],P=M({job:n,spanId:`acp:${n.sessionId}:tool:${l}`,parentSpanId:z?.spanId??o,kind:"tool_call",name:f(a.event.toolName)??"tool",sequence:_++,status:g?"completed":"running",startedAt:a.observedAt,endedAt:g?.observedAt??n.endedAt,nativeEventType:"tool_use",nativeIds:{toolCallId:l},rawAttributes:{toolUseEvent:a.event,...g?{toolResultEvent:g.event}:{}}}),D=f(a.event.toolInput);D&&k(P.inputRefs,R(u,i,{role:"tool_arguments",format:"json",value:D,captureLevel:"runtime_exact"}));const E=f(g?.event.toolOutput)??f(g?.event.content);if(E){const T=R(u,i,{role:"tool_result",format:"text",value:E,captureLevel:"runtime_exact"});k(P.outputRefs,T);const $=v.find(G=>Date.parse(G.startedAt)>=Date.parse(g.observedAt));$&&k($.inputRefs,T)}c.push(P)}const w=t.events.filter(l=>l.event.type==="text").map(l=>f(l.event.content)??"").join(""),h=v.at(-1);if(s.inputOutput&&w&&h&&!h.outputRefs.some(l=>l.role==="assistant_text")&&k(h.outputRefs,R(u,i,{role:"assistant_text",format:"text",value:w,captureLevel:"runtime_exact"})),s.thinking&&h){const l=t.events.filter(a=>a.event.type==="thinking").map(a=>f(a.event.content)??"").join("");l&&k(h.outputRefs,R(u,i,{role:"thinking",format:"text",value:l,captureLevel:"runtime_exact"}))}return ne(c),{spans:c,contents:u,anomalies:t.anomalies,collection:t,capture:s}}async correlate(n,r){return r}validate(n,r){const t=r,s=t.spans.filter(d=>d.kind==="llm_request"),c=t.spans.filter(d=>d.kind==="tool_call"),u=!t.capture.inputOutput||n.input!==void 0,i=!t.capture.inputOutput||n.finalOutput!==void 0||s.some(d=>d.outputRefs.length>0),_=!t.capture.tools||c.every(d=>d.status!=="running"),x=s.length>0&&s.every(d=>d.usage?.completeness==="complete"),o=[...t.collection.gaps];t.capture.rawProviderBody&&o.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"Generic ACP exposes agent events/native session records, not raw model HTTP bodies"});const m=u&&i&&_&&x&&o.length===0;return{status:s.length===0?"failed":m?"complete":"partial",inputComplete:u,outputComplete:i,toolCallsComplete:_,subagentsComplete:!0,usageComplete:x,rawRequestsComplete:!1,gaps:o}}}export{ie as GenericAcpAuditAdapter};
|
|
1
|
+
import{readFile as $,readdir as H,stat as W}from"node:fs/promises";import{homedir as N}from"node:os";import{basename as K,join as M}from"node:path";import{referenceCaptureContent as Q}from"../../core/content-reference.js";const X=Object.freeze({inputOutput:!0,tools:!0,subagents:!1,thinking:!0,rawProviderBody:!1});function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function d(e){return typeof e=="string"&&e.length>0?e:void 0}function w(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Y(e){return e.options?.enabled===!0?e.options.capture:X}function D(e){if(typeof e=="number"&&Number.isFinite(e)){const t=e>1e10?e:e*1e3;return new Date(t).toISOString()}if(typeof e=="string"&&Number.isFinite(Date.parse(e)))return new Date(e).toISOString()}function F(e,t){if(!e)return!1;const r=Date.parse(e);return r>=Date.parse(t.startedAt)-5e3&&r<=Date.parse(t.endedAt)+3e4}function J(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:m(t)?d(t.text)??d(t.data)??"":"").join(""):""}function z(e,t){const r=m(e.message)?e.message:{};return(Array.isArray(r.parts)?r.parts:[]).filter(s=>m(s)&&s.thought===!0===t).map(s=>m(s)?d(s.text)??"":"").join("")}function G(e,t){const r=t.input?.value?.trim();if(r)for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="user"&&JSON.stringify(s).includes(r))return n}for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="user"&&F(D(s.timestamp),t))return n}return-1}async function B(e){return(await $(e,"utf8")).split(`
|
|
2
|
+
`).flatMap(r=>{if(!r.trim())return[];try{const n=JSON.parse(r);return m(n)?[n]:[]}catch{return[]}})}async function Z(e,t,r){const n=M(N(),".qwen","projects",r.replace(/[/\\]/g,"-"),"chats",`${t}.jsonl`);try{await W(n)}catch{return{records:[]}}const s=await B(n),l=G(s,e);if(l<0)return{records:[],sourcePath:n};const f=s.slice(l+1),c=f.findIndex(a=>a.type==="user");return{records:(c>=0?f.slice(0,c):f).flatMap((a,v)=>{if(a.type!=="assistant"||!m(a.usageMetadata))return[];const h=a.usageMetadata,i=w(h.promptTokenCount),_=w(h.candidatesTokenCount),I=w(h.cachedContentTokenCount)??0,y=w(h.thoughtsTokenCount);if(i===void 0||_===void 0)return[];const q=D(a.timestamp)??e.endedAt,A=d(a.model);return[{requestId:d(a.uuid)??`qwen-${v}`,model:A??"qwen",...A?{modelId:A}:{},endedAt:q,output:z(a,!1),thinking:z(a,!0),sourcePath:n,raw:a,inputTotal:i,outputTotal:_,uncached:Math.max(0,i-I),cacheRead:I,cacheWrite:null,reasoning:y??null,visible:y===void 0?null:Math.max(0,_-y),requestCount:1}]}),sourcePath:n}}async function j(e,t){const r=M(N(),".gemini","tmp",K(t),"chats");try{const n=await H(r),s=e.slice(0,8),l=n.filter(c=>c.startsWith("session-")&&c.includes(s)&&(c.endsWith(".json")||c.endsWith(".jsonl")));return(await Promise.all(l.map(async c=>{const g=M(r,c);return{sourcePath:g,modifiedAt:(await W(g)).mtimeMs}}))).sort((c,g)=>g.modifiedAt-c.modifiedAt)[0]?.sourcePath}catch{return}}async function ee(e,t,r){const n=await j(t,r);if(!n)return{records:[]};const s=n.endsWith(".jsonl")?await B(n):await(async()=>{const a=JSON.parse(await $(n,"utf8"));return Array.isArray(a)?a.filter(m):m(a)&&Array.isArray(a.messages)?a.messages.filter(m):[]})(),l=G(s,e);if(l<0)return{records:[],sourcePath:n};const f=s.slice(l+1),c=f.findIndex(a=>a.type==="user");return{records:(c>=0?f.slice(0,c):f).flatMap((a,v)=>{if(a.type!=="gemini"||!m(a.tokens))return[];const h=a.tokens,i=w(h.input),_=w(h.output),I=w(h.thoughts)??0,y=w(h.cached)??0;if(i===void 0||_===void 0)return[];const q=d(a.model);return[{requestId:d(a.id)??`gemini-${v}`,model:q??"gemini",...q?{modelId:q}:{},endedAt:D(a.timestamp)??e.endedAt,output:J(a.content),thinking:Array.isArray(a.thoughts)?a.thoughts.map(A=>m(A)?d(A.description)??"":"").join(""):void 0,sourcePath:n,raw:a,inputTotal:i,outputTotal:_+I,uncached:Math.max(0,i-y),cacheRead:y,cacheWrite:null,reasoning:I,visible:_,requestCount:1}]}),sourcePath:n}}async function te(e,t){const r=M(N(),".kiro","sessions","cli",`${t}.json`);let n;try{n=JSON.parse(await $(r,"utf8"))}catch{return{records:[]}}const s=m(n)?n:{},l=m(s.session_state)?s.session_state:{},f=m(l.conversation_metadata)?l.conversation_metadata:{},c=m(l.rts_model_state)?l.rts_model_state:{},g=m(c.model_info)?c.model_info:{};return{records:(Array.isArray(f.user_turn_metadatas)?f.user_turn_metadatas.filter(m):[]).flatMap((v,h)=>{const i=D(v.end_timestamp),_=m(v.result)?v.result:{},I=m(_.Ok)?_.Ok:{},y=w(v.input_token_count),q=w(v.output_token_count);if(!F(i,e)||y===void 0||q===void 0)return[];const A=d(g.model_id);return[{requestId:d(I.id)??`kiro-turn-${h}`,model:A??"kiro",...A?{modelId:A}:{},endedAt:i,output:J(I.content),sourcePath:r,raw:v,inputTotal:y,outputTotal:q,uncached:null,cacheRead:null,cacheWrite:null,reasoning:null,visible:null,requestCount:Math.max(1,w(v.total_request_count)??1)}]}),sourcePath:r}}async function ne(e){const t=String(e.boundary.agentType??"").toLowerCase(),r=d(e.boundary.providerSessionId),n=d(e.boundary.cwd);return r?t==="qwen"&&n?Z(e,r,n):t==="gemini"&&n?ee(e,r,n):t==="kiro"?te(e,r):{records:[]}:{records:[]}}function x(e,t,r){const n=[r.role,r.sourcePath??"",r.value??""].join("\0");if(t.has(n))return t.get(n);const s=Q(r);return t.set(n,s),e.push(r),s}function R(e,t){t&&!e.some(r=>r.contentId===t.contentId)&&e.push(t)}function E(e){const t=e.startedAt??e.job.startedAt,r=e.endedAt??e.job.endedAt,n=Date.parse(t),s=Date.parse(r);return{spanId:e.spanId,traceId:e.job.traceId,turnId:e.job.turnId,sessionId:e.job.sessionId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},kind:e.kind,name:e.name,sequence:e.sequence,status:e.status??"completed",startedAt:t,endedAt:r,...Number.isFinite(n)&&Number.isFinite(s)?{durationMs:Math.max(0,s-n)}:{},inputRefs:[],outputRefs:[],provider:{provider:"acp",nativeEventType:e.nativeEventType,nativeIds:Object.fromEntries(Object.entries(e.nativeIds??{}).filter(l=>typeof l[1]=="string")),...e.rawAttributes?{rawAttributes:e.rawAttributes}:{}},provenance:{source:"provider_event",accuracy:"provider_reported"}}}function se(e){const t=e.uncached!==null&&e.cacheRead!==null&&e.cacheWrite!==null;return{input:{total:e.inputTotal,uncached:e.uncached,cacheRead:e.cacheRead,cacheWrite:e.cacheWrite,other:t?0:null},output:{total:e.outputTotal,reasoning:e.reasoning,visible:e.visible},totalProcessed:e.inputTotal+e.outputTotal,requestCount:e.requestCount,accuracy:"provider_reported",completeness:t?"complete":"partial",provider:"acp",providerUsageRaw:e.raw,normalization:{adapter:"generic-acp-native-session",version:1,formula:"provider input total + provider output total; available cache/reasoning dimensions remain explicit, unavailable dimensions are null"}}}function re(e){[...e].sort((r,n)=>r.kind==="turn"?-1:n.kind==="turn"?1:Date.parse(r.startedAt)-Date.parse(n.startedAt)||r.sequence-n.sequence).forEach((r,n)=>{r.sequence=n})}class ce{provider="acp";async collect(t){const r={events:[],usageRecords:[],sourcePaths:[],anomalies:[],gaps:[]},n=m(t.boundary.acpEvidence)?t.boundary.acpEvidence:void 0;if(n&&Array.isArray(n.events))for(const s of n.events){if(!m(s)||!m(s.event)||typeof s.sequence!="number"||typeof s.observedAt!="string"){r.anomalies.push({code:"acp_audit_event_malformed",message:"ACP evidence row is malformed"}),r.gaps.push({category:"acp_event",reason:"correlation_failed"});continue}r.events.push({sequence:s.sequence,observedAt:s.observedAt,event:s.event})}r.events.sort((s,l)=>s.sequence-l.sequence);try{const s=await ne(t);r.usageRecords=s.records,s.sourcePath&&r.sourcePaths.push(s.sourcePath)}catch(s){r.anomalies.push({code:"acp_native_usage_source_unreadable",message:s instanceof Error?s.message:String(s)})}return r}async normalize(t,r){const n=r,s=Y(t),l=[],f=[],c=new Map;let g=0;const k=d(t.boundary.agentType)??"ACP",a=`acp:${t.turnId}:turn`,v=E({job:t,spanId:a,kind:"turn",name:`${k} audited turn`,sequence:g++,status:t.outcome==="completed"?"completed":t.outcome==="cancelled"?"cancelled":"failed",nativeEventType:"acp_turn",nativeIds:{providerSessionId:d(t.boundary.providerSessionId)}});l.push(v);const h=s.inputOutput&&t.input?x(f,c,{...t.input,captureLevel:t.input.captureLevel??"runtime_exact"}):void 0;R(v.inputRefs,h),s.inputOutput&&t.finalOutput&&R(v.outputRefs,x(f,c,{...t.finalOutput,captureLevel:t.finalOutput.captureLevel??"runtime_exact"}));const i=[],_=n.usageRecords.length>0?n.usageRecords:[{requestId:`${k}-${t.turnId}`,model:k,endedAt:t.endedAt,sourcePath:"",raw:{},inputTotal:0,outputTotal:0,uncached:null,cacheRead:null,cacheWrite:null,reasoning:null,visible:null,requestCount:1}];for(const[u,o]of _.entries()){const p=E({job:t,spanId:`acp:${t.sessionId}:request:${o.requestId}`,parentSpanId:a,kind:"llm_request",name:o.model,sequence:g++,startedAt:o.startedAt??(u===0?t.startedAt:_[u-1].endedAt),endedAt:o.endedAt,nativeEventType:"native_session_usage",nativeIds:{requestId:o.requestId,providerSessionId:d(t.boundary.providerSessionId)},rawAttributes:{sourcePath:o.sourcePath,nativeUsage:o.raw}});o.modelId&&(p.modelId=o.modelId),u===0&&R(p.inputRefs,h),n.usageRecords.length>0&&(p.usage=se(o)),s.inputOutput&&o.output&&R(p.outputRefs,x(f,c,{role:"assistant_text",format:"text",value:o.output,sourcePath:o.sourcePath,captureLevel:"provider_exact"})),s.thinking&&o.thinking&&R(p.outputRefs,x(f,c,{role:"thinking",format:"text",value:o.thinking,sourcePath:o.sourcePath,captureLevel:"provider_exact"})),s.rawProviderBody&&n.usageRecords.length>0&&R(p.outputRefs,x(f,c,{role:"model_response",format:"json",value:JSON.stringify(o.raw),sourcePath:o.sourcePath,captureLevel:"provider_exact"})),l.push(p),i.push(p)}n.usageRecords.length===0&&n.gaps.push({category:"provider_usage",reason:"provider_usage_missing",detail:`${k} native session usage is unavailable`});const I=new Map,y=new Map,q=new Map,A=new Map;for(const u of n.events){const o=d(u.event.toolCallId);o&&(u.event.type==="tool_use"&&I.set(o,u),u.event.type==="tool_result"&&y.set(o,u));const p=d(u.event.requestId);p&&(u.event.type==="permission_request"&&q.set(p,u),u.event.type==="permission_response"&&A.set(p,u))}if(s.tools)for(const[u,o]of q){const p=A.get(u),P=m(o.event.permissionRequest)?o.event.permissionRequest:void 0,b=d(P?.toolCallId)??d(o.event.toolCallId),S=[...i].reverse().find(T=>Date.parse(T.startedAt)<=Date.parse(o.observedAt))??i[0],O=E({job:t,spanId:`acp:${t.sessionId}:permission:${u}`,parentSpanId:S?.spanId??a,kind:"permission",name:d(P?.toolName)??d(o.event.toolName)??"permission_request",sequence:g++,status:p?p.event.permissionDecision==="dropped"?"failed":"completed":"running",startedAt:o.observedAt,endedAt:p?.observedAt??t.endedAt,nativeEventType:"permission_request",nativeIds:{requestId:u,toolCallId:b},rawAttributes:{permissionRequestEvent:o.event,...p?{permissionResponseEvent:p.event,decision:d(p.event.permissionDecision)}:{}}});l.push(O)}if(s.tools)for(const[u,o]of I){const p=y.get(u),P=[...i].reverse().find(T=>Date.parse(T.startedAt)<=Date.parse(o.observedAt))??i[0],b=E({job:t,spanId:`acp:${t.sessionId}:tool:${u}`,parentSpanId:P?.spanId??a,kind:"tool_call",name:d(o.event.toolName)??"tool",sequence:g++,status:p?"completed":"running",startedAt:o.observedAt,endedAt:p?.observedAt??t.endedAt,nativeEventType:"tool_use",nativeIds:{toolCallId:u},rawAttributes:{toolUseEvent:o.event,...p?{toolResultEvent:p.event}:{}}}),S=d(o.event.toolInput);S&&R(b.inputRefs,x(f,c,{role:"tool_arguments",format:"json",value:S,captureLevel:"runtime_exact"}));const O=d(p?.event.toolOutput)??d(p?.event.content);if(O){const T=x(f,c,{role:"tool_result",format:"text",value:O,captureLevel:"runtime_exact"});R(b.outputRefs,T);const U=i.find(V=>Date.parse(V.startedAt)>=Date.parse(p.observedAt));U&&R(U.inputRefs,T)}l.push(b)}const L=n.events.filter(u=>u.event.type==="text").map(u=>d(u.event.content)??"").join(""),C=i.at(-1);if(s.inputOutput&&L&&C&&!C.outputRefs.some(u=>u.role==="assistant_text")&&R(C.outputRefs,x(f,c,{role:"assistant_text",format:"text",value:L,captureLevel:"runtime_exact"})),s.thinking&&C){const u=n.events.filter(o=>o.event.type==="thinking").map(o=>d(o.event.content)??"").join("");u&&R(C.outputRefs,x(f,c,{role:"thinking",format:"text",value:u,captureLevel:"runtime_exact"}))}return re(l),{spans:l,contents:f,anomalies:n.anomalies,collection:n,capture:s}}async correlate(t,r){return r}validate(t,r){const n=r,s=n.spans.filter(i=>i.kind==="llm_request"),l=n.spans.filter(i=>i.kind==="tool_call"),f=n.spans.filter(i=>i.kind==="permission"),c=!n.capture.inputOutput||t.input!==void 0,g=!n.capture.inputOutput||t.finalOutput!==void 0||s.some(i=>i.outputRefs.length>0),k=!n.capture.tools||l.every(i=>i.status!=="running")&&f.every(i=>i.status!=="running"),a=s.length>0&&s.every(i=>i.usage?.completeness==="complete"),v=[...n.collection.gaps];n.capture.rawProviderBody&&v.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"Generic ACP exposes agent events/native session records, not raw model HTTP bodies"});const h=c&&g&&k&&a&&v.length===0;return{status:s.length===0?"failed":h?"complete":"partial",inputComplete:c,outputComplete:g,toolCallsComplete:k,subagentsComplete:!0,usageComplete:a,rawRequestsComplete:!1,gaps:v}}}export{ce as GenericAcpAuditAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{referenceCaptureContent as
|
|
1
|
+
import{referenceCaptureContent as B}from"../../core/content-reference.js";const U=Object.freeze({inputOutput:!0,tools:!0,subagents:!1,thinking:!0,rawProviderBody:!1});function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a(e){return typeof e=="string"&&e.length>0?e:void 0}function w(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function J(e){return e.options?.enabled===!0?e.options.capture:U}function O(e,n,r){const s=[r.role,r.value??""].join("\0");if(n.has(s))return n.get(s);const o=B(r);return n.set(s,o),e.push(r),o}function _(e,n){n&&!e.some(r=>r.contentId===n.contentId)&&e.push(n)}function M(e,n){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():typeof e=="string"&&Number.isFinite(Date.parse(e))?e:n}function D(e){const n=e.startedAt??e.job.startedAt,r=e.endedAt??e.job.endedAt,s=Date.parse(n),o=Date.parse(r);return{spanId:e.spanId,traceId:e.job.traceId,turnId:e.job.turnId,sessionId:e.job.sessionId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},kind:e.kind,name:e.name,sequence:e.sequence,status:e.status??"completed",startedAt:n,endedAt:r,...Number.isFinite(s)&&Number.isFinite(o)?{durationMs:Math.max(0,o-s)}:{},inputRefs:[],outputRefs:[],provider:{provider:"opencode",nativeEventType:e.nativeEventType,nativeIds:Object.fromEntries(Object.entries(e.nativeIds??{}).filter(f=>typeof f[1]=="string")),...e.rawAttributes?{rawAttributes:e.rawAttributes}:{}},provenance:{source:"provider_event",accuracy:"provider_reported"}}}function H(e){const n=w(e.input),r=w(e.output),s=w(e.reasoning),o=w(e.total),f=q(e.cache)?e.cache:{},m=w(f.read),v=w(f.write);if(n===void 0||r===void 0||s===void 0||o===void 0||m===void 0||v===void 0)return;const I=n+m+v,g=o===I+r+s,h=o===I+r&&s<=r;if(!g&&!h)return;const A=g?r+s:r,S=g?r:r-s;return{input:{total:I,uncached:n,cacheRead:m,cacheWrite:v,other:0},output:{total:A,reasoning:s,visible:S},totalProcessed:o,requestCount:1,accuracy:"provider_reported",completeness:"complete",provider:"opencode",providerUsageRaw:e,normalization:{adapter:"opencode-sse",version:1,formula:g?"input + cache.read + cache.write + output + reasoning":"input + cache.read + cache.write + output; reasoning is an output subset"}}}class W{provider="opencode";async collect(n){const r={events:[],anomalies:[],gaps:[]},s=q(n.boundary.openCodeEvidence)?n.boundary.openCodeEvidence:void 0;if(!s||!Array.isArray(s.events))return r.gaps.push({category:"opencode_event",reason:"source_log_missing",detail:"boundary.openCodeEvidence.events is missing"}),r;for(const o of s.events){if(!q(o)||!q(o.event)||typeof o.sequence!="number"||typeof o.observedAt!="string"){r.anomalies.push({code:"opencode_audit_event_malformed",message:"OpenCode evidence row is malformed"}),r.gaps.push({category:"opencode_event",reason:"correlation_failed"});continue}r.events.push({sequence:o.sequence,observedAt:o.observedAt,event:o.event})}return r.events.sort((o,f)=>o.sequence-f.sequence),r}async normalize(n,r){const s=r,o=J(n),f=[],m=[],v=new Map;let I=0;const g=`opencode:${n.turnId}:turn`,h=D({job:n,spanId:g,kind:"turn",name:"OpenCode audited turn",sequence:I++,status:n.outcome==="completed"?"completed":n.outcome==="cancelled"?"cancelled":"failed",nativeEventType:"sse_turn",nativeIds:{providerSessionId:a(n.boundary.providerSessionId)}});f.push(h);const A=o.inputOutput&&n.input?O(m,v,{...n.input,captureLevel:n.input.captureLevel??"runtime_exact"}):void 0;_(h.inputRefs,A),o.inputOutput&&n.finalOutput&&_(h.outputRefs,O(m,v,{...n.finalOutput,captureLevel:n.finalOutput.captureLevel??"runtime_exact"}));const S=new Map,c=new Map;for(const p of s.events){if(p.event.type==="message.updated"&&q(p.event.info)){const d=p.event.info;if(d.role!=="assistant")continue;const y=a(d.id);if(!y)continue;const x=S.get(y);S.set(y,{firstSequence:x?.firstSequence??p.sequence,item:p,info:d})}if(p.event.type==="message.part.updated"&&q(p.event.part)){const d=a(p.event.part.id);d&&c.set(d,{sequence:p.sequence,item:p,part:p.event.part})}}const F=[...S.values()].sort((p,d)=>p.firstSequence-d.firstSequence),E=new Map;let $=A?[A]:[];for(const p of F){const d=p.info,y=a(d.id),x=q(d.time)?d.time:{},C=a(d.modelID),t=D({job:n,spanId:`opencode:${n.sessionId}:request:${y}`,parentSpanId:g,kind:"llm_request",name:[a(d.providerID),C].filter(Boolean).join("/")||"OpenCode model request",sequence:I++,status:d.error?"failed":"completed",startedAt:M(x.created,p.item.observedAt),endedAt:M(x.completed,p.item.observedAt),nativeEventType:"message.updated",nativeIds:{messageId:y,providerSessionId:a(d.sessionID)??a(n.boundary.providerSessionId)},rawAttributes:{message:d}});C&&(t.modelId=C);for(const i of $)_(t.inputRefs,i);$=[],q(d.tokens)&&(t.usage=H(d.tokens)),t.usage||s.gaps.push({category:"provider_usage",reason:"provider_usage_missing",detail:y});const u=[...c.values()].filter(({part:i})=>i.messageID===y).sort((i,l)=>i.sequence-l.sequence);for(const{part:i}of u)o.inputOutput&&i.type==="text"&&typeof i.text=="string"&&i.text&&_(t.outputRefs,O(m,v,{role:"assistant_text",format:"text",value:i.text,captureLevel:"provider_exact"})),o.thinking&&i.type==="reasoning"&&typeof i.text=="string"&&i.text&&_(t.outputRefs,O(m,v,{role:"thinking",format:"text",value:i.text,captureLevel:"provider_exact"}));o.rawProviderBody&&_(t.outputRefs,O(m,v,{role:"model_response",format:"json",value:JSON.stringify(d),captureLevel:"provider_exact"})),f.push(t),E.set(y,t)}if(o.tools){const p=[...c.values()].filter(({part:t})=>t.type==="tool").sort((t,u)=>t.sequence-u.sequence);for(const{part:t,item:u}of p){const i=a(t.callID)??a(t.id);if(!i||!q(t.state))continue;const l=t.state,b=a(l.status)??"pending",k=q(l.time)?l.time:{},T=D({job:n,spanId:`opencode:${n.sessionId}:tool:${i}`,parentSpanId:E.get(a(t.messageID)??"")?.spanId??g,kind:"tool_call",name:a(t.tool)??"tool",sequence:I++,status:b==="completed"?"completed":b==="error"?"failed":"running",startedAt:M(k.start,u.observedAt),endedAt:M(k.end,u.observedAt),nativeEventType:"message.part.updated",nativeIds:{toolCallId:i,messageId:a(t.messageID)},rawAttributes:{part:t}});l.input!==void 0&&_(T.inputRefs,O(m,v,{role:"tool_arguments",format:"json",value:typeof l.input=="string"?l.input:JSON.stringify(l.input),captureLevel:"provider_exact"}));const R=l.output??l.error;if(R!==void 0){const L=O(m,v,{role:"tool_result",format:typeof R=="string"?"text":"json",value:typeof R=="string"?R:JSON.stringify(R),captureLevel:"provider_exact"});if(_(T.outputRefs,L),L){const z=Date.parse(T.endedAt??u.observedAt),N=f.find(P=>P.kind==="llm_request"&&Date.parse(P.startedAt)>=z);N&&_(N.inputRefs,L)}}f.push(T)}const d=new Map,y=new Map,x=[];let C=-1;for(const t of s.events)t.sequence>C&&(C=t.sequence),t.event.type==="permission.asked"&&a(t.event.id)?d.set(t.event.id,t):t.event.type==="permission.replied"&&a(t.event.requestID)?y.set(t.event.requestID,t):t.event.type==="permission.updated"&&q(t.event.permission)&&x.push(t);for(const[t,u]of d){const i=y.get(t),l=q(u.event.tool)?u.event.tool:void 0,b=a(l?.messageID),k=D({job:n,spanId:`opencode:${n.sessionId}:permission:${t}`,parentSpanId:(b?E.get(b)?.spanId:void 0)??g,kind:"permission",name:a(u.event.permission)??"permission_request",sequence:I++,status:i?a(i.event.reply)==="reject"?"failed":"completed":"running",startedAt:u.observedAt,endedAt:i?.observedAt??u.observedAt,nativeEventType:"permission.asked",nativeIds:{requestId:t,messageId:b,toolCallId:a(l?.callID)},rawAttributes:{permissionRequest:u.event,...i?{permissionReply:i.event}:{}}});f.push(k)}for(const t of x){const u=t.event.permission,i=a(u.messageID),l=a(u.id)??`legacy:${t.sequence}`,b=t.sequence<C,k=D({job:n,spanId:`opencode:${n.sessionId}:permission:${l}`,parentSpanId:(i?E.get(i)?.spanId:void 0)??g,kind:"permission",name:a(u.type)??a(u.title)??"permission_request",sequence:I++,status:b?"completed":"running",startedAt:t.observedAt,endedAt:t.observedAt,nativeEventType:"permission.updated",nativeIds:{requestId:l,messageId:i,toolCallId:a(u.callID)},rawAttributes:{permission:u}});f.push(k)}}return{spans:f,contents:m,anomalies:s.anomalies,collection:s,capture:o}}async correlate(n,r){return r}validate(n,r){const s=r,o=s.spans.filter(c=>c.kind==="llm_request"),f=s.spans.filter(c=>c.kind==="tool_call"),m=s.spans.filter(c=>c.kind==="permission"),v=!s.capture.inputOutput||n.input!==void 0,I=!s.capture.inputOutput||n.finalOutput!==void 0||o.some(c=>c.outputRefs.length>0),g=!s.capture.tools||f.every(c=>c.status!=="running")&&m.every(c=>c.status!=="running"),h=o.length>0&&o.every(c=>c.usage?.completeness==="complete"),A=[...s.collection.gaps];s.capture.rawProviderBody&&A.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"OpenCode exposes provider-normalized SSE events, not raw HTTP bodies"});const S=v&&I&&g&&h&&A.length===0;return{status:s.collection.events.length===0||o.length===0?"failed":S?"complete":"partial",inputComplete:v,outputComplete:I,toolCallsComplete:g,subagentsComplete:!0,usageComplete:h,rawRequestsComplete:!1,gaps:A}}}export{W as OpenCodeAuditAdapter};
|