blade-code 0.10.139 → 0.10.141
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-jb4hmk56.js → chunk-0b67y4j1.js} +2 -2
- package/dist/{chunk-5w8pmsqe.js → chunk-0chvj0qt.js} +2 -2
- package/dist/chunk-0s0er9wr.js +1 -0
- package/dist/{chunk-1bqatrxs.js → chunk-28tzj187.js} +1 -1
- package/dist/chunk-2b3j2egw.js +1 -0
- package/dist/{chunk-bgzj85za.js → chunk-34fmx68h.js} +1 -1
- package/dist/{chunk-05cv54r8.js → chunk-3da7sqx6.js} +1 -1
- package/dist/chunk-3kszepm6.js +2 -0
- package/dist/chunk-44edbaa1.js +1 -0
- package/dist/{chunk-mh3ne2sf.js → chunk-4dtshx9v.js} +2 -2
- package/dist/{chunk-dw0mewc2.js → chunk-4pexd8a7.js} +2 -2
- package/dist/{chunk-5qwpdx3n.js → chunk-4w8v677q.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-ft1bdqbs.js → chunk-5q4z0sfr.js} +2 -2
- package/dist/{chunk-gc4kj295.js → chunk-5v3eng7c.js} +1 -1
- package/dist/chunk-5vxhttdq.js +10 -0
- package/dist/{chunk-f4cn6v8t.js → chunk-6w8p6c0g.js} +2 -2
- package/dist/{chunk-25r1v5rn.js → chunk-7azws27d.js} +43 -43
- package/dist/chunk-7g76xzzg.js +2 -0
- package/dist/{chunk-d64b7wta.js → chunk-7wcxjbyg.js} +1 -1
- package/dist/{chunk-5j68055h.js → chunk-7xhw74hk.js} +1 -1
- package/dist/{chunk-t88sfhjj.js → chunk-7xtxvrh8.js} +1 -1
- package/dist/{chunk-esff371k.js → chunk-83je3g6c.js} +3 -3
- package/dist/chunk-8tvf39jm.js +1 -0
- package/dist/{chunk-65c3vjwm.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-6ezffjq1.js → chunk-9tk6wq70.js} +1 -1
- package/dist/{chunk-zx78c1an.js → chunk-9xbwtjac.js} +1 -1
- package/dist/{chunk-40pd090k.js → chunk-ae0fws1f.js} +2 -2
- package/dist/chunk-be1fyzb3.js +181 -0
- package/dist/{chunk-3ekz3zms.js → chunk-cbgsjzdw.js} +2 -2
- package/dist/chunk-enf0egke.js +1 -0
- package/dist/{chunk-az08pq83.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-mtfjwsn2.js → chunk-f2jm4x5q.js} +2 -2
- package/dist/{chunk-bq6d0v5b.js → chunk-f2y0gxyq.js} +2 -2
- package/dist/chunk-f5t7a64t.js +1 -0
- package/dist/{chunk-8py443a5.js → chunk-frvdjy8y.js} +1 -1
- package/dist/{chunk-1h3736q2.js → chunk-fx4xr1g6.js} +365 -361
- package/dist/{chunk-awheqy52.js → chunk-fx9vm1n5.js} +2 -2
- package/dist/{chunk-jy7k2dwm.js → chunk-gm2yfq3r.js} +2 -2
- package/dist/chunk-h273dnvq.js +1 -0
- package/dist/{chunk-2jq9ed09.js → chunk-h5xad96g.js} +1 -1
- package/dist/{chunk-rhwkvx96.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/{chunk-7pg5y3pg.js → chunk-j1pptwsq.js} +1 -1
- package/dist/chunk-j7784bxm.js +1 -0
- package/dist/{chunk-8rccn1y2.js → chunk-jbpasjg9.js} +1 -1
- package/dist/chunk-jr402gf8.js +1 -0
- package/dist/{chunk-dv2m2xe5.js → chunk-jsv3e4k6.js} +1 -1
- package/dist/{chunk-grx6fv9w.js → chunk-k1tfry97.js} +2 -2
- package/dist/{chunk-hrcz179j.js → chunk-k3ne93k8.js} +2 -2
- package/dist/{chunk-mec8yedz.js → chunk-kf9j9z9k.js} +1 -1
- package/dist/{chunk-fbrdcveb.js → chunk-n34qsnks.js} +1 -1
- package/dist/{chunk-earhezc8.js → chunk-n9819k4p.js} +1 -1
- package/dist/{chunk-6j5v5emj.js → chunk-ppp4gpy4.js} +6 -6
- package/dist/{chunk-9m7d3ajv.js → chunk-pv6cgfv1.js} +1 -1
- package/dist/{chunk-zz5n2qxk.js → chunk-pzxg2sdv.js} +1 -1
- package/dist/{chunk-x3c718v5.js → chunk-r5dmdsjb.js} +2 -2
- package/dist/{chunk-a5hkv8er.js → chunk-rv80nkve.js} +2 -2
- package/dist/{chunk-cefmcwyv.js → chunk-ryyzbd76.js} +2 -2
- package/dist/chunk-s56t6kzj.js +2 -0
- package/dist/{chunk-npc7jt96.js → chunk-sd9bze9x.js} +1 -1
- package/dist/{chunk-516adpx6.js → chunk-sdapqhj0.js} +1 -1
- package/dist/chunk-se0q0p3v.js +1 -0
- package/dist/chunk-sz5g7eh5.js +1 -0
- package/dist/{chunk-sdhdn0yx.js → chunk-tp4yy3a6.js} +3 -3
- package/dist/{chunk-04t21rey.js → chunk-tqg9y2p6.js} +1 -1
- package/dist/{chunk-7j4s1nrc.js → chunk-tya95jej.js} +1 -1
- package/dist/{chunk-6qhbdcse.js → chunk-v1mamd1x.js} +2 -2
- package/dist/{chunk-v2fewxvw.js → chunk-v67st2xb.js} +2 -2
- package/dist/chunk-wemdt9n6.js +6 -0
- package/dist/{chunk-3eskgvpy.js → chunk-wm896gnx.js} +1 -1
- package/dist/chunk-yjbpfd3b.js +1 -0
- package/dist/{chunk-qrv72yy6.js → chunk-ze1ra6f9.js} +2 -2
- package/dist/{chunk-sj4gz23a.js → chunk-zj32chp7.js} +1 -1
- package/dist/chunk-znrafpad.js +1 -0
- package/dist/chunk-zqjm9yd8.js +1 -0
- package/dist/{chunk-16648v5c.js → chunk-zrgfvc4k.js} +1 -1
- package/dist/web/assets/ChatView-BBYsaZIk.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-CYhxXWvb.js → CodeBlockHighlighter-BC17_i4m.js} +1 -1
- package/dist/web/assets/{FilePreview-ByTaE1GR.js → FilePreview-DuvfuHLi.js} +1 -1
- package/dist/web/assets/{KanbanBoard-KMmGvNPc.js → KanbanBoard-B-Z7lSaC.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C6lKOJaG.js → MarkdownRenderer-DF-nYnJu.js} +3 -3
- package/dist/web/assets/{ScrollArea-Bo6cZ3PH.js → ScrollArea-dipnxnqf.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-Cymc4xw0.js → SessionHistorySurface-CnMBkiZW.js} +1 -1
- package/dist/web/assets/{SettingsModal-D36xhHwa.js → SettingsModal-DLA1WQ6g.js} +1 -1
- package/dist/web/assets/{Sidebar-DEGQINYb.js → Sidebar-tu4OcImk.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BEISb7-8.js → TaskSwitcher-D2TIUyr3.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B7PXaRGh.js → TerminalPanel-CcJVvSnz.js} +1 -1
- package/dist/web/assets/{archive-Dyn5Oz68.js → archive-EoUobrxu.js} +1 -1
- package/dist/web/assets/{arrow-left-mWU3P1zb.js → arrow-left-Y8E5lnQ1.js} +1 -1
- package/dist/web/assets/{calendar-clock-B6b0Cb3d.js → calendar-clock-Cl0Spu99.js} +1 -1
- package/dist/web/assets/{chevron-right-Cl6g5_0e.js → chevron-right-DmM1dl1s.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-FKryGzO4.js → chevrons-up-down-DFQNAYac.js} +1 -1
- package/dist/web/assets/{clock-3-CfVjvMmA.js → clock-3-D3dzsSrc.js} +1 -1
- package/dist/web/assets/{copy-CIYuf7du.js → copy-BwNmbccC.js} +1 -1
- package/dist/web/assets/{download-DecDFX8n.js → download-DHzGZhJT.js} +1 -1
- package/dist/web/assets/{external-link-DaSwvjf7.js → external-link-Dr_8T3Ah.js} +1 -1
- package/dist/web/assets/{folder-DZtlKvFm.js → folder-DcgRdL_P.js} +1 -1
- package/dist/web/assets/index-BZZUIkal.js +203 -0
- package/dist/web/assets/{pause-Bd-STGLc.js → pause-DXzNhd_w.js} +1 -1
- package/dist/web/assets/{pencil-BoTIqqxX.js → pencil-CYRCKPnu.js} +1 -1
- package/dist/web/assets/{play-C4ctis0t.js → play-CfNxuNSd.js} +1 -1
- package/dist/web/assets/{plus-D08TlGJu.js → plus-DBUPwsji.js} +1 -1
- package/dist/web/assets/session-events-DTVYDdaH.js +29 -0
- package/dist/web/assets/{settings-BGRhMFaU.js → settings-K2UJIIf_.js} +1 -1
- package/dist/web/assets/{team-CPme0l2K.js → team-BoulGGnJ.js} +1 -1
- package/dist/web/assets/{teamService-CVCtTVfY.js → teamService-Cfm0Cd6e.js} +1 -1
- package/dist/web/assets/{terminal-D7GsyYki.js → terminal-C9ZyLrcq.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2agbk8ef.js +0 -1
- package/dist/chunk-2bty4510.js +0 -6
- package/dist/chunk-2f7nr9hh.js +0 -1
- package/dist/chunk-2t9vtt75.js +0 -1
- package/dist/chunk-3aaehgva.js +0 -1
- package/dist/chunk-3t5r41yh.js +0 -1
- package/dist/chunk-5xgyx25z.js +0 -2
- package/dist/chunk-gjc1hhhv.js +0 -1
- package/dist/chunk-gx4seq5c.js +0 -10
- package/dist/chunk-h2gp7smy.js +0 -1
- package/dist/chunk-mc2mr1kn.js +0 -2
- package/dist/chunk-mkckss82.js +0 -1
- package/dist/chunk-ntpwqfy3.js +0 -1
- package/dist/chunk-q82ntq7t.js +0 -1
- package/dist/chunk-recafw5r.js +0 -171
- package/dist/chunk-smjfqtws.js +0 -1
- package/dist/chunk-wazhd8bm.js +0 -1
- package/dist/chunk-wf4s1hp2.js +0 -1
- package/dist/chunk-yvmexv2c.js +0 -2
- package/dist/chunk-z9qv0d6k.js +0 -1
- package/dist/web/assets/ChatView-CQnuGDqk.js +0 -63
- package/dist/web/assets/index-DQaqO-lw.js +0 -203
- package/dist/web/assets/session-events-DKjIMNKI.js +0 -29
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{nh as s}from"./chunk-s56t6kzj.js";import{Ui as M,Vi as i,Xi as o}from"./chunk-514va7ce.js";import{Cj as $1,Gj as $,Hj as Z,Ij as b,Jj as K}from"./chunk-5q4z0sfr.js";import{ek as e}from"./chunk-7xtxvrh8.js";var w=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],B1={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},l=new Map;function I(J,B,j){let Y=new Set;for(let H of J.split(",")){let[k,W]=H.split("/"),V=W?Number.parseInt(W,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${J}"`);let X=B,Q=j;if(k!=="*"&&k!=="")if(k.includes("-")){let[G,Z1]=k.split("-");X=Number.parseInt(G,10),Q=Number.parseInt(Z1,10)}else X=Number.parseInt(k,10),Q=X;if(!Number.isInteger(X)||!Number.isInteger(Q)||X<B||Q>j||X>Q)throw Error(`Invalid cron range "${k}" in field "${J}"`);for(let G=X;G<=Q;G+=V)Y.add(G)}return Y}function u(J){let B=J.trim().split(/\s+/);if(B.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${B.length}`);let[j,Y,H,k,W]=B,V=I(W,w[4].min,w[4].max),X=new Set([...V].map((Q)=>Q===7?0:Q));return{minutes:I(j,w[0].min,w[0].max),hours:I(Y,w[1].min,w[1].max),daysOfMonth:I(H,w[2].min,w[2].max),months:I(k,w[3].min,w[3].max),daysOfWeek:X,domRestricted:H.trim()!=="*",dowRestricted:W.trim()!=="*"}}function K1(J,B){if(!B)return{minute:J.getMinutes(),hour:J.getHours(),dayOfMonth:J.getDate(),month:J.getMonth()+1,dayOfWeek:J.getDay()};let j=l.get(B);if(!j)j=new Intl.DateTimeFormat("en-US",{timeZone:B,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),l.set(B,j);let Y=Object.fromEntries(j.formatToParts(J).filter((H)=>H.type!=="literal").map((H)=>[H.type,H.value]));return{minute:Number(Y.minute),hour:Number(Y.hour),dayOfMonth:Number(Y.day),month:Number(Y.month),dayOfWeek:B1[Y.weekday]??-1}}function Y1(J,B,j){let Y=K1(B,j);if(!J.minutes.has(Y.minute))return!1;if(!J.hours.has(Y.hour))return!1;if(!J.months.has(Y.month))return!1;let H=J.daysOfMonth.has(Y.dayOfMonth),k=J.daysOfWeek.has(Y.dayOfWeek);if(J.domRestricted&&J.dowRestricted)return H||k;if(J.domRestricted)return H;if(J.dowRestricted)return k;return!0}function j1(J,B,j){let Y=u(J),H=new Date(B.getTime());H.setSeconds(0,0),H.setMinutes(H.getMinutes()+1);let k=new Date(B.getTime());k.setFullYear(k.getFullYear()+4);while(H.getTime()<=k.getTime()){if(Y1(Y,H,j))return new Date(H.getTime());H.setMinutes(H.getMinutes()+1)}return null}var d={s:1000,m:60000,h:3600000,d:86400000};function a1(J){let j=J.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!j)return null;let Y=Number.parseInt(j[1],10);if(!Number.isInteger(Y)||Y<=0)return null;let H=j[2]||"m";return Y*d[H]}function H1(J){for(let B of["d","h","m","s"]){let j=d[B];if(J%j===0)return`${J/j}${B}`}return`${Math.round(J/1000)}s`}function U(J,B,j){switch(J.kind){case"cron":{if(!J.cron)return null;try{return j1(J.cron,B,J.timezone)}catch{return null}}case"interval":{if(!J.intervalMs||J.intervalMs<=0)return null;let H=new Date((j??B).getTime()+J.intervalMs);return H.getTime()<=B.getTime()?new Date(B.getTime()+1000):H}case"once":{if(!J.runAt)return null;let Y=new Date(J.runAt);if(Number.isNaN(Y.getTime()))return null;return Y.getTime()>B.getTime()?Y:null}default:return null}}function F(J){switch(J.kind){case"cron":if(!J.cron)return"cron trigger requires a cron expression";try{if(u(J.cron),J.timezone)new Intl.DateTimeFormat("en-US",{timeZone:J.timezone}).format();return null}catch(B){return B instanceof Error?B.message:"invalid cron expression"}case"interval":if(!J.intervalMs||J.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!J.runAt)return"once trigger requires runAt timestamp";let B=new Date(J.runAt);if(Number.isNaN(B.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function t1(J){switch(J.kind){case"cron":return`cron: ${J.cron??"?"}`;case"interval":return`every ${J.intervalMs?H1(J.intervalMs):"?"}`;case"once":return`once at ${J.runAt??"?"}`;default:return"unknown"}}import{mkdir as c1,readFile as g1}from"node:fs/promises";import J1 from"node:path";import{nanoid as n1}from"nanoid";import i1 from"write-file-atomic";var x=160,k1=240,m=$.String({pattern:"^[a-f0-9]{64}$"}),Q1=Z($.Object({id:$.String({minLength:1,maxLength:128}),position:$.Integer({minimum:0,maximum:x-1}),queuedAt:$.String({minLength:20,maxLength:32}),kind:K(["user","internal"]),state:K(["pending","locked"]),delivery:K(["current_turn","next_turn","recovery"]),mutable:$.Boolean(),preview:$.Optional($.String({maxLength:k1})),previewTruncated:$.Boolean(),attachmentCount:$.Integer({minimum:0,maximum:20})},{additionalProperties:!1})),h=Z($.Object({version:m,pending:$.Integer({minimum:0,maximum:x}),mutable:$.Integer({minimum:0,maximum:x}),locked:$.Integer({minimum:0,maximum:x}),internal:$.Integer({minimum:0,maximum:x}),items:$.Array(Q1,{maxItems:x})},{additionalProperties:!1})),X1=$.Union([$.Object({type:$.Literal("remove"),messageId:$.String({minLength:1,maxLength:128})},{additionalProperties:!1}),$.Object({type:$.Literal("move"),messageId:$.String({minLength:1,maxLength:128}),toPosition:$.Integer({minimum:0,maximum:x-1})},{additionalProperties:!1})]),T1=Z($.Object({expectedVersion:m,operation:X1},{additionalProperties:!1})),p1=Z($.Object({snapshot:h},{additionalProperties:!1})),b1=K(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]),e1=Z($.Object({error:$.Object({code:b1,message:$.String({minLength:1,maxLength:256})},{additionalProperties:!1}),snapshot:h},{additionalProperties:!1}));var G1=K(["preferences","conventions","lessons","debugging"]),W1=$.Object({outcome:K(["nothing_to_store","disabled","failed"]),entries:$.Literal(0),topics:$.Tuple([])},{additionalProperties:!1}),V1=$.Object({outcome:$.Literal("written"),entries:$.Integer({minimum:1,maximum:20}),topics:$.Array(G1,{minItems:1,maxItems:4,uniqueItems:!0})},{additionalProperties:!1}),Z0=Z($.Union([V1,W1]));var c=128,w1=128,D1=8,z1=1e6,x1=8640000000000000,D=$.Integer({minimum:0,maximum:z1}),L=$.Integer({minimum:0,maximum:x1}),O1=$.String({minLength:1,maxLength:c,pattern:"^[^\x00-\x1F]+$"}),q1=K(["starting","thinking","responding","executing_tools","compacting","continuing"]),v1=$.Refine($.Object({name:O1,kind:$.Optional(K(["readonly","write","execute"])),startedAt:L,progress:$.Optional(D),total:$.Optional(D)},{additionalProperties:!1}),(J)=>J.progress===void 0&&J.total===void 0||J.progress!==void 0&&J.total!==void 0&&J.progress<=J.total,()=>"progress and total must be present together with progress <= total"),P1=$.Refine($.Object({phase:q1,startedAt:L,updatedAt:L,turn:D,maxTurns:$.Union([D,$.Null()]),outputStarted:$.Boolean(),toolCallsStarted:D,toolCallsCompleted:D,activeTools:$.Array(v1,{maxItems:D1}),activeToolOverflow:D},{additionalProperties:!1}),(J)=>J.startedAt<=J.updatedAt&&J.toolCallsCompleted<=J.toolCallsStarted&&J.activeTools.length+J.activeToolOverflow<=J.toolCallsStarted-J.toolCallsCompleted,()=>"turn activity snapshot counters and timestamps are inconsistent"),Y0=Z($.Object({version:$.Literal(1),generation:$.String({minLength:1,maxLength:w1,pattern:"^[^\x00-\x1F]+$"}),revision:D,snapshot:$.Union([P1,$.Null()])},{additionalProperties:!1}));function j0(J){let B=[...J].filter((j)=>{let Y=j.codePointAt(0)??0;return Y>31&&Y!==127}).join("").trim().slice(0,c);if(!B)throw Error("Turn activity tool name is empty");return B}var g=16384;function k0(J){let B=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec(J);if(!B)return;return{question:(B[1]??"").trim()}}var O=Z(K(["default","autoEdit","yolo","plan"]));var A=Z(K(["user","assistant","system","tool"])),f1=Z($.Union([$.Object({type:$.Literal("text"),text:$.String()}),$.Object({type:$.Literal("image_url"),image_url:$.Object({url:$.String()})})])),a=$.Union([$.String(),$.Array(f1)]),w0=Z($.Object({id:$.String(),role:A,content:a,timestamp:$.Number(),metadata:$.Optional($.Record($.String(),$.Unknown())),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),I1=Z(K(["queued","running","completed","failed","cancelled","interrupted"])),N=Z(K(["local","worktree"])),R=Z(K(["high","medium","low"])),E=Z(K(["feature","bug","maintenance","research"])),N1=Z(K(["applied","discarded","conflicted"])),C1=Z($.Object({status:N1,updatedAt:$.String(),sourceCommit:$.Optional($.String()),changedFiles:$.Optional($.Integer({minimum:0})),message:$.Optional($.String())})),U1=Z($.Object({changedFiles:$.Integer({minimum:0}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),commits:$.Integer({minimum:0})})),F1=Z($.Object({path:$.String({minLength:1}),patch:$.String({maxLength:2097152}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),binary:$.Boolean(),truncated:$.Boolean()})),D0=Z($.Object({sessionId:$.String(),projectPath:$.String(),baseCommit:$.String(),files:$.Array(F1,{maxItems:100}),truncated:$.Boolean()})),L1=$.Union([$.String(),$.Number(),$.Boolean(),$.Array($.String())]),M1=Z($.Object({name:$.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:$.String(),description:$.Optional($.String()),required:$.Boolean(),defaultValue:$.Optional(L1),options:$.Optional($.Array($.Object({value:$.String(),label:$.String()}))),format:$.Optional(K(["date","uri","email","date-time"])),minimum:$.Optional($.Number()),maximum:$.Optional($.Number()),minLength:$.Optional($.Number()),maxLength:$.Optional($.Number()),minItems:$.Optional($.Number()),maxItems:$.Optional($.Number())})),z0=Z($.Object({serverName:$.String(),mode:K(["form","url"]),message:$.String(),fields:$.Optional($.Array(M1)),requestedSchema:$.Optional($.Record($.String(),$.Unknown())),url:$.Optional($.String()),domain:$.Optional($.String()),elicitationId:$.Optional($.String())})),A1=Z($.Object({type:K(["permission","question","elicitation"]),requestId:$.String()})),R1=Z($.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:$.String({minLength:1,maxLength:500}),retryable:$.Boolean(),resource:$.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),q=Z(K(["auto","off","minimal","low","medium","high","xhigh","max"])),v=Z(K(["auto","standard","fast","flex"])),P=Z(K(["auto","low","medium","high"])),z=Z($.Union([K(["auto","pragmatic","friendly","explanatory"]),$.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),C=Z($.Object({sessionId:$.String(),projectPath:$.String(),title:$.Optional($.String()),gitBranch:$.Optional($.String()),rootId:$.String(),parentId:$.Optional($.String()),relationType:$.Optional(K(["subagent","fork"])),resumedFrom:$.Optional($.String()),rootAgentId:$.Optional($.String()),resumeDepth:$.Optional($.Integer({minimum:0})),taskStatus:b(I1,"completed"),taskStatusReason:$.Optional($.String()),taskFailure:$.Optional(R1),taskStartedAt:$.Optional($.String()),taskCompletedAt:$.Optional($.String()),taskPromptSummary:$.Optional($.String()),taskPriority:$.Optional(R),taskKind:$.Optional(E),taskDueAt:$.Optional($.String()),taskModelId:$.Optional($.String()),selectedModelId:$.Optional($.String()),permissionMode:$.Optional(O),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),communicationStyleDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:$.Optional($.Boolean()),taskRetriedFrom:$.Optional($.Object({sessionId:$.String(),projectPath:$.String()})),taskDelivery:$.Optional(C1),taskIsolation:$.Optional(N),taskSourceProjectPath:$.Optional($.String()),taskWorktreePath:$.Optional($.String()),taskWorktreeBranch:$.Optional($.String()),taskBaseCommit:$.Optional($.String()),taskDiffStat:$.Optional(U1),taskQueuePosition:$.Optional($.Integer({minimum:1})),taskQueueDepth:$.Optional($.Integer({minimum:0})),taskConcurrencyLimit:$.Optional($.Integer({minimum:1})),archivedAt:$.Optional($.String()),archivedBySessionId:$.Optional($.String()),pendingInteraction:$.Optional(A1),messageCount:$.Number(),firstMessageTime:$.String(),lastMessageTime:$.String(),hasErrors:$.Boolean()})),x0=Z($.Object({sessions:$.Array(C),nextCursor:$.Optional($.String())})),O0=Z($.Object({session:C,archivedSessionIds:$.Array($.String())})),q0=Z($.Object({session:C,restoredSessionIds:$.Array($.String())})),v0=Z($.Object({version:$.Union([$.Literal(1),$.Literal(2)]),sessionId:$.String(),goalId:$.String(),objective:$.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:$.Optional($.Number()),tokensUsed:$.Number(),timeUsedSeconds:$.Number(),continuationCount:$.Number(),statusReason:$.Optional($.String()),completionVerification:$.Optional($.Object({attempt:$.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:$.String(),completedAt:$.Optional($.String()),verifierSessionId:$.Optional($.String()),summary:$.Optional($.String()),evidenceSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:$.Optional($.Object({pattern:$.Unsafe({type:"string"}),consecutiveCount:$.Integer({minimum:1}),detectedAt:$.String()})),executionHostFailure:$.Optional($.Object({category:K(s),consecutiveCount:$.Integer({minimum:1,maximum:3}),detectedAt:$.String()},{additionalProperties:!1})),verificationStall:$.Optional($.Unsafe({type:"object"})),executionFrontier:$.Optional($.Object({taskListId:$.String({minLength:1,maxLength:256}),total:$.Integer({minimum:0}),completed:$.Integer({minimum:0}),inProgress:$.Integer({minimum:0}),pending:$.Integer({minimum:0}),blocked:$.Integer({minimum:0}),nextTask:$.Optional($.Object({id:$.String({minLength:1}),subject:$.String({minLength:1,maxLength:512}),priority:K(["high","medium","low"])})),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),observedAt:$.String()})),frontierStall:$.Optional($.Object({category:K(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:$.Integer({minimum:1,maximum:3}),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:$.String()})),createdAt:$.String(),updatedAt:$.String()})),t=Z($.Object({role:A,content:a,metadata:$.Optional($.Unknown()),reasoningContent:$.Optional($.String()),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),P0=Z($.Object({session:C,messages:$.Array(t)})),r=Z(K(["conversation","code","both"])),E1=Z($.Object({messageId:$.String(),preview:$.String(),createdAt:$.String(),fileCount:$.Integer({minimum:0})})),f0=Z($.Object({targetMessageId:$.String({minLength:1}),mode:b(r,"conversation")})),I0=Z($.Object({checkpoint:E1,mode:r,removedTurns:$.Integer({minimum:1}),restoredFiles:$.Array($.String()),messages:$.Array(t)})),_1=K(["running","completed","failed","cancelled"]),n=Z($.Object({id:$.String(),subagentType:$.String(),description:$.String(),status:_1,background:$.Boolean(),rootAgentId:$.String(),resumedFrom:$.Optional($.String()),resumeDepth:$.Integer({minimum:0}),createdAt:$.Number(),lastActiveAt:$.Number(),completedAt:$.Optional($.Number()),restartRecovery:$.Optional($.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:$.Number()})),result:$.Optional($.Object({success:$.Boolean(),message:$.String(),error:$.Optional($.String()),verificationCommands:$.Optional($.Array($.String())),verificationVerdict:$.Optional(K(["pass","fail","partial"])),modifiedFiles:$.Optional($.Array($.String()))})),stats:$.Optional($.Object({tokens:$.Optional($.Number()),toolCalls:$.Optional($.Number()),duration:$.Optional($.Number())}))})),N0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"})})),C0=Z($.Object({source:n,session:n})),U0=Z($.Object({sessionId:$.String(),projectPath:$.String()})),F0=Z($.Object({path:$.String(),name:$.String(),gitBranch:$.Optional($.String()),available:$.Boolean(),isCurrent:$.Boolean(),boundAt:$.String()})),L0=Z($.Union([$.Object({cancelled:$.Literal(!0)}),$.Object({cancelled:$.Literal(!1),path:$.String({minLength:1})})])),M0=Z($.Object({type:$.String(),seq:$.Optional($.Number()),properties:$.Record($.String(),$.Unknown())})),y=$.Object({type:K(["file","image","url"]),path:$.Optional($.String()),url:$.Optional($.String()),content:$.Optional($.String({maxLength:i})),mimeType:$.Optional($.String()),name:$.Optional($.String())}),T=$.Record($.String(),$.Unknown()),A0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:b(R,"medium"),taskKind:b(E,"feature"),taskDueAt:$.Optional($.String({minLength:1,maxLength:64})),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default"),attachments:$.Optional($.Array(y,{maxItems:M})),outputSchema:$.Optional(T)})),R0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:$.Optional(R),taskKind:$.Optional(E),taskDueAt:$.Optional($.Union([$.String({minLength:1,maxLength:64}),$.Null()]))})),E0=Z($.Object({session:C,runId:$.String(),messageId:$.String(),status:K(["queued","running"]),queuePosition:$.Optional($.Integer({minimum:1})),queueDepth:$.Optional($.Integer({minimum:0})),maxConcurrentTasks:$.Optional($.Integer({minimum:1}))})),_0=Z($.Object({action:K(["apply","discard"])})),_=Z($.Object({kind:K(["cron","interval","once"]),cron:$.Optional($.String({minLength:1,maxLength:120})),intervalMs:$.Optional($.Integer({minimum:60000})),runAt:$.Optional($.String({minLength:1,maxLength:40})),timezone:$.Optional($.String({minLength:1,maxLength:80}))})),S1=Z($.Object({modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default")})),S=Z($.Object({id:$.String(),title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:_,dispatch:S1,enabled:$.Boolean(),createdAt:$.String(),updatedAt:$.String(),nextRunAt:$.Union([$.String(),$.Null()]),expiresAt:$.Union([$.String(),$.Null()]),lastRunAt:$.Optional($.String()),lastRunSessionId:$.Optional($.String()),lastStatus:$.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:$.Optional($.String()),runCount:$.Integer({minimum:0})})),S0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:_,modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default"),enabled:b($.Boolean(),!0)})),l0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.Optional($.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:$.Optional(_),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:$.Optional(N),permissionMode:$.Optional(O),enabled:$.Optional($.Boolean())})),u0=Z($.Object({schedules:$.Array(S)})),d0=Z($.Object({content:$.String({maxLength:o}),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),permissionMode:$.Optional(O),attachments:$.Optional($.Array(y,{maxItems:M})),outputSchema:$.Optional(T)})),l1=K(["completed","failed","aborted","timed_out","spawn_error"]),u1=Z($.Object({version:$.Literal(1),command:$.String(),status:l1,exitCode:$.Union([$.Integer(),$.Null()]),durationMs:$.Number({minimum:0}),stdout:$.String(),stderr:$.String(),stdoutOmittedBytes:$.Integer({minimum:0}),stderrOmittedBytes:$.Integer({minimum:0}),binaryOutput:$.Boolean(),truncated:$.Boolean()})),m0=Z($.Object({command:$.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),h0=Z($.Object({executionId:$.String(),messageId:$.String(),record:u1,auxiliary:$.Boolean(),delivery:$.Optional(K(["current_turn","next_turn"])),queued:$.Optional($.Integer({minimum:0}))})),c0=Z($.Object({question:$.String({minLength:1,maxLength:g,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),g0=Z($.Object({response:$.String({minLength:1}),durationMs:$.Number({minimum:0}),modelId:$.Optional($.String()),usage:$.Optional($.Object({promptTokens:$.Number({minimum:0}),completionTokens:$.Number({minimum:0}),totalTokens:$.Number({minimum:0}),reasoningTokens:$.Optional($.Number({minimum:0})),cacheCreationInputTokens:$.Optional($.Number({minimum:0})),cacheReadInputTokens:$.Optional($.Number({minimum:0})),costUsd:$.Optional($.Number({minimum:0}))}))})),n0=Z($.Object({projectPath:$.String(),kind:K(["uncommitted","base","commit"]),ref:$.Optional($.String({maxLength:200})),instructions:$.Optional($.String({maxLength:4000})),modelId:$.Optional($.String({minLength:1,maxLength:200}))})),i0=Z($.Object({reviewId:$.String(),status:$.Literal("running")})),o0=Z($.Object({messageId:$.String(),role:A,content:$.String(),timestamp:$.String()})),s0=Z($.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(K(["once","session","project"])),targetMode:$.Optional(O),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:K(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),d1=Z($.Object({id:z,name:$.String({minLength:1,maxLength:80}),description:$.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),a0=Z($.Object({id:$.String(),displayName:$.Optional($.String()),provider:$.String(),model:$.String(),contextWindow:$.Optional($.Number()),maxTokens:$.Optional($.Number()),reasoning:$.Optional($.Boolean()),supportedReasoningEfforts:$.Optional($.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:$.Optional($.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:$.Optional($.Array(K(["low","medium","high"]))),communicationStyles:$.Optional($.Array(d1,{maxItems:36})),input:$.Optional($.Array(K(["text","image"]))),overrides:$.Optional($.Object({baseUrl:$.Optional($.String()),temperature:$.Optional($.Number()),maxOutputTokens:$.Optional($.Number()),timeout:$.Optional($.Number()),streamIdleTimeout:$.Optional($.Number({minimum:1000}))}))})),t0=Z(K(["vs-dark","vs-light","hc-black"])),m1=Z(K(["light","dark","system"])),h1=Z($.Object({language:$.String(),codeTheme:$.String(),uiTheme:m1,autoSaveSessions:$.Boolean(),notifyBuild:$.Boolean(),notifyErrors:$.Boolean(),notifySounds:$.Boolean(),privacyTelemetry:$.Boolean(),privacyCrash:$.Boolean(),agentTeamsEnabled:$.Boolean(),communicationStyle:$.Optional(z)})),r0=Z($.Partial(h1));var p=$1("Service"),o1=1;function s1(){return J1.join(e(),"schedules.json")}class f{filePath;static instance;static getInstance(){if(!f.instance)f.instance=new f;return f.instance}writeChain=Promise.resolve();constructor(J=s1()){this.filePath=J}async readFile(){try{let J=await g1(this.filePath,"utf-8"),B=JSON.parse(J);if(!B||!Array.isArray(B.schedules))return[];let j=[],Y=0;for(let H of B.schedules){let k=S.safeParse(H);if(k.success)j.push(k.data);else Y+=1}if(Y>0)p.warn(`[ScheduleStore] Ignored ${Y} invalid persisted schedule(s)`);return j}catch(J){let B=J;if(B.code!=="ENOENT")p.warn("[ScheduleStore] Failed to read schedules; treating as empty:",B);return[]}}async writeFile(J){await c1(J1.dirname(this.filePath),{recursive:!0,mode:493});let B={version:o1,schedules:J};await i1(this.filePath,JSON.stringify(B,null,2),{mode:384})}serializeWrite(J){let B=this.writeChain.then(J,J);return this.writeChain=B.then(()=>{return},()=>{return}),B}async list(){return this.readFile()}async get(J){return(await this.readFile()).find((j)=>j.id===J)}async create(J){return this.serializeWrite(async()=>{let B=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,j=F(B);if(j)throw Error(j);let Y=new Date;if(B.kind==="once"&&new Date(B.runAt).getTime()<=Y.getTime())throw Error("once trigger runAt must be in the future");let H=Y.toISOString(),k=U(B,Y),W={id:n1(10),title:J.title,prompt:J.prompt,projectPath:J.projectPath,trigger:B,dispatch:{modelId:J.modelId,reasoningEffort:J.reasoningEffort,serviceTier:J.serviceTier,responseVerbosity:J.responseVerbosity,communicationStyle:J.communicationStyle,isolation:J.isolation??"worktree",permissionMode:J.permissionMode??"default"},enabled:J.enabled??!0,createdAt:H,updatedAt:H,nextRunAt:k?k.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(W),await this.writeFile(V),W})}async update(J,B){return this.serializeWrite(async()=>{let j=await this.readFile(),Y=j.findIndex((Q)=>Q.id===J);if(Y===-1)return;let H=j[Y];if(B.trigger){let Q=B.trigger.kind==="cron"&&!B.trigger.timezone?{...B.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:B.trigger,G=F(Q);if(G)throw Error(G);if(Q.kind==="once"&&new Date(Q.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");B={...B,trigger:Q}}let k={...H,...B,dispatch:B.dispatch?{...H.dispatch,...B.dispatch}:H.dispatch,updatedAt:new Date().toISOString()},W=!H.enabled,V=k.enabled,X=B.trigger!==void 0;if((X||W&&V)&&B.nextRunAt===void 0){let Q=new Date,G=U(k.trigger,Q);if(k.nextRunAt=G?G.toISOString():null,X)k.expiresAt=null}return j[Y]=k,await this.writeFile(j),k})}async remove(J){return this.serializeWrite(async()=>{let B=await this.readFile(),j=B.filter((Y)=>Y.id!==J);if(j.length===B.length)return!1;return await this.writeFile(j),!0})}async setEnabled(J,B){return this.update(J,{enabled:B})}}var W2=f.getInstance();
|
|
2
|
+
export{g as Ra,k0 as Sa,x as Ta,k1 as Ua,m as Va,h as Wa,X1 as Xa,D1 as Ya,Y0 as Za,j0 as _a,Z0 as $a,a1 as ab,U as bb,F as cb,t1 as db,D0 as eb,C as fb,f0 as gb,N0 as hb,A0 as ib,R0 as jb,E0 as kb,_0 as lb,S as mb,S0 as nb,l0 as ob,u0 as pb,d0 as qb,m0 as rb,c0 as sb,n0 as tb,f as ub,W2 as vb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as ug,g as vg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
|
|
2
|
-
export{B as
|
|
2
|
+
export{B as cg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import*as z from"node:os";import*as x from"node:path";function F(){return process.env.BLADE_STORAGE_ROOT||x.join(z.homedir(),".blade")}import{AsyncLocalStorage as Lq}from"node:async_hooks";import{createHash as Vq}from"node:crypto";import{lstat as L,mkdir as Cq,readdir as bq,realpath as N}from"node:fs/promises";import Z from"node:path";import{createHash as Gq}from"node:crypto";var E=new WeakSet,j=new WeakSet,Jq={"not-absolute":"ACP remote file path must be absolute","style-mismatch":"ACP remote file path does not match the expected style","drive-relative":"ACP remote file path cannot be drive-relative","root-relative":"ACP remote file path cannot be root-relative","unc-not-supported":"ACP remote file path must be absolute; UNC paths are not supported","device-namespace-not-supported":"ACP remote file path device namespaces are not supported","trailing-dot-or-space":"ACP remote file path components cannot end with a dot or space","alternate-data-stream":"ACP remote file path alternate data streams are not supported","reserved-device-name":"ACP remote file path reserved device names are not supported","short-name-alias":"ACP remote file path short-name aliases are not supported","invalid-character":"ACP remote file path contains characters that are not supported"},Oq=new Set(["CON","PRN","AUX","NUL","CONIN$","CONOUT$","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9","COM¹","COM²","COM³","LPT¹","LPT²","LPT³"]);class _ extends Error{reason;style;name="AcpRemotePathError";code="acp_remote_path_invalid";constructor(q,G){super(Jq[q]);this.reason=q;this.style=G;Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,reason:this.reason,style:this.style,message:this.message}}}class V extends Error{name="AcpRemotePathIdentityError";code="acp_remote_path_identity_invalid";constructor(){super("ACP remote path identity is invalid");Object.setPrototypeOf(this,new.target.prototype)}}function Qq(q){if(!E.has(q))throw new V}function Uq(q){if(!j.has(q))throw new V;if(Qq(q.workspace),q.style!==q.workspace.style)throw new V}function gq(q){Uq(q);let G=Object.freeze({style:q.style,workspace:q.workspace});return j.add(G),G}function Rq(q){let G=C(q),J=Object.freeze({style:G.style,workspace:G});return j.add(J),J}function C(q,G){let J=W(q,G);if(J.kind==="error")throw new _(J.reason,J.style);let O=J.style==="win32"?Yq(q):Xq(q);return k(J.style,O)}function Sq(q,G){let J=C(q),O=J.style==="win32"?Fq(J.wirePath,G):_q(J.wirePath,G);return k(J.style,O)}function W(q,G){if(R(q))return{kind:"error",reason:"device-namespace-not-supported",style:"win32"};if(g(q))return{kind:"error",reason:"unc-not-supported",style:G==="posix"?"posix":"win32"};if(S(q))return{kind:"error",reason:"unc-not-supported",style:"win32"};if(P(q)){if(G==="posix")return{kind:"error",reason:"style-mismatch",style:"posix"};return{kind:"absolute",style:"win32"}}if(Mq(q))return{kind:"error",reason:"drive-relative",style:"win32"};if(q.startsWith("\\"))return{kind:"error",reason:"root-relative",style:"win32"};if(q.startsWith("/")){if(G==="win32")return{kind:"error",reason:"style-mismatch",style:"win32"};return{kind:"absolute",style:"posix"}}return{kind:"error",reason:"not-absolute",style:"unknown"}}function k(q,G){let J=q==="win32"?G.toUpperCase():G,O=Object.freeze({style:q,wirePath:G,exactIdentity:I("acp-remote-exact-path",q,G),collisionIdentity:I("acp-remote-collision-path",q,J)});return E.add(O),O}function I(q,G,J){return`${q}:${Gq("sha256").update(`${G}\x00${J}`).digest("hex")}`}function Xq(q){let G=q.split("/"),J=[];for(let O of G.slice(1)){if(O.length===0||O===".")continue;if(O===".."){if(J.length>0)J.pop();continue}A(O),J.push(O)}return J.length===0?"/":`/${J.join("/")}`}function Yq(q){let G=q[0].toUpperCase(),J=Bq(q),O=[],Q="";for(let U of q.slice(2)){if(m(U)){if(Q.length>0)v(O,Q),Q="";continue}Q+=U}if(Q.length>0)v(O,Q);if(J&&O.length>0)throw new _("trailing-dot-or-space","win32");if(O.length===0)return`${G}:\\`;return`${G}:\\${O.join("\\")}`}function Zq(q,G){let J=q==="/"?[]:q.slice(1).split("/"),O=[...J];for(let Q of G.split("/")){if(Q.length===0||Q===".")continue;if(Q===".."){if(O.length===J.length)throw new _("not-absolute","posix");O.pop();continue}A(Q),O.push(Q)}return O.length===0?"/":`/${O.join("/")}`}function _q(q,G){if(R(G))throw new _("device-namespace-not-supported","win32");if(g(G))throw new _("unc-not-supported","posix");if(S(G))throw new _("unc-not-supported","win32");if(P(G)||G.startsWith("/"))throw new _("style-mismatch","posix");return Zq(q,G)}function $q(q,G){let J=q.indexOf("\\"),O=J===q.length-1?[]:q.slice(J+1).split("\\"),Q=[...O],U="";for(let K of G){if(m(K)){if(U.length>0)y(O.length,Q,U),U="";continue}U+=K}if(U.length>0)y(O.length,Q,U);let $=q.slice(0,J+1);if(Q.length===0)return $;return`${$}${Q.join("\\")}`}function Fq(q,G){let J=W(G,"win32");if(J.kind==="absolute")throw new _("style-mismatch","win32");if(J.reason!=="not-absolute")throw new _(J.reason,J.style);return $q(q,G)}function y(q,G,J){if(J===".")return;if(J===".."){if(G.length===q)throw new _("not-absolute","win32");G.pop();return}f(J),G.push(J)}function v(q,G){if(G===".")return;if(G===".."){if(q.length>0)q.pop();return}f(G),q.push(G)}function A(q){if(q.includes("\x00"))throw new _("invalid-character","posix")}function f(q){let G=Hq(q),J=Kq(G);if(J!==void 0&&Oq.has(J.toUpperCase()))throw new _("reserved-device-name","win32");if(G!==q)throw new _("trailing-dot-or-space","win32");if(q.includes(":"))throw new _("alternate-data-stream","win32");if(/~\d/u.test(q))throw new _("short-name-alias","win32");for(let O of q){let Q=O.codePointAt(0);if(Q===void 0||Q===0||Q>=1&&Q<=31||'<>"|?*'.includes(O))throw new _("invalid-character","win32")}}function Hq(q){let G=q.length;while(G>0){let J=q[G-1];if(J!=="."&&J!==" ")break;G-=1}return q.slice(0,G)}function Kq(q){if(q.length===0)return;let G=q.indexOf(".");return G===-1?q:q.slice(0,G)}function g(q){return q.startsWith("//")||q.startsWith("/\\")}function R(q){return/^([\\/]){2}[?.][\\/]/u.test(q)}function S(q){return/^[\\/]{2}/u.test(q)}function P(q){return/^[A-Za-z]:[\\/]/u.test(q)}function Mq(q){return/^[A-Za-z]:(?![\\/])/u.test(q)}function m(q){return q==="\\"||q==="/"}function Bq(q){if(q.length<=3)return!1;let G=q[q.length-1];return G==="\\"||G==="/"}var H="acp-remote-workspaces",d=/^[a-f0-9]{64}$/,b=new Map,h=new Lq,Nq;class X extends Error{name="AcpRemoteWorkspaceStateError";code="acp_remote_workspace_state_invalid";constructor(q){super(`ACP remote workspace durable state is invalid (${q})`);Object.setPrototypeOf(this,new.target.prototype)}}function iq(q){return{version:1,kind:"acp-remote",style:q.style,wirePath:q.workspace.wirePath,exactIdentity:q.workspace.exactIdentity,collisionIdentity:q.workspace.collisionIdentity}}function Tq(q){if(!q||typeof q!=="object"||Array.isArray(q))throw new X("descriptor-shape");let G=q;if(G.version!==1)throw new X("descriptor-version");if(G.kind!=="acp-remote")throw new X("descriptor-kind");if(G.style!=="posix"&&G.style!=="win32")throw new X("descriptor-style");if(typeof G.wirePath!=="string"||typeof G.exactIdentity!=="string"||typeof G.collisionIdentity!=="string")throw new X("descriptor-shape");let J;try{J=C(G.wirePath,G.style)}catch{throw new X("descriptor-wire-path")}if(J.exactIdentity!==G.exactIdentity||J.collisionIdentity!==G.collisionIdentity)throw new X("descriptor-identity");return{version:1,kind:"acp-remote",style:G.style,wirePath:J.wirePath,exactIdentity:J.exactIdentity,collisionIdentity:J.collisionIdentity}}function cq(q,G=F()){if(typeof q!=="string"||!/^acp-remote-collision-path:[a-f0-9]{64}$/.test(q))throw new X("descriptor-collision-identity");let J=Z.resolve(G),O=Vq("sha256").update(`acp-remote-host-state\x00${q}`).digest("hex");return Z.join(J,H,O)}async function sq(q){let G=Z.resolve(F());await jq(q,G)}async function rq(q,G){let J=Z.resolve(F());return s(q,J,G)}async function oq(q,G){let J=String(q);if(Z.dirname(G)!==J)throw new X("state-file-path");let O=await L(G);if(O.isSymbolicLink()||!O.isFile())throw new X("state-file-type");if(typeof process.getuid==="function"&&O.uid!==process.getuid())throw new X("state-file-owner");let Q=typeof O.mode==="bigint"?Number(O.mode&BigInt(511)):O.mode&511;if(process.platform!=="win32"&&Q!==384)throw new X("state-file-mode");await M(G,J,Z.basename(G))}async function aq(q,G,J){let O=String(q);if(Z.dirname(G)!==O)throw new X("state-file-path");let[Q,U]=await Promise.all([J.stat({bigint:!0}),L(G,{bigint:!0})]);if(U.isSymbolicLink()||!U.isFile()||!Q.isFile()||U.dev!==Q.dev||U.ino!==Q.ino)throw new X("state-file-replaced");if(typeof process.getuid==="function"&&(Number(U.uid)!==process.getuid()||Number(Q.uid)!==process.getuid()))throw new X("state-file-owner");let $=Number(U.mode&BigInt(511)),K=Number(Q.mode&BigInt(511));if(process.platform!=="win32"&&($!==384||K!==384))throw new X("state-file-mode");await M(G,O,Z.basename(G))}function tq(q,G,J,O){let Q=q[0];if(Q?.type!=="session_created"||Q.sessionId!==G||Q.data.sessionId!==G||Q.cwd!==J||Q.projectPath!==J)throw new X("remote-session-identity");if(O){let U=Tq(Q.data.remoteWorkspace);if(U.version!==O.version||U.kind!==O.kind||U.style!==O.style||U.wirePath!==O.wirePath||U.exactIdentity!==O.exactIdentity||U.collisionIdentity!==O.collisionIdentity)throw new X("remote-session-workspace")}for(let U of q)if(U.sessionId!==G||U.cwd!==J||U.projectPath!==J)throw new X("remote-session-event-identity");return Q}function n(q){return d.test(q)}async function p(q=F()){let G=Z.resolve(q);return u(`${G}\x00${H}`,async()=>{let J=Z.join(G,H),O;try{O=await c(G,(U)=>bq(U,{withFileTypes:!0}))}catch(U){if(U.code==="ENOENT")return[];throw U}await Nq?.();let Q=[];for(let U of O){if(!n(U.name))continue;let $=Z.join(J,U.name);try{let K=await s($,G,async(qq)=>qq);Q.push(K)}catch(K){if(K.code==="ENOENT")throw new X("protected-root-missing");throw K}}return Q.sort((U,$)=>U.localeCompare($))})}function i(q,G){if(typeof q!=="string"||!Z.isAbsolute(q))throw new X("protected-root-shape");let J=Z.resolve(q);if(J!==q)throw new X("protected-root-shape");let O=Z.relative(G,J),Q=`${H}${Z.sep}`;if(O===""||O===H||!O.startsWith(Q)||O.includes(`${Z.sep}..`)||O.startsWith(`..${Z.sep}`)||Z.isAbsolute(O))throw new X("protected-root-shape");let U=O.split(Z.sep);if(U.length!==2||U[0]!==H)throw new X("protected-root-shape");if(!d.test(U[1]??""))throw new X("protected-root-digest");return{storageRoot:G,digest:U[1]}}async function c(q,G){await r(q,q);let J=Z.join(q,H);try{await D(J,q),await M(J,q,H)}catch(O){if(O.code==="ENOENT")throw O;throw O}return G(J)}async function jq(q,G){await u(q,async()=>{let J=i(q,G);if(J.storageRoot!==G)throw new X("storage-root-mismatch");await r(J.storageRoot,G);let O=Z.join(J.storageRoot,H);await l(O,J.storageRoot),await M(O,G,H);let Q=Z.join(O,J.digest);await l(Q,O),await M(Q,O,J.digest)})}async function s(q,G,J){return u(q,async()=>{let O=i(q,G);if(O.storageRoot!==G)throw new X("storage-root-mismatch");let Q=Z.join(O.storageRoot,H);await c(G,async($)=>{if($!==Q)throw new X("protected-root-shape")});let U=Z.join(Q,O.digest);return await D(U,Q),await M(U,Q,O.digest),J(U)})}async function l(q,G){try{let J=await L(q);o(J,q)}catch(J){if(J.code!=="ENOENT")throw J;await Cq(q,{recursive:!1,mode:448})}await D(q,G)}async function D(q,G){let J=await L(q);o(J,q),await M(q,G,Z.basename(q))}async function r(q,G){let J=await L(q);Dq(J,q),await uq(q,G)}function Dq(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&((J&448)!==448||(J&18)!==0))throw new X("protected-root-mode")}function o(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&J!==448)throw new X("protected-root-mode")}function a(q,G){if(q.isSymbolicLink()||!q.isDirectory())throw new X("protected-root-symlink");if(typeof process.getuid==="function"&&q.uid!==process.getuid())throw new X("protected-root-owner");if(G.includes(`..${Z.sep}`))throw new X("protected-root-shape")}function t(q){return typeof q.mode==="bigint"?Number(q.mode&BigInt(511)):q.mode&511}async function M(q,G,J){let O=await N(q),Q=await N(G),U=Z.join(Q,J);if(O!==U)throw new X("protected-root-realpath")}async function uq(q,G){let J=await N(q),O=await N(G);if(J!==O)throw new X("protected-root-realpath")}async function u(q,G){let J=h.getStore();if(J?.has(q))throw new X("state-root-reentry");let O=b.get(q)??Promise.resolve(),Q=new Set(J??[]);Q.add(q);let U=O.catch(()=>{return}).then(()=>h.run(Q,G)),$=U.then(()=>{return},()=>{return});b.set(q,$);try{return await U}finally{if(b.get(q)===$)b.delete(q)}}import{execSync as wq}from"node:child_process";import{createHash as zq}from"node:crypto";import{realpathSync as xq}from"node:fs";import{readdir as Iq}from"node:fs/promises";import*as Y from"node:path";function yq(q){return Y.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function vq(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function Eq(q){let G=yq(q);return Y.join(F(),"projects",G)}function e(q){let G=Y.resolve(q),J=[];while(!0)try{return Y.resolve(xq.native(G),...J.reverse())}catch(O){let Q=O.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw O;let U=Y.dirname(G);if(U===G)return Y.resolve(q);J.push(Y.basename(G)),G=U}}function XG(q,G="projectPath"){if(!Y.isAbsolute(q))throw Error(`${G} must be absolute`);let J=Y.resolve(q),O=e(J),Q=Y.join(e(F()),"acp-remote-workspaces"),U=Y.relative(Q,O),$=U.split(Y.sep)[0];if(U===""||U!==".."&&!Y.isAbsolute(U)&&!U.startsWith(`..${Y.sep}`)&&$!==void 0&&/^[a-f0-9]{64}$/i.test($))throw Error(`${G} must reference a local workspace`);return J}function w(q){return Eq(q)}function T(q){return String(q)}function Wq(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function B(q){if(!Wq(q))throw Error(`Invalid session ID: ${q}`)}function YG(q,G){return B(G),Y.join(w(q),`${G}.jsonl`)}function ZG(q,G){return B(G),Y.join(T(q),`${G}.jsonl`)}function _G(q,G){return B(G),Y.join(w(q),`${G}.inbox.json`)}function $G(q,G){return B(G),Y.join(T(q),`${G}.inbox.json`)}function FG(q,G){return B(G),Y.join(w(q),`${G}.goal.json`)}function HG(q,G){return B(G),Y.join(T(q),`${G}.goal.json`)}function KG(q,G){B(G);let J=zq("sha256").update(G).digest("hex");return Y.join(T(q),`.session-lease-${J}.lock`)}function MG(q){try{return wq("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}async function kq(){try{let q=Y.join(F(),"projects");return(await Iq(q,{withFileTypes:!0})).filter((J)=>J.isDirectory()).map((J)=>J.name)}catch{return[]}}async function BG(){let q=Y.resolve(F()),G=await kq().then((O)=>O.map((Q)=>({storagePath:Y.join(q,"projects",Q),projectPath:vq(Q),kind:"local"}))).catch(()=>[]),J=await p().then((O)=>O.map((Q)=>({storagePath:String(Q),projectPath:String(Q),kind:"acp-remote"})));return[...G,...J]}
|
|
2
|
-
export{F as
|
|
2
|
+
export{F as ek,_ as fk,Qq as gk,Uq as hk,gq as ik,Rq as jk,C as kk,Sq as lk,X as mk,iq as nk,Tq as ok,cq as pk,sq as qk,rq as rk,oq as sk,aq as tk,tq as uk,p as vk,vq as wk,Eq as xk,XG as yk,Wq as zk,B as Ak,YG as Bk,ZG as Ck,_G as Dk,$G as Ek,FG as Fk,HG as Gk,KG as Hk,MG as Ik,kq as Jk,BG as Kk};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{v as HH,w as JH}from"./chunk-
|
|
1
|
+
import{v as HH,w as JH}from"./chunk-4w8v677q.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-34fmx68h.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-zj32chp7.js";import{Aa as yz,Ba as hz,Ca as kz,N as R,W as Az,X as Oz,ca as Ez,fa as qz,ga as Tz,ja as Pz,za as Iz}from"./chunk-fx4xr1g6.js";import"./chunk-zrgfvc4k.js";import{Qa as ez}from"./chunk-h5xad96g.js";import{Sa as Nz,Wa as i,Za as a}from"./chunk-7g76xzzg.js";import{Mb as Kz,Yb as wz,gc as l}from"./chunk-be1fyzb3.js";import{rc as d}from"./chunk-wm896gnx.js";import{Bd as Bz,Ld as I,Md as v,Nd as Gz,Sd as Vz,Vd as jz,Xd as M,_d as Dz,de as Fz,ge as F}from"./chunk-ryyzbd76.js";import"./chunk-9xbwtjac.js";import{Ee as _z,Le as r,Me as Uz}from"./chunk-rv80nkve.js";import"./chunk-fx9vm1n5.js";import{xf as LH}from"./chunk-cbgsjzdw.js";import"./chunk-v1mamd1x.js";import{Sf as oz,Tf as nz}from"./chunk-r5dmdsjb.js";import"./chunk-v508x7cg.js";import{cg as e}from"./chunk-7xhw74hk.js";import{hg as Wz}from"./chunk-k1tfry97.js";import{pg as m}from"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import{ug as sz}from"./chunk-7wcxjbyg.js";import"./chunk-0chvj0qt.js";import"./chunk-6w8p6c0g.js";import"./chunk-3kszepm6.js";import"./chunk-s56t6kzj.js";import{qh as tz}from"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-tp4yy3a6.js";import"./chunk-28tzj187.js";import{ti as az,wi as rz}from"./chunk-ae0fws1f.js";import"./chunk-sd9bze9x.js";import{Ui as g,Vi as Xz,Xi as c,Yi as p}from"./chunk-514va7ce.js";import{aj as t}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import{Cj as y}from"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import{Pj as lz,Sj as iz}from"./chunk-9kj19a8t.js";import"./chunk-f2jm4x5q.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import{ek as $z,fk as dz,jk as zz,nk as Hz,ok as vz,pk as Jz}from"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(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 L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.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.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
|
|
@@ -9,12 +9,12 @@ import{v as HH,w as JH}from"./chunk-5qwpdx3n.js";import{A as S,x as Cz,y as fz,z
|
|
|
9
9
|
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${J.files.length}${J.blockedWrite?" (write retry required)":""}
|
|
10
10
|
`}});break;case"provider_admission":_=J.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":J.phase!=="admitted"?{phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,...J.reason!==void 0?{reason:J.reason}:{},queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:J.phase,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.retryAfterMs!==void 0?{retryAfterMs:J.retryAfterMs}:{},...J.nextProbeAt!==void 0?{nextProbeAt:J.nextProbeAt}:{},openDurationMs:J.openDurationMs,...J.sampleCount!==void 0?{sampleCount:J.sampleCount}:{},...J.failureCount!==void 0?{failureCount:J.failureCount}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.delayMs!==void 0?{delayMs:J.delayMs}:{},...J.nextRetryAt!==void 0?{nextRetryAt:J.nextRetryAt}:{},...J.mode!==void 0?{mode:J.mode}:{},...J.recoveryBudgetMs!==void 0?{recoveryBudgetMs:J.recoveryBudgetMs}:{},...J.recoveryElapsedMs!==void 0?{recoveryElapsedMs:J.recoveryElapsedMs}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{},...J.exhaustedBy!==void 0?{exhaustedBy:J.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":J.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted}}});break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:J.from,to:J.to,candidate:J.candidate,candidateCount:J.candidateCount,trigger:J.trigger}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware}}});break;case"task_update":this.sendPlanUpdate(J.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:J.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:J.goal.goalId,status:J.goal.status,taskListId:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,inProgress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,nextTask:J.frontier.nextTask,digestSha256:J.frontier.digestSha256,...J.goal.frontierStall?{stall:{category:J.goal.frontierStall.category,consecutiveCount:J.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(J.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(J.queue);let D=0;for(let A of J.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of cz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),D++}if(D>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${D} queued instruction${D===1?"":"s"} recovered after restart]
|
|
11
11
|
`}});break}case"goal_updated":if(J.goal)this.sendUpdate(this.goalSessionUpdate(J.goal));if(J.goal&&J.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${J.goal.status}: ${J.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:Cz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let L="preflight",Y=!1,$,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){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(G.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");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(L){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw L}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
|
|
12
|
+
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{},...J.goal.executionHostFailure?{executionHostFailure:{category:J.goal.executionHostFailure.category,consecutiveCount:J.goal.executionHostFailure.consecutiveCount}}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{},...J.memory?{memory:J.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:Cz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let L="preflight",Y=!1,$,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){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(G.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");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(L){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw L}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
|
|
13
13
|
`}),X+=1;if(L.push(Z),Z.type==="text")X+=Z.text.length};for(let Z of z)if(Z.type==="text")H.push(Z.text),Q({type:"text",text:Z.text});else if(Z.type==="image"){let _=`data:${Z.mimeType};base64,${Z.data}`;Y+=1,$+=_.length,H.push(`[Image: ${Z.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if(Z.type==="resource"){let _=Z.resource;if("text"in _){let U=`<file path="${_.uri}">
|
|
14
14
|
${_.text}
|
|
15
15
|
</file>`;H.push(U),Q({type:"text",text:U})}}else if(Z.type==="resource_link"){let _=`[Resource: ${Z.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if($>Xz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
|
|
16
16
|
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=H.join(`
|
|
17
|
-
`);return{content:Y>0?L:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":UH(H.data)}})}sendProviderRecoveryProjection(z){let H=m.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRecovery":H.data}})}sendTurnActivityProjection(z){let H=a.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnActivity":H.data}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((L)=>({content:L.subject,priority:L.priority,status:L.status}));G.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);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let L=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(L))return G.debug(`[AcpSession ${this.id}] Auto-approving ${L} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(L==="write"||L==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${L} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),$=[];if(z.message)$.push({type:"content",content:{type:"text",text:z.message}});if(z.details)$.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)$.push({type:"content",content:{type:"text",text:`Risks:
|
|
17
|
+
`);return{content:Y>0?L:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount,...z.executionHostFailure?{executionHostFailure:{category:z.executionHostFailure.category,consecutiveCount:z.executionHostFailure.consecutiveCount}}:{}}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":UH(H.data)}})}sendProviderRecoveryProjection(z){let H=m.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRecovery":H.data}})}sendTurnActivityProjection(z){let H=a.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnActivity":H.data}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((L)=>({content:L.subject,priority:L.priority,status:L.status}));G.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);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let L=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(L))return G.debug(`[AcpSession ${this.id}] Auto-approving ${L} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(L==="write"||L==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${L} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),$=[];if(z.message)$.push({type:"content",content:{type:"text",text:z.message}});if(z.details)$.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)$.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
18
|
- ${z.risks.join(`
|
|
19
19
|
- `)}`}});let X=this.mapToolKind(L),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:$,kind:X}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),H);if(!W)return{approved:!1,reason:d};let B=W.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let Z=B.optionId;if(Z==="allow_always")return{approved:!0,scope:"project"};if(Z==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let _=Z==="allow_once";return{approved:_,scope:"once",reason:_?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let L=z.questions??[];if(L.length===0)return{approved:!1,reason:"No structured questions were provided"};if(L.some(($)=>$.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[$,X]of L.entries()){let Q=X.options.map((_,U)=>`answer:${$}:${U}`),W=`answer:${$}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((_,U)=>({optionId:Q[U],name:_.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((_)=>`${_.label}: ${_.description}`)].join(`
|
|
20
20
|
`)}}]}}),H);if(!B)return{approved:!1,reason:d};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let Z=Q.indexOf(B.outcome.optionId);if(Z<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[X.header]=X.options[Z].label}return{approved:!0,answers:Y}}catch($){return G.warn(`[AcpSession ${this.id}] Question request failed:`,$),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,H){let L=z.mcpElicitation;if(!L)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(L.mode==="url"){let $=await this.requestElicitationChoice("MCP external authorization",[L.message,`Server: ${L.serverName}`,`Domain: ${L.domain??"unknown"}`,`URL: ${L.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$b as i,Pb as a,Qb as b,Sb as c,Wb as d,Xb as e,Yb as f,Zb as g,_b as h,ac as j,bc as k,jc as l,kc as m,lc as n,mc as o,oc as p,pc as q,qc as r}from"./chunk-be1fyzb3.js";import"./chunk-wm896gnx.js";import"./chunk-ryyzbd76.js";import"./chunk-9xbwtjac.js";import"./chunk-rv80nkve.js";import"./chunk-fx9vm1n5.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-7wcxjbyg.js";import"./chunk-3kszepm6.js";import"./chunk-s56t6kzj.js";import"./chunk-hv8nt7wj.js";import"./chunk-tp4yy3a6.js";import"./chunk-28tzj187.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-f2jm4x5q.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as Pj,p as Qj,u as Rj,S as Sj,c as Tj,l as Uj};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ea as h,Ga as f,Ha as k}from"./chunk-
|
|
1
|
+
import{Ea as h,Ga as f,Ha as k}from"./chunk-zrgfvc4k.js";import"./chunk-sdapqhj0.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var q;((h)=>{h.ReadOnly="readonly";h.Write="write";h.Execute="execute"})(q||={});function w(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function z(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}var j=Symbol("blade.tool-result-model-images");function B(b,c){return Object.defineProperty(b,j,{value:c,enumerable:!1,configurable:!1,writable:!1}),b}function v(b){return b[j]}function C(b,c){let f=b.success?v(b):void 0;return f&&f.length>0?[{type:"text",text:c},...f]:c}function F(b){return b==="readonly"}
|
|
2
|
-
export{q as
|
|
2
|
+
export{q as he,w as ie,z as je,B as ke,C as le,F as me};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ti as K}from"./chunk-sd9bze9x.js";import{Ui as wt,Vi as ft}from"./chunk-514va7ce.js";import{aj as I}from"./chunk-jsv3e4k6.js";import{bj as tt,cj as Dt,dj as Bt,hj as Gt,ij as et,jj as Kt,kj as Ht,lj as Yt,mj as cn,nj as Ft,oj as qt,pj as Mt,qj as Vt,rj as Jt,sj as _t,tj as Qt,uj as jt,vj as Wt,wj as Zt,xj as kt,yj as yt}from"./chunk-n34qsnks.js";import{Cj as Un,Ej as bn,Fj as _n,Gj as T}from"./chunk-5q4z0sfr.js";import{Lj as zt,Oj as v}from"./chunk-0b67y4j1.js";import{Wj as xn,Xj as Cn}from"./chunk-f2jm4x5q.js";import{bk as a}from"./chunk-gm2yfq3r.js";import{ek as Ln}from"./chunk-7xtxvrh8.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${e.map((M)=>` - ${M}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
-
export{B as
|
|
44
|
+
export{B as Dh,nn as Eh,f as Fh,En as Gh,hn as Hh,C as Ih,ot as Jh,VM as Kh,W as Lh,jM as Mh,WM as Nh,ZM as Oh,ct as Ph,Ce as Qh,kM as Rh,he as Sh,yM as Th,Pt as Uh,n_ as Vh,t_ as Wh,M_ as Xh,__ as Yh,r_ as Zh,Ct as _h,S_ as $h,E_ as ai,u_ as bi,o_ as ci,Y as di,Rn as ei,F as fi,q as gi,Xn as hi,V as ii,TM as ji,sM as ki,J as li,Q as mi,h as ni,xM as oi,zn as pi,Dn as qi,hM as ri,Bn as si,Gn as ti,Kn as ui,Hn as vi,Yn as wi,Fn as xi,XM as yi,qn as zi,Vn as Ai,Jn as Bi,Qn as Ci,jn as Di,Wn as Ei,Zn as Fi,kn as Gi,yn as Hi,ln as Ii,vn as Ji,nt as Ki,s as Li,d as Mi,Le as Ni,z as Oi,l as Pi,X as Qi,W_ as Ri};
|