blade-code 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-jakzknh3.js → chunk-04920kz2.js} +268 -268
- package/dist/chunk-42ch5zg4.js +1 -0
- package/dist/{chunk-ydb9myhe.js → chunk-61952mn3.js} +1 -1
- package/dist/{chunk-nned222j.js → chunk-6yqzfz8t.js} +1 -1
- package/dist/chunk-7j6rxyt8.js +9 -0
- package/dist/{chunk-d08wbxjr.js → chunk-cnftrx3g.js} +1 -1
- package/dist/{chunk-gytwh5y1.js → chunk-epp5jx5f.js} +1 -1
- package/dist/{chunk-hrnd3wjg.js → chunk-j6hpzkpq.js} +1 -1
- package/dist/{chunk-e4a240t7.js → chunk-k47ssv3b.js} +1 -1
- package/dist/chunk-n4f8tseg.js +2 -0
- package/dist/{chunk-bggvft3z.js → chunk-nc4kfwef.js} +1 -1
- package/dist/{chunk-ychj0e5q.js → chunk-neenhtxw.js} +1 -1
- package/dist/{chunk-6es6av6j.js → chunk-pdydx73a.js} +1 -1
- package/dist/{chunk-yqxw7zz4.js → chunk-sr3bzb95.js} +1 -1
- package/dist/{chunk-jqr2pknb.js → chunk-x6gt63vz.js} +15 -15
- package/dist/web/assets/{CodeBlockHighlighter-C1cp8dDv.js → CodeBlockHighlighter-D8_cOYpG.js} +1 -1
- package/dist/web/assets/{FilePreview-DvgnEspB.js → FilePreview-Chqi7chf.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-e1ZUy6jV.js → MarkdownRenderer-JJScfgAO.js} +1 -1
- package/dist/web/assets/{McpModal-Raois2g1.js → McpModal-CiCuIUxC.js} +2 -2
- package/dist/web/assets/{SettingsModal-Dzuatoea.js → SettingsModal-Bew818xl.js} +1 -1
- package/dist/web/assets/{SettingsStore-BxDA0Usw.js → SettingsStore-B_4zN-c-.js} +1 -1
- package/dist/web/assets/{SkillsModal-Cg2-befH.js → SkillsModal-Cot4Rb89.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CEoQI9Lu.js → TerminalPanel-DxB67ObY.js} +1 -1
- package/dist/web/assets/index-B-b3Yc5H.css +1 -0
- package/dist/web/assets/index-B3dW1Scg.js +16 -0
- package/dist/web/assets/{useRequest-DITGl55G.js → useRequest-B4kP-cmG.js} +1 -1
- package/dist/web/assets/{vendor-icons-BuFpOlRn.js → vendor-icons-DqO8ishN.js} +2 -2
- package/dist/web/assets/{vendor-markdown-Bo4W9Tae.js → vendor-markdown-b9iCqZWK.js} +1 -1
- package/dist/web/assets/vendor-radix-DyP_DOwV.js +45 -0
- package/dist/web/assets/{vendor-react-BalntB5F.js → vendor-react-FPIC4Czm.js} +2 -2
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-3gw66r7a.js +0 -2
- package/dist/chunk-bxbagv76.js +0 -9
- package/dist/chunk-n8ymp6nd.js +0 -1
- package/dist/web/assets/index-BvGeIa_-.js +0 -16
- package/dist/web/assets/index-DDJnZJcp.css +0 -1
- package/dist/web/assets/vendor-radix-CESj0OOY.js +0 -45
package/dist/web/index.html
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>BladeCode</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-B3dW1Scg.js"></script>
|
|
9
|
+
<link rel="stylesheet" crossorigin href="/assets/index-B-b3Yc5H.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
|
12
12
|
<div id="root"></div>
|
package/package.json
CHANGED
package/dist/chunk-3gw66r7a.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{e as Ax,f as Wx}from"./chunk-xhnyy54e.js";import{$ as zx,A as Dx,C as Yx,D as HO,E as kO,G as _O,H as Jx,I as p,K as Nx,L as ZO,M as C,N as y,P as yO,Q as mO,S as Qx}from"./chunk-jakzknh3.js";import{ca as n}from"./chunk-e4a240t7.js";import{Ca as o,va as $O,xa as lO,ya as cO,za as dO}from"./chunk-tv4r86ez.js";import{Ka as VO}from"./chunk-6es6av6j.js";import{Qa as Hx,Sa as AO,ab as FO}from"./chunk-1pt090dg.js";import{sb as Gx}from"./chunk-9xkjb87h.js";import{Ab as oO,Bb as E,wb as g,yb as S,zb as q}from"./chunk-ctqf59q1.js";import{Cb as Vx}from"./chunk-jt62ctz7.js";import{Ib as h}from"./chunk-gsfkrr25.js";import{Tb as L}from"./chunk-34pdtz4q.js";import{Yb as $x,dc as r}from"./chunk-hjx5n3dw.js";import{ec as PO}from"./chunk-dr06x0cw.js";var v0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function u0(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{Hono as C0}from"hono";import{cors as E0}from"hono/cors";import{existsSync as hx,readFileSync as wO}from"node:fs";import{createServer as y0}from"node:http";import{networkInterfaces as m0}from"node:os";import{dirname as h0,extname as f0,join as xO}from"node:path";import{fileURLToPath as k0}from"node:url";import{WebSocketServer as P0}from"ws";class I extends Error{code;statusCode;constructor(O,$,x=500){super($);this.code=O;this.statusCode=x;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class m extends I{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class b extends I{constructor(O){super("BAD_REQUEST",O,400)}}class i extends I{constructor(O){super("CONFLICT",O,409)}}class l extends I{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends I{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var d0=S.Object({error:S.Object({code:S.String(),message:S.String()})});import{Hono as Px}from"hono";var zO=L("Service"),px=S.Object({updates:S.Record(S.String(),S.Any()),options:S.Optional(S.Object({scope:S.Optional(E(["local","project","global"])),immediate:S.Optional(S.Boolean())}))});function Rx(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,theme:O.theme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash}}var gO=()=>{let O=new Px;return O.get("/",async($)=>{try{let x=$O();return $.json(x?Rx(x):{})}catch(x){return zO.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),V=g(px,x);if(!V.success)throw new b("Invalid config update format");let{updates:Y,options:j}=V.data;return await o().updateConfig(Y,j),$.json({success:!0,updates:Y})}catch(x){throw zO.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=$O();return $.json(x?.permissions||{})}catch(x){return zO.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as Ix}from"hono";var vO=()=>{let O=new Ix;return O.get("/health",($)=>{return $.json({healthy:!0,version:VO()})}),O.get("/info",($)=>{return $.json({version:VO(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:h()})}),O};import{Hono as gx}from"hono";var QO=L("Service"),uO=()=>{let O=new gx;return O.get("/",async($)=>{try{let V=n.getInstance().getAllServers(),Y=Array.from(V.entries()).map(([j,N])=>({id:j,name:j,status:N.status==="connected"?"connected":N.status==="connecting"?"connecting":N.lastError?"error":"offline",endpoint:N.config.command?`${N.config.command} ${(N.config.args||[]).join(" ")}`.trim():N.config.url||"Unknown",description:`MCP server: ${j}`,tools:N.tools.map((X)=>X.name),connectedAt:N.connectedAt?.toISOString(),error:N.lastError?.message}));return $.json(Y)}catch(x){return QO.error("[McpRoutes] Failed to get MCP servers:",x),$.json([])}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name");return await n.getInstance().connectServer(x),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name");return await n.getInstance().disconnectServer(x),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await n.getInstance().unregisterServer(x);let Y=$O();if(Y?.mcpServers){let{[x]:j,...N}=Y.mcpServers;await o().updateConfig({mcpServers:N})}return $.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:V,config:Y}=x;if(!V||!Y)return $.json({success:!1,error:"Missing name or config"},400);await n.getInstance().registerServer(V,Y);let N=$O();return await o().updateConfig({mcpServers:{...N?.mcpServers,[V]:Y}}),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{Hono as vx}from"hono";var XO=L("Service");function ux(O,$){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,input:$.input}}function lx(O){let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}var tO=()=>{let O=new vx;return O.get("/",async($)=>{try{let x=lO(),V=cO(),Y=r(),j=(N)=>ux(N,Y.resolveConfig(N));return $.json({configured:x.map(j),current:V?j(V):null})}catch(x){return XO.error("[ModelsRoutes] Failed to get models:",x),$.json({configured:[],current:null})}}),O.post("/",async($)=>{try{let x=await $.req.json(),{provider:V,displayName:Y,model:j,overrides:N,apiKey:X}=x;if(!V||!j)throw new b("provider and model are required");if(r().getModel(V,j),X?.trim())await r().setApiKey(V,X.trim());let W=await o().addModel({provider:V,displayName:Y||void 0,model:j,overrides:N||void 0});return $.json({success:!0,model:W})}catch(x){throw XO.error("[ModelsRoutes] Failed to add model:",x),x}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),V=await $.req.json(),{displayName:Y,overrides:j,model:N}=V,X=dO(x);if(!X)throw new b("model config not found");if(N)r().getModel(X.provider,N);return await o().updateModel(x,lx({displayName:Y,overrides:j,model:N})),$.json({success:!0})}catch(x){throw XO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await o().removeModel(x),$.json({success:!0})}catch(x){throw XO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as j0}from"hono";import Sx from"node:path";import{Mutex as nx}from"async-mutex";import{Hono as rx}from"hono";import{streamSSE as sx}from"hono/streaming";import{LRUCache as ex}from"lru-cache";import{nanoid as GO}from"nanoid";var iO=q(E(["default","autoEdit","yolo","plan"]));var TO=q(E(["user","assistant","system","tool"])),cx=q(S.Union([S.Object({type:S.Literal("text"),text:S.String()}),S.Object({type:S.Literal("image_url"),image_url:S.Object({url:S.String()})})])),nO=S.Union([S.String(),S.Array(cx)]),BS=q(S.Object({id:S.String(),role:TO,content:nO,timestamp:S.Number(),metadata:S.Optional(S.Record(S.String(),S.Unknown())),thinkingContent:S.Optional(S.String()),tool_call_id:S.Optional(S.String()),name:S.Optional(S.String()),tool_calls:S.Optional(S.Unknown())})),dx=q(S.Object({sessionId:S.String(),projectPath:S.String(),title:S.Optional(S.String()),gitBranch:S.Optional(S.String()),rootId:S.String(),parentId:S.Optional(S.String()),relationType:S.Optional(E(["subagent","fork"])),resumedFrom:S.Optional(S.String()),rootAgentId:S.Optional(S.String()),resumeDepth:S.Optional(S.Integer({minimum:0})),messageCount:S.Number(),firstMessageTime:S.String(),lastMessageTime:S.String(),hasErrors:S.Boolean()})),HS=q(S.Object({version:S.Literal(1),sessionId:S.String(),goalId:S.String(),objective:S.String(),status:E(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:S.Optional(S.Number()),tokensUsed:S.Number(),timeUsedSeconds:S.Number(),continuationCount:S.Number(),statusReason:S.Optional(S.String()),createdAt:S.String(),updatedAt:S.String()})),rO=q(S.Object({role:TO,content:nO,metadata:S.Optional(S.Unknown()),reasoningContent:S.Optional(S.String()),thinkingContent:S.Optional(S.String()),tool_call_id:S.Optional(S.String()),name:S.Optional(S.String()),tool_calls:S.Optional(S.Unknown())})),wS=q(S.Object({session:dx,messages:S.Array(rO)})),sO=q(E(["conversation","code","both"])),tx=q(S.Object({messageId:S.String(),preview:S.String(),createdAt:S.String(),fileCount:S.Integer({minimum:0})})),eO=q(S.Object({targetMessageId:S.String({minLength:1}),mode:oO(sO,"conversation")})),KS=q(S.Object({checkpoint:tx,mode:sO,removedTurns:S.Integer({minimum:1}),restoredFiles:S.Array(S.String()),messages:S.Array(rO)})),ax=E(["running","completed","failed","cancelled"]),aO=q(S.Object({id:S.String(),subagentType:S.String(),description:S.String(),status:ax,rootAgentId:S.String(),resumedFrom:S.Optional(S.String()),resumeDepth:S.Integer({minimum:0}),createdAt:S.Number(),lastActiveAt:S.Number(),completedAt:S.Optional(S.Number()),result:S.Optional(S.Object({success:S.Boolean(),message:S.String(),error:S.Optional(S.String()),verificationCommands:S.Optional(S.Array(S.String()))})),stats:S.Optional(S.Object({tokens:S.Optional(S.Number()),toolCalls:S.Optional(S.Number()),duration:S.Optional(S.Number())}))})),Ox=q(S.Object({prompt:S.String({minLength:1,maxLength:32000})})),DS=q(S.Object({source:aO,session:aO})),zS=q(S.Object({sessionId:S.String(),projectPath:S.String()})),TS=q(S.Object({type:S.String(),properties:S.Record(S.String(),S.Unknown())})),xx=q(S.Object({content:S.String(),projectPath:S.Optional(S.String()),permissionMode:S.Optional(iO),attachments:S.Optional(S.Array(S.Object({type:E(["file","image","url"]),path:S.Optional(S.String()),url:S.Optional(S.String()),content:S.Optional(S.String()),mimeType:S.Optional(S.String()),name:S.Optional(S.String())})))})),bS=q(S.Object({messageId:S.String(),role:TO,content:S.String(),timestamp:S.String()})),qS=q(S.Object({approved:S.Boolean(),remember:S.Optional(S.Boolean()),scope:S.Optional(E(["once","session","project"])),targetMode:S.Optional(iO),feedback:S.Optional(S.String()),answers:S.Optional(S.Record(S.String(),S.Union([S.String(),S.Array(S.String())])))})),FS=q(S.Object({id:S.String(),displayName:S.Optional(S.String()),provider:S.String(),model:S.String(),contextWindow:S.Optional(S.Number()),maxTokens:S.Optional(S.Number()),reasoning:S.Optional(S.Boolean()),input:S.Optional(S.Array(E(["text","image"]))),overrides:S.Optional(S.Object({baseUrl:S.Optional(S.String()),temperature:S.Optional(S.Number()),maxOutputTokens:S.Optional(S.Number()),timeout:S.Optional(S.Number())}))})),LS=q(E(["vs-dark","vs-light","hc-black"])),ox=q(E(["light","dark","system"])),ix=q(S.Object({language:S.String(),theme:S.String(),uiTheme:ox,autoSaveSessions:S.Boolean(),notifyBuild:S.Boolean(),notifyErrors:S.Boolean(),notifySounds:S.Boolean(),privacyTelemetry:S.Boolean(),privacyCrash:S.Boolean()})),CS=q(S.Partial(ix));var F=L("Service"),O0=S.Object({title:S.Optional(S.String()),projectPath:S.Optional(S.String())}),x0=xx,S0=S.Object({title:S.Optional(S.String()),projectPath:S.Optional(S.String())}),$0=S.Object({projectPath:S.String()}),V0=S.Object({objective:S.String({minLength:1}),tokenBudget:S.Optional(S.Integer({minimum:1})),permissionMode:S.Optional(E(["default","autoEdit","plan","yolo"]))}),G0=S.Union([S.Object({action:S.Literal("pause")}),S.Object({action:S.Literal("resume")}),S.Object({action:S.Literal("edit"),objective:S.String({minLength:1})})]),P=new Map,f=new ex({max:100,ttl:1800000,dispose:(O,$)=>{if(O.status==="running"||O.status==="waiting_permission")O.abortController.abort(),F.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}});function Y0(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function MO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;return O.pendingPermission=void 0,x?.resolve({approved:!1,reason:Gx}),O.abortController.abort($),O.status="cancelled",y.publish(Y0(O),"run.cancelled",{runId:O.id}),!0}function Zx(O,$=!1){let{permissionId:x,details:V}=O;if(V.type==="askUserQuestion"&&V.questions)return{type:"question.required",properties:{requestId:x,toolCallId:x,questions:V.questions,details:V,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:V.toolName,description:V.message,args:V.args,details:V,...$?{replayed:!0}:{}}}}function J0(){for(let O of f.values())MO(O,"route-reset");f.clear(),P.clear()}var jx=(O)=>{if(!O||typeof O!=="object")return O;let $={...O},x=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>x)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>x)delete $.newContent;return $};function N0(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)y.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),y.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)y.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:!x.result.error,summary:x.result.metadata?.summary,output:mO(yO(x.toolCall.function.name,x.result)),metadata:jx(x.result.metadata)});break;case"content_delta":y.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":y.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":y.publish(O,"subagent.stream.end",{subagentSessionId:$});break;default:break}}function LO(O,$="projectPath"){if(!Sx.isAbsolute(O))throw new b(`${$} must be absolute`);return Sx.resolve(O)}function CO(O){try{$x(O)}catch($){throw new b($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function v(O){return{sessionId:O.id,projectPath:O.projectPath}}function bO(O,$){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,messages:$}}function qO(O){return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function c(O,$){if(CO(O),$!==void 0){let V=ZO({sessionId:O,projectPath:LO($)});if(P.has(C(V)))return V;let Y=await p.findSessionMetadata(V.sessionId,V.projectPath);if(!Y)throw new m("Session",O);return ZO({sessionId:Y.sessionId,projectPath:Y.projectPath})}let x=new Map;for(let V of P.values()){if(V.id!==O)continue;let Y=v(V);x.set(C(Y),Y)}for(let V of await p.listSessions()){if(V.sessionId!==O)continue;let Y=ZO({sessionId:V.sessionId,projectPath:V.projectPath});x.set(C(Y),Y)}if(x.size===0)try{let V=await p.findSessionMetadata(O);if(!V)throw new m("Session",O);return ZO({sessionId:V.sessionId,projectPath:V.projectPath})}catch(V){if(V instanceof m)throw V;if(V instanceof Error&&V.message.startsWith("Ambiguous session ID:"))throw new l;throw V}if(x.size>1)throw new l;return x.values().next().value}function EO(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
2
|
-
`)}function Q0(O,$){let x=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(x.length===0)return O;let V=[];if(O.trim())V.push({type:"text",text:O});return V.push(...x),V}var Ux=()=>{J0();let O=new rx;O.onError((G,Z)=>{if(G instanceof I)return Z.json(G.toObject(),G.statusCode);return F.error("[SessionRoutes] Unhandled route error:",G),Z.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,V=new Map,Y=new Map,j=(G)=>{let Z=C(G),J=Y.get(Z);if(!J)J=new nx,Y.set(Z,J);return J},N=async(G)=>{let Z=C(v(G)),J=$.get(Z);if(J)return J;let Q=x.get(Z);if(!Q)Q=Nx.create({sessionId:G.id,workspaceRoot:G.projectPath}),x.set(Z,Q);try{let U=await Q;return $.set(Z,U),U}finally{if(x.get(Z)===Q)x.delete(Z)}},X=async(G)=>{let Z=C(G),J=P.get(Z);if(J)return J;let Q=V.get(Z);if(!Q)Q=(async()=>{let U=await p.findSessionMetadata(G.sessionId,G.projectPath);if(!U)throw new m("Session",G.sessionId);let M=bO(U,await p.loadSession(G.sessionId,G.projectPath));return P.set(Z,M),M})(),V.set(Z,Q);try{return await Q}finally{if(V.get(Z)===Q)V.delete(Z)}},W=async(G,Z)=>{return X(await c(G,Z))},A=(G,Z,J,Q={})=>{let U=GO(12),M={id:U,sessionId:G.id,projectPath:G.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return f.set(U,M),G.currentRunId=U,M.completion=Z0(M,G,Z,J,N,{pendingInputOnly:Q.pendingInputOnly,preparedInputTurn:Q.preparedInputTurn,goalContinuationOnly:Q.goalContinuationOnly}).catch((_)=>{F.error(`[SessionRoutes] Run ${U} failed:`,_)}),M},D=async(G)=>{let Z=G.currentRunId?f.get(G.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return;let J=await N(G),Q=G.currentRunId?f.get(G.currentRunId):void 0;if(Q&&(Q.status==="running"||Q.status==="waiting_permission"))return;let U=J.getPendingSteeringCount()>0,_=(U?null:await J.getGoal())?.status==="active";if(!U&&!_||J.hasTurnOwner())return;A(G,"","default",{pendingInputOnly:U,goalContinuationOnly:_})};return O.get("/",async(G)=>{try{let Z=await p.listSessions(),J=new Set(Z.filter((w)=>w.relationType==="subagent").map((w)=>C({sessionId:w.sessionId,projectPath:w.projectPath}))),Q=Array.from(P.values()).filter((w)=>!J.has(C(v(w)))&&w.relationType!=="subagent").map((w)=>qO(w)),U=new Set(Q.map((w)=>C({sessionId:w.sessionId,projectPath:w.projectPath}))),M=Z.filter((w)=>{if(w.relationType==="subagent")return!1;return!U.has(C({sessionId:w.sessionId,projectPath:w.projectPath}))}),_=new Set(U),K=M.filter((w)=>{let H=C({sessionId:w.sessionId,projectPath:w.projectPath});if(_.has(H))return!1;return _.add(H),!0}),z=[...Q,...K];return G.json(z)}catch(Z){throw F.error("[SessionRoutes] Failed to list sessions:",Z),new t("Failed to list sessions")}}),O.post("/",async(G)=>{try{let Z=await G.req.json(),J=g(O0,Z);if(!J.success)throw new b("Invalid request body");let{title:Q,projectPath:U}=J.data,M=Vx("web",12),_=LO(U||G.get("directory")||h(),U?"projectPath":"directory"),K=await p.createSessionMetadata(M,_,{title:Q}),z=bO(K,[]);return P.set(C(v(z)),z),G.json({...qO(z),status:void 0,agentType:void 0,model:void 0})}catch(Z){if(F.error("[SessionRoutes] Failed to create session:",Z),Z instanceof b)throw Z;throw new t("Failed to create session")}}),O.post("/:sessionId/fork",async(G)=>{let Z=G.req.param("sessionId");try{CO(Z);let J=await G.req.json(),Q=g($0,J);if(!Q.success)throw new b("Invalid request body");let U=LO(Q.data.projectPath),M=await p.findSessionMetadata(Z,U);if(!M)throw new m("Session",Z);let _=await p.forkSession(Z,{sourceProjectPath:M.projectPath,targetProjectPath:M.projectPath}),K=bO(_.metadata,_.messages);return P.set(C(v(K)),K),G.json({session:_.metadata,messages:_.messages},201)}catch(J){if(J instanceof b||J instanceof m||J instanceof i)throw J;if(J instanceof Jx)throw new i("Session has no durable creation record");throw F.error("[SessionRoutes] Failed to fork session:",J),new t("Failed to fork session")}}),O.get("/:sessionId",async(G)=>{let Z=G.req.param("sessionId");try{let J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(Q)return G.json(qO(Q));let U=await p.findSessionMetadata(J.sessionId,J.projectPath);if(!U)throw new m("Session",Z);return G.json(U)}catch(J){if(J instanceof b||J instanceof m||J instanceof l)throw J;throw F.error("[SessionRoutes] Failed to get session:",J),new t("Failed to get session")}}),O.patch("/:sessionId",async(G)=>{let Z=G.req.param("sessionId");try{let J=await G.req.json(),Q=g(S0,J);if(!Q.success)throw new b("Invalid request body");if(Q.data.title===void 0)throw new b("title is required");let U=await c(Z,Q.data.projectPath),M=await p.updateSessionMetadata(U.sessionId,U.projectPath,{title:Q.data.title}),_=P.get(C(U));if(_)_.title=M.title??_.title,_.updatedAt=new Date(M.lastMessageTime);return G.json({success:!0,title:M.title})}catch(J){if(F.error("[SessionRoutes] Failed to update session:",J),J instanceof b||J instanceof m||J instanceof l)throw J;throw new t("Failed to update session")}}),O.get("/:sessionId/rewind",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=await N(Z);return G.json({checkpoints:await J.listRewindCheckpoints()})}),O.post("/:sessionId/rewind",async(G)=>{let Z=g(eO,await G.req.json());if(!Z.success)throw new b("Invalid rewind request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))throw new i("Cannot rewind while a run is active");let M=await N(J),_;try{_=await M.rewindSession(Z.data)}catch(K){if(K instanceof Error&&K.message.startsWith("Cannot rewind while"))throw new i(K.message);throw K}return J.messages=[..._.messages],J.updatedAt=new Date,y.publish(Q,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:_.messages}),G.json(_)})}),O.get("/:sessionId/subagents",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=await N(Z);return G.json({subagents:J.listSubagents().map(_O)})}),O.post("/:sessionId/subagents/:agentId/resume",async(G)=>{CO(G.req.param("agentId"));let Z=Ox.safeParse(await G.req.json());if(!Z.success)throw new b("Invalid subagent resume request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))throw new i("Cannot resume a subagent while a parent run is active");let M=await N(J),_=!1,K,z=(H)=>{y.publish(Q,"subagent.complete",{subagentSessionId:H.id,success:H.status==="completed",status:H.status,summary:H.result?.message?.slice(0,500),resumedFrom:H.resumedFrom,rootAgentId:H.rootAgentId,resumeDepth:H.resumeDepth})},w;try{w=M.resumeSubagent({agentId:G.req.param("agentId"),prompt:Z.data.prompt,onEvent:(H,B)=>{N0(Q,B,H)},onCompleted:(H)=>{if(_)z(H);else K=H}})}catch(H){if(H instanceof Error&&(H.message.startsWith("Cannot resume")||H.message.startsWith("Subagent cannot")))throw new i(H.message);if(H instanceof Error&&H.message.startsWith("Subagent not found"))throw new m(H.message);throw H}if(y.publish(Q,"subagent.start",{subagentSessionId:w.session.id,type:w.session.subagentType,description:w.session.description,resumedFrom:w.source.id,rootAgentId:w.session.rootAgentId,resumeDepth:w.session.resumeDepth}),_=!0,K)z(K);return G.json({source:_O(w.source),session:_O(w.session)})})}),O.get("/:sessionId/goal",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath"));return G.json({goal:await new Yx(Z.projectPath,Z.id).get()})}),O.put("/:sessionId/goal",async(G)=>{let Z=g(V0,await G.req.json());if(!Z.success)throw new b("Invalid goal request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))return G.json({status:"rejected",reason:"run_active"},409);let _=await(await N(J)).createGoal(Z.data);y.publish(Q,"goal.updated",{goal:_});let K=Z.data.permissionMode??"default",z=A(J,"",K,{goalContinuationOnly:!0});return G.json({status:"running",runId:z.id,goal:_},202)})}),O.patch("/:sessionId/goal",async(G)=>{let Z=g(G0,await G.req.json());if(!Z.success)throw new b("Invalid goal update");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=await N(J),M;if(Z.data.action==="pause")M=await U.pauseGoal();else if(Z.data.action==="edit")M=await U.editGoal(Z.data.objective);else M=await U.resumeGoal();if(y.publish(Q,"goal.updated",{goal:M}),M.status==="active"&&(!J.currentRunId||!["running","waiting_permission"].includes(f.get(J.currentRunId)?.status??""))){let _=A(J,"","default",{goalContinuationOnly:!0});return G.json({status:"running",runId:_.id,goal:M},202)}return G.json({status:M.status,goal:M})})}),O.delete("/:sessionId/goal",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=v(Z),U=await(await N(Z)).clearGoal();if(U)y.publish(J,"goal.cleared",{});return G.json({cleared:U})}),O.delete("/:sessionId",async(G)=>{let Z=G.req.param("sessionId"),J=G.req.query("projectPath");try{let Q=await c(Z,J),U=C(Q),M=P.get(U),_=$.get(U),K;if(M?.currentRunId){let z=f.get(M.currentRunId);if(z)MO(z),await z.completion,K=z.id}if(_)await _.clearGoal().catch((z)=>{F.warn("[SessionRoutes] Failed to clear session goal:",z)});if(await p.deleteSession(Q.sessionId,Q.projectPath),K)f.delete(K);if(P.delete(U),V.delete(U),x.delete(U),Y.delete(U),_){if(await _.dispose(),$.delete(U),$.size===0)await n.getInstance().disconnectAll()}return G.json({success:!0})}catch(Q){if(F.error("[SessionRoutes] Failed to delete session:",Q),Q instanceof b||Q instanceof m||Q instanceof l)throw Q;throw new t("Failed to delete session")}}),O.get("/:sessionId/message",async(G)=>{let Z=G.req.param("sessionId");try{let J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J)),U=Q?.messages?Q.messages:await p.loadSession(J.sessionId,J.projectPath);return G.json(U)}catch(J){if(F.error("[SessionRoutes] Failed to get messages:",J),J instanceof b||J instanceof m||J instanceof l)throw J;throw new t("Failed to get messages")}}),O.get("/:sessionId/events",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=await X(J);return sx(G,async(U)=>{let _,K,z=!1,w=()=>{if(K!==void 0)clearInterval(K),K=void 0;_?.(),_=void 0},H=()=>{if(z)return;z=!0,w()},B=new Set;U.onAbort(H),_=y.subscribe((T)=>{if(T.sessionId!==J.sessionId||T.projectPath!==J.projectPath)return;let d=T.properties.requestId;if((T.type==="permission.asked"||T.type==="question.required")&&typeof d==="string"){if(B.has(d))return;B.add(d)}U.writeSSE({data:JSON.stringify({type:T.type,properties:{...T.properties,sessionId:T.sessionId,projectPath:T.projectPath}})}).catch(H)});try{if(U.aborted||z)return;if(await U.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:J.sessionId,projectPath:J.projectPath,timestamp:Date.now()}})}).catch((k)=>{throw H(),k}),U.aborted||z)return;let d=(Q.currentRunId?f.get(Q.currentRunId):void 0)?.pendingPermission;if(d){B.add(d.permissionId);let k=Zx(d,!0);await U.writeSSE({data:JSON.stringify({type:k.type,properties:{...k.properties,sessionId:J.sessionId,projectPath:J.projectPath}})})}D(Q).catch((k)=>{F.error(`[SessionRoutes] Failed to resume pending input for ${Z}:`,k)}),K=setInterval(()=>{if(!U.aborted)U.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(H)},15000);while(!U.aborted&&!z)await new Promise((k)=>setTimeout(k,1000))}finally{H()}})}),O.post("/:sessionId/message",async(G)=>{let Z=G.req.param("sessionId"),J=await G.req.json(),Q=g(x0,J);if(!Q.success)throw new b("Invalid message format");let{content:U,attachments:M,permissionMode:_,projectPath:K}=Q.data,z=_||"default",w=Q0(U,M),H=await W(Z,K??G.req.query("projectPath")),B=v(H);return j(B).runExclusive(async()=>{let T=H.currentRunId?f.get(H.currentRunId):void 0;if(T&&(T.status==="running"||T.status==="waiting_permission")){let u=await(await N(H)).enqueueSteering(w,{allowBeforeTurn:!0});if(!u.accepted)return G.json({status:"rejected",reason:u.reason??"turn_unavailable"},409);let SO=u.messageId??GO(12),UO=u.queued;y.publish(B,"message.created",{messageId:SO,role:"user",content:EO(w)});let DO=u.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(y.publish(B,DO,{runId:T.id,messageId:SO,queued:UO}),u.delivery==="next_turn"&&T.status!=="running"&&T.status!=="waiting_permission")D(H).catch((kx)=>{F.error(`[SessionRoutes] Failed to wake queued follow-up for ${Z}:`,kx)});if(u.delivery==="next_turn")T.pendingFollowUpRequested=!0;return G.json({runId:T.id,messageId:SO,status:u.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:UO},202)}let k=await(await N(H)).prepareInputTurn(w);if(!k.accepted)return G.json({status:"rejected",reason:k.reason},k.reason==="queue_full"?429:409);let NO=A(H,w,z,{preparedInputTurn:k});return G.json({runId:NO.id,messageId:k.messageId,status:"running"},202)})}),O.post("/:sessionId/abort",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(Q?.currentRunId){let U=f.get(Q.currentRunId);if(U)MO(U),await U.completion}return G.json({success:!0})}),O.get("/:sessionId/status",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(!Q?.currentRunId)return G.json({sessionId:Z,projectPath:J.projectPath,status:"idle"});let U=f.get(Q.currentRunId);return G.json({sessionId:Z,projectPath:J.projectPath,runId:Q.currentRunId,status:U?.status||"idle"})}),O};async function Z0(O,$,x,V,Y,j={}){let{abortController:N,sessionId:X,id:W}=O,A=j.preparedInputTurn?.messageId??GO(12),G=j.pendingInputOnly===!0||j.preparedInputTurn?.mode==="pending"||j.goalContinuationOnly===!0?void 0:GO(12),Z,J=v($),Q=(U,M)=>{y.publish(J,U,M)};try{if(!j.pendingInputOnly&&!j.goalContinuationOnly)Q("message.created",{messageId:A,role:"user",content:EO(x)});if(Q("session.status",{status:"running"}),G)Q("message.created",{messageId:G,role:"assistant",content:""});Z=await Y($);let U=Z,M=await Qx.createWithRuntime(U,{sessionId:X}),_=async(B)=>{let T=GO(12),d=300000;O.status="waiting_permission";let k=new Promise((SO)=>{let UO=setTimeout(()=>{F.warn(`[SessionRoutes] Permission ${T} timed out after 300000ms`),Q("permission.timeout",{requestId:T}),SO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:T,resolve:(DO)=>{clearTimeout(UO),SO(DO)},details:B}}),NO=O.pendingPermission;if(!NO)throw Error("Permission request was not registered");let KO=Zx(NO);Q(KO.type,KO.properties),F.info(`[SessionRoutes] Permission request created: ${T}, runId: ${W}`);let u=await k;if(F.info(`[SessionRoutes] Permission response received: ${T}, approved: ${u.approved}`),!N.signal.aborted)O.status="running";if(O.pendingPermission===NO)O.pendingPermission=void 0;return u},K={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:N.signal,permissionMode:V,confirmationHandler:{requestConfirmation:_}},z=()=>{if(!G)G=GO(12),Q("message.created",{messageId:G,role:"assistant",content:""});return G},w=async(B)=>{switch(B.kind){case"content_delta":Q("message.delta",{messageId:z(),delta:B.delta});break;case"thinking_delta":Q("thinking.delta",{delta:B.delta});break;case"tool_start":if("function"in B.toolCall)Q("tool.start",{messageId:z(),toolName:B.toolCall.function.name,toolCallId:B.toolCall.id,arguments:B.toolCall.function.arguments,toolKind:B.toolKind});break;case"tool_result":if("function"in B.toolCall)Q("tool.result",{messageId:z(),toolName:B.toolCall.function.name,toolCallId:B.toolCall.id,success:B.result.success,summary:B.result.metadata?.summary,output:mO(yO(B.toolCall.function.name,B.result)),metadata:jx(B.result.metadata)});break;case"token_usage":Q("token.usage",{...B.usage});break;case"turn_start":Q("turn.started",{turn:B.turn,maxTurns:B.maxTurns});break;case"steering_applied":Q("steering.applied",{runId:W,messageIds:B.messageIds,count:B.count,recovered:B.recovered,delivery:B.delivery,queued:U.getPendingSteeringCount()});break;case"follow_up_started":{if(G)Q("message.complete",{messageId:G}),G=void 0;for(let T of B.messages){if(!T.recovered||T.persisted)continue;Q("message.created",{messageId:T.id,role:"user",content:EO(T.content),recovered:!0})}Q("follow_up.started",{runId:W,queued:B.queued,recovered:B.recovered}),z();break}case"goal_updated":Q("goal.updated",{goal:B.goal});break;case"goal_continuation_started":Q("goal.continuation.started",{goal:B.goal,continuation:B.continuation}),z();break;case"compaction":Q(B.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":Q("model.fallback",{});break;case"task_update":Q("task.updated",{tasks:B.tasks});break;default:break}},H=await FO(M.chatStream(x,K,{stream:!0,pendingInputOnly:j.pendingInputOnly,preparedInputTurn:j.preparedInputTurn,goalContinuationOnly:j.goalContinuationOnly}),w);if(!H.success)throw Error(H.error?.message??"Agent run failed");for(let B=0;B<20;B++){let T=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,U.getPendingSteeringCount()===0){if(!T)break;continue}if(N.signal.aborted)break;if(H=await FO(M.chatStream("",K,{stream:!0,pendingInputOnly:!0}),w),!H.success)throw Error(H.error?.message??"Agent follow-up failed")}if($.messages=[...K.messages],$.updatedAt=new Date,N.signal.aborted||O.status==="cancelled"){Q("session.status",{status:"idle"});return}if(G)Q("message.complete",{messageId:G});Q("thinking.completed",{}),O.status="completed",Q("session.completed",{runId:W,outputTruncated:H.metadata?.outputTruncated??!1}),Q("session.status",{status:"idle"})}catch(U){if(Z&&j.preparedInputTurn)await Z.finishTurn(j.preparedInputTurn.handle).catch(()=>{return});if(N.signal.aborted||O.status==="cancelled"){MO(O,"runtime-abort"),Q("session.status",{status:"idle"});return}F.error("[SessionRoutes] Agent execution error:",U),O.status="failed",Q("session.error",{error:U instanceof Error?U.message:"Unknown error"}),Q("session.status",{status:"error"})}}function Xx(O,$,x){F.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),F.info(`[SessionRoutes] Active runs: ${f.size}`);for(let[V,Y]of f.entries())if(F.info(`[SessionRoutes] Checking run ${V}: sessionId=${Y.sessionId}, projectPath=${Y.projectPath}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===O.sessionId&&Y.projectPath===O.projectPath&&Y.pendingPermission?.permissionId===$)return Y.pendingPermission.resolve(x),F.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0;return F.error(`[SessionRoutes] Permission not found: ${$}`),!1}var hO=L("Service"),U0=S.Object({approved:S.Boolean(),remember:S.Optional(S.Boolean()),scope:S.Optional(E(["once","session","project"])),targetMode:S.Optional(E(["default","autoEdit","plan","yolo"])),feedback:S.Optional(S.String()),answers:S.Optional(S.Record(S.String(),S.Union([S.String(),S.Array(S.String())])))}),_x=()=>{let O=new j0;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),V=$.req.query("sessionId"),Y=$.req.query("projectPath");hO.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${V}`);try{let j=await $.req.json(),N=g(U0,j);if(!N.success)throw new b("Invalid permission response format");let{approved:X,remember:W,scope:A,targetMode:D,feedback:G,answers:Z}=N.data;if(!V)throw new b("sessionId query parameter is required");let J=await c(V,Y);if(!Xx(J,x,{approved:X,reason:G,scope:A,targetMode:D,feedback:G,answers:Z}))throw new m("Permission request",x);return hO.info(`[PermissionRoutes] Permission ${x} ${X?"approved":"denied"}`),$.json({success:!0,approved:X,remember:W})}catch(j){if(hO.error("[PermissionRoutes] Failed to respond to permission:",j),j instanceof b||j instanceof l||j instanceof m||j instanceof I)throw j;throw j}}),O};import{Hono as X0}from"hono";var Mx=L("Service"),Bx=()=>{let O=new X0;return O.get("/",async($)=>{try{let x=await Ax();return $.json(x)}catch(x){return Mx.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let V=await Wx(x);return $.json(V)}catch(V){return Mx.error("[ProviderRoutes] Failed to list models:",V),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),V=await $.req.json();if(!V.apiKey?.trim())throw new b("apiKey is required");return await r().setApiKey(x,V.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await r().clearCredential($.req.param("provider")),$.json({success:!0})}),O};import{Hono as _0}from"hono";import*as s from"node:fs/promises";import{homedir as M0}from"node:os";import*as WO from"node:path";var OO=L("Service"),fO=WO.join(M0(),".blade","skills-config.json");async function wx(){try{let O=await s.readFile(fO,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function A0(O){await s.mkdir(WO.dirname(fO),{recursive:!0}),await s.writeFile(fO,JSON.stringify(O,null,2))}async function W0(O,$){let x=await wx();if($)x.disabled=x.disabled.filter((V)=>V!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await A0(x)}var YO=null,B0=300000;async function H0(){if(YO&&Date.now()-YO.timestamp<B0)return YO.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok)return OO.warn(`GitHub API returned ${O.status}`),YO?.data||[];let $=await O.json(),x=[];for(let V of $){if(V.type!=="dir")continue;let Y=`Official ${V.name} skill`;try{let j=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(j.ok){let X=(await j.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)Y=X[1].trim().slice(0,100)}}catch{}x.push({name:V.name,description:Y,tag:"Official",author:"Anthropic"})}return YO={data:x,timestamp:Date.now()},x}catch(O){return OO.warn("Failed to fetch skills catalog from GitHub:",O),YO?.data||[]}}var Kx=()=>{let O=new _0;return O.get("/",async($)=>{try{let x=AO();await x.initialize();let V=x.getAll(),Y=await wx(),j=V.map((N)=>({id:N.name,name:N.name,enabled:!Y.disabled.includes(N.name),description:N.description||"",version:N.version||"1.0.0",provider:"Local",location:N.source==="builtin"?"Built-in":N.basePath,capabilities:["prompts"],allowedTools:N.allowedTools||[]}));return $.json(j)}catch(x){return OO.error("[SkillsRoutes] Failed to get skills:",x),$.json([])}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),V=await $.req.json();return await W0(x,V.enabled),$.json({success:!0,enabled:V.enabled})}catch(x){return OO.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),V=`${process.env.HOME}/.blade/skills/${x}`;return await s.rm(V,{recursive:!0,force:!0}),await AO().refresh(),$.json({success:!0})}catch(x){return OO.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),V=Hx(),Y=AO(),j=!1;if(x.source==="catalog"&&x.name){if(j=await V.installOfficialSkill(x.name),!j)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(j=await V.installFromRepo(x.url,x.name),!j)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(j=await V.installFromLocal(x.path,x.name),!j)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Y.refresh(),$.json({success:!0})}catch(x){return OO.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await H0();return $.json(x)}catch(x){return OO.error("[SkillsRoutes] Failed to get catalog:",x),$.json([])}}),O};import w0 from"fast-glob";import{Hono as K0}from"hono";import{execSync as D0}from"node:child_process";import{readdir as z0}from"node:fs/promises";import BO from"node:path";var jO=L("Service"),T0=(O)=>{try{return D0("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},b0=[...HO.map((O)=>`${O}/**`),...HO,...kO.map((O)=>`**/${O}`)],q0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Tx=()=>{let O=new K0;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",V=zx(x).filter((Y)=>!q0.has(Y.command));return $.json(V)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",V=$.get("directory")||h(),Y=Math.min(Number($.req.query("limit"))||100,1000),N=(await w0("**/*",{cwd:V,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:b0})).map((A)=>A.replace(/\\/g,"/"));if(!x)return $.json(N.slice(0,Y));let X=x.toLowerCase(),W=N.filter((A)=>A.toLowerCase().includes(X)).slice(0,Y);return $.json(W)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||h(),V=$.req.query("path")||"",Y=V?BO.join(x,V):x,N=(await z0(Y,{withFileTypes:!0})).map((A)=>({name:A.name,path:V?`${V}/${A.name}`:A.name,type:A.isDirectory()?"dir":"file"}));N.sort((A,D)=>{if(A.type!==D.type)return A.type==="dir"?-1:1;return A.name.localeCompare(D.name)});let X=new Set(HO),W=N.filter((A)=>{let D=A.name;if(D.startsWith("."))return!1;if(X.has(D))return!1;for(let G of kO)if(D.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(W)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let V=$.get("directory")||h(),Y=BO.resolve(V,x),j=BO.relative(V,Y);if(j.startsWith("..")||BO.isAbsolute(j))return $.json({error:"Invalid file path"},400);let N=Dx(),X=await N.stat(Y);if(!X?.isFile)return $.json({error:"File not found"},404);let W=200000,A=await N.readTextFile(Y),D=A.length>W;return $.json({path:x,content:D?A.slice(0,W):A,truncated:D,size:X.size})}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||h(),V=T0(x);return $.json({branch:V})}catch(x){return jO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as F0}from"hono";var e=L("Service"),JO=new Map,bx=2097152,qx=65536;function Fx(){return typeof globalThis.Bun<"u"}async function L0(O,$,x){if(Fx()){let{spawn:j}=await import("bun-pty"),N=j(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:N.pid,write:(X)=>N.write(X),resize:(X,W)=>N.resize(X,W),kill:()=>N.kill(),onData:(X)=>N.onData(X),onExit:(X)=>N.onExit(X)}}let Y=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Y.pid,write:(j)=>Y.write(j),resize:(j,N)=>Y.resize(j,N),kill:()=>Y.kill(),onData:(j)=>{Y.onData(j)},onExit:(j)=>{Y.onExit(j)}}}var RO=void 0,pO;if(Fx())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();pO=$.upgradeWebSocket,RO=$.websocket}catch(O){e.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function Lx(O,$){let x=`term-${Date.now()}`;e.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let V=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=V.endsWith("sh")?["-l"]:[],j=await L0(V,Y,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),N={id:x,process:j,cwd:O,buffer:"",subscribers:new Set};if(JO.set(x,N),N.subscribers.add($),j.onData((X)=>{let W=!1;for(let A of N.subscribers)try{A.send(X),W=!0}catch{N.subscribers.delete(A)}if(W)return;if(N.buffer+=X,N.buffer.length>bx)N.buffer=N.buffer.slice(-bx)}),j.onExit(({exitCode:X})=>{e.info(`[Terminal] Process exited: ${x}, code: ${X}`);for(let W of N.subscribers)try{W.close()}catch{}JO.delete(x)}),N.buffer){let X=N.buffer;N.buffer="";for(let W=0;W<X.length;W+=qx)$.send(X.slice(W,W+qx))}return{session:N,cleanup:()=>{if(e.info(`[Terminal] Connection closed: ${x}`),N.subscribers.delete($),N.subscribers.size===0){try{N.process.kill()}catch{}JO.delete(x)}}}}function Cx(O,$){O.on("connection",async(x,V)=>{let Y=new URL(V.url||"/",`http://${V.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){x.close();return}let j=Y.searchParams.get("cwd")||$()||h();try{let{session:N,cleanup:X}=await Lx(j,{send:(W)=>x.send(W),close:()=>x.close()});x.on("message",(W)=>{try{N.process.write(String(W))}catch(A){e.error("[Terminal] Failed to write to PTY:",A)}}),x.on("close",X),x.on("error",X)}catch(N){e.error("[Terminal] Failed to spawn PTY:",N),x.close()}})}var Ex=()=>{let O=new F0;if(O.get("/status",($)=>{let x=Array.from(JO.values()).map((V)=>({id:V.id,cwd:V.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),V=JO.get(x);if(V){try{V.process.kill()}catch{}for(let Y of V.subscribers)Y.close();return JO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),pO)O.get("/ws",pO(($)=>{let x=$.req.query("cwd")||$.get("directory")||h(),V;return{async onOpen(Y,j){try{V=await Lx(x,{send:(N)=>j.send(N),close:()=>j.close()})}catch(N){e.error("[Terminal] Failed to spawn PTY:",N),j.close()}},onMessage(Y){if(!V)return;try{V.session.process.write(String(Y.data))}catch(j){e.error("[Terminal] Failed to write to PTY:",j)}},onClose(){V?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};var R=L("Service"),IO=[];function p0(){let O=h0(k0(import.meta.url)),$=[xO(O,"web"),xO(h(),"dist/web"),xO(h(),"packages/cli/dist/web")];for(let x of $){let V=xO(x,"index.html");if(hx(V)){if(wO(V,"utf-8").includes("/assets/"))return R.debug(`[Server] Found web dist at: ${x}`),x}}return null}function R0(){let O=new C0;O.onError((x,V)=>{if(R.error("[Server] Request error:",x),x instanceof I)return V.json(x.toObject(),x.statusCode);let Y=x instanceof Error?x.message:String(x);return V.json({error:{code:"INTERNAL_ERROR",message:Y}},500)}),O.use(async(x,V)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return V();let j=x.req.path;if(j==="/"||j.startsWith("/assets/")||j.endsWith(".html")||j.endsWith(".js")||j.endsWith(".css"))return V();let N=x.req.header("Authorization");if(!N?.startsWith("Basic "))return x.header("WWW-Authenticate",'Basic realm="Blade Server"'),x.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(N.slice(6),"base64").toString(),[W,A]=X.split(":"),D=process.env.BLADE_SERVER_USERNAME??"blade";if(W!==D||A!==Y)return x.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),O.use(async(x,V)=>{let Y=x.req.path==="/health"||x.req.path==="/global/health"||x.req.path.startsWith("/assets/");if(!Y)R.debug(`[Server] ${x.req.method} ${x.req.path}`);let j=Date.now();if(await V(),!Y){let N=Date.now()-j;R.debug(`[Server] ${x.req.method} ${x.req.path} - ${x.res.status} (${N}ms)`)}}),O.use(E0({origin(x){if(!x)return;if(x.startsWith("http://localhost:"))return x;if(x.startsWith("http://127.0.0.1:"))return x;if(x==="tauri://localhost"||x==="http://tauri.localhost")return x;if(IO.includes(x))return x;return}})),O.use(async(x,V)=>{let Y=x.req.query("directory")||x.req.header("x-blade-directory")||h();try{Y=decodeURIComponent(Y)}catch{}return x.set("directory",Y),V()}),O.route("/global",vO()),O.route("/sessions",Ux()),O.route("/configs",gO()),O.route("/permissions",_x()),O.route("/providers",Bx()),O.route("/models",tO()),O.route("/suggestions",Tx()),O.route("/terminal",Ex()),O.route("/mcp",uO()),O.route("/skills",Kx()),O.get("/health",(x)=>{return x.json({healthy:!0,version:VO()})});let $=p0();if($)R.info(`[Server] Serving static files from ${$}`),O.get("/assets/*",(x)=>{let V=xO($,x.req.path);if(!hx(V))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${x.req.path}`}},404);let Y=wO(V),j=f0(V).toLowerCase(),X={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[j]||"application/octet-stream";return new Response(Y,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),O.get("/",(x)=>{let V=xO($,"index.html"),Y=wO(V,"utf-8");return x.html(Y)}),O.get("*",(x)=>{let V=x.req.path;if(V.includes("."))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${V}`}},404);let Y=xO($,"index.html"),j=wO(Y,"utf-8");return x.html(j)});else R.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(x)=>{return x.json({message:"Blade API Server",version:VO(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(x)=>{return x.json({error:{code:"NOT_FOUND",message:`Route not found: ${x.req.path}`}},404)});return O}function I0(){let O=m0(),$=[];for(let x of Object.keys(O)){let V=O[x];if(!V)continue;for(let Y of V){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function yx(){return typeof globalThis.Bun<"u"}function mx(O,$){let x=globalThis.Bun,V=(j)=>{try{return x.serve({hostname:$.hostname,port:j,fetch:O.fetch,idleTimeout:0,websocket:RO})}catch(N){R.error("Failed to start Bun server:",N);return}},Y=$.port===0?V(4096)??V(0):V($.port);if(!Y)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function g0(O,$){return new Promise((x,V)=>{let Y=y0(async(A,D)=>{let G=new URL(A.url||"/",`http://${A.headers.host}`),Z=new Headers;for(let[U,M]of Object.entries(A.headers))if(M)if(Array.isArray(M))for(let _ of M)Z.append(U,_);else Z.set(U,M);let J;if(A.method!=="GET"&&A.method!=="HEAD")J=(await new Promise((M)=>{let _=[];A.on("data",(K)=>_.push(K)),A.on("end",()=>M(Buffer.concat(_)))})).toString();let Q=new Request(G.toString(),{method:A.method,headers:Z,body:J});try{let U=await O.fetch(Q);if(D.statusCode=U.status,U.headers.forEach((M,_)=>{D.setHeader(_,M)}),U.body){let M=U.body.getReader(),_=async()=>{let{done:K,value:z}=await M.read();if(K){D.end();return}return D.write(z),_()};await _()}else{let M=await U.text();D.end(M)}}catch(U){R.error("[Server] Node request error:",U),D.statusCode=500,D.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),j=new P0({noServer:!0}),N=h();Cx(j,()=>N),Y.on("upgrade",(A,D,G)=>{if(new URL(A.url||"/",`http://${A.headers.host}`).pathname==="/terminal/ws")j.handleUpgrade(A,D,G,(J)=>{j.emit("connection",J,A)});else D.destroy()});let X=(A)=>{return new Promise((D,G)=>{Y.once("error",(Z)=>{if(Z.code==="EADDRINUSE")G(Z);else G(Z)}),Y.listen(A,$.hostname,()=>{let Z=Y.address();if(Z&&typeof Z==="object")D(Z.port);else D(A)})})};(async()=>{let A;if($.port===0)try{A=await X(4096)}catch{A=await X(0)}else A=await X($.port);let D=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${A}`);x({url:D,port:A,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{j.close(()=>{Y.close(()=>G())})})}})})().catch(V)})}var fx;((Y1)=>{let O,$;function x(){if(!$)$=R0();return $}Y1.getApp=x;function V(N){IO=N.cors??[];let X=x();if(yx())O=mx(X,N),R.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let W=O;return{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}Y1.listen=V;async function Y(N){IO=N.cors??[];let X=x();if(yx())O=mx(X,N),R.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await g0(X,N),R.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);let W=O;return{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}Y1.listenAsync=Y;function j(){return O!==void 0}Y1.isRunning=j})(fx||={});export{v0 as a,u0 as b,I0 as c,fx as d};
|
package/dist/chunk-bxbagv76.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{B,I as j,K as T,P as h,Q as q,S as N,X as A,Z as b,_ as x}from"./chunk-jakzknh3.js";import"./chunk-9ad7tt9s.js";import{ca as u}from"./chunk-e4a240t7.js";import"./chunk-bm8vwfez.js";import{va as I}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import{Ia as C}from"./chunk-d4ex0qvs.js";import"./chunk-6es6av6j.js";import{ab as K}from"./chunk-1pt090dg.js";import{sb as E}from"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import{Cb as S}from"./chunk-jt62ctz7.js";import{Ib as M}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import{Tb as L}from"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import{Readable as p,Writable as m}from"node:stream";import*as P from"@agentclientprotocol/sdk";import k from"node:path";import{PROTOCOL_VERSION as d}from"@agentclientprotocol/sdk";import{nanoid as O}from"nanoid";var V=L("Agent");function f(z){return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function c(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function g(z){return Object.fromEntries(z.map((H)=>[H.name,c(H)]))}function y(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Q=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Q)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Q[1]??"image/png",data:Q[2]??""}]})}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;availableCommandsTimer=null;destroyed=!1;messages;mode="default";constructor(z,H,J,Q,X={}){this.id=z;this.cwd=H;this.connection=J;this.clientCapabilities=Q;this.options=X;this.messages=[...X.initialMessages??[]]}async initialize(){V.debug(`[AcpSession ${this.id}] Initializing...`),B.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),V.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?g(this.options.mcpServers):void 0;this.runtime=await T.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),V.debug(`[AcpSession ${this.id}] Agent created successfully`);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 z of this.messages){if(!this.canSendUpdates())return;let H=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let J of y(z.content)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:J}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.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(z,H){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],await this.agent?.destroy(),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),$}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let U=!1,W,G=(F)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:F.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:F.result?.message||F.result?.error||`Subagent ${F.status}`}}]})},w=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(F)=>{if(U)G(F);else W=F}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.session.id,status:"in_progress",title:`Resuming ${w.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${w.source.id} at depth ${w.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),U=!0,W)G(W);return w}},signal:H,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,U)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(U);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:G})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},Q=await b(z,J),X=Q.data?.action;if(X==="start_goal"||X==="resume_goal")this.schedulePendingResume();if(X==="rewind_session"&&Array.isArray(Q.data?.messages))this.messages=[...Q.data.messages];if((Q.message==="compact_completed"||Q.message==="compact_fallback")&&Q.data?.compactedMessages)this.messages=[...Q.data.compactedMessages];let Y=Q.content||Q.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(J){return V.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=x(),H=["model","permissions","theme","config","exit","ide"],Q=z.filter((X)=>!H.includes(X.name)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),V.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(B.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(J.trim()))return this.handleSlashCommand(J,this.pendingPrompt.signal);let X=await this.runtime.enqueueSteering(J,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Q=new AbortController;this.pendingPrompt=Q;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${J.slice(0,100)}...`),A(J))return await this.handleSlashCommand(J,Q.signal);let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Q.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}};if(await K(this.agent.chatStream(J,X,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly}),async(Y)=>{switch(Y.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let Z=Y.toolCall,$="function"in Z?Z.function.name:Z.type,U=this.mapToolKind(Y.toolKind),W=`Executing ${$}`;if($==="Task"&&"function"in Z)try{let G=JSON.parse(Z.function.arguments),w=G.resume_from??G.resume;if(typeof w==="string")W=`Resuming ${String(G.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.id,status:"in_progress",title:W,content:[],kind:U});break}case"tool_result":{let{toolCall:Z,result:$}=Y,U=[],W=$.metadata;if(W?.kind==="edit"&&typeof W.file_path==="string"&&typeof W.oldContent==="string"&&(typeof W.newContent==="string"||W.newContent===void 0))U.push({type:"diff",path:W.file_path,oldText:W.oldContent,newText:W.newContent??null});else{let w="function"in Z?Z.function.name:Z.type,F=q(h(w,$));U.push({type:"content",content:{type:"text",text:F}})}let G=$.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.id,status:G,content:U});break}case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Z of Y.messages){if(!Z.recovered||Z.persisted)continue;for(let $ of y(Z.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:$})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
|
|
2
|
-
`}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
|
|
3
|
-
`}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...X.messages],Q.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(X){if(Q.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===Q){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}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.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,J=(z?null:await this.runtime.getGoal())?.status==="active";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Q)=>{V.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Q)})}cancel(){if(V.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,V.info(`[AcpSession ${this.id}] Cancelled successfully`);else V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"];this.mode=H.includes(z)?z:"default",V.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;let z=this.agent,H=this.runtime;this.agent=null,this.runtime=null;let J,Q=async(X)=>{try{await X()}catch(Y){J??=Y}};if(await Q(()=>this.cancel()),z)await Q(()=>z.destroy());if(H)await Q(()=>H.dispose());if(await Q(()=>B.destroySession(this.id)),V.debug(`[AcpSession ${this.id}] Destroyed`),J!==void 0)throw J}resolvePrompt(z){let H=[];for(let J of z)if(J.type==="text")H.push(J.text);else if(J.type==="image")H.push(`[Image: ${J.mimeType}]`);else if(J.type==="resource"){let Q=J.resource;if("text"in Q)H.push(`<file path="${Q.uri}">
|
|
4
|
-
${Q.text}
|
|
5
|
-
</file>`)}else if(J.type==="resource_link")H.push(`[Resource: ${J.uri}]`);return H.join(`
|
|
6
|
-
`)}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:z}),this.canSendUpdates()}sendUpdate(z){if(!this.canSendUpdates())return;let H={sessionId:this.id,update:z};this.connection.sessionUpdate(H).catch((J)=>{V.warn(`[AcpSession ${this.id}] Failed to send update:`,J)})}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);let J=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(J))return V.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Q=O(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
7
|
-
- ${z.risks.join(`
|
|
8
|
-
- `)}`}});let Y=this.mapToolKind(J),Z={sessionId:this.id,options:[{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:Q,status:"pending",title:z.title||"Permission Required",content:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),H);if(!$)return{approved:!1,reason:E};let U=$.outcome;if(U.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=U.optionId;if(W==="allow_always")return{approved:!0,scope:"project"};if(W==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let G=W==="allow_once";return{approved:G,scope:"once",reason:G?void 0:"User denied the operation"}}catch(Q){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,Q),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Q={};try{for(let[X,Y]of J.entries()){let Z=Y.options.map((G,w)=>`answer:${X}:${w}`),$=`answer:${X}:cancel`,U=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((G,w)=>({optionId:Z[w],name:G.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:O(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((G)=>`${G.label}: ${G.description}`)].join(`
|
|
9
|
-
`)}}]}}),H);if(!U)return{approved:!1,reason:E};if(U.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Z.indexOf(U.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};Q[Y.header]=Y.options[W].label}return{approved:!0,answers:Q}}catch(X){return V.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Q)=>{let X=!1,Y=($)=>{if(X)return;X=!0,H.removeEventListener("abort",Z),$()},Z=()=>Y(()=>J(void 0));if(H.addEventListener("abort",Z,{once:!0}),H.aborted)Z();z.then(($)=>Y(()=>J($)),($)=>Y(()=>Q($)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var D=L("Agent");class R{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(z){this.connection=z}async initialize(z){return D.info("[BladeAgent] Initializing ACP connection"),D.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:d,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=S("acp");D.info(`[BladeAgent] Creating new session: ${H}`),D.debug(`[BladeAgent] Session cwd: ${z.cwd||M()}`);let J=new _(H,z.cwd||M(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await J.initialize(),this.assertNotDestroyed()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(H,J),D.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),J.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H)}async unstable_listSessions(z){if(z.cwd!=null&&!k.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let H=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:H.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime})),nextCursor:H.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!k.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let H=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd});this.assertNotDestroyed();let J=new _(H.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H.messages,mcpServers:z.mcpServers});try{await J.initialize(),this.assertNotDestroyed()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(H.sessionId,J),J.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H.sessionId)}async loadSession(z){this.assertNotDestroyed(),D.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Q=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Q);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Q)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed();let H=this.sessions.get(z.sessionId);if(H)try{await H.destroy()}finally{if(this.sessions.get(z.sessionId)===H)this.sessions.delete(z.sessionId)}let J=await j.loadSession(z.sessionId,z.cwd),Q=new _(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:J,mcpServers:z.mcpServers});try{await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed()}catch(X){throw await Q.destroy().catch(()=>{return}),X}return this.sessions.set(z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup()}buildChildSessionResponse(z){return{sessionId:z,...this.buildSessionSetup()}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(){let z=I(),H=z?.models||[],J=z?.currentModelId||H[0]?.id,Q=H.map((Y)=>({modelId:Y.id,name:C(Y),description:`${Y.provider}/${Y.model}`}));return{modes:{availableModes:[{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"}],currentModeId:"default"},models:Q.length>0?{availableModels:Q,currentModelId:J}:void 0}}async prompt(z){let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return H.prompt(z)}async cancel(z){D.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.sessions.get(z.sessionId);if(H)D.info("[BladeAgent] Found session, calling session.cancel()"),H.cancel();else D.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){D.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.sessions.get(z.sessionId);if(H)await H.setMode(z.modeId);return{}}async unstable_setSessionModel(z){D.info(`[BladeAgent] Setting session model: ${z.modelId}`);let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return await H.setModel(z.modelId),{}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of this.sessions.values())try{await H.destroy()}catch(J){z??=J}this.sessions.clear();try{await u.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function Bz(){let z=m.toWeb(process.stdout),H=p.toWeb(process.stdin),J=P.ndJsonStream(z,H);await new P.AgentSideConnection((X)=>new R(X),J).closed}export{Bz as runAcpIntegration};
|
package/dist/chunk-n8ymp6nd.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as a,u as b}from"./chunk-nned222j.js";import"./chunk-6es6av6j.js";import"./chunk-dr06x0cw.js";export{a as globalOptions,b as cliConfig};
|