blade-code 0.10.15 → 0.10.17
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/blade.js +2 -2
- package/dist/{chunk-gav4hxcv.js → chunk-1n60pgsq.js} +2 -2
- package/dist/{chunk-n72www7h.js → chunk-2675vkx5.js} +3 -3
- package/dist/{chunk-dpt56hah.js → chunk-2c3zavy2.js} +1 -1
- package/dist/chunk-2x0marf0.js +1 -0
- package/dist/{chunk-afxpp33r.js → chunk-3d4cgnpw.js} +1 -1
- package/dist/chunk-3qhqbj09.js +2 -0
- package/dist/chunk-4svjvyyd.js +1 -0
- package/dist/{chunk-8j01ssaf.js → chunk-5chec8rs.js} +1 -1
- package/dist/{chunk-4dq9y7zn.js → chunk-6207mbmr.js} +2 -2
- package/dist/{chunk-7x5cqfy7.js → chunk-677ywzhs.js} +2 -2
- package/dist/chunk-69ma931b.js +100 -0
- package/dist/{chunk-nfqsnkbt.js → chunk-6aw8vpf8.js} +39 -39
- package/dist/{chunk-g11hq0e5.js → chunk-6g5k5de1.js} +1 -1
- package/dist/{chunk-vmq248m7.js → chunk-6pa6c2n0.js} +1 -1
- package/dist/{chunk-heqs3xan.js → chunk-6sb7cg95.js} +1 -1
- package/dist/chunk-6yjn2wj7.js +200 -0
- package/dist/chunk-774jxdm3.js +22 -0
- package/dist/chunk-87vsgqvy.js +1 -0
- package/dist/chunk-88639hse.js +1 -0
- package/dist/{chunk-4hawehmd.js → chunk-8rzwyknk.js} +15 -13
- package/dist/{chunk-agdamn30.js → chunk-8vd6q2wt.js} +2 -2
- package/dist/{chunk-kvx3sb3z.js → chunk-96h588rd.js} +1 -1
- package/dist/chunk-a0hk9xrj.js +10 -0
- package/dist/chunk-ab3a9gdc.js +1 -0
- package/dist/chunk-amdw5728.js +1 -0
- package/dist/chunk-bcxbrbvd.js +1 -0
- package/dist/{chunk-jjy8sg10.js → chunk-bjzykvs1.js} +2 -2
- package/dist/{chunk-0z7rg4f3.js → chunk-bpnyda6p.js} +2 -2
- package/dist/{chunk-zn7c21zj.js → chunk-bqgd4db7.js} +2 -2
- package/dist/{chunk-m4f213hk.js → chunk-c18qckn4.js} +2 -2
- package/dist/{chunk-eav8jpk1.js → chunk-cd087ckq.js} +2 -2
- package/dist/{chunk-732n8xj6.js → chunk-d9k98jy2.js} +1 -1
- package/dist/{chunk-74shfpve.js → chunk-entmz5b1.js} +1 -1
- package/dist/{chunk-z8c5rhdh.js → chunk-fa6313dv.js} +1 -1
- package/dist/chunk-fm8vpym2.js +1 -0
- package/dist/chunk-fneamw65.js +4 -0
- package/dist/{chunk-xx1d9kfd.js → chunk-fvj1mzgs.js} +1 -1
- package/dist/{chunk-ee7an1kq.js → chunk-gjw014rv.js} +1 -1
- package/dist/chunk-hm3yme2m.js +1 -0
- package/dist/chunk-hxcd65h1.js +1 -0
- package/dist/{chunk-s5666ta0.js → chunk-jpwfq49n.js} +2 -2
- package/dist/{chunk-ktf3bpmw.js → chunk-k3nkcaap.js} +2 -2
- package/dist/{chunk-2mzcxq6c.js → chunk-kbpc97n3.js} +2 -2
- package/dist/chunk-kjet3e74.js +6 -0
- package/dist/chunk-ncj12cv0.js +1 -0
- package/dist/{chunk-x1qw695m.js → chunk-nqj9c68w.js} +4 -4
- package/dist/{chunk-5s123nbs.js → chunk-prgh321y.js} +1 -1
- package/dist/{chunk-7wjy6kgt.js → chunk-q3c07kb4.js} +1 -1
- package/dist/{chunk-afkhzdfc.js → chunk-qkrssft1.js} +1 -1
- package/dist/{chunk-p4zt7ts9.js → chunk-qt114yth.js} +1 -1
- package/dist/{chunk-9tnaads5.js → chunk-r1jxbx1h.js} +1 -1
- package/dist/{chunk-7bq9p4ab.js → chunk-rgy886ad.js} +2 -2
- package/dist/{chunk-zmg66vp7.js → chunk-rn04c7hs.js} +2 -2
- package/dist/{chunk-mtk2tf9n.js → chunk-t3b689pm.js} +1 -1
- package/dist/{chunk-a170cgzr.js → chunk-w320ev24.js} +1 -1
- package/dist/{chunk-5wecprcp.js → chunk-w9zgpqjd.js} +2 -2
- package/dist/{chunk-632rgzcf.js → chunk-wt7gy9bm.js} +2 -2
- package/dist/{chunk-ng8a4btc.js → chunk-wvh6entt.js} +3 -3
- package/dist/chunk-wygpe92c.js +1 -0
- package/dist/{chunk-k47f7zqm.js → chunk-wzvy13p2.js} +1 -1
- package/dist/chunk-xet98pc1.js +5 -0
- package/dist/{chunk-3aqdjrtm.js → chunk-y2g5a5bp.js} +1 -1
- package/dist/chunk-y72p0x68.js +1 -0
- package/dist/{chunk-dsj62dcg.js → chunk-yqfqj7mh.js} +1 -1
- package/dist/{chunk-363pgv1e.js → chunk-yvf4nmds.js} +2 -2
- package/dist/{chunk-ybvdac8k.js → chunk-yz2bsntj.js} +1 -1
- package/dist/chunk-z9mpf0t7.js +1 -0
- package/dist/{chunk-r76wc1cn.js → chunk-zdkc4kj1.js} +1 -1
- package/dist/{chunk-4zs5r4n4.js → chunk-zt5wq0qj.js} +1 -1
- package/dist/web/assets/{ChatView-rHWZ9qCy.js → ChatView-YFotW0KS.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-KpN8jpS4.js → CodeBlockHighlighter-DYuOTwXS.js} +1 -1
- package/dist/web/assets/{FilePreview-BbEcYewq.js → FilePreview-CWOBOnzz.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-Cpqkv5Ml.js → MarkdownRenderer-YiYvkN2w.js} +3 -3
- package/dist/web/assets/{SettingsModal-D6NZP8vM.js → SettingsModal-BT-oFKGN.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-cT1qKR6s.js → TaskSwitcher-D5Gd6FN9.js} +1 -1
- package/dist/web/assets/{TerminalPanel-0MehdzKr.js → TerminalPanel-C1hLHq_K.js} +1 -1
- package/dist/web/assets/{index-BYd4kNGp.js → index-DuYx6fkN.js} +4 -4
- package/dist/web/assets/{session-events-BH7O5JJl.js → session-events-K_9Lexp8.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-09k2b1tw.js +0 -10
- package/dist/chunk-1amhvwmj.js +0 -22
- package/dist/chunk-1c9rkm57.js +0 -1
- package/dist/chunk-25abj6rx.js +0 -1
- package/dist/chunk-2cqsqrxx.js +0 -4
- package/dist/chunk-3m8pschr.js +0 -1
- package/dist/chunk-5psydp1v.js +0 -1
- package/dist/chunk-5tpjb8yn.js +0 -1
- package/dist/chunk-67vf8r5v.js +0 -6
- package/dist/chunk-6y9w5296.js +0 -1
- package/dist/chunk-csn0epd2.js +0 -100
- package/dist/chunk-d7976m5f.js +0 -5
- package/dist/chunk-f4z3gkbs.js +0 -2
- package/dist/chunk-fvrmjhz5.js +0 -1
- package/dist/chunk-h6w3ggx9.js +0 -1
- package/dist/chunk-hxp5qs1x.js +0 -1
- package/dist/chunk-mc29y7tj.js +0 -200
- package/dist/chunk-qpd1jmm4.js +0 -1
- package/dist/chunk-t6cmqsdj.js +0 -1
- package/dist/chunk-wz3z8908.js +0 -1
- package/dist/chunk-z5zcwwfm.js +0 -1
- package/dist/chunk-zn2cec1d.js +0 -1
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import{r as E}from"./chunk-3d4cgnpw.js";import{s as YJ}from"./chunk-wzvy13p2.js";import{$ as o,F as m,I as d,J as l,L as i,Z as r,_ as a,aa as n,v as A}from"./chunk-nqj9c68w.js";import{ka as WJ}from"./chunk-gjw014rv.js";import"./chunk-qt114yth.js";import{Va as c,Ya as p,hb as v}from"./chunk-6yjn2wj7.js";import{sb as T}from"./chunk-095x2ykj.js";import{Hb as f,Qb as M,Rb as u,Tb as R,Wb as g,_b as N,bc as D}from"./chunk-69ma931b.js";import"./chunk-8rzwyknk.js";import"./chunk-k3nkcaap.js";import"./chunk-bqgd4db7.js";import"./chunk-6pa6c2n0.js";import{hd as ZJ}from"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import{sd as $J}from"./chunk-5chec8rs.js";import"./chunk-c18qckn4.js";import"./chunk-8vd6q2wt.js";import"./chunk-r1jxbx1h.js";import{Xd as zJ}from"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wvh6entt.js";import"./chunk-q3c07kb4.js";import{ie as b}from"./chunk-6207mbmr.js";import"./chunk-rgy886ad.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import{gf as I,hf as S,if as y}from"./chunk-3qhqbj09.js";import{mf as e}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import{sf as JJ,vf as QJ}from"./chunk-yqfqj7mh.js";import"./chunk-677ywzhs.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import{Readable as VJ,Writable as wJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as BJ}from"@agentclientprotocol/sdk";import s from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var j=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function XJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function jJ(J){let Z={};for(let Q of J){let Y=XJ(Q);if(Y)Z[Q.name]=Y}return Z}function t(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function DJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:M(Z)}]:t(J.content)}function LJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return i.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?jJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await m.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.error==="Command timed out",aborted:F.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await a(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=p.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of DJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,L=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},B=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)L(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)L(X);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),X=await G.completion,L=(await E.list(this.cwd,this.id)).find((B)=>B.start.reviewId===G.reviewId);if(!L)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:L})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await o(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=g(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),r(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},X=await c(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,_=w.function.name;if(_===R)break;let q=this.mapToolKind(W.toolKind),V=`Executing ${_}`;if(_==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:q});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let _=W.result,q=[],V=_.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;q.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))q.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,HJ=l(d(K,_));q.push({type:"content",content:{type:"text",text:HJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=_.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:q});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of W.messages){if(!w.recovered||w.persisted)continue;for(let _ of t(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:_})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...G.messages];let L=await D.loadSession(this.id,this.cwd);if(this.messages=L.length>0?L:[...G.messages],!X.success){let W=X.error?.type??"unknown";throw GJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let B={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(B).length>0?{_meta:B}:{}}}catch(G){if(F.signal.aborted||G instanceof Error&&G.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,G),G}finally{if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let G=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?LJ(F.record):G}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){j.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)j.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,j.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(j.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof N)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(G)=>{if(Q.length>0)Q.push({type:"text",text:`
|
|
13
|
+
`}),z+=1;if(Q.push(G),G.type==="text")z+=G.text.length};for(let G of J)if(G.type==="text")Z.push(G.text),$({type:"text",text:G.text});else if(G.type==="image"){let X=`data:${G.mimeType};base64,${G.data}`;Y+=1,H+=X.length,Z.push(`[Image: ${G.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(G.type==="resource"){let X=G.resource;if("text"in X){let L=`<file path="${X.uri}">
|
|
14
|
+
${X.text}
|
|
15
|
+
</file>`;Z.push(L),$({type:"text",text:L})}}else if(G.type==="resource_link"){let X=`[Resource: ${G.uri}]`;Z.push(X),$({type:"text",text:X})}if(Y>I)throw Error(`ACP prompt contains more than ${I} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>y)throw Error(`ACP prompt text exceeds ${y} characters`);let F=Z.join(`
|
|
16
|
+
`);return{content:Y>0?Q:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));j.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
|
|
17
|
+
- ${J.risks.join(`
|
|
18
|
+
- `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let G=F.outcome;if(G.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=G.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(Y){return j.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((L,B)=>`answer:${H}:${B}`),F=`answer:${H}:cancel`,G=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,B)=>({optionId:$[B],name:L.label,kind:"allow_once"})),{optionId:F,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
|
|
19
|
+
`)}}]}}),Z);if(!G)return{approved:!1,reason:T};if(G.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(G.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[X].label}return{approved:!0,answers:Y}}catch(H){return j.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
20
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return j.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
|
|
21
|
+
`),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
|
|
22
|
+
`),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:BJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=ZJ("acp"),Q=J.cwd||e(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await YJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let G=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await G.initialize(),this.assertNotDestroyed()}catch(X){throw await G.destroy().catch(()=>{return}),X}return this.sessions.set(Z,G),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),G.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,G.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!s.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!s.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&QJ(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&JJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&zJ(J.value))U.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await WJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function eJ(){let J=wJ.toWeb(process.stdout),Z=VJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{eJ as runAcpIntegration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-d9k98jy2.js";import"./chunk-6g5k5de1.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{od as a}from"./chunk-xet98pc1.js";import"./chunk-6207mbmr.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as createChatServiceAsync};
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ie as n}from"./chunk-6207mbmr.js";import{Gf as l,If as C,Kf as N,Of as L,Pf as o}from"./chunk-yvf4nmds.js";import{Qf as f}from"./chunk-6g5k5de1.js";import{stat as i}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var a=50,s=100,t=/^[A-Za-z0-9_-]+$/,e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function __(_){return typeof _==="string"&&e.test(_)&&Number.isFinite(Date.parse(_))}function p(_){return typeof _==="string"&&U.isAbsolute(_)}function E_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function R_(_){try{if(!t.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||p(R.cwd))||!__(R.lastMessageTime)||!p(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function q(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function W_(_){if(!_.cursor)return;let E=R_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function w_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?a:W;if(!Number.isInteger(k)||k<1||k>s)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function $_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function x_(_,E){let R=[..._],W=W_(E);if(W)R=R.filter((k)=>$_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:E_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function k_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:P(_,E),createdAt:R.data.createdAt}}function P(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function c(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!k_(k)})}function z(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=c(E,R.data.targetMessageId)}return E}function I_(_){let E=z(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:P(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function q_(_,E){let R=z(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:c(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as x from"node:fs";import{createReadStream as H_}from"node:fs";import*as X from"node:fs/promises";import*as y from"node:path";import{createInterface as M_}from"node:readline";var S=65536;function Q_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function w(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
|
-
`),$=[];for(let[H,k]of R.entries())try{let M=Q_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class
|
|
3
|
+
`),$=[];for(let[H,k]of R.entries())try{let M=Q_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map((k)=>JSON.stringify(k)).join(`
|
|
4
4
|
`)}
|
|
5
|
-
`;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await X.open(this.filePath,"wx",384);let W=`${
|
|
5
|
+
`;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await X.open(this.filePath,"wx",384);let W=`${Y.stampSeq(_,[]).map(($)=>JSON.stringify($)).join(`
|
|
6
6
|
`)}
|
|
7
7
|
`;await E.writeFile(W,"utf-8"),await E.sync()}catch(R){if(E)await E.close(),E=void 0,await X.unlink(this.filePath).catch(()=>{return});throw R}finally{await E?.close()}}async readAll(){if(!x.existsSync(this.filePath))return[];let _=await X.readFile(this.filePath,"utf-8");return w(_,this.filePath)}async readStream(_){return new Promise((E,R)=>{if(!x.existsSync(this.filePath)){E();return}let W=H_(this.filePath,"utf-8"),$=M_({input:W,crlfDelay:Number.POSITIVE_INFINITY}),H=0;$.on("line",async(k)=>{let M=k.trim();if(M.length===0)return;try{let V=JSON.parse(M);if(H+=1,typeof V.seq!=="number")V.seq=H;await _(V)}catch(V){console.warn(`[JSONLStore] 解析 JSON 行失败: ${M}`,V)}}),$.on("close",()=>E()),$.on("error",R),W.on("error",R)})}async filter(_){let E=[];return await this.readStream((R)=>{if(_(R))E.push(R)}),E}async readLast(_){return(await this.readAll()).slice(-_)}async readFromSeq(_){return(await this.readAll()).filter((R)=>(R.seq??0)>=_)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let _=await X.stat(this.filePath),R=(await X.readFile(this.filePath,"utf-8")).split(`
|
|
8
|
-
`).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await X.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await X.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await X.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=w(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await X.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
`).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await X.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await X.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await X.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=w(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await X.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedBatch(_){return this.appendValidatedBatchAsync(async(E)=>_(E))}async appendValidatedBatchAsync(_){return this.enqueue(async()=>{let E=await X.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R);if(H.length===0)return[];let k=Y.stampSeq(H,R),M=`${k.map((V)=>JSON.stringify(V)).join(`
|
|
9
|
+
`)}
|
|
10
|
+
`;return await E.write(W+M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}async appendValidatedAsync(_){return this.enqueue(async()=>{let E=await X.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R),[k]=Y.stampSeq([H],R),M=`${W}${JSON.stringify(k)}
|
|
11
|
+
`;return await E.write(M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(Y.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});Y.appendQueues.set(this.filePath,W);try{return await R}finally{if(Y.appendQueues.get(this.filePath)===W)Y.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=w(W,E),{size:H}=await _.stat();return{entries:$,separator:R,size:H}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-S),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
|
|
12
|
+
`);for(let k=$.length-1;k>=0;k--){let M=$[k].trim();if(!M)continue;if(k===0&&R>0)break;try{let V=JSON.parse(M).seq;if(typeof V==="number")return V}catch{}break}let H=await _.readFile("utf8");return Y.maxSeq(w(H,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
|
|
13
|
+
`}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-S),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let H=$.lastIndexOf(10);if(H>=0)return W+H+1;R=W}return 0}}function V_(){return typeof globalThis.Bun<"u"}function X_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function Y_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var G_=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
12
14
|
`);async function m(_){try{let E;if(V_()){let{Database:W}=await import("bun:sqlite");E=Y_(new W(_))}else{let $=(await import("better-sqlite3")).default;E=X_(new $(_))}return E.exec(G_),E}catch{return null}}function h(_){let E=Number(_.pragma("user_version")??0);if(E===3)return;if(E>0&&E!==3)_.exec(`
|
|
13
15
|
DROP TABLE IF EXISTS parts_fts;
|
|
14
16
|
DROP TABLE IF EXISTS parts;
|
|
@@ -81,10 +83,10 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
81
83
|
seq UNINDEXED,
|
|
82
84
|
tokenize = 'unicode61'
|
|
83
85
|
);
|
|
84
|
-
`),_.exec("PRAGMA user_version=3;")}var
|
|
86
|
+
`),_.exec("PRAGMA user_version=3;")}var T_=n("Service"),D;function d(){return B.join(L(),"index.db")}async function Z_(){let _=d();if(D&&D.path===_)return D.db;let E=(async()=>{let R=await m(_);if(!R)return null;try{return h(R),R}catch{return null}})();return D={path:_,db:E},E}function K_(){D=void 0}function U_(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function g_(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let M of W)if(M.type==="message_created")$.set(M.data.messageId,M.data.role);let H=_.prepare(`INSERT OR REPLACE INTO parts
|
|
85
87
|
(project_path, session_id, part_id, message_id, part_type, role, seq, timestamp, text)
|
|
86
88
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),k=_.prepare(`INSERT INTO parts_fts (text, project_path, session_id, part_id, role, timestamp, seq)
|
|
87
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let V=
|
|
89
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let V=U_(M.data.payload);if(V===null)continue;let G=$.get(M.data.messageId)??"assistant",g=M.seq??0;if(H.run(E,R,M.data.partId,M.data.messageId,M.data.partType,G,g,M.timestamp,V),G==="user"||G==="assistant")k.run(V,E,R,M.data.partId,G,M.timestamp,g)}}function F_(_,E){_.prepare(`INSERT INTO sessions
|
|
88
90
|
(project_path, session_id, root_id, parent_id, relation_type, title,
|
|
89
91
|
agent_type, model, task_status, archived_at, last_message_time, project_sort_key,
|
|
90
92
|
session_sort_key, first_message_time, message_count, has_errors,
|
|
@@ -100,15 +102,15 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
100
102
|
session_sort_key=excluded.session_sort_key,
|
|
101
103
|
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
102
104
|
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
103
|
-
metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,
|
|
105
|
+
metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,q(E.projectPath),q(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function r(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function j(_,E,R){r(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function O(_,E,R,W,$,H){_.prepare(`INSERT INTO projection_state
|
|
104
106
|
(project_path, session_id, last_seq, file_size, mtime_ms)
|
|
105
107
|
VALUES (?, ?, ?, ?, ?)
|
|
106
108
|
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
107
109
|
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
108
|
-
mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function D_(_,E,R,W,$=N(R,E)){let H;try{let Q=await i($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>j(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let V=await new
|
|
109
|
-
FROM projection_state`).all(),V=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),
|
|
110
|
+
mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function D_(_,E,R,W,$=N(R,E)){let H;try{let Q=await i($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>j(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let V=await new Y($).readAll(),G=V.reduce((Q,Z)=>typeof Z.seq==="number"&&Z.seq>Q?Z.seq:Q,0),g=z(V),T=W(V,E,R);if(V.length===0||!T)return _.transaction(()=>{r(_,R,E),O(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0;let F=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(T.projectPath,T.sessionId),A=B.resolve($)===B.resolve(N(T.projectPath,T.sessionId));if(F&&!A&&typeof F.last_message_time==="string"&&F.last_message_time>T.lastMessageTime)return O(_,R,E,G,H.size,Math.floor(H.mtimeMs)),!0;return _.transaction(()=>{F_(_,T),g_(_,T.projectPath,T.sessionId,g),O(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0}var b=new WeakMap;async function B_(_,E,R=0){let W=b.get(_)??{};if(b.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=A_(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function A_(_,E){let{readdir:R}=await import("node:fs/promises"),W=await o(),$=new Set,k=(await Promise.all(W.map(async(Q)=>{let Z=l(Q),K=B.join(L(),"projects",Q);try{return(await R(K)).flatMap((I)=>{if(!I.endsWith(".jsonl"))return[];let v=I.slice(0,-6);if(!C(v))return[];return[{filePath:B.join(K,I),projectPath:Z,sessionId:v}]})}catch{return[]}}))).flat();for(let Q of k)$.add(`${Q.projectPath}\x00${Q.sessionId}`);let M=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
|
|
111
|
+
FROM projection_state`).all(),V=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),G=[],g=Math.min(128,k.length),T=0;await Promise.all(Array.from({length:g},async()=>{while(T<k.length){let Q=k[T++];if(!Q)continue;try{let Z=await i(Q.filePath),K=V.get(`${Q.projectPath}\x00${Q.sessionId}`);if(K&&K.file_size===Z.size&&K.mtime_ms===Math.floor(Z.mtimeMs))continue}catch{}G.push(Q)}}));let F=Math.min(32,G.length),A=0;await Promise.all(Array.from({length:F},async()=>{while(A<G.length){let Q=G[A++];if(!Q)continue;try{await D_(_,Q.sessionId,Q.projectPath,E,Q.filePath)}catch(Z){if(Z.code!=="ENOENT")T_.warn(`[SessionService] Skipping invalid session transcript: ${Q.sessionId}`)}}}));for(let Q of M)if(!$.has(`${Q.project_path}\x00${Q.session_id}`))_.transaction(()=>j(_,Q.project_path,Q.session_id))}function o_(_,E,R){_.transaction(()=>j(_,R,E))}async function n_(_){let{rm:E}=await import("node:fs/promises");K_();let R=d();for(let H of["","-wal","-shm"])await E(`${R}${H}`,{force:!0}).catch(()=>{return});let W=await Z_();if(!W)return null;return await B_(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function i_(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let H=`"${$}"*`,k=R?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
110
112
|
WHERE parts_fts MATCH ? AND project_path = ?
|
|
111
113
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
112
114
|
WHERE parts_fts MATCH ?
|
|
113
115
|
ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
|
|
114
|
-
export{z as
|
|
116
|
+
export{z as cc,I_ as dc,q_ as ec,w as fc,Y as gc,q as hc,W_ as ic,w_ as jc,$_ as kc,x_ as lc,d as mc,Z_ as nc,K_ as oc,D_ as pc,B_ as qc,o_ as rc,n_ as sc,i_ as tc};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Sd as L1,Td as Z0,Ud as G1}from"./chunk-r1jxbx1h.js";import{Yd as $O,Zd as HO}from"./chunk-6sb7cg95.js";import{ae as Y1}from"./chunk-2c3zavy2.js";import{be as B0,de as M0}from"./chunk-wvh6entt.js";import{ie as h,je as z}from"./chunk-6207mbmr.js";import{Me as V0,Ne as o1,We as j0}from"./chunk-rgy886ad.js";import{af as u,cf as W,ff as R1}from"./chunk-96h588rd.js";import{mf as b}from"./chunk-prgh321y.js";import{zf as d0}from"./chunk-677ywzhs.js";import{Ef as T}from"./chunk-1n60pgsq.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
|
|
2
2
|
|
|
3
3
|
You are a fresh, independent, adversarial verifier. The parent Agent has claimed
|
|
4
4
|
that a persisted goal is complete. Your job is to refute that claim unless the
|
|
@@ -722,4 +722,4 @@ ${q.join(`
|
|
|
722
722
|
</${Q}>`:"";return{content:J,files:[...O],references:O.map(h$),triggerPaths:[...$],contentBytes:Buffer.byteLength(J,"utf8"),provenanceSha256:_0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
|
|
723
723
|
`))}}function WO(O,$){let Q=$,q=[];for(let Z=O.length-1;Z>=0;Z-=1){let J=O[Z];if(!J)continue;let K=Buffer.byteLength(J.content,"utf8");if(K>Q)continue;q.push(J),Q-=K}return q.reverse()}class p{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=O1(O),this.definitions=Object.freeze([...$].sort(Q1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=_0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
|
|
724
724
|
`))}static empty(O){return new p(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new p(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=T$){if(this.definitions.length===0)return $0([],[],"project-instructions");let Q=this.relativeSourcePath(O),q=this.definitions.filter((Z)=>!Z.conditional&&$1(Z.scopeDirectory,Q));return $0(WO(q,$),[],"project-instructions")}contextualRules(O,$,Q,q=w$){if(this.definitions.length===0)return $0([],[],"contextual-project-instructions");let Z=this.relativeSourcePath(O),J=[...new Set($.map((G)=>q1(B.relative(this.projectRoot,O1(G)))).filter(Z1))].sort(),K=new Map;for(let G of J)for(let L of this.definitions){if(Q.has(L.id))continue;if(!$1(L.scopeDirectory,G))continue;if(L.conditional){let Y=B.posix.relative(L.scopeDirectory||".",G);if(!L.patterns?.some((V)=>XO(V,{dot:!0})(Y)))continue}else if($1(L.scopeDirectory,Z))continue;K.set(L.id,L)}let X=WO([...K.values()].sort(Q1),q);return $0(X,J,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let q=this.byId.get(Q.id);if(!q||q.contentSha256!==Q.contentSha256||q.relativePath!==Q.relativePath||q.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return q});return $0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(Q1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=q1(B.relative(this.projectRoot,O1(O)));if($&&!Z1($))throw Error("Project instruction source is outside the catalog root");return $}}async function k$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>ZO)throw Error(`Project rule exceeds ${ZO} bytes`);let q=await m.realpath($),Z=q1(B.relative(O,q));if(!Z1(Z))throw Error("Project rule escapes its repository root");let J=await m.readFile(q,"utf8");if(LO(J))throw Error("Project rule contains hidden control characters");let K=_$(J),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=E$(K.data.paths),L=f$(Z),Y=_0(JSON.stringify({relativePath:Z,patterns:G??[],content:X}));return{id:`${L.source}:${_0(Z).slice(0,20)}`,relativePath:Z,source:L.source,kind:L.kind,scopeDirectory:L.scopeDirectory,priority:L.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function YO(O,$){let Q=y$(O);if(!$.projectTrusted)return p.empty(Q);let q=await m.realpath(Q),Z=A$.stream([...R$],{cwd:q,absolute:!0,dot:!0,deep:C$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...v$]}),J=[];for await(let L of Z)if(J.push(L.toString()),J.length>qO)throw Error(`Project rule catalog exceeds ${qO} files`);J.sort();let K=new Set(J.filter((L)=>B.basename(L)==="AGENTS.override.md").map((L)=>B.dirname(L))),X=[],G=0;for(let L of J){if(B.basename(L)==="AGENTS.md"&&K.has(B.dirname(L)))continue;try{let Y=await k$(q,L);if(G+=Buffer.byteLength(Y.content,"utf8"),G>JO)throw Error(`Project rule catalog exceeds ${JO} bytes`);X.push(Y)}catch(Y){N$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new p(q,X)}var Q0=new Map,FO=[];async function P$(O){let $=await T.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await e0(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function d$(O){let $={...O};for(let Q of Object.values(B0))$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}function v2(O){FO=[...new Set(O.map(($)=>J1.resolve($)))]}async function y2(O,$={}){let Q=J1.resolve(O),q=Q0.get(Q);if(!q)q=(async()=>{let J=await T.getInstance().getStatus(Q),K=i(Q),X=P({cwd:Q}),G=w.getInstance(Q),L=z0(Q);if(K.getAllNames().length===0)K.loadFromStandardLocations(J.state==="trusted");await Promise.all([X.initialize(),G.isInitialized()?void 0:G.initialize(Q),L.isInitialized()?void 0:L.initialize(Q,[...$.cliPluginDirs??FO])]),x0(Q),await a0(Q);let Y=await e0(Q,{projectTrusted:J.state==="trusted",plugins:L.getActive()}),V=await YO(Q,{projectTrusted:J.state==="trusted"});return{workspaceRoot:Q,subagents:K,skills:X,commands:G,plugins:L,communicationStyles:Y,projectRules:V}})().catch((J)=>{throw Q0.delete(Q),J}),Q0.set(Q,q);let Z=await q;if($.reconcilePlugins)x0(Q),await a0(Q),await P$(Z);return Z}function E2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:J1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??HO.snapshot(),projectRules:O.projectRules?.snapshot()??p.empty($),hooks:d$("hooks"in O&&O.hooks?O.hooks:M0.getInstance().getConfig($))}}function f2(){for(let O of Q0.keys())x0(O);Q0.clear(),y.resetInstances(),k.resetInstance(),w.resetInstance(),f.resetInstance()}
|
|
725
|
-
export{g$ as
|
|
725
|
+
export{g$ as xd,u$ as yd,W1 as zd,i as Ad,X4 as Bd,U1 as Cd,P as Dd,CO as Ed,w as Fd,o0 as Gd,S0 as Hd,f as Id,z0 as Jd,a0 as Kd,x0 as Ld,p as Md,P$ as Nd,v2 as Od,y2 as Pd,E2 as Qd,f2 as Rd};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
|
|
2
|
-
export{a as
|
|
2
|
+
export{a as af,f as bf,l as cf,x as df,b as ef,V as ff};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{f as Q,g as R,h as T,i as W}from"./chunk-2675vkx5.js";import"./chunk-zdkc4kj1.js";import"./chunk-fa6313dv.js";import"./chunk-3d4cgnpw.js";import"./chunk-wzvy13p2.js";import"./chunk-nqj9c68w.js";import"./chunk-gjw014rv.js";import"./chunk-qt114yth.js";import"./chunk-6yjn2wj7.js";import"./chunk-095x2ykj.js";import"./chunk-69ma931b.js";import"./chunk-8rzwyknk.js";import"./chunk-k3nkcaap.js";import{Xc as M}from"./chunk-bqgd4db7.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-c18qckn4.js";import"./chunk-8vd6q2wt.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wvh6entt.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-rgy886ad.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import{zf as J}from"./chunk-677ywzhs.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import b from"chalk";import H from"open";var $=`
|
|
2
|
+
____ _ _
|
|
3
|
+
| __ )| | __ _ __| | ___
|
|
4
|
+
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
+
| |_) | | (_| | (_| | __/
|
|
6
|
+
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
+
`,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await M(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
+
`));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${J()}
|
|
9
|
+
`)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
|
|
10
|
+
`)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$c as k,Rc as a,Sc as b,Tc as c,Uc as d,Vc as e,Wc as f,Xc as g,Yc as h,Zc as i,_c as j,ad as l,bd as m,cd as n,dd as o,ed as p,fd as q}from"./chunk-bqgd4db7.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-6207mbmr.js";import"./chunk-rgy886ad.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-677ywzhs.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{wc as a,xc as b,yc as c}from"./chunk-w9zgpqjd.js";import"./chunk-wt7gy9bm.js";import"./chunk-bqgd4db7.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-2c3zavy2.js";import"./chunk-6207mbmr.js";import"./chunk-rgy886ad.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-677ywzhs.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pd as a,qd as b,rd as c}from"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-
|
|
2
|
-
`);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.
|
|
1
|
+
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-fneamw65.js";import{F as y,L as w}from"./chunk-nqj9c68w.js";import"./chunk-gjw014rv.js";import"./chunk-qt114yth.js";import{Va as x,hb as U}from"./chunk-6yjn2wj7.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-69ma931b.js";import"./chunk-8rzwyknk.js";import{uc as P}from"./chunk-bpnyda6p.js";import{wc as h,xc as O,yc as M}from"./chunk-w9zgpqjd.js";import{zc as z}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Wc as N}from"./chunk-bqgd4db7.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-c18qckn4.js";import"./chunk-8vd6q2wt.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wvh6entt.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-rgy886ad.js";import{Ye as D}from"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as E}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-677ywzhs.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
|
|
2
|
+
`);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSessionModelContext(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
|
|
3
3
|
`);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
|
|
4
4
|
`);else q.stdout.write(`${k(H.record)}
|
|
5
5
|
`);return H.record.status==="completed"?0:H.record.status==="aborted"?130:H.record.exitCode??1}let f=await w.createWithRuntime(B,{sessionId:G,systemPrompt:j.systemPrompt,appendSystemPrompt:j.appendSystemPrompt,maxTurns:j.maxTurns,modelId:j.model,permissionMode:Z,toolWhitelist:j.allowedTools,toolBlacklist:j.disallowedTools,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig}),A={messages:[..._],userId:"cli-user",sessionId:G,workspaceRoot:W,permissionMode:Z},Q=await x(X?f.chatStream(K,A,{outputSchema:X}):f.chatStream(K,A));if(!Q.success)throw Error(Q.error?.message??"Agent execution failed");let L=Q.finalMessage||"",$=Q.metadata?.structuredOutput;if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify({response:L,...$?{structured_output:$,output_schema_digest:Q.metadata?.structuredOutputSchemaDigest}:{},input:K,model:j.model,timestamp:new Date().toISOString()},null,2)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{q as
|
|
1
|
+
import{Bf as h,zf as d}from"./chunk-677ywzhs.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
|
+
export{q as uc,w as vc};
|