blade-code 0.7.8 → 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-04920kz2.js +1570 -0
- package/dist/{chunk-rnfd5ebv.js → chunk-06h100e2.js} +1 -1
- package/dist/chunk-07jvw0kn.js +1 -0
- package/dist/chunk-0dj326ms.js +5 -0
- package/dist/chunk-14erxdhd.js +1 -0
- package/dist/{chunk-48q9msfk.js → chunk-1pt090dg.js} +38 -38
- package/dist/{chunk-cjmxggke.js → chunk-1smf2dj3.js} +2 -2
- package/dist/chunk-34pdtz4q.js +3 -0
- package/dist/chunk-42ch5zg4.js +1 -0
- package/dist/chunk-49g067ek.js +41 -0
- package/dist/{chunk-71n472hj.js → chunk-61952mn3.js} +1 -1
- package/dist/{chunk-s4mke0t6.js → chunk-6yqzfz8t.js} +1 -1
- package/dist/chunk-7j6rxyt8.js +9 -0
- package/dist/{chunk-g7caymjr.js → chunk-9ad7tt9s.js} +1 -1
- package/dist/{chunk-jm2xhnrv.js → chunk-9xkjb87h.js} +1 -1
- package/dist/chunk-a12tmmfr.js +1 -0
- package/dist/{chunk-0e0z8yc1.js → chunk-bm8vwfez.js} +2 -2
- package/dist/chunk-cnftrx3g.js +1 -0
- package/dist/chunk-ctqf59q1.js +2 -0
- package/dist/chunk-d4ex0qvs.js +2 -0
- package/dist/{chunk-f9ybv4ph.js → chunk-dr06x0cw.js} +1 -1
- package/dist/chunk-epp5jx5f.js +6 -0
- package/dist/{chunk-4dmdn3a9.js → chunk-gsfkrr25.js} +1 -1
- package/dist/chunk-hjx5n3dw.js +3 -0
- package/dist/chunk-j39q2kx7.js +1 -0
- package/dist/chunk-j6hpzkpq.js +6 -0
- package/dist/{chunk-t70aqrm4.js → chunk-jt62ctz7.js} +1 -1
- package/dist/chunk-k47ssv3b.js +34 -0
- package/dist/{chunk-t2spryz0.js → chunk-kawv31m3.js} +1 -1
- package/dist/chunk-n4f8tseg.js +2 -0
- package/dist/chunk-nc4kfwef.js +1 -0
- package/dist/{chunk-9kejtkey.js → chunk-neenhtxw.js} +1 -1
- package/dist/chunk-pdydx73a.js +2 -0
- package/dist/chunk-qwdbqjh7.js +22 -0
- package/dist/{chunk-g6ted982.js → chunk-sr3bzb95.js} +1 -1
- package/dist/chunk-syj3anec.js +6 -0
- package/dist/chunk-tv4r86ez.js +24 -0
- package/dist/chunk-twem6p0g.js +2 -0
- package/dist/chunk-v3ctg84r.js +1 -0
- package/dist/chunk-v5rn5r1h.js +1 -0
- package/dist/{chunk-fb7amc2s.js → chunk-wmes2tt9.js} +1 -1
- package/dist/chunk-x6gt63vz.js +151 -0
- package/dist/chunk-xhnyy54e.js +2 -0
- package/dist/{chunk-6hn2jgw5.js → chunk-yhpm9azy.js} +1 -1
- package/dist/web/assets/{CodeBlockHighlighter-C1cp8dDv.js → CodeBlockHighlighter-D8_cOYpG.js} +1 -1
- package/dist/web/assets/{FilePreview-DRKRs8i2.js → FilePreview-Chqi7chf.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DFqPpAnM.js → MarkdownRenderer-JJScfgAO.js} +1 -1
- package/dist/web/assets/{McpModal-CX5-hlNv.js → McpModal-CiCuIUxC.js} +2 -2
- package/dist/web/assets/SettingsModal-Bew818xl.js +1 -0
- package/dist/web/assets/{SettingsStore-jup_Kikq.js → SettingsStore-B_4zN-c-.js} +1 -1
- package/dist/web/assets/{SkillsModal-DaAUrwXO.js → SkillsModal-Cot4Rb89.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DzlllDH7.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 +4 -11
- package/dist/chunk-1w6tqkxd.js +0 -34
- package/dist/chunk-2049tv49.js +0 -41
- package/dist/chunk-4745ktjj.js +0 -1570
- package/dist/chunk-5be6qr2v.js +0 -2
- package/dist/chunk-67vzgcs5.js +0 -2
- package/dist/chunk-6811kbxn.js +0 -1
- package/dist/chunk-6js5wp6t.js +0 -1
- package/dist/chunk-6kp3z956.js +0 -9
- package/dist/chunk-78txnq4n.js +0 -151
- package/dist/chunk-7r1hm0qz.js +0 -6
- package/dist/chunk-a7yjnqhd.js +0 -3
- package/dist/chunk-bwaqaktn.js +0 -1
- package/dist/chunk-cb82rf5h.js +0 -1
- package/dist/chunk-ce11m8bq.js +0 -1
- package/dist/chunk-e4rhdg3h.js +0 -1
- package/dist/chunk-faq7ay4j.js +0 -24
- package/dist/chunk-ky8ctbdc.js +0 -1
- package/dist/chunk-mpskff34.js +0 -1
- package/dist/chunk-pd1yqxcv.js +0 -9
- package/dist/chunk-phhmmybg.js +0 -2
- package/dist/chunk-qnevwq1q.js +0 -2
- package/dist/chunk-r1spf93b.js +0 -26
- package/dist/chunk-z4c68ve0.js +0 -6
- package/dist/chunk-z9zbcenc.js +0 -6
- package/dist/web/assets/SettingsModal-CfR_q6N7.js +0 -1
- package/dist/web/assets/index-BJTSF3fc.js +0 -9
- package/dist/web/assets/index-CL6apjgo.css +0 -1
- package/dist/web/assets/vendor-radix-CESj0OOY.js +0 -45
package/dist/chunk-5be6qr2v.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Fb as Q,Gb as W,Hb as Y}from"./chunk-6kp3z956.js";import{Zb as X}from"./chunk-a7yjnqhd.js";var J=X("Service"),$="https://models.dev/api.json",j=3600000,G=null,Z=async()=>{if(G&&Date.now()-G.timestamp<j)return G.data;try{J.info("Fetching models.dev data...");let q=await fetch($,{headers:{"User-Agent":"Blade-CLI/1.0"}});if(!q.ok)throw Error(`HTTP ${q.status}: ${q.statusText}`);let x=await q.json();return G={data:x,timestamp:Date.now()},J.info(`Loaded ${Object.keys(x).length} providers from models.dev`),x}catch(q){throw J.error("Failed to fetch models.dev data:",q),q}},y=async()=>{let q=await Z(),x=[];for(let[w,k]of Object.entries(q)){let z=Object.keys(k.models||{}).length;if(z===0)continue;x.push({id:w,name:k.name||w,icon:W[w]||W.default,description:`${z} 个模型`,envVars:k.env||[],docUrl:k.doc,defaultBaseUrl:Y[w]})}return x.sort((w,k)=>{let z=Q.indexOf(w.id),K=Q.indexOf(k.id);if(z!==-1&&K!==-1)return z-K;if(z!==-1)return-1;if(K!==-1)return 1;return w.name.localeCompare(k.name)})},f=async(q)=>{let w=(await Z())[q];if(!w?.models)return J.warn(`No models found for provider: ${q}`),[];return Object.values(w.models).map((k)=>({id:k.id,name:k.name||k.id,contextWindow:k.limit?.context,maxOutput:k.limit?.output,inputCost:k.cost?.input,outputCost:k.cost?.output}))};
|
|
2
|
-
export{y as j,f as k};
|
package/dist/chunk-67vzgcs5.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{j as b0,k as N0}from"./chunk-5be6qr2v.js";import{A as K0,C as M0,D as wx,E as Px,G as bx,H as G0,I as k,L as Y0,M as Zx,N as C,O as F,Q as Ex,R as Lx,T as J0,aa as m0}from"./chunk-4745ktjj.js";import{da as i}from"./chunk-1w6tqkxd.js";import{Da as t,wa as jx,ya as lx,za as dx}from"./chunk-faq7ay4j.js";import{Ja as Vx}from"./chunk-phhmmybg.js";import{$a as qx,Pa as _0,Ra as Tx}from"./chunk-48q9msfk.js";import{rb as V0}from"./chunk-jm2xhnrv.js";import{vb as j0}from"./chunk-t70aqrm4.js";import{Bb as L}from"./chunk-4dmdn3a9.js";import{Pb as $0,Zb as q}from"./chunk-a7yjnqhd.js";import{$b as kx}from"./chunk-f9ybv4ph.js";var P$={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 k$($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{Hono as H$}from"hono";import{cors as W$}from"hono/cors";import{existsSync as E0,readFileSync as Kx}from"node:fs";import{createServer as A$}from"node:http";import{networkInterfaces as D$}from"node:os";import{dirname as q$,extname as C$,join as e}from"node:path";import{fileURLToPath as B$}from"node:url";import{WebSocketServer as F$}from"ws";import{z as Ox}from"zod";class R extends Error{code;statusCode;constructor($,j,x=500){super(j);this.code=$;this.statusCode=x;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class E extends R{constructor($,j){super("NOT_FOUND",j?`${$} not found: ${j}`:`${$} not found`,404)}}class A extends R{constructor($){super("BAD_REQUEST",$,400)}}class a extends R{constructor($){super("CONFLICT",$,409)}}class u extends R{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class o extends R{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var g$=Ox.object({error:Ox.object({code:Ox.string(),message:Ox.string()})});import{Hono as h0}from"hono";import{z as $x}from"zod";var Hx=q("Service"),P0=$x.object({updates:$x.record($x.any()),options:$x.object({scope:$x.enum(["local","project","global"]).optional(),immediate:$x.boolean().optional()}).optional()}),Ix=()=>{let $=new h0;return $.get("/",async(j)=>{try{let x=jx();return j.json(x||{})}catch(x){return Hx.error("[ConfigRoutes] Failed to get config:",x),j.json({})}}),$.put("/",async(j)=>{try{let x=await j.req.json(),V=P0.safeParse(x);if(!V.success)throw new A("Invalid config update format");let{updates:Y,options:X}=V.data;return await t().updateConfig(Y,X),j.json({success:!0,updates:Y})}catch(x){throw Hx.error("[ConfigRoutes] Failed to update config:",x),x}}),$.get("/permissions",async(j)=>{try{let x=jx();return j.json(x?.permissions||{})}catch(x){return Hx.error("[ConfigRoutes] Failed to get permissions:",x),j.json({})}}),$};import{Hono as k0}from"hono";var vx=()=>{let $=new k0;return $.get("/health",(j)=>{return j.json({healthy:!0,version:Vx()})}),$.get("/info",(j)=>{return j.json({version:Vx(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:L()})}),$};import{Hono as S0}from"hono";var Qx=q("Service"),ux=()=>{let $=new S0;return $.get("/",async(j)=>{try{let V=i.getInstance().getAllServers(),Y=Array.from(V.entries()).map(([X,Z])=>({id:X,name:X,status:Z.status==="connected"?"connected":Z.status==="connecting"?"connecting":Z.lastError?"error":"offline",endpoint:Z.config.command?`${Z.config.command} ${(Z.config.args||[]).join(" ")}`.trim():Z.config.url||"Unknown",description:`MCP server: ${X}`,tools:Z.tools.map((T)=>T.name),connectedAt:Z.connectedAt?.toISOString(),error:Z.lastError?.message}));return j.json(Y)}catch(x){return Qx.error("[McpRoutes] Failed to get MCP servers:",x),j.json([])}}),$.post("/:name/connect",async(j)=>{try{let x=j.req.param("name");return await i.getInstance().connectServer(x),j.json({success:!0})}catch(x){return Qx.error("[McpRoutes] Failed to connect MCP server:",x),j.json({success:!1,error:x.message},500)}}),$.post("/:name/disconnect",async(j)=>{try{let x=j.req.param("name");return await i.getInstance().disconnectServer(x),j.json({success:!0})}catch(x){return Qx.error("[McpRoutes] Failed to disconnect MCP server:",x),j.json({success:!1,error:x.message},500)}}),$.delete("/:name",async(j)=>{try{let x=j.req.param("name");await i.getInstance().unregisterServer(x);let Y=jx();if(Y?.mcpServers){let{[x]:X,...Z}=Y.mcpServers;await t().updateConfig({mcpServers:Z})}return j.json({success:!0})}catch(x){return Qx.error("[McpRoutes] Failed to delete MCP server:",x),j.json({success:!1,error:x.message},500)}}),$.post("/",async(j)=>{try{let x=await j.req.json(),{name:V,config:Y}=x;if(!V||!Y)return j.json({success:!1,error:"Missing name or config"},400);await i.getInstance().registerServer(V,Y);let Z=jx();return await t().updateConfig({mcpServers:{...Z?.mcpServers,[V]:Y}}),j.json({success:!0})}catch(x){return Qx.error("[McpRoutes] Failed to add MCP server:",x),j.json({success:!1,error:x.message},500)}}),$};import{Hono as R0}from"hono";var fx=q("Service"),ox=()=>{let $=new R0;return $.get("/",async(j)=>{try{let x=lx(),V=dx();return j.json({configured:x,current:V})}catch(x){return fx.error("[ModelsRoutes] Failed to get models:",x),j.json({configured:[],current:null})}}),$.post("/",async(j)=>{try{let x=await j.req.json(),{provider:V,name:Y,model:X,baseUrl:Z,apiKey:T}=x;if(!X)throw new A("model is required");let _=await t().addModel({provider:V||"openai-compatible",name:Y||X,model:X,baseUrl:Z||void 0,apiKey:T||void 0});return j.json({success:!0,model:_})}catch(x){throw fx.error("[ModelsRoutes] Failed to add model:",x),x}}),$.put("/:modelId",async(j)=>{try{let x=j.req.param("modelId"),V=await j.req.json(),{baseUrl:Y,apiKey:X,model:Z}=V;return await t().updateModel(x,{baseUrl:Y||void 0,apiKey:X||void 0,model:Z||void 0}),j.json({success:!0})}catch(x){throw fx.error("[ModelsRoutes] Failed to update model:",x),x}}),$.delete("/:modelId",async(j)=>{try{let x=j.req.param("modelId");return await t().removeModel(x),j.json({success:!0})}catch(x){throw fx.error("[ModelsRoutes] Failed to delete model:",x),x}}),$};import{Hono as G$}from"hono";import{z as v}from"zod";import x0 from"node:path";import{Mutex as d0}from"async-mutex";import{Hono as o0}from"hono";import{streamSSE as c0}from"hono/streaming";import{LRUCache as t0}from"lru-cache";import{nanoid as Mx}from"nanoid";import{z as B}from"zod";import{z as M}from"zod";var tx=M.enum(["default","autoEdit","yolo","plan"]);var Wx=M.enum(["user","assistant","system","tool"]),ax=M.union([M.object({type:M.literal("text"),text:M.string()}),M.object({type:M.literal("image_url"),image_url:M.object({url:M.string()})})]),Uj=M.object({id:M.string(),role:Wx,content:M.union([M.string(),M.array(ax)]),timestamp:M.number(),metadata:M.record(M.unknown()).optional(),thinkingContent:M.string().optional(),tool_call_id:M.string().optional(),name:M.string().optional(),tool_calls:M.unknown().optional()}),g0=M.object({sessionId:M.string(),projectPath:M.string(),title:M.string().optional(),gitBranch:M.string().optional(),rootId:M.string(),parentId:M.string().optional(),relationType:M.enum(["subagent","fork"]).optional(),resumedFrom:M.string().optional(),rootAgentId:M.string().optional(),resumeDepth:M.number().int().nonnegative().optional(),messageCount:M.number(),firstMessageTime:M.string(),lastMessageTime:M.string(),hasErrors:M.boolean()}),Xj=M.object({version:M.literal(1),sessionId:M.string(),goalId:M.string(),objective:M.string(),status:M.enum(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:M.number().optional(),tokensUsed:M.number(),timeUsedSeconds:M.number(),continuationCount:M.number(),statusReason:M.string().optional(),createdAt:M.string(),updatedAt:M.string()}),ix=M.object({role:Wx,content:M.union([M.string(),M.array(ax)]),metadata:M.unknown().optional(),reasoningContent:M.string().optional(),thinkingContent:M.string().optional(),tool_call_id:M.string().optional(),name:M.string().optional(),tool_calls:M.unknown().optional()}),Oj=M.object({session:g0,messages:M.array(ix)}),nx=M.enum(["conversation","code","both"]),I0=M.object({messageId:M.string(),preview:M.string(),createdAt:M.string(),fileCount:M.number().int().nonnegative()}),rx=M.object({targetMessageId:M.string().min(1),mode:nx.default("conversation")}),fj=M.object({checkpoint:I0,mode:nx,removedTurns:M.number().int().positive(),restoredFiles:M.array(M.string()),messages:M.array(ix)}),v0=M.enum(["running","completed","failed","cancelled"]),cx=M.object({id:M.string(),subagentType:M.string(),description:M.string(),status:v0,rootAgentId:M.string(),resumedFrom:M.string().optional(),resumeDepth:M.number().int().nonnegative(),createdAt:M.number(),lastActiveAt:M.number(),completedAt:M.number().optional(),result:M.object({success:M.boolean(),message:M.string(),error:M.string().optional(),verificationCommands:M.array(M.string()).optional()}).optional(),stats:M.object({tokens:M.number().optional(),toolCalls:M.number().optional(),duration:M.number().optional()}).optional()}),sx=M.object({prompt:M.string().trim().min(1).max(32000)}),bj=M.object({source:cx,session:cx}),Nj=M.object({sessionId:M.string(),projectPath:M.string()}),Tj=M.object({type:M.string(),properties:M.record(M.unknown())}),ex=M.object({content:M.string(),projectPath:M.string().optional(),permissionMode:tx.optional(),attachments:M.array(M.object({type:M.enum(["file","image","url"]),path:M.string().optional(),url:M.string().optional(),content:M.string().optional(),mimeType:M.string().optional(),name:M.string().optional()})).optional()}),_j=M.object({messageId:M.string(),role:Wx,content:M.string(),timestamp:M.string()}),yj=M.object({approved:M.boolean(),remember:M.boolean().optional(),scope:M.enum(["once","session","project"]).optional(),targetMode:tx.optional(),feedback:M.string().optional(),answers:M.record(M.union([M.string(),M.array(M.string())])).optional()}),wj=M.object({id:M.string(),name:M.string(),provider:M.string(),model:M.string(),baseUrl:M.string().optional(),apiKey:M.string().optional(),maxContextTokens:M.number().optional()}),Kj=M.enum(["vs-dark","vs-light","hc-black"]),u0=M.enum(["light","dark","system"]),l0=M.object({language:M.string(),theme:M.string(),uiTheme:u0,autoSaveSessions:M.boolean(),notifyBuild:M.boolean(),notifyErrors:M.boolean(),notifySounds:M.boolean(),privacyTelemetry:M.boolean(),privacyCrash:M.boolean()}),mj=l0.partial();var D=q("Service"),a0=B.object({title:B.string().optional(),projectPath:B.string().optional()}),i0=ex,n0=B.object({title:B.string().optional(),projectPath:B.string().optional()}),r0=B.object({projectPath:B.string()}),s0=B.object({objective:B.string().min(1),tokenBudget:B.number().int().positive().optional(),permissionMode:B.enum(["default","autoEdit","plan","yolo"]).optional()}),e0=B.discriminatedUnion("action",[B.object({action:B.literal("pause")}),B.object({action:B.literal("resume")}),B.object({action:B.literal("edit"),objective:B.string().min(1)})]),P=new Map,p=new t0({max:100,ttl:1800000,dispose:($,j)=>{if($.status==="running"||$.status==="waiting_permission")$.abortController.abort(),D.debug(`[SessionRoutes] Run ${j} disposed due to cache eviction`)}});function x$($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function Nx($,j="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let x=$.pendingPermission;return $.pendingPermission=void 0,x?.resolve({approved:!1,reason:V0}),$.abortController.abort(j),$.status="cancelled",F.publish(x$($),"run.cancelled",{runId:$.id}),!0}function Q0($,j=!1){let{permissionId:x,details:V}=$;if(V.type==="askUserQuestion"&&V.questions)return{type:"question.required",properties:{requestId:x,toolCallId:x,questions:V.questions,details:V,...j?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:V.toolName,description:V.message,args:V.args,details:V,...j?{replayed:!0}:{}}}}function $$(){for(let $ of p.values())Nx($,"route-reset");p.clear(),P.clear()}var Z0=($)=>{if(!$||typeof $!=="object")return $;let j={...$},x=200000;if(typeof j.oldContent==="string"&&j.oldContent.length>x)delete j.oldContent;if(typeof j.newContent==="string"&&j.newContent.length>x)delete j.newContent;return j};function j$($,j,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)F.publish($,"subagent.update",{subagentSessionId:j,toolName:x.toolCall.function.name}),F.publish($,"subagent.tool.start",{subagentSessionId:j,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)F.publish($,"subagent.tool.result",{subagentSessionId:j,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:!x.result.error,summary:x.result.metadata?.summary,output:Lx(Ex(x.toolCall.function.name,x.result)),metadata:Z0(x.result.metadata)});break;case"content_delta":F.publish($,"subagent.delta",{subagentSessionId:j,delta:x.delta});break;case"thinking_delta":F.publish($,"subagent.thinking.delta",{subagentSessionId:j,delta:x.delta});break;case"stream_end":F.publish($,"subagent.stream.end",{subagentSessionId:j});break;default:break}}function Cx($,j="projectPath"){if(!x0.isAbsolute($))throw new A(`${j} must be absolute`);return x0.resolve($)}function Bx($){try{$0($)}catch(j){throw new A(j instanceof Error?j.message:`Invalid session ID: ${$}`)}}function g($){return{sessionId:$.id,projectPath:$.projectPath}}function Ax($,j){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,messages:j}}function Dx($){return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function l($,j){if(Bx($),j!==void 0){let V=Zx({sessionId:$,projectPath:Cx(j)});if(P.has(C(V)))return V;let Y=await k.findSessionMetadata(V.sessionId,V.projectPath);if(!Y)throw new E("Session",$);return Zx({sessionId:Y.sessionId,projectPath:Y.projectPath})}let x=new Map;for(let V of P.values()){if(V.id!==$)continue;let Y=g(V);x.set(C(Y),Y)}for(let V of await k.listSessions()){if(V.sessionId!==$)continue;let Y=Zx({sessionId:V.sessionId,projectPath:V.projectPath});x.set(C(Y),Y)}if(x.size===0)try{let V=await k.findSessionMetadata($);if(!V)throw new E("Session",$);return Zx({sessionId:V.sessionId,projectPath:V.projectPath})}catch(V){if(V instanceof E)throw V;if(V instanceof Error&&V.message.startsWith("Ambiguous session ID:"))throw new u;throw V}if(x.size>1)throw new u;return x.values().next().value}function Fx($){if(typeof $==="string")return $;return $.filter((j)=>j.type==="text").map((j)=>j.text).join(`
|
|
2
|
-
`)}function V$($,j){let x=(j??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(x.length===0)return $;let V=[];if($.trim())V.push({type:"text",text:$});return V.push(...x),V}var U0=()=>{$$();let $=new o0;$.onError((G,U)=>{if(G instanceof R)return U.json(G.toObject(),G.statusCode);return D.error("[SessionRoutes] Unhandled route error:",G),U.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let j=new Map,x=new Map,V=new Map,Y=new Map,X=(G)=>{let U=C(G),J=Y.get(U);if(!J)J=new d0,Y.set(U,J);return J},Z=async(G)=>{let U=C(g(G)),J=j.get(U);if(J)return J;let Q=x.get(U);if(!Q)Q=Y0.create({sessionId:G.id,workspaceRoot:G.projectPath}),x.set(U,Q);try{let O=await Q;return j.set(U,O),O}finally{if(x.get(U)===Q)x.delete(U)}},T=async(G)=>{let U=C(G),J=P.get(U);if(J)return J;let Q=V.get(U);if(!Q)Q=(async()=>{let O=await k.findSessionMetadata(G.sessionId,G.projectPath);if(!O)throw new E("Session",G.sessionId);let b=Ax(O,await k.loadSession(G.sessionId,G.projectPath));return P.set(U,b),b})(),V.set(U,Q);try{return await Q}finally{if(V.get(U)===Q)V.delete(U)}},_=async(G,U)=>{return T(await l(G,U))},N=(G,U,J,Q={})=>{let O=Mx(12),b={id:O,sessionId:G.id,projectPath:G.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return p.set(O,b),G.currentRunId=O,b.completion=M$(b,G,U,J,Z,{pendingInputOnly:Q.pendingInputOnly,preparedInputTurn:Q.preparedInputTurn,goalContinuationOnly:Q.goalContinuationOnly}).catch((f)=>{D.error(`[SessionRoutes] Run ${O} failed:`,f)}),b},z=async(G)=>{let U=G.currentRunId?p.get(G.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))return;let J=await Z(G),Q=G.currentRunId?p.get(G.currentRunId):void 0;if(Q&&(Q.status==="running"||Q.status==="waiting_permission"))return;let O=J.getPendingSteeringCount()>0,f=(O?null:await J.getGoal())?.status==="active";if(!O&&!f||J.hasTurnOwner())return;N(G,"","default",{pendingInputOnly:O,goalContinuationOnly:f})};return $.get("/",async(G)=>{try{let U=await k.listSessions(),J=new Set(U.filter((K)=>K.relationType==="subagent").map((K)=>C({sessionId:K.sessionId,projectPath:K.projectPath}))),Q=Array.from(P.values()).filter((K)=>!J.has(C(g(K)))&&K.relationType!=="subagent").map((K)=>Dx(K)),O=new Set(Q.map((K)=>C({sessionId:K.sessionId,projectPath:K.projectPath}))),b=U.filter((K)=>{if(K.relationType==="subagent")return!1;return!O.has(C({sessionId:K.sessionId,projectPath:K.projectPath}))}),f=new Set(O),m=b.filter((K)=>{let w=C({sessionId:K.sessionId,projectPath:K.projectPath});if(f.has(w))return!1;return f.add(w),!0}),H=[...Q,...m];return G.json(H)}catch(U){throw D.error("[SessionRoutes] Failed to list sessions:",U),new o("Failed to list sessions")}}),$.post("/",async(G)=>{try{let U=await G.req.json(),J=a0.safeParse(U);if(!J.success)throw new A("Invalid request body");let{title:Q,projectPath:O}=J.data,b=j0("web",12),f=Cx(O||G.get("directory")||L(),O?"projectPath":"directory"),m=await k.createSessionMetadata(b,f,{title:Q}),H=Ax(m,[]);return P.set(C(g(H)),H),G.json({...Dx(H),status:void 0,agentType:void 0,model:void 0})}catch(U){if(D.error("[SessionRoutes] Failed to create session:",U),U instanceof A)throw U;throw new o("Failed to create session")}}),$.post("/:sessionId/fork",async(G)=>{let U=G.req.param("sessionId");try{Bx(U);let J=await G.req.json(),Q=r0.safeParse(J);if(!Q.success)throw new A("Invalid request body");let O=Cx(Q.data.projectPath),b=await k.findSessionMetadata(U,O);if(!b)throw new E("Session",U);let f=await k.forkSession(U,{sourceProjectPath:b.projectPath,targetProjectPath:b.projectPath}),m=Ax(f.metadata,f.messages);return P.set(C(g(m)),m),G.json({session:f.metadata,messages:f.messages},201)}catch(J){if(J instanceof A||J instanceof E||J instanceof a)throw J;if(J instanceof G0)throw new a("Session has no durable creation record");throw D.error("[SessionRoutes] Failed to fork session:",J),new o("Failed to fork session")}}),$.get("/:sessionId",async(G)=>{let U=G.req.param("sessionId");try{let J=await l(U,G.req.query("projectPath")),Q=P.get(C(J));if(Q)return G.json(Dx(Q));let O=await k.findSessionMetadata(J.sessionId,J.projectPath);if(!O)throw new E("Session",U);return G.json(O)}catch(J){if(J instanceof A||J instanceof E||J instanceof u)throw J;throw D.error("[SessionRoutes] Failed to get session:",J),new o("Failed to get session")}}),$.patch("/:sessionId",async(G)=>{let U=G.req.param("sessionId");try{let J=await G.req.json(),Q=n0.safeParse(J);if(!Q.success)throw new A("Invalid request body");if(Q.data.title===void 0)throw new A("title is required");let O=await l(U,Q.data.projectPath),b=await k.updateSessionMetadata(O.sessionId,O.projectPath,{title:Q.data.title}),f=P.get(C(O));if(f)f.title=b.title??f.title,f.updatedAt=new Date(b.lastMessageTime);return G.json({success:!0,title:b.title})}catch(J){if(D.error("[SessionRoutes] Failed to update session:",J),J instanceof A||J instanceof E||J instanceof u)throw J;throw new o("Failed to update session")}}),$.get("/:sessionId/rewind",async(G)=>{let U=await _(G.req.param("sessionId"),G.req.query("projectPath")),J=await Z(U);return G.json({checkpoints:await J.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(G)=>{let U=rx.safeParse(await G.req.json());if(!U.success)throw new A("Invalid rewind request");let J=await _(G.req.param("sessionId"),G.req.query("projectPath")),Q=g(J);return X(Q).runExclusive(async()=>{let O=J.currentRunId?p.get(J.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))throw new a("Cannot rewind while a run is active");let b=await Z(J),f;try{f=await b.rewindSession(U.data)}catch(m){if(m instanceof Error&&m.message.startsWith("Cannot rewind while"))throw new a(m.message);throw m}return J.messages=[...f.messages],J.updatedAt=new Date,F.publish(Q,"session.rewound",{targetMessageId:f.checkpoint.messageId,mode:f.mode,removedTurns:f.removedTurns,restoredFiles:f.restoredFiles,messages:f.messages}),G.json(f)})}),$.get("/:sessionId/subagents",async(G)=>{let U=await _(G.req.param("sessionId"),G.req.query("projectPath")),J=await Z(U);return G.json({subagents:J.listSubagents().map(bx)})}),$.post("/:sessionId/subagents/:agentId/resume",async(G)=>{Bx(G.req.param("agentId"));let U=sx.safeParse(await G.req.json());if(!U.success)throw new A("Invalid subagent resume request");let J=await _(G.req.param("sessionId"),G.req.query("projectPath")),Q=g(J);return X(Q).runExclusive(async()=>{let O=J.currentRunId?p.get(J.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))throw new a("Cannot resume a subagent while a parent run is active");let b=await Z(J),f=!1,m,H=(w)=>{F.publish(Q,"subagent.complete",{subagentSessionId:w.id,success:w.status==="completed",status:w.status,summary:w.result?.message?.slice(0,500),resumedFrom:w.resumedFrom,rootAgentId:w.rootAgentId,resumeDepth:w.resumeDepth})},K;try{K=b.resumeSubagent({agentId:G.req.param("agentId"),prompt:U.data.prompt,onEvent:(w,y)=>{j$(Q,y,w)},onCompleted:(w)=>{if(f)H(w);else m=w}})}catch(w){if(w instanceof Error&&(w.message.startsWith("Cannot resume")||w.message.startsWith("Subagent cannot")))throw new a(w.message);if(w instanceof Error&&w.message.startsWith("Subagent not found"))throw new E(w.message);throw w}if(F.publish(Q,"subagent.start",{subagentSessionId:K.session.id,type:K.session.subagentType,description:K.session.description,resumedFrom:K.source.id,rootAgentId:K.session.rootAgentId,resumeDepth:K.session.resumeDepth}),f=!0,m)H(m);return G.json({source:bx(K.source),session:bx(K.session)})})}),$.get("/:sessionId/goal",async(G)=>{let U=await _(G.req.param("sessionId"),G.req.query("projectPath"));return G.json({goal:await new M0(U.projectPath,U.id).get()})}),$.put("/:sessionId/goal",async(G)=>{let U=s0.safeParse(await G.req.json());if(!U.success)throw new A("Invalid goal request");let J=await _(G.req.param("sessionId"),G.req.query("projectPath")),Q=g(J);return X(Q).runExclusive(async()=>{let O=J.currentRunId?p.get(J.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))return G.json({status:"rejected",reason:"run_active"},409);let f=await(await Z(J)).createGoal(U.data);F.publish(Q,"goal.updated",{goal:f});let m=U.data.permissionMode??"default",H=N(J,"",m,{goalContinuationOnly:!0});return G.json({status:"running",runId:H.id,goal:f},202)})}),$.patch("/:sessionId/goal",async(G)=>{let U=e0.safeParse(await G.req.json());if(!U.success)throw new A("Invalid goal update");let J=await _(G.req.param("sessionId"),G.req.query("projectPath")),Q=g(J);return X(Q).runExclusive(async()=>{let O=await Z(J),b;if(U.data.action==="pause")b=await O.pauseGoal();else if(U.data.action==="edit")b=await O.editGoal(U.data.objective);else b=await O.resumeGoal();if(F.publish(Q,"goal.updated",{goal:b}),b.status==="active"&&(!J.currentRunId||!["running","waiting_permission"].includes(p.get(J.currentRunId)?.status??""))){let f=N(J,"","default",{goalContinuationOnly:!0});return G.json({status:"running",runId:f.id,goal:b},202)}return G.json({status:b.status,goal:b})})}),$.delete("/:sessionId/goal",async(G)=>{let U=await _(G.req.param("sessionId"),G.req.query("projectPath")),J=g(U),O=await(await Z(U)).clearGoal();if(O)F.publish(J,"goal.cleared",{});return G.json({cleared:O})}),$.delete("/:sessionId",async(G)=>{let U=G.req.param("sessionId"),J=G.req.query("projectPath");try{let Q=await l(U,J),O=C(Q),b=P.get(O),f=j.get(O),m;if(b?.currentRunId){let H=p.get(b.currentRunId);if(H)Nx(H),await H.completion,m=H.id}if(f)await f.clearGoal().catch((H)=>{D.warn("[SessionRoutes] Failed to clear session goal:",H)});if(await k.deleteSession(Q.sessionId,Q.projectPath),m)p.delete(m);if(P.delete(O),V.delete(O),x.delete(O),Y.delete(O),f){if(await f.dispose(),j.delete(O),j.size===0)await i.getInstance().disconnectAll()}return G.json({success:!0})}catch(Q){if(D.error("[SessionRoutes] Failed to delete session:",Q),Q instanceof A||Q instanceof E||Q instanceof u)throw Q;throw new o("Failed to delete session")}}),$.get("/:sessionId/message",async(G)=>{let U=G.req.param("sessionId");try{let J=await l(U,G.req.query("projectPath")),Q=P.get(C(J)),O=Q?.messages?Q.messages:await k.loadSession(J.sessionId,J.projectPath);return G.json(O)}catch(J){if(D.error("[SessionRoutes] Failed to get messages:",J),J instanceof A||J instanceof E||J instanceof u)throw J;throw new o("Failed to get messages")}}),$.get("/:sessionId/events",async(G)=>{let U=G.req.param("sessionId"),J=await l(U,G.req.query("projectPath")),Q=await T(J);return c0(G,async(O)=>{let f,m,H=!1,K=()=>{if(m!==void 0)clearInterval(m),m=void 0;f?.(),f=void 0},w=()=>{if(H)return;H=!0,K()},y=new Set;O.onAbort(w),f=F.subscribe((W)=>{if(W.sessionId!==J.sessionId||W.projectPath!==J.projectPath)return;let d=W.properties.requestId;if((W.type==="permission.asked"||W.type==="question.required")&&typeof d==="string"){if(y.has(d))return;y.add(d)}O.writeSSE({data:JSON.stringify({type:W.type,properties:{...W.properties,sessionId:W.sessionId,projectPath:W.projectPath}})}).catch(w)});try{if(O.aborted||H)return;if(await O.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:J.sessionId,projectPath:J.projectPath,timestamp:Date.now()}})}).catch((h)=>{throw w(),h}),O.aborted||H)return;let d=(Q.currentRunId?p.get(Q.currentRunId):void 0)?.pendingPermission;if(d){y.add(d.permissionId);let h=Q0(d,!0);await O.writeSSE({data:JSON.stringify({type:h.type,properties:{...h.properties,sessionId:J.sessionId,projectPath:J.projectPath}})})}z(Q).catch((h)=>{D.error(`[SessionRoutes] Failed to resume pending input for ${U}:`,h)}),m=setInterval(()=>{if(!O.aborted)O.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(w)},15000);while(!O.aborted&&!H)await new Promise((h)=>setTimeout(h,1000))}finally{w()}})}),$.post("/:sessionId/message",async(G)=>{let U=G.req.param("sessionId"),J=await G.req.json(),Q=i0.safeParse(J);if(!Q.success)throw new A("Invalid message format");let{content:O,attachments:b,permissionMode:f,projectPath:m}=Q.data,H=f||"default",K=V$(O,b),w=await _(U,m??G.req.query("projectPath")),y=g(w);return X(y).runExclusive(async()=>{let W=w.currentRunId?p.get(w.currentRunId):void 0;if(W&&(W.status==="running"||W.status==="waiting_permission")){let I=await(await Z(w)).enqueueSteering(K,{allowBeforeTurn:!0});if(!I.accepted)return G.json({status:"rejected",reason:I.reason??"turn_unavailable"},409);let xx=I.messageId??Mx(12),Xx=I.queued;F.publish(y,"message.created",{messageId:xx,role:"user",content:Fx(K)});let zx=I.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(F.publish(y,zx,{runId:W.id,messageId:xx,queued:Xx}),I.delivery==="next_turn"&&W.status!=="running"&&W.status!=="waiting_permission")z(w).catch((p0)=>{D.error(`[SessionRoutes] Failed to wake queued follow-up for ${U}:`,p0)});if(I.delivery==="next_turn")W.pendingFollowUpRequested=!0;return G.json({runId:W.id,messageId:xx,status:I.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:Xx},202)}let h=await(await Z(w)).prepareInputTurn(K);if(!h.accepted)return G.json({status:"rejected",reason:h.reason},h.reason==="queue_full"?429:409);let Jx=N(w,K,H,{preparedInputTurn:h});return G.json({runId:Jx.id,messageId:h.messageId,status:"running"},202)})}),$.post("/:sessionId/abort",async(G)=>{let U=G.req.param("sessionId"),J=await l(U,G.req.query("projectPath")),Q=P.get(C(J));if(Q?.currentRunId){let O=p.get(Q.currentRunId);if(O)Nx(O),await O.completion}return G.json({success:!0})}),$.get("/:sessionId/status",async(G)=>{let U=G.req.param("sessionId"),J=await l(U,G.req.query("projectPath")),Q=P.get(C(J));if(!Q?.currentRunId)return G.json({sessionId:U,projectPath:J.projectPath,status:"idle"});let O=p.get(Q.currentRunId);return G.json({sessionId:U,projectPath:J.projectPath,runId:Q.currentRunId,status:O?.status||"idle"})}),$};async function M$($,j,x,V,Y,X={}){let{abortController:Z,sessionId:T,id:_}=$,N=X.preparedInputTurn?.messageId??Mx(12),G=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:Mx(12),U,J=g(j),Q=(O,b)=>{F.publish(J,O,b)};try{if(!X.pendingInputOnly&&!X.goalContinuationOnly)Q("message.created",{messageId:N,role:"user",content:Fx(x)});if(Q("session.status",{status:"running"}),G)Q("message.created",{messageId:G,role:"assistant",content:""});U=await Y(j);let O=U,b=await J0.createWithRuntime(O,{sessionId:T}),f=async(y)=>{let W=Mx(12),d=300000;$.status="waiting_permission";let h=new Promise((xx)=>{let Xx=setTimeout(()=>{D.warn(`[SessionRoutes] Permission ${W} timed out after 300000ms`),Q("permission.timeout",{requestId:W}),xx({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:W,resolve:(zx)=>{clearTimeout(Xx),xx(zx)},details:y}}),Jx=$.pendingPermission;if(!Jx)throw Error("Permission request was not registered");let mx=Q0(Jx);Q(mx.type,mx.properties),D.info(`[SessionRoutes] Permission request created: ${W}, runId: ${_}`);let I=await h;if(D.info(`[SessionRoutes] Permission response received: ${W}, approved: ${I.approved}`),!Z.signal.aborted)$.status="running";if($.pendingPermission===Jx)$.pendingPermission=void 0;return I},m={messages:[...j.messages],userId:"web-user",sessionId:T,workspaceRoot:j.projectPath,signal:Z.signal,permissionMode:V,confirmationHandler:{requestConfirmation:f}},H=()=>{if(!G)G=Mx(12),Q("message.created",{messageId:G,role:"assistant",content:""});return G},K=async(y)=>{switch(y.kind){case"content_delta":Q("message.delta",{messageId:H(),delta:y.delta});break;case"thinking_delta":Q("thinking.delta",{delta:y.delta});break;case"tool_start":if("function"in y.toolCall)Q("tool.start",{messageId:H(),toolName:y.toolCall.function.name,toolCallId:y.toolCall.id,arguments:y.toolCall.function.arguments,toolKind:y.toolKind});break;case"tool_result":if("function"in y.toolCall)Q("tool.result",{messageId:H(),toolName:y.toolCall.function.name,toolCallId:y.toolCall.id,success:y.result.success,summary:y.result.metadata?.summary,output:Lx(Ex(y.toolCall.function.name,y.result)),metadata:Z0(y.result.metadata)});break;case"token_usage":Q("token.usage",{...y.usage});break;case"turn_start":Q("turn.started",{turn:y.turn,maxTurns:y.maxTurns});break;case"steering_applied":Q("steering.applied",{runId:_,messageIds:y.messageIds,count:y.count,recovered:y.recovered,delivery:y.delivery,queued:O.getPendingSteeringCount()});break;case"follow_up_started":{if(G)Q("message.complete",{messageId:G}),G=void 0;for(let W of y.messages){if(!W.recovered||W.persisted)continue;Q("message.created",{messageId:W.id,role:"user",content:Fx(W.content),recovered:!0})}Q("follow_up.started",{runId:_,queued:y.queued,recovered:y.recovered}),H();break}case"goal_updated":Q("goal.updated",{goal:y.goal});break;case"goal_continuation_started":Q("goal.continuation.started",{goal:y.goal,continuation:y.continuation}),H();break;case"compaction":Q(y.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":Q("model.fallback",{});break;case"task_update":Q("task.updated",{tasks:y.tasks});break;default:break}},w=await qx(b.chatStream(x,m,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly}),K);if(!w.success)throw Error(w.error?.message??"Agent run failed");for(let y=0;y<20;y++){let W=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,O.getPendingSteeringCount()===0){if(!W)break;continue}if(Z.signal.aborted)break;if(w=await qx(b.chatStream("",m,{stream:!0,pendingInputOnly:!0}),K),!w.success)throw Error(w.error?.message??"Agent follow-up failed")}if(j.messages=[...m.messages],j.updatedAt=new Date,Z.signal.aborted||$.status==="cancelled"){Q("session.status",{status:"idle"});return}if(G)Q("message.complete",{messageId:G});Q("thinking.completed",{}),$.status="completed",Q("session.completed",{runId:_,outputTruncated:w.metadata?.outputTruncated??!1}),Q("session.status",{status:"idle"})}catch(O){if(U&&X.preparedInputTurn)await U.finishTurn(X.preparedInputTurn.handle).catch(()=>{return});if(Z.signal.aborted||$.status==="cancelled"){Nx($,"runtime-abort"),Q("session.status",{status:"idle"});return}D.error("[SessionRoutes] Agent execution error:",O),$.status="failed",Q("session.error",{error:O instanceof Error?O.message:"Unknown error"}),Q("session.status",{status:"error"})}}function X0($,j,x){D.info(`[SessionRoutes] Looking for permission ${j} in session ${$.sessionId}`),D.info(`[SessionRoutes] Active runs: ${p.size}`);for(let[V,Y]of p.entries())if(D.info(`[SessionRoutes] Checking run ${V}: sessionId=${Y.sessionId}, projectPath=${Y.projectPath}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===$.sessionId&&Y.projectPath===$.projectPath&&Y.pendingPermission?.permissionId===j)return Y.pendingPermission.resolve(x),D.info(`[SessionRoutes] Permission ${j} responded, runId: ${Y.id}`),!0;return D.error(`[SessionRoutes] Permission not found: ${j}`),!1}var px=q("Service"),Y$=v.object({approved:v.boolean(),remember:v.boolean().optional(),scope:v.enum(["once","session","project"]).optional(),targetMode:v.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:v.string().optional(),answers:v.record(v.union([v.string(),v.array(v.string())])).optional()}),O0=()=>{let $=new G$;return $.post("/:permissionId",async(j)=>{let x=j.req.param("permissionId"),V=j.req.query("sessionId"),Y=j.req.query("projectPath");px.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${V}`);try{let X=await j.req.json(),Z=Y$.safeParse(X);if(!Z.success)throw new A("Invalid permission response format");let{approved:T,remember:_,scope:N,targetMode:z,feedback:G,answers:U}=Z.data;if(!V)throw new A("sessionId query parameter is required");let J=await l(V,Y);if(!X0(J,x,{approved:T,reason:G,scope:N,targetMode:z,feedback:G,answers:U}))throw new E("Permission request",x);return px.info(`[PermissionRoutes] Permission ${x} ${T?"approved":"denied"}`),j.json({success:!0,approved:T,remember:_})}catch(X){if(px.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof A||X instanceof u||X instanceof E||X instanceof R)throw X;throw X}}),$};import{Hono as J$}from"hono";var f0=q("Service"),T0=()=>{let $=new J$;return $.get("/",async(j)=>{try{let x=await b0();return j.json(x)}catch(x){return f0.error("[ProviderRoutes] Failed to list providers:",x),j.json([])}}),$.get("/:provider/models",async(j)=>{let x=j.req.param("provider");try{let V=await N0(x);return j.json(V)}catch(V){return f0.error("[ProviderRoutes] Failed to list models:",V),j.json([])}}),$};import{Hono as Q$}from"hono";import*as n from"node:fs/promises";import{homedir as Z$}from"node:os";import*as _x from"node:path";var s=q("Service"),hx=_x.join(Z$(),".blade","skills-config.json");async function y0(){try{let $=await n.readFile(hx,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function U$($){await n.mkdir(_x.dirname(hx),{recursive:!0}),await n.writeFile(hx,JSON.stringify($,null,2))}async function X$($,j){let x=await y0();if(j)x.disabled=x.disabled.filter((V)=>V!==$);else if(!x.disabled.includes($))x.disabled.push($);await U$(x)}var Gx=null,O$=300000;async function f$(){if(Gx&&Date.now()-Gx.timestamp<O$)return Gx.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok)return s.warn(`GitHub API returned ${$.status}`),Gx?.data||[];let j=await $.json(),x=[];for(let V of j){if(V.type!=="dir")continue;let Y=`Official ${V.name} skill`;try{let X=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(X.ok){let T=(await X.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)Y=T[1].trim().slice(0,100)}}catch{}x.push({name:V.name,description:Y,tag:"Official",author:"Anthropic"})}return Gx={data:x,timestamp:Date.now()},x}catch($){return s.warn("Failed to fetch skills catalog from GitHub:",$),Gx?.data||[]}}var w0=()=>{let $=new Q$;return $.get("/",async(j)=>{try{let x=Tx();await x.initialize();let V=x.getAll(),Y=await y0(),X=V.map((Z)=>({id:Z.name,name:Z.name,enabled:!Y.disabled.includes(Z.name),description:Z.description||"",version:Z.version||"1.0.0",provider:"Local",location:Z.source==="builtin"?"Built-in":Z.basePath,capabilities:["prompts"],allowedTools:Z.allowedTools||[]}));return j.json(X)}catch(x){return s.error("[SkillsRoutes] Failed to get skills:",x),j.json([])}}),$.post("/:name/toggle",async(j)=>{try{let x=j.req.param("name"),V=await j.req.json();return await X$(x,V.enabled),j.json({success:!0,enabled:V.enabled})}catch(x){return s.error("[SkillsRoutes] Failed to toggle skill:",x),j.json({success:!1,error:x.message},500)}}),$.delete("/:name",async(j)=>{try{let x=j.req.param("name"),V=`${process.env.HOME}/.blade/skills/${x}`;return await n.rm(V,{recursive:!0,force:!0}),await Tx().refresh(),j.json({success:!0})}catch(x){return s.error("[SkillsRoutes] Failed to uninstall skill:",x),j.json({success:!1,error:x.message},500)}}),$.post("/install",async(j)=>{try{let x=await j.req.json(),V=_0(),Y=Tx(),X=!1;if(x.source==="catalog"&&x.name){if(X=await V.installOfficialSkill(x.name),!X)return j.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(X=await V.installFromRepo(x.url,x.name),!X)return j.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(X=await V.installFromLocal(x.path,x.name),!X)return j.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 j.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Y.refresh(),j.json({success:!0})}catch(x){return s.error("[SkillsRoutes] Failed to install skill:",x),j.json({success:!1,error:x.message},500)}}),$.get("/catalog",async(j)=>{try{let x=await f$();return j.json(x)}catch(x){return s.error("[SkillsRoutes] Failed to get catalog:",x),j.json([])}}),$};import b$ from"fast-glob";import{Hono as N$}from"hono";import{execSync as T$}from"node:child_process";import{readdir as _$}from"node:fs/promises";import yx from"node:path";var Ux=q("Service"),y$=($)=>{try{return T$("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},w$=[...wx.map(($)=>`${$}/**`),...wx,...Px.map(($)=>`**/${$}`)],K$=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),z0=()=>{let $=new N$;return $.get("/commands",async(j)=>{try{let x=j.req.query("q")||"",V=m0(x).filter((Y)=>!K$.has(Y.command));return j.json(V)}catch(x){return Ux.error("[SuggestionsRoutes] Failed to get command suggestions:",x),j.json([])}}),$.get("/files",async(j)=>{try{let x=j.req.query("q")||"",V=j.get("directory")||L(),Y=Math.min(Number(j.req.query("limit"))||100,1000),Z=(await b$("**/*",{cwd:V,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:w$})).map((N)=>N.replace(/\\/g,"/"));if(!x)return j.json(Z.slice(0,Y));let T=x.toLowerCase(),_=Z.filter((N)=>N.toLowerCase().includes(T)).slice(0,Y);return j.json(_)}catch(x){return Ux.error("[SuggestionsRoutes] Failed to get file suggestions:",x),j.json([])}}),$.get("/files/tree",async(j)=>{try{let x=j.get("directory")||L(),V=j.req.query("path")||"",Y=V?yx.join(x,V):x,Z=(await _$(Y,{withFileTypes:!0})).map((N)=>({name:N.name,path:V?`${V}/${N.name}`:N.name,type:N.isDirectory()?"dir":"file"}));Z.sort((N,z)=>{if(N.type!==z.type)return N.type==="dir"?-1:1;return N.name.localeCompare(z.name)});let T=new Set(wx),_=Z.filter((N)=>{let z=N.name;if(z.startsWith("."))return!1;if(T.has(z))return!1;for(let G of Px)if(z.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return j.json(_)}catch(x){return Ux.error("[SuggestionsRoutes] Failed to get file tree:",x),j.json([])}}),$.get("/files/content",async(j)=>{try{let x=j.req.query("path");if(!x)return j.json({error:"Missing file path"},400);let V=j.get("directory")||L(),Y=yx.resolve(V,x),X=yx.relative(V,Y);if(X.startsWith("..")||yx.isAbsolute(X))return j.json({error:"Invalid file path"},400);let Z=K0(),T=await Z.stat(Y);if(!T?.isFile)return j.json({error:"File not found"},404);let _=200000,N=await Z.readTextFile(Y),z=N.length>_;return j.json({path:x,content:z?N.slice(0,_):N,truncated:z,size:T.size})}catch(x){return Ux.error("[SuggestionsRoutes] Failed to get file content:",x),j.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(j)=>{try{let x=j.get("directory")||L(),V=y$(x);return j.json({branch:V})}catch(x){return Ux.error("[SuggestionsRoutes] Failed to get git info:",x),j.json({branch:null})}}),$};import{Hono as m$}from"hono";var r=q("Service"),Yx=new Map,H0=2097152,W0=65536;function A0(){return typeof globalThis.Bun<"u"}async function z$($,j,x){if(A0()){let{spawn:X}=await import("bun-pty"),Z=X($,j,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:Z.pid,write:(T)=>Z.write(T),resize:(T,_)=>Z.resize(T,_),kill:()=>Z.kill(),onData:(T)=>Z.onData(T),onExit:(T)=>Z.onExit(T)}}let Y=(await import("node-pty")).spawn($,j,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Y.pid,write:(X)=>Y.write(X),resize:(X,Z)=>Y.resize(X,Z),kill:()=>Y.kill(),onData:(X)=>{Y.onData(X)},onExit:(X)=>{Y.onExit(X)}}}var Rx=void 0,Sx;if(A0())try{let{createBunWebSocket:$}=await import("hono/bun"),j=$();Sx=j.upgradeWebSocket,Rx=j.websocket}catch($){r.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function D0($,j){let x=`term-${Date.now()}`;r.info(`[Terminal] New connection: ${x}, cwd: ${$}`);let V=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=V.endsWith("sh")?["-l"]:[],X=await z$(V,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Z={id:x,process:X,cwd:$,buffer:"",subscribers:new Set};if(Yx.set(x,Z),Z.subscribers.add(j),X.onData((T)=>{let _=!1;for(let N of Z.subscribers)try{N.send(T),_=!0}catch{Z.subscribers.delete(N)}if(_)return;if(Z.buffer+=T,Z.buffer.length>H0)Z.buffer=Z.buffer.slice(-H0)}),X.onExit(({exitCode:T})=>{r.info(`[Terminal] Process exited: ${x}, code: ${T}`);for(let _ of Z.subscribers)try{_.close()}catch{}Yx.delete(x)}),Z.buffer){let T=Z.buffer;Z.buffer="";for(let _=0;_<T.length;_+=W0)j.send(T.slice(_,_+W0))}return{session:Z,cleanup:()=>{if(r.info(`[Terminal] Connection closed: ${x}`),Z.subscribers.delete(j),Z.subscribers.size===0){try{Z.process.kill()}catch{}Yx.delete(x)}}}}function q0($,j){$.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 X=Y.searchParams.get("cwd")||j()||L();try{let{session:Z,cleanup:T}=await D0(X,{send:(_)=>x.send(_),close:()=>x.close()});x.on("message",(_)=>{try{Z.process.write(String(_))}catch(N){r.error("[Terminal] Failed to write to PTY:",N)}}),x.on("close",T),x.on("error",T)}catch(Z){r.error("[Terminal] Failed to spawn PTY:",Z),x.close()}})}var C0=()=>{let $=new m$;if($.get("/status",(j)=>{let x=Array.from(Yx.values()).map((V)=>({id:V.id,cwd:V.cwd}));return j.json({active:x.length,terminals:x})}),$.post("/kill/:terminalId",(j)=>{let x=j.req.param("terminalId"),V=Yx.get(x);if(V){try{V.process.kill()}catch{}for(let Y of V.subscribers)Y.close();return Yx.delete(x),j.json({success:!0})}return j.json({success:!1,error:"Terminal not found"},404)}),Sx)$.get("/ws",Sx((j)=>{let x=j.req.query("cwd")||j.get("directory")||L(),V;return{async onOpen(Y,X){try{V=await D0(x,{send:(Z)=>X.send(Z),close:()=>X.close()})}catch(Z){r.error("[Terminal] Failed to spawn PTY:",Z),X.close()}},onMessage(Y){if(!V)return;try{V.session.process.write(String(Y.data))}catch(X){r.error("[Terminal] Failed to write to PTY:",X)}},onClose(){V?.cleanup()}}}));else $.get("/ws",(j)=>{return j.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};var S=q("Service"),gx=[];function E$(){let $=q$(B$(import.meta.url)),j=[e($,"web"),e(L(),"dist/web"),e(L(),"packages/cli/dist/web")];for(let x of j){let V=e(x,"index.html");if(E0(V)){if(Kx(V,"utf-8").includes("/assets/"))return S.debug(`[Server] Found web dist at: ${x}`),x}}return null}function L$(){let $=new H$;$.onError((x,V)=>{if(S.error("[Server] Request error:",x),x instanceof R)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)}),$.use(async(x,V)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return V();let X=x.req.path;if(X==="/"||X.startsWith("/assets/")||X.endsWith(".html")||X.endsWith(".js")||X.endsWith(".css"))return V();let Z=x.req.header("Authorization");if(!Z?.startsWith("Basic "))return x.header("WWW-Authenticate",'Basic realm="Blade Server"'),x.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let T=Buffer.from(Z.slice(6),"base64").toString(),[_,N]=T.split(":"),z=process.env.BLADE_SERVER_USERNAME??"blade";if(_!==z||N!==Y)return x.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),$.use(async(x,V)=>{let Y=x.req.path==="/health"||x.req.path==="/global/health"||x.req.path.startsWith("/assets/");if(!Y)S.debug(`[Server] ${x.req.method} ${x.req.path}`);let X=Date.now();if(await V(),!Y){let Z=Date.now()-X;S.debug(`[Server] ${x.req.method} ${x.req.path} - ${x.res.status} (${Z}ms)`)}}),$.use(W$({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(gx.includes(x))return x;return}})),$.use(async(x,V)=>{let Y=x.req.query("directory")||x.req.header("x-blade-directory")||L();try{Y=decodeURIComponent(Y)}catch{}return x.set("directory",Y),V()}),$.route("/global",vx()),$.route("/sessions",U0()),$.route("/configs",Ix()),$.route("/permissions",O0()),$.route("/providers",T0()),$.route("/models",ox()),$.route("/suggestions",z0()),$.route("/terminal",C0()),$.route("/mcp",ux()),$.route("/skills",w0()),$.get("/health",(x)=>{return x.json({healthy:!0,version:Vx()})});let j=E$();if(j)S.info(`[Server] Serving static files from ${j}`),$.get("/assets/*",(x)=>{let V=e(j,x.req.path);if(!E0(V))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${x.req.path}`}},404);let Y=Kx(V),X=C$(V).toLowerCase(),T={".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"}[X]||"application/octet-stream";return new Response(Y,{headers:{"Content-Type":T,"Cache-Control":"public, max-age=31536000, immutable"}})}),$.get("/",(x)=>{let V=e(j,"index.html"),Y=Kx(V,"utf-8");return x.html(Y)}),$.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=e(j,"index.html"),X=Kx(Y,"utf-8");return x.html(X)});else S.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(x)=>{return x.json({message:"Blade API Server",version:Vx(),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"}})}),$.all("*",(x)=>{return x.json({error:{code:"NOT_FOUND",message:`Route not found: ${x.req.path}`}},404)});return $}function p$(){let $=D$(),j=[];for(let x of Object.keys($)){let V=$[x];if(!V)continue;for(let Y of V){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;j.push(Y.address)}}return j}function B0(){return typeof globalThis.Bun<"u"}function F0($,j){let x=globalThis.Bun,V=(X)=>{try{return x.serve({hostname:j.hostname,port:X,fetch:$.fetch,idleTimeout:0,websocket:Rx})}catch(Z){S.error("Failed to start Bun server:",Z);return}},Y=j.port===0?V(4096)??V(0):V(j.port);if(!Y)throw Error(`Failed to start Bun server on port ${j.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function h$($,j){return new Promise((x,V)=>{let Y=A$(async(N,z)=>{let G=new URL(N.url||"/",`http://${N.headers.host}`),U=new Headers;for(let[O,b]of Object.entries(N.headers))if(b)if(Array.isArray(b))for(let f of b)U.append(O,f);else U.set(O,b);let J;if(N.method!=="GET"&&N.method!=="HEAD")J=(await new Promise((b)=>{let f=[];N.on("data",(m)=>f.push(m)),N.on("end",()=>b(Buffer.concat(f)))})).toString();let Q=new Request(G.toString(),{method:N.method,headers:U,body:J});try{let O=await $.fetch(Q);if(z.statusCode=O.status,O.headers.forEach((b,f)=>{z.setHeader(f,b)}),O.body){let b=O.body.getReader(),f=async()=>{let{done:m,value:H}=await b.read();if(m){z.end();return}return z.write(H),f()};await f()}else{let b=await O.text();z.end(b)}}catch(O){S.error("[Server] Node request error:",O),z.statusCode=500,z.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),X=new F$({noServer:!0}),Z=L();q0(X,()=>Z),Y.on("upgrade",(N,z,G)=>{if(new URL(N.url||"/",`http://${N.headers.host}`).pathname==="/terminal/ws")X.handleUpgrade(N,z,G,(J)=>{X.emit("connection",J,N)});else z.destroy()});let T=(N)=>{return new Promise((z,G)=>{Y.once("error",(U)=>{if(U.code==="EADDRINUSE")G(U);else G(U)}),Y.listen(N,j.hostname,()=>{let U=Y.address();if(U&&typeof U==="object")z(U.port);else z(N)})})};(async()=>{let N;if(j.port===0)try{N=await T(4096)}catch{N=await T(0)}else N=await T(j.port);let z=new URL(`http://${j.hostname==="0.0.0.0"?"localhost":j.hostname}:${N}`);x({url:z,port:N,hostname:j.hostname,stop:async()=>{return new Promise((G)=>{X.close(()=>{Y.close(()=>G())})})}})})().catch(V)})}var L0;((iV)=>{let $,j;function x(){if(!j)j=L$();return j}iV.getApp=x;function V(Z){gx=Z.cors??[];let T=x();if(B0())$=F0(T,Z),S.info(`[Server] Blade server listening on ${$.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 _=$;return{url:_.url,port:_.port,hostname:_.hostname,stop:async()=>{if($)await $.stop(),$=void 0,j=void 0,S.info("[Server] Blade server stopped")}}}iV.listen=V;async function Y(Z){gx=Z.cors??[];let T=x();if(B0())$=F0(T,Z),S.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await h$(T,Z),S.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);let _=$;return{url:_.url,port:_.port,hostname:_.hostname,stop:async()=>{if($)await $.stop(),$=void 0,j=void 0,S.info("[Server] Blade server stopped")}}}iV.listenAsync=Y;function X(){return $!==void 0}iV.isRunning=X})(L0||={});export{P$ as f,k$ as g,p$ as h,L0 as i};
|
package/dist/chunk-6811kbxn.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$a as f,Va as a,Wa as b,Ya as c,Za as d,_a as e,ab as g,bb as h,cb as i,db as j,eb as k,fb as l,gb as m,hb as n,ib as o,lb as p,mb as q,nb as r}from"./chunk-48q9msfk.js";import"./chunk-jm2xhnrv.js";import"./chunk-2049tv49.js";import"./chunk-t70aqrm4.js";import"./chunk-4dmdn3a9.js";import"./chunk-6kp3z956.js";import"./chunk-a7yjnqhd.js";import"./chunk-f9ybv4ph.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,e as ConversationState};
|
package/dist/chunk-6js5wp6t.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as y,g as A,h as C,i as D}from"./chunk-67vzgcs5.js";import"./chunk-5be6qr2v.js";import"./chunk-4745ktjj.js";import"./chunk-g7caymjr.js";import"./chunk-1w6tqkxd.js";import"./chunk-0e0z8yc1.js";import{xa as q}from"./chunk-faq7ay4j.js";import"./chunk-r1spf93b.js";import"./chunk-phhmmybg.js";import"./chunk-48q9msfk.js";import"./chunk-jm2xhnrv.js";import"./chunk-2049tv49.js";import"./chunk-t70aqrm4.js";import"./chunk-4dmdn3a9.js";import"./chunk-6kp3z956.js";import"./chunk-a7yjnqhd.js";import"./chunk-f9ybv4ph.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
package/dist/chunk-6kp3z956.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{Zb as U}from"./chunk-a7yjnqhd.js";var g=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],n={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},i={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},h={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},y=(X)=>{return h[X]||{}};import{createAnthropic as M}from"@ai-sdk/anthropic";import{createAzure as S}from"@ai-sdk/azure";import{createDeepSeek as v}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as O}from"@ai-sdk/google";import{createOpenAI as f}from"@ai-sdk/openai";import{createOpenAICompatible as R}from"@ai-sdk/openai-compatible";import{generateText as b,jsonSchema as u,streamText as c}from"ai";var k=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function I(X){return typeof X==="string"&&k.has(X)}function o(X){if(!X.aborted)return;if(I(X.reason))return X.reason;return"user-cancel"}function a(X){if(I(X))return!0;if(!(X instanceof Error))return!1;if(X.name==="AbortError")return!0;if(X instanceof DOMException&&X.name==="AbortError")return!0;if(X.message.includes("aborted"))return!0;return!1}function s(...X){let Q=X.filter(Boolean);if(Q.length===0)return new AbortController().signal;if(Q.length===1)return Q[0];let Z=AbortSignal;if(typeof Z.any==="function")return Z.any(Q);for(let J of Q)if(J.aborted)return J;let B=new AbortController,Y=new Map;for(let J of Q){let W=()=>{B.abort(J.reason);for(let[$,_]of Y)$.removeEventListener("abort",_)};Y.set(J,W)}for(let[J,W]of Y)J.addEventListener("abort",W,{once:!0});return B.signal}function D(X,Q,Z){let B=Z?.throwOnAbort??!1;if(Q?.aborted){if(B)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((Y,J)=>{let W,$=setTimeout(()=>{if(Q&&W)Q.removeEventListener("abort",W);Y()},X);if(Q)W=()=>{if(clearTimeout($),B)J(new DOMException("Aborted","AbortError"));else Y()},Q.addEventListener("abort",W,{once:!0})})}var L=U("Chat");function x(X){let Q=[];for(let Z=0;Z<X.length;Z++){let B=X[Z];if(B.role==="tool")continue;let Y=B.role==="assistant"&&B.tool_calls?.length?B.tool_calls:void 0;if(!Y){Q.push(B);continue}let J=[],W=Z+1;while(W<X.length&&X[W].role==="tool")J.push(X[W]),W++;let $=new Set(Y.map((G)=>G.id)),_=J.filter((G)=>G.tool_call_id&&$.has(G.tool_call_id)),F=new Set(_.flatMap((G)=>G.tool_call_id?[G.tool_call_id]:[]));if($.size===Y.length&&_.length===$.size&&F.size===$.size&&[...F].every((G)=>$.has(G)))Q.push(B,..._);Z=W-1}return Q}function K(X){if(typeof X==="string")return X;return X.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join(`
|
|
2
|
-
`)}function A(X){let Q=X;return Q.text??Q.textDelta??Q.delta}function p(X,Q={}){try{return JSON.parse(X)}catch{return L.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:X}),Q}}class T{model;config;constructor(X){this.config=X,this.model=this.createModel(X),L.debug("[VercelAIChatService] Initialized",{provider:X.provider,model:X.model})}createModel(X){let{provider:Q,apiKey:Z,baseUrl:B,model:Y,customHeaders:J,apiVersion:W}=X;switch(Q){case"openai":return f({apiKey:Z,baseURL:B||void 0,headers:J})(Y);case"anthropic":return M({apiKey:Z,baseURL:B||void 0,headers:J})(Y);case"gemini":{if(B&&!this.isGeminiOfficialUrl(B))return R({name:"gemini",apiKey:Z,baseURL:B,headers:J})(Y);return O({apiKey:Z,baseURL:B||void 0})(Y)}case"google":case"google-generative-ai":case"google-vertex":{if(B&&!this.isGeminiOfficialUrl(B))return R({name:Q,apiKey:Z,baseURL:B,headers:J})(Y);return O({apiKey:Z,baseURL:B||void 0})(Y)}case"azure-openai":{let $=this.extractAzureResourceName(B);if($)return S({apiKey:Z,resourceName:$,apiVersion:W||"2024-08-01-preview"})(Y);let _=this.buildAzureBaseUrl(B,Y);return R({name:"azure-openai",apiKey:Z,baseURL:_,headers:{...J,"api-key":Z},queryParams:{"api-version":W||"2024-08-01-preview"}})(Y)}case"azure":{let $=this.extractAzureResourceName(B);if($)return S({apiKey:Z,resourceName:$,apiVersion:W||"2024-08-01-preview"})(Y);let _=this.buildAzureBaseUrl(B,Y);return R({name:"azure-openai",apiKey:Z,baseURL:_,headers:{...J,"api-key":Z},queryParams:{"api-version":W||"2024-08-01-preview"}})(Y)}case"deepseek":return v({apiKey:Z,baseURL:B||void 0,headers:J})(Y);default:return R({name:Q,apiKey:Z,baseURL:B,headers:J})(Y)}}extractAzureResourceName(X){if(!X)return;let Q=X.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return Q?Q[1]:void 0}buildAzureBaseUrl(X,Q){if(!X)return"";let Z=X.replace(/\/$/,"").replace(/\?.*$/,"");if(Z.includes("/openai/deployments/"))return Z;return`${Z}/openai/deployments/${Q}`}isGeminiOfficialUrl(X){return X.includes("generativelanguage.googleapis.com")||X.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(X){let Q=X?.trim();if(!Q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:Q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}hasNonThinkingToolHistory(X){if(!this.needsThinkingReplayMetadata())return!1;return X.some((Q)=>Q.role==="assistant"&&Boolean(Q.tool_calls?.length)&&!Q.reasoningContent?.trim())}flattenDeepSeekThinkingToolHistory(X){let Q=[],Z,B=()=>{if(!Z)return;Q.push({role:"assistant",content:K(Z.content).trim()||"I will use the requested tool and continue from its result."}),Z=void 0};for(let Y of X){if(Y.role==="system"){B(),Q.push({role:"user",content:`<system>
|
|
3
|
-
${K(Y.content)}
|
|
4
|
-
</system>`});continue}if(Y.role==="assistant"&&Y.tool_calls&&Y.tool_calls.length>0&&Y.reasoningContent?.trim()){B(),Z=Y;continue}if(Y.role==="tool"&&Z){let J=Z.tool_calls?.find(($)=>$.id===Y.tool_call_id),W=J?.type==="function"?J.function:void 0;Q.push({role:"user",content:`Tool result for ${Y.name||W?.name||"tool"}${W?.arguments?`(${W.arguments})`:""}:
|
|
5
|
-
${K(Y.content)}
|
|
6
|
-
|
|
7
|
-
Continue from this tool result.`});continue}B(),Q.push(Y)}return B(),Q}convertMessages(X){let Q=[],Z=this.needsThinkingReplayMetadata(),B=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(X):X;for(let Y of B)if(Y.role==="system")if(Array.isArray(Y.content)){let J=Y.content.find(($)=>$.type==="text"),W={role:"system",content:K(Y.content)};if(J?.providerOptions)W.providerOptions=J.providerOptions;Q.push(W)}else Q.push({role:"system",content:Y.content});else if(Y.role==="user")if(Array.isArray(Y.content)){let J=Y.content.map((W)=>{if(W.type==="text"){let $={type:"text",text:W.text};if(W.providerOptions)$.providerOptions=W.providerOptions;return $}return{type:"image",image:W.image_url.url}});Q.push({role:"user",content:J})}else Q.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.tool_calls&&Y.tool_calls.length>0){let J=Y.tool_calls.map((F)=>{let z=F.function;return{type:"tool-call",toolCallId:F.id,toolName:z?.name||"",input:p(z?.arguments||"{}",{})}}),W=K(Y.content),$=Z&&Y.reasoningContent?.trim()?[{type:"reasoning",text:Y.reasoningContent}]:[],_=this.getThinkingReplayProviderOptions(Y.reasoningContent);if(W){let F={role:"assistant",content:[...$,{type:"text",text:W},...J]};if(_)F.providerOptions=_;Q.push(F)}else if($.length>0){let F={role:"assistant",content:[...$,...J]};if(_)F.providerOptions=_;Q.push(F)}else Q.push({role:"assistant",content:J})}else if(Z&&Y.reasoningContent?.trim()){let J=K(Y.content),W=[{type:"reasoning",text:Y.reasoningContent}];if(J)W.push({type:"text",text:J});let $={role:"assistant",content:W},_=this.getThinkingReplayProviderOptions(Y.reasoningContent);if(_)$.providerOptions=_;Q.push($)}else Q.push({role:"assistant",content:K(Y.content)});else if(Y.role==="tool")Q.push({role:"tool",content:[{type:"tool-result",toolCallId:Y.tool_call_id,toolName:Y.name||"unknown",output:{type:"text",value:K(Y.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let Y=0;for(let J of Q)if(J.role==="system"&&Y<2)J.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},Y++;for(let J=Q.length-1;J>=0;J--)if(Q[J].role==="user"){Q[J].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return Q}convertTools(X){if(!X||X.length===0)return;let Q={};for(let Z of X)Q[Z.name]={description:Z.description,inputSchema:u(Z.parameters)};return Q}convertToolCalls(X){return X.map((Q)=>({id:Q.toolCallId,type:"function",function:{name:Q.toolName,arguments:JSON.stringify(Q.args??Q.input??{})}}))}convertUsage(X,Q){if(!X)return;let Z=X.promptTokens??X.inputTokens??0,B=X.completionTokens??X.outputTokens??0,Y={promptTokens:Z,completionTokens:B,totalTokens:X.totalTokens??Z+B};if(X.reasoningTokens)Y.reasoningTokens=X.reasoningTokens;if(Q?.anthropic){if(Q.anthropic.cacheCreationInputTokens!==void 0)Y.cacheCreationInputTokens=Q.anthropic.cacheCreationInputTokens;if(Q.anthropic.cacheReadInputTokens!==void 0)Y.cacheReadInputTokens=Q.anthropic.cacheReadInputTokens}return Y}isFallbackableError(X){let Q=[],Z=new Set,B=X;while(B&&!Z.has(B)){if(Q.push(B),Z.add(B),typeof B!=="object")break;let $=B;B=$.lastError??$.cause}let Y=Q.filter(($)=>$ instanceof Error).map(($)=>$.message.toLowerCase()),J=Y.join(`
|
|
8
|
-
`);if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some(($)=>J.includes($)))return!1;let W=["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up","connection reset","connection refused"];if(W.some(($)=>J.includes($)))return!0;for(let $ of Q){if(!$||typeof $!=="object")continue;let _=$,F=_.status??_.statusCode??_.response?.status??_.response?.statusCode;if(F!==void 0&&([408,409,429].includes(F)||F>=500))return!0;let z=_.code;if(typeof z==="string"&&W.some((G)=>z.toLowerCase().includes(G)))return!0}for(let $ of Y){let _=$.match(/\bstatus(?:\s+code)?[:\s]*(\d{3})\b/),F=_?Number(_[1]):void 0;if(F!==void 0&&([408,409,429].includes(F)||F>=500))return!0}return!1}async retryWithBackoff(X,Q,Z=2,B=1000){let Y;for(let J=0;J<=Z;J++)try{return await X()}catch(W){if(Y=W,Q?.aborted)await D(0,Q,{throwOnAbort:!0});if(J>=Z)break;if(!this.isFallbackableError(W))throw W;let $=B*Math.pow(2,J);L.debug(`[VercelAIChatService] Retry ${J+1}/${Z} after ${$}ms`),await D($,Q,{throwOnAbort:!0})}throw Y}getFallbackModelIds(){let X=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)X.push(...this.config.fallbackModels);else if(this.config.fallbackModel)X.push(this.config.fallbackModel);return X}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let X=this.config.thinkingMode??"budget";if(X==="off")return;let Q=X==="adaptive",Z=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:Q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Z}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:Q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Z}}};return}getStreamTextOptions(X,Q,Z,B,Y,J=Boolean(Y?.toolChoice)){let W=B;if(this.config.timeout&&this.config.timeout>0){let F=AbortSignal.timeout(this.config.timeout);if(B)W=AbortSignal.any([B,F]);else W=F}let $={model:X,messages:Q,tools:Z,maxOutputTokens:this.config.maxOutputTokens,maxRetries:0,temperature:this.config.temperature??0,abortSignal:W,allowSystemInMessages:!0,...Y?.toolChoice?{toolChoice:Y.toolChoice}:{}};if(Y?.toolChoice&&!Z)throw Error(`Required tool is unavailable: ${Y.toolChoice.toolName}`);let _=J?this.getRequiredToolProviderOptions():this.getThinkingProviderOptions();if(_)$.providerOptions=_;return $}getRequiredToolProviderOptions(){if(this.config.provider!=="deepseek"&&!/deepseek/i.test(this.config.model))return;return{deepseek:{thinking:{type:"disabled"}}}}async chat(X,Q,Z,B){let Y=Date.now();L.debug("[VercelAIChatService] Starting chat request");let J=x(X),W=this.convertMessages(J),$=this.convertTools(Q),_=Boolean(B?.toolChoice)||this.hasNonThinkingToolHistory(J),F=async(z)=>{let G=await b(this.getStreamTextOptions(z,W,$,Z,B,_)),P=G.toolCalls&&G.toolCalls.length>0?this.convertToolCalls(G.toolCalls):void 0,H=Array.isArray(G.reasoning)?G.reasoning.map((q)=>q.text).join(""):void 0;return{content:G.text,reasoningContent:H,toolCalls:P,usage:this.convertUsage(G.usage,G.providerMetadata),finishReason:G.finishReason}};try{return await this.retryWithBackoff(()=>F(this.model),Z,this.config.maxRetries)}catch(z){let G=Date.now()-Y;if(L.error("[VercelAIChatService] Chat failed after",G,"ms"),Z?.aborted)await D(0,Z,{throwOnAbort:!0});if(!this.isFallbackableError(z))throw z;let P=this.getFallbackModelIds();if(P.length===0)throw z;for(let H of P){L.warn(`[VercelAIChatService] Trying fallback model: ${H}`);let q=this.createModel({...this.config,model:H});try{return await F(q)}catch(w){if(L.warn(`[VercelAIChatService] Fallback ${H} failed: ${w instanceof Error?w.message:w}`),Z?.aborted)await D(0,Z,{throwOnAbort:!0});if(!this.isFallbackableError(w))throw w}}throw z}}async*streamChat(X,Q,Z,B){let Y=Date.now();L.debug("[VercelAIChatService] Starting stream request");let J=x(X),W=this.convertMessages(J),$=this.convertTools(Q),_=Boolean(B?.toolChoice)||this.hasNonThinkingToolHistory(J),F=async function*(w,N){let V=c(w.getStreamTextOptions(N,W,$,Z,B,_)),E=0;for await(let j of V.fullStream)switch(j.type){case"text-delta":yield{content:A(j)};break;case"reasoning-delta":yield{reasoningContent:A(j)};break;case"tool-call":yield{toolCalls:[{index:E++,id:j.toolCallId,type:"function",function:{name:j.toolName,arguments:JSON.stringify(j.args??j.input??{})}}]};break;case"finish":yield{finishReason:j.finishReason,usage:w.convertUsage(j.totalUsage,j.providerMetadata)};break}},z=this.config.maxRetries??2,G,P=!1;for(let w=0;w<=z;w++)try{for await(let V of F(this,this.model))P=!0,yield V;let N=Date.now()-Y;L.debug("[VercelAIChatService] Stream completed in",N,"ms");return}catch(N){if(G=N,Z?.aborted)await D(0,Z,{throwOnAbort:!0});if(P)throw N;if(!this.isFallbackableError(N))throw N;if(w<z){let V=1000*Math.pow(2,w);L.debug(`[VercelAIChatService] Stream retry ${w+1}/${z} after ${V}ms`),await D(V,Z,{throwOnAbort:!0});continue}}let H=Date.now()-Y;L.error("[VercelAIChatService] Stream failed after",H,"ms");let q=this.getFallbackModelIds();if(q.length===0)throw G;for(let w of q){L.warn(`[VercelAIChatService] Stream fallback: ${w}`),yield{modelFallback:!0};let N=this.createModel({...this.config,model:w}),V=!1;try{for await(let E of F(this,N))V=!0,yield E;return}catch(E){if(L.warn(`[VercelAIChatService] Stream fallback ${w} failed`),Z?.aborted)await D(0,Z,{throwOnAbort:!0});if(V)throw E;if(!this.isFallbackableError(E))throw E}}throw G}getConfig(){return{...this.config}}updateConfig(X){L.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...X},this.model=this.createModel(this.config),L.debug("[VercelAIChatService] Configuration updated")}}var m=U("Service");async function LQ(X){let Q=X;if(Q.provider){let Z=y(Q.provider);if(Object.keys(Z).length>0)Q={...Q,customHeaders:{...Z,...Q.customHeaders}},m.debug(`Injected ${Q.provider} specific headers:`,Object.keys(Z))}return d(Q)}function d(X){return new T(X)}
|
|
9
|
-
export{g as Fb,n as Gb,i as Hb,o as Ib,a as Jb,s as Kb,LQ as Lb};
|