blade-code 0.10.136 → 0.10.137
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-r51afpkk.js → chunk-0c82q1sz.js} +1 -1
- package/dist/chunk-0ccm29qy.js +2 -0
- package/dist/{chunk-na3nregt.js → chunk-0k2x2ae6.js} +1 -1
- package/dist/{chunk-v2qxszks.js → chunk-1evc05gr.js} +1 -1
- package/dist/chunk-35668hyn.js +1 -0
- package/dist/{chunk-13sdjfks.js → chunk-39de5k03.js} +1 -1
- package/dist/chunk-3gmcvd0c.js +1 -0
- package/dist/{chunk-vvawhvea.js → chunk-4jqw75ce.js} +1 -1
- package/dist/chunk-5774a669.js +1 -0
- package/dist/{chunk-qjydadex.js → chunk-5btfnf2r.js} +5 -5
- package/dist/{chunk-91pb41e7.js → chunk-5dwmhsrx.js} +1 -1
- package/dist/{chunk-c5rfnzhf.js → chunk-5sf2rc1z.js} +3 -3
- package/dist/{chunk-sv5z5sna.js → chunk-69nwa6bn.js} +1 -1
- package/dist/{chunk-wj16pvvn.js → chunk-69rjav47.js} +1 -1
- package/dist/{chunk-ntd69c0k.js → chunk-6e3mh79j.js} +1 -1
- package/dist/{chunk-gdnyt8a7.js → chunk-6xvrrypm.js} +1 -1
- package/dist/{chunk-tev70rzj.js → chunk-74bswv4z.js} +2 -2
- package/dist/{chunk-g45camrd.js → chunk-75yy9yre.js} +1 -1
- package/dist/chunk-7n035mhg.js +1 -0
- package/dist/{chunk-hx10bph0.js → chunk-7ykqvsph.js} +1 -1
- package/dist/chunk-9a7bppj7.js +2 -0
- package/dist/{chunk-kbnxbb23.js → chunk-9frd4fpk.js} +1 -1
- package/dist/chunk-a26vtcv5.js +5 -0
- package/dist/{chunk-c85xvthj.js → chunk-affzv7f1.js} +1 -1
- package/dist/chunk-b08thknq.js +1 -0
- package/dist/{chunk-sy0vxdc3.js → chunk-bx75fd0d.js} +311 -311
- package/dist/chunk-bzqbmz6t.js +171 -0
- package/dist/{chunk-77x1rrz9.js → chunk-c2mx5zg0.js} +1 -1
- package/dist/chunk-chspy9f8.js +23 -0
- package/dist/chunk-d6tbr25k.js +1 -0
- package/dist/chunk-dt9n4f4e.js +1 -0
- package/dist/{chunk-82x77b2p.js → chunk-e76gej4y.js} +2 -2
- package/dist/{chunk-g4vgnxh4.js → chunk-e8pfbb6c.js} +1 -1
- package/dist/chunk-ermypm1x.js +2 -0
- package/dist/chunk-esp69w6w.js +1 -0
- package/dist/{chunk-5sknjz9b.js → chunk-etf3e9kt.js} +1 -1
- package/dist/{chunk-1cbaqh71.js → chunk-f2b9cyj5.js} +2 -2
- package/dist/chunk-g1y60ey9.js +1 -0
- package/dist/{chunk-jc28ddt0.js → chunk-g799czsy.js} +1 -1
- package/dist/{chunk-w2n1vwzg.js → chunk-g9vdmvk2.js} +2 -2
- package/dist/chunk-gf5v8aff.js +1 -0
- package/dist/chunk-gpj7k3er.js +6 -0
- package/dist/{chunk-hqwpnb0x.js → chunk-h05qhgrb.js} +1 -1
- package/dist/{chunk-24rsvr6e.js → chunk-h74p51hg.js} +1 -1
- package/dist/{chunk-f7hsagj6.js → chunk-karq4wfd.js} +1 -1
- package/dist/{chunk-9z9v8v4j.js → chunk-ky9br0z8.js} +1 -1
- package/dist/chunk-m9kh7djg.js +6 -0
- package/dist/{chunk-qm96k94k.js → chunk-mavranwn.js} +3 -3
- package/dist/{chunk-6rvrx275.js → chunk-mthf5akx.js} +2 -2
- package/dist/{chunk-jb8stg10.js → chunk-mzye1ah2.js} +1 -1
- package/dist/chunk-na4wzne8.js +1 -0
- package/dist/chunk-ntmkzrs8.js +1 -0
- package/dist/{chunk-1p9sjb8d.js → chunk-nxnmqk4s.js} +1 -1
- package/dist/{chunk-mq1mk3v5.js → chunk-p0gbxaqz.js} +1 -1
- package/dist/chunk-pj15kt5b.js +10 -0
- package/dist/chunk-pv1vwasz.js +1 -0
- package/dist/{chunk-mm1atkae.js → chunk-ramana2t.js} +2 -2
- package/dist/{chunk-1pmvyqed.js → chunk-rgjr7jsd.js} +1 -1
- package/dist/{chunk-0qq64xqm.js → chunk-v5503t2t.js} +3 -3
- package/dist/chunk-vda03kxj.js +1 -0
- package/dist/{chunk-cgkbdh2m.js → chunk-vg3zwv4g.js} +1 -1
- package/dist/chunk-vp6d1fqp.js +3 -0
- package/dist/{chunk-xtngc0th.js → chunk-w9z34f27.js} +1 -1
- package/dist/{chunk-nzwh9v6t.js → chunk-wa71vstt.js} +1 -1
- package/dist/{chunk-ffh4c30x.js → chunk-wc9wsyrc.js} +1 -1
- package/dist/{chunk-bdtpq7j9.js → chunk-wxtj6gqb.js} +1 -1
- package/dist/{chunk-zy2etr3v.js → chunk-wxypv01z.js} +2 -2
- package/dist/{chunk-s3a017q7.js → chunk-xg9fyvw0.js} +2 -2
- package/dist/{chunk-fnc97xg7.js → chunk-xt0ktytp.js} +1 -1
- package/dist/{chunk-46jmq302.js → chunk-y6jee9w7.js} +1 -1
- package/dist/{chunk-yacv7f7h.js → chunk-ybc5myz7.js} +1 -1
- package/dist/{chunk-mxe4pr8t.js → chunk-zk9rf1d7.js} +1 -1
- package/dist/web/assets/ChatView-DpvPjAh7.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-41xRPXs2.js → CodeBlockHighlighter-Czp4VZIg.js} +1 -1
- package/dist/web/assets/{FilePreview-lcc_hL7J.js → FilePreview-BJWuYfyF.js} +7 -7
- package/dist/web/assets/{KanbanBoard-BHgM338V.js → KanbanBoard-DrYzt5Kh.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BMAuTkc6.js → MarkdownRenderer-DxkR5r7t.js} +3 -3
- package/dist/web/assets/{ScrollArea-DJq2Kdpi.js → ScrollArea-D71pJjgW.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DSe8ePBJ.js → SessionHistorySurface-2y9bnndm.js} +1 -1
- package/dist/web/assets/{SettingsModal-Cih4bWul.js → SettingsModal-BbaTL5Rk.js} +1 -1
- package/dist/web/assets/{Sidebar-DnWlUKmO.js → Sidebar-COZltpL9.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-D3mrXv_i.js → TaskSwitcher-3giB7l1P.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BNKHhBVM.js → TerminalPanel-gvTTiTgX.js} +1 -1
- package/dist/web/assets/{archive-Dof4YpyT.js → archive-DndqAA2q.js} +1 -1
- package/dist/web/assets/{arrow-left-DGFXaGox.js → arrow-left-XNYfpUAb.js} +1 -1
- package/dist/web/assets/{calendar-clock-BoxUNOvH.js → calendar-clock-BQOfNcCK.js} +1 -1
- package/dist/web/assets/{chevron-right-Brb1rhaA.js → chevron-right-Cvq3LzHK.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-N-VshXV_.js → chevrons-up-down-Dia1U9Sz.js} +1 -1
- package/dist/web/assets/{clock-3-gdZEKe2U.js → clock-3-CnxLS8cv.js} +1 -1
- package/dist/web/assets/{copy-d9M8JUfQ.js → copy-CWCS3Lql.js} +1 -1
- package/dist/web/assets/{download-CQ-Pwfq0.js → download-DXdsM18t.js} +1 -1
- package/dist/web/assets/{external-link-GRAtjoO2.js → external-link-1IN2ZfaO.js} +1 -1
- package/dist/web/assets/{folder-CqLD0IBh.js → folder-Bpq602dI.js} +1 -1
- package/dist/web/assets/index-57UZsfTt.css +1 -0
- package/dist/web/assets/index-DEOQizD2.js +203 -0
- package/dist/web/assets/{pause-BqsFgQi0.js → pause-BYhoGDZq.js} +1 -1
- package/dist/web/assets/{pencil-Ca9289F-.js → pencil-pRZQVHFU.js} +1 -1
- package/dist/web/assets/{play-DmEPnYDS.js → play-DGZdCyPk.js} +1 -1
- package/dist/web/assets/{plus-kIBLgk0p.js → plus-CAQ3qlUJ.js} +1 -1
- package/dist/web/assets/session-events-C5_Q0kZV.js +29 -0
- package/dist/web/assets/{settings-BuSrJl6s.js → settings-BPfzj_Vf.js} +1 -1
- package/dist/web/assets/{teamService-B7Fp8Oyg.js → teamService-BScT9o9A.js} +1 -1
- package/dist/web/assets/{terminal-Qkr_gcNu.js → terminal-CldJbdMr.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1dscf8xj.js +0 -23
- package/dist/chunk-1n5d6b5k.js +0 -1
- package/dist/chunk-1qdemrkr.js +0 -1
- package/dist/chunk-83nxcfz3.js +0 -1
- package/dist/chunk-9y7j565j.js +0 -6
- package/dist/chunk-acsfh1cw.js +0 -5
- package/dist/chunk-as8stb2j.js +0 -10
- package/dist/chunk-azaqc1b6.js +0 -1
- package/dist/chunk-e1warjkn.js +0 -171
- package/dist/chunk-g13jmewd.js +0 -1
- package/dist/chunk-g7h0peka.js +0 -3
- package/dist/chunk-gq7fdc8c.js +0 -2
- package/dist/chunk-gwjah260.js +0 -1
- package/dist/chunk-n238rdz8.js +0 -1
- package/dist/chunk-nfzad4te.js +0 -2
- package/dist/chunk-pnanbvn3.js +0 -1
- package/dist/chunk-pz91qga3.js +0 -1
- package/dist/chunk-s4b1r3my.js +0 -1
- package/dist/chunk-t6cajkaj.js +0 -6
- package/dist/chunk-tah2002b.js +0 -1
- package/dist/chunk-tzfd2fza.js +0 -1
- package/dist/chunk-v3veeja5.js +0 -1
- package/dist/chunk-vptn8fhx.js +0 -2
- package/dist/chunk-wj813rcc.js +0 -1
- package/dist/web/assets/ChatView-Bc9twpWM.js +0 -63
- package/dist/web/assets/index-CPpIFWLG.css +0 -1
- package/dist/web/assets/index-DiRs2_w4.js +0 -203
- package/dist/web/assets/session-events-BqQQkbAN.js +0 -29
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a5 as e,T as t,a6 as r,p as m}from"./session-events-
|
|
1
|
+
import{a5 as e,T as t,a6 as r,p as m}from"./session-events-C5_Q0kZV.js";import{Z as s}from"./index-DEOQizD2.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-D6QrtXqd.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:r(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:r(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:r(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:r(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(r(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,a,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:a,message:g})})},delete:async(n,i)=>{const a=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${a.toString()}`,{method:"DELETE"}))}};export{u as teamService};
|
package/dist/web/index.html
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>BladeCode</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-DEOQizD2.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-DofNRwfy.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/vendor-radix-D6QrtXqd.js">
|
|
11
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
11
|
+
<link rel="stylesheet" crossorigin href="/assets/index-57UZsfTt.css">
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|
|
14
14
|
<div id="root"></div>
|
package/package.json
CHANGED
package/dist/chunk-1dscf8xj.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{v as ez,w as zJ}from"./chunk-9z9v8v4j.js";import{A as S,x as hz,y as kz,z as Cz}from"./chunk-46jmq302.js";import{B as tz,C as Ez,D as Tz,E as xz,F as bz,G as Rz}from"./chunk-g4vgnxh4.js";import{Aa as yz,Ba as Mz,Ca as Iz,N as R,W as wz,X as Oz,ca as Nz,fa as Az,ga as qz,ja as Pz,za as Sz}from"./chunk-sy0vxdc3.js";import"./chunk-24rsvr6e.js";import{Qa as sz}from"./chunk-hx10bph0.js";import{Sa as Fz,Wa as l}from"./chunk-gq7fdc8c.js";import{Fb as Kz,Rb as Dz,_b as d}from"./chunk-c5rfnzhf.js";import{jc as m}from"./chunk-wzkh3e6a.js";import{Dd as M,Ed as v,Fd as jz,Kd as Gz,Nd as Vz,Pd as y,Sd as Uz,Xd as _z,_d as D,td as Qz}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import{De as i,Ee as Bz,we as Xz}from"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import{pf as JJ}from"./chunk-v2qxszks.js";import"./chunk-kbnxbb23.js";import{Kf as rz,Lf as az}from"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import{Wf as s}from"./chunk-q0s3gcjm.js";import{$f as Hz}from"./chunk-acsfh1cw.js";import"./chunk-tev70rzj.js";import{kg as oz}from"./chunk-vvawhvea.js";import"./chunk-82x77b2p.js";import"./chunk-1cbaqh71.js";import"./chunk-5sknjz9b.js";import{eh as nz}from"./chunk-f7hsagj6.js";import"./chunk-sv5z5sna.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import{hi as lz,ki as iz}from"./chunk-mm1atkae.js";import"./chunk-gdnyt8a7.js";import{Ii as g,Ji as Wz,Li as c,Mi as p}from"./chunk-vptn8fhx.js";import{Qi as n}from"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import{wj as I}from"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import{Dj as vz,Gj as dz}from"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import{Uj as Lz,Vj as pz,Zj as t,bk as e,ck as mz,dk as zz}from"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";import{Readable as KJ,Writable as DJ}from"node:stream";import*as f from"@agentclientprotocol/sdk";import r from"node:path";import{PROTOCOL_VERSION as jJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as fz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=I("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Yz(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function YJ(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Yz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Yz("headers"in z?z.headers:void 0)};return null}function LJ(z){let J={};for(let Z of z){let L=YJ(Z);if(L)J[Z.name]=L}return J}function uz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,L=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!L)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:L[1]??"image/png",data:L[2]??""}]})}function WJ(z){let J=Bz(z.metadata);return J?[{type:"text",text:i(J)}]:uz(z.content)}function HJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function QJ(z){if(!Hz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function XJ(z){if(!(z instanceof fz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!jz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}function BJ(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;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,L,H={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=L;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Rz({maxPendingItems:Ez,maxPendingBytes:Tz,writeTimeoutMs:xz,signal:Z.signal,sizeOf:(Q)=>Buffer.byteLength(JSON.stringify(Q)),write:async(Q)=>{await Z.sessionUpdate(Q)},onFailure:(Q)=>this.handleUpdateEgressFailure(Q)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?D.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):D.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?D.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):D.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await D.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await D.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof _z)&&Z.code!=="ENOENT")throw Z;await D.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await D.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await D.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(){V.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(W)=>{await this.sendUpdateAndWait(W)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?LJ(this.options.mcpServers):void 0,L=R.getInstance().getTerminalService(this.id),H=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 Nz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...H?{workspace:H}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,j)=>{let G=await L.execute(W,{cwd:j.cwd,env:j.env,timeout:j.timeoutMs,signal:j.signal,allowLocalFallback:!1,onOutput:(U)=>j.onOutput?.("stdout",U)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.failureKind==="timeout",aborted:G.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);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.roots.hostStateRoot)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="follow_up.queue.changed"){let j=l.safeParse(W.properties.queue);if(j.success)this.sendFollowUpQueueSnapshot(j.data);return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:j,messageId:G,content:U}=W.properties,E=W.properties.metadata;if(W.type==="team.message.received"&&typeof j==="string"&&typeof G==="string"&&typeof U==="string"&&Oz(E,{messageId:G,teamName:j}))(async()=>{let q=await this.runtime?.enqueueSteering(U,{allowBeforeTurn:!0,messageId:G,origin:"team_message",metadata:E});if(!q?.accepted)return;if(q.queue)this.sendFollowUpQueueSnapshot(q.queue);if(await new wz(j,Lz()).markDelivered([G]),q.delivery==="next_turn")this.requestPendingResume()})().catch((q)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,q)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Y?.status==="active"||Y?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Xz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let L of WJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:L}))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);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot())}catch{V.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={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(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Y);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Y)=>{if(await this.setReasoningEffort(Y),!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(Y)=>{if(await this.setServiceTier(Y),!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(Y)=>{if(await this.setResponseVerbosity(Y),!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(Y)=>{if(await this.setCommunicationStyle(Y),!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(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,W,j=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Y,prompt:X,onCompleted:(U)=>{if(B)j(U);else W=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,W)j(W);return G}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Y)},getPrompt:async(Y,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Y,X,B)},complete:async(Y,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Y,X,B)},listTasks:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Y)},getTask:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Y)},cancelTask:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Y,X)},getLogs:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Y,X)},setLoggingLevel:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Y,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Y,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Y,X)=>{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:Y,signal:X,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),W=await B.completion,j=(await S.list(this.roots.hostStateRoot,this.id)).find((G)=>G.start.reviewId===B.reviewId);if(!j)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:W.status,findings:W.findings.length,content:Qz(j.start,W)}}}}:{},signal:J,acp:{sendMessage:(Y)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}})},sendToolStart:(Y,X,B)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Y}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:j})},sendToolResult:(Y,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},L=await Mz(z,Z),H=L.data?.action;if(H==="start_goal"||H==="resume_goal")this.requestPendingResume();if(H==="rewind_session"&&Array.isArray(L.data?.messages))this.messages=[...L.data.messages],this.contextMessages=await this.loadModelContextOr(L.data.messages);if((L.message==="compact_completed"||L.message==="compact_fallback")&&L.data?.compactedMessages){this.contextMessages=[...L.data.compactedMessages];let Y=await this.loadPersistedMessages();if(Y.length>0)this.messages=Y}let Q=L.content||L.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(L.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${L.error}`}});return await this.flushUpdates(),{stopReason:L.success?"end_turn":"cancelled"}}catch(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,L=new Promise((H)=>{Z=H});this.pendingSideConversation=J,this.pendingSideConversationCompletion=L;try{return await this.handleSlashCommand(z,J.signal)}catch(H){if(J.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(Z(),this.pendingSideConversationCompletion===L)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Iz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],L=z.filter((H)=>!J.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let Q;if(H.usage){let Y=H.usage.replace(/^\/\w+\s*/,"").trim();if(Y)Q=Y}if(H.aliases?.length){let Y=`Aliases: ${H.aliases.join(", ")}`;Q=Q?`${Q} | ${Y}`:Y}return{name:H.name,description:H.description,input:Q?{hint:Q}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(L.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:L}),V.info(`[AcpSession ${this.id}] Sent ${L.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),L=Z.content,H=Z.displayText,Q=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((_)=>_.outputSchema)?.outputSchema:void 0),Y;if(Q!==void 0)Y=Uz(Q).schema;if(H.trimStart().startsWith("!")){if(Y)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let X=Fz(H);if(X){if(Y)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(L)&&L.some((_)=>_.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(X.question?`/btw ${X.question}`:"/btw")}if(this.pendingPrompt){if(Y)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let _=await this.runtime.enqueueSteering(L,{allowBeforeTurn:!0});if(!_.accepted)throw Error(_.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${_.queued})`),this.sendFollowUpQueueSnapshot(_.queue??await this.runtime.getFollowUpQueueSnapshot()),_.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,W=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)W();else J.abortSignal?.addEventListener("abort",W,{once:!0});let j=!1,G=!1,U=!1,E,q=new Promise((_)=>{E=_});this.pendingPrompt=B,this.pendingPromptCompletion=q;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Sz(H)){if(Y)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,B.signal)}let _={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($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Dz(this.agent.chatStream(L,_,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Y}),async($)=>{switch($.kind){case"content_delta":if(Y)break;if($.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{U=!0;let K=$.toolCall,N=K.function.name;if(N===y)break;let P=this.mapToolKind($.toolKind),F=`Executing ${N}`;if(N==="Task"&&"function"in K)try{let b=JSON.parse(K.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")F=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:F,content:[],kind:P});break}case"tool_progress":{U=!0;let K=$.toolCall;if(K.function.name===y)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{U=!0;let K=$.toolCall;if(K.function.name===y)break;let N=$.result,P=[],F=N.metadata;if(F?.kind==="patch"&&Array.isArray(F.changes))for(let w of F.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;P.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(F?.kind==="edit"&&typeof F.file_path==="string"&&typeof F.oldContent==="string"&&(typeof F.newContent==="string"||F.newContent===void 0))P.push({type:"diff",path:F.file_path,oldText:F.oldContent,newText:F.newContent??null});else{let w=K.function.name,ZJ=qz(Vz(Az(w,N),Gz));P.push({type:"content",content:{type:"text",text:ZJ}})}if(K.function.name==="Task"&&(F?.verificationVerdict==="pass"||F?.verificationVerdict==="fail"||F?.verificationVerdict==="partial"))P.unshift({type:"content",content:{type:"text",text:`Verification result: ${F.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:b,content:P});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":j=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot($.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot($.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot($.queue);let K=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let P of uz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:P});J.projectedRecoveredInputIds?.add(N.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[..._.messages];let Zz=await this.loadPersistedMessages();if(this.messages=Zz.length>0?Zz:[..._.messages],!O.success){let $=O.error?.type??"unknown",K=O.error?.details??O.error?.message??"Agent execution failed",N=QJ(K)??v(K);throw fz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:G,toolExecutionStarted:U,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let $z={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys($z).length>0?{_meta:$z}:{}}}catch(_){if(B.signal.aborted||_ instanceof Error&&_.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,_),_}finally{if(J.abortSignal?.removeEventListener("abort",W),j&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(E(),this.pendingPromptCompletion===q)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 J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,L,H=new Promise((X)=>{L=X});this.pendingUserShell=Z,this.pendingUserShellCompletion=H;let Q,Y="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(W)=>{if(Q=W.executionId,W.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.executionId,status:"in_progress",title:`! ${W.command}`,content:[],kind:"execute"});return}if(W.type==="output"){Y+=W.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.chunk}}]});return}let j=i(W.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.executionId,status:W.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Y?HJ(W.record):j}}]})}}),B={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(B),this.contextMessages.push(B),X.queue)this.sendFollowUpQueueSnapshot(X.queue);if(X.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(Q)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Q,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(L(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){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 J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}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 J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}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,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:hz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.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,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",L=!1,H,Q=null;try{let Y=this.runtime.getPendingSteeringCount()>0,X=Y?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=X?.status==="active"||X?.status==="verifying",W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none"&&(W.state==="requires_attention"||!Y&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}});if(!Y&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(W.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Y?"pending_input":"goal",L=!0;let j=kz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(j<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let G=new AbortController;Q=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},j),Q.unref?.();let U=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Y,goalContinuationOnly:B,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(U.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Y){if(z!==this.pendingResumeGeneration)return;let X=L?XJ(Y):{taskFailure:v(Y),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,W=Cz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:X});if(W.phase==="retry_scheduled")this.pendingResumeRequested=!0,H=W.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:X?.taskFailure,delayMs:W.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${W.delayMs}ms`);else{let j=W.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(j,{attempt:J,kind:Z,taskFailure:X?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${W.retryable}, phase=${j})`,Y),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(Q!==null)clearTimeout(Q);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=H??0}}cancel(){V.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)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",L=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(L),this.mode=Z,V.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(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((L)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,L)});throw Z}}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 J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}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 J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}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 J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}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 J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(L){throw await this.runtime.refresh({communicationStyle:J.selection}),L}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),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 bz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,L=this.pendingPromptCompletion,H=this.pendingUserShellCompletion,Q=this.pendingSideConversationCompletion,Y=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let X,B=async(W)=>{try{await W()}catch(j){X??=j}};if(await B(()=>this.cancel()),L)await B(()=>L);if(H)await B(()=>H);if(Q)await B(()=>Q);if(Y)await B(()=>Y);if(z&&L&&Z)await B(()=>Z.discardPendingInput());if(J)await B(()=>J.destroy());if(Z)await B(()=>Z.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,V.debug(`[AcpSession ${this.id}] Destroyed`),X!==void 0)throw X}resolvePrompt(z){let J=[],Z=[],L=0,H=0,Q=0,Y=(W)=>{if(Z.length>0)Z.push({type:"text",text:`
|
|
13
|
-
`}),Q+=1;if(Z.push(W),W.type==="text")Q+=W.text.length};for(let W of z)if(W.type==="text")J.push(W.text),Y({type:"text",text:W.text});else if(W.type==="image"){let j=`data:${W.mimeType};base64,${W.data}`;L+=1,H+=j.length,J.push(`[Image: ${W.mimeType}]`),Y({type:"image_url",image_url:{url:j}})}else if(W.type==="resource"){let j=W.resource;if("text"in j){let G=`<file path="${j.uri}">
|
|
14
|
-
${j.text}
|
|
15
|
-
</file>`;J.push(G),Y({type:"text",text:G})}}else if(W.type==="resource_link"){let j=`[Resource: ${W.uri}]`;J.push(j),Y({type:"text",text:j})}if(L>g)throw Error(`ACP prompt contains more than ${g} images`);if(H>Wz)throw Error("ACP prompt images exceed the 5 MiB limit");if(Q>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
-
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=J.join(`
|
|
17
|
-
`);return{content:L>0?Z:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.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 J=l.safeParse(z);if(!J.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":BJ(J.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;V.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 J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return V.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let L=u(),H=[];if(z.message)H.push({type:"content",content:{type:"text",text:z.message}});if(z.details)H.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let Q=this.mapToolKind(Z),Y={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:L,status:"pending",title:z.title||"Permission Required",content:H,kind:Q}},X=await this.waitForClientInteraction(this.connection.requestPermission(Y),J);if(!X)return{approved:!1,reason:m};let B=X.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=B.optionId;if(W==="allow_always")return{approved:!0,scope:"project"};if(W==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let j=W==="allow_once";return{approved:j,scope:"once",reason:j?void 0:"User denied the operation"}}catch(L){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,L),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let L={};try{for(let[H,Q]of Z.entries()){let Y=Q.options.map((j,G)=>`answer:${H}:${G}`),X=`answer:${H}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.options.map((j,G)=>({optionId:Y[G],name:j.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:Q.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Q.question,...Q.options.map((j)=>`${j.label}: ${j.description}`)].join(`
|
|
20
|
-
`)}}]}}),J);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Y.indexOf(B.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};L[Q.header]=Q.options[W].label}return{approved:!0,answers:L}}catch(H){return V.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let L=Object.create(null);for(let H of Z.fields??[]){let Q=await this.collectAcpElicitationField(H,J);if(Q.cancelled)return{approved:!1,reason:Q.reason,elicitation:{action:"cancel"}};if(Q.value!==void 0)L[H.name]=Q.value}return{approved:!0,elicitation:{action:"accept",content:L}}}catch(L){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,L),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Q,Y)=>({id:`option:${Y}`,label:Q.label,value:Q.value})),L=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...Z.map((Q)=>({id:Q.id,label:Q.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(L==="skip")return{cancelled:!1};let H=Z.find((Q)=>Q.id===L);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(z.defaultValue!==void 0){let Z=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,Z,L){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((Q)=>({optionId:Q.id,name:Q.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),L);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,L)=>{let H=!1,Q=(X)=>{if(H)return;H=!0,J.removeEventListener("abort",Y),X()},Y=()=>Q(()=>Z(void 0));if(J.addEventListener("abort",Y,{once:!0}),J.aborted)Y();z.then((X)=>Q(()=>Z(X)),(X)=>Q(()=>L(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=I("Agent"),GJ="remote task isolation is not supported";function h(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function VJ(z){return C.invalidParams({code:z.code,reason:z.reason})}function UJ(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:GJ})}function gz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function cz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return t(z)}catch(J){if(J instanceof pz)throw VJ(J);throw J}}function a(z,J){let Z=e(z);return Object.freeze({kind:"acp-remote",hostStateRoot:zz(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function o(z,J){let Z=mz(z.remoteWorkspace),L=zz(Z.collisionIdentity);if(z.projectPath!==L)throw Error("ACP remote workspace durable state is invalid");let H=t(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:L,executionRoot:Z.wirePath,hostResourceRoot:J,profile:H,descriptor:Z})}function _J(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Jz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=r.resolve(n())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=rz();this.runtimeResidencyValue=new zJ({maxResident:z?.maxResidentSessionRuntimes??lz,idleMs:z?.sessionRuntimeIdleMs??iz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof ez)throw C.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:jJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=s("acp"),Z=z.cwd||n(),L=h(this.clientCapabilities),H=L?k(Z):void 0,Q=z._meta?.["blade/taskIsolation"],Y=Q==="local"||Q==="worktree"?Q:void 0;if(L&&Y)throw UJ();let X=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(J),W;try{let j,G;if(H){let E=a(H,this.hostResourceRoot);j=await D.createRemoteSessionMetadata(J,E.hostStateRoot,E.descriptor,{}),G=o(j,this.hostResourceRoot)}else G=T(Z);let U=!L&&Y?await tz.createSessionTask({sessionId:J,prompt:typeof X==="string"&&X.trim()?X:"ACP task session",sourceProjectPath:Z,isolation:Y}):void 0;if(U)G=T(U.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${G.kind}`),W=new x(J,G,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{}}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(J,W,B),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,U?.metadata,W.getModelConfiguration())}catch(j){throw B.cancel(),await W?.destroy().catch(()=>{return}),j}}async listSessions(z){let J=h(this.clientCapabilities);if(!J&&z.cwd!=null&&!r.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await D.listRemoteSessionPage({...z.cwd!=null?{descriptor:e(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await D.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((L)=>({sessionId:L.sessionId,cwd:J?_J(L):L.projectPath,title:L.title??null,updatedAt:L.lastMessageTime,_meta:{"blade/taskStatus":L.taskStatus,...L.taskStatusReason?{"blade/taskStatusReason":L.taskStatusReason}:{},...L.taskFailure?{"blade/taskFailure":L.taskFailure}:{},...L.taskStartedAt?{"blade/taskStartedAt":L.taskStartedAt}:{},...L.taskCompletedAt?{"blade/taskCompletedAt":L.taskCompletedAt}:{},...L.taskModelId?{"blade/taskModelId":L.taskModelId}:{},...L.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...L.taskRetriedFrom?{"blade/taskRetriedFrom":L.taskRetriedFrom}:{},...L.taskDelivery?{"blade/taskDelivery":L.taskDelivery}:{},...L.taskIsolation?{"blade/taskIsolation":L.taskIsolation}:{},...L.taskSourceProjectPath?{"blade/taskSourceProjectPath":L.taskSourceProjectPath}:{},...L.taskWorktreeBranch?{"blade/taskWorktreeBranch":L.taskWorktreeBranch}:{},...L.taskBaseCommit?{"blade/taskBaseCommit":L.taskBaseCommit}:{},...L.taskDiffStat?{"blade/taskDiffStat":L.taskDiffStat}:{},...L.taskQueuePosition?{"blade/taskQueuePosition":L.taskQueuePosition}:{},...L.taskQueueDepth!==void 0?{"blade/taskQueueDepth":L.taskQueueDepth}:{},...L.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":L.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=h(this.clientCapabilities),Z=J?a(k(z.cwd),this.hostResourceRoot):void 0;if(!J&&!r.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let L=s("fork"),H=await this.reserveSessionRuntime(L),Q;try{let Y;try{Y=await D.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:L,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(B){if(cz(B))throw gz();throw B}this.assertNotDestroyed();let X=J?o(Y.metadata,this.hostResourceRoot):T(Y.projectPath??z.cwd);return Q=new x(Y.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:Y.messages,permissionMode:Y.metadata.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),this.assertNotDestroyed(),this.commitSession(Y.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Y.sessionId,J?void 0:Y.metadata,Q.getModelConfiguration())}catch(Y){throw H.cancel(),await Q?.destroy().catch(()=>{return}),Y}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),L=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,L);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===L)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!h(this.clientCapabilities)){await D.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),B;try{let[W,j]=await Promise.all([D.loadSession(z.sessionId,z.cwd),D.findSessionMetadata(z.sessionId,z.cwd)]);if(!j)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,T(z.cwd),this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:j.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,X),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(W){throw X.cancel(),await B?.destroy().catch(()=>{return}),W}}let Z=a(k(z.cwd),this.hostResourceRoot),L;try{L=await D.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(X){if(cz(X))throw gz();throw X}let H=o(L,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let Q=await this.reserveSessionRuntime(z.sessionId),Y;try{let X=await D.loadRemoteSession(z.sessionId,H.hostStateRoot,H.descriptor);return Y=new x(z.sessionId,H,this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:L.permissionMode,mcpServers:z.mcpServers}),await Y.initialize(),await Y.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Y,Q),Y.sendAvailableCommandsDelayed(),this.buildSessionSetup(Y.getModelConfiguration(),Y.getMode())}catch(X){throw Q.cancel(),await Y?.destroy().catch(()=>{return}),X}}commitSession(z,J,Z){let L=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),L.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let L=this.runtimeResidency.owns(z,Z),H;try{await Z.destroy(J)}catch(Y){H=Y}let Q=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(L&&!Q&&H===void 0)throw Error(`ACP Session is still active: ${z}`);if(H!==void 0)throw H}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],L=(z?.currentModelId&&Z.some((Y)=>Y.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],Q=[];if(Z.length>0)Q.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:L,options:Z.map((Y)=>({value:Y.id,name:Y.displayName??Y.model,description:`${z?.modelProviders[Y.provider]?.name??Y.provider} · ${Y.model}`}))});if(z?.reasoning)Q.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:Y==="off"?"Disable model reasoning":`Use ${Y} reasoning effort`}))]});if(z?.serviceTier)Q.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:Y==="fast"?"Use the provider priority tier":Y==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Q.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:`Use ${Y} response verbosity`}))]});if(z?.communicationStyle)Q.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Y)=>({value:Y.id,name:Y.name,description:`${Y.description} · ${Y.source}`}))});return{modes:{availableModes:H,currentModeId:J},configOptions:Q.length>0?Q:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),L=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,L);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===L)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&dz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&nz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await sz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function KZ(){let z=DJ.toWeb(process.stdout),J=KJ.toWeb(process.stdin),Z=f.ndJsonStream(z,J),L,H=new f.AgentSideConnection((Y)=>{return L=new Jz(Y),L},Z),Q=JJ(async()=>{await L?.destroy()});try{await H.closed}finally{Q(),await L?.destroy()}}export{KZ as runAcpIntegration,T as createLocalAcpSessionRoots};
|
package/dist/chunk-1n5d6b5k.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ud as a,Vd as b,Wd as c,Xd as d,Yd as e,Zd as f,_d as g}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import"./chunk-vvawhvea.js";import"./chunk-f7hsagj6.js";import"./chunk-77x1rrz9.js";import"./chunk-vptn8fhx.js";import"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-g7h0peka.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
package/dist/chunk-1qdemrkr.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Jj as a,Kj as b,Lj as c,Mj as d,Nj as e,Oj as f}from"./chunk-w2n1vwzg.js";import"./chunk-ntd69c0k.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
package/dist/chunk-83nxcfz3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Pj as a,Qj as b,Rj as c}from"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
package/dist/chunk-9y7j565j.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{p as yH,q as bH,r as IH,s as RH,t as gH,u as kH}from"./chunk-xtngc0th.js";import{B as TH,C as JH,D as KH,E as VH,F as p,G as ZH}from"./chunk-g4vgnxh4.js";import{H as XH,ca as GH,ea as PH,fa as FH,ja as EH}from"./chunk-sy0vxdc3.js";import"./chunk-24rsvr6e.js";import"./chunk-hx10bph0.js";import"./chunk-gq7fdc8c.js";import{Fb as r,Rb as UH,_b as _H}from"./chunk-c5rfnzhf.js";import"./chunk-wzkh3e6a.js";import{Jd as jH,Nd as xH,Pd as m,_d as s}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import{if as zH}from"./chunk-hqwpnb0x.js";import{kf as fH,lf as AH,mf as SH}from"./chunk-t6cajkaj.js";import{nf as MH}from"./chunk-13sdjfks.js";import"./chunk-kbnxbb23.js";import{Nf as WH}from"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-acsfh1cw.js";import"./chunk-tev70rzj.js";import"./chunk-vvawhvea.js";import"./chunk-82x77b2p.js";import"./chunk-1cbaqh71.js";import{ah as qH}from"./chunk-5sknjz9b.js";import"./chunk-f7hsagj6.js";import"./chunk-sv5z5sna.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import"./chunk-mm1atkae.js";import{Gi as DH}from"./chunk-gdnyt8a7.js";import{Li as i,Mi as o}from"./chunk-vptn8fhx.js";import{Qi as k}from"./chunk-jc28ddt0.js";import{Ri as LH,Ti as H,Ui as $H,Wi as N}from"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
|
-
`)}function cJ(K){return`[task] [${K.status}] ${K.subject}`}function uJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function dJ(K){if(!(K instanceof Error))return"Unknown error";let X=K.lastError??K;if(X.responseBody)try{let W=JSON.parse(X.responseBody)?.error?.message;if(W)return X.statusCode?`${W} (HTTP ${X.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function pJ(K){return K==="jsonl"?"jsonl":"text"}function NH(K,V){let Q=(...X)=>{for(let J of X){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function vJ(K,V,Q,X){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!X.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(X.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:X.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function QH(K,V,Q=!1){let X=(J,Z)=>{K.stdout.write(`${JSON.stringify(BH(J,Z))}
|
|
3
|
-
`)};return{contentDelta(J){if(V==="jsonl"){X("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return X("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){X("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){X("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
|
-
`);if(J)K.stdout.write(`
|
|
5
|
-
`)},content(J){if(V==="jsonl"){X("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){X("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){X("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){X("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){X("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){X("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){X("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){X("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){X("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){X("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){X("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){X("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){X("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){X("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){X("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){X("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){X("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){X("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){X("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,cJ(Z))},goalFrontier(J){if(V==="jsonl"){X("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let Z=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";L(K.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${Z}`)},turnRecovery(J){let Z=J.assessment;if(V==="jsonl"){X("turn_recovery",{state:Z.state,turn_id:Z.turnId,input_message_count:Z.inputMessageCount,reason:Z.state==="requires_attention"?Z.reason:void 0});return}L(K.stderr,`[turn-recovery:${Z.state}] ${Z.turnId}`)},goal(J){if(V==="jsonl"){X("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){X("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){X("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){X("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}`)},providerAdmission(J){if(V==="jsonl"){X("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){X("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){X("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){X("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){X("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){X("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){X("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){X("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){X("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){X("error",{message:J});return}L(K.stderr,J)}}}async function lJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let X="text",J=new CH,Z={targetLocked:!1},W,x,j,P=kJ(Q),T=!1,F=new l(V,{signal:P.signal,onFailure:(B)=>{T=!0,P.abort(B)}}),c={stdout:{write:(B)=>F.write("stdout",B)},stderr:{write:(B)=>F.write("stderr",B)}},Y=QH(c,X),u=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(B)=>{return x?.(),x=void 0,j?.(),j=void 0,await u()?B:1};try{let B=wJ(K);X=pJ(B.outputFormat);let y=await gH(B);Y=QH(c,X,Boolean(y)),await yH();let n=B.forkSession!==!0&&(B.continue===!0||typeof B.resume==="string"&&B.resume.length>0)?await IH({message:B.message,_:B._,stdin:Q?.stdin}):await bH({...B,stdin:Q?.stdin}),M=n===void 0,_=M?{mode:"agent",content:""}:await RH(n);if(_.mode==="output"){if(_.content)Y.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>i)throw Error(`User prompt exceeds the ${i}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>o)throw Error(`User prompt exceeds the ${o}-byte durable input limit`);let C=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:t,metadata:e}=await kH({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),R=B.permissionMode??e?.permissionMode??"yolo",HH=B.model&&B.model!=="inherit"?B.model:WH()?.id,U=B.taskIsolation?await TH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:k(),isolation:B.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:k(),isolation:B.taskIsolation,permissionMode:R,...HH?{modelId:HH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??e?.projectPath??k();if(j=r.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let q=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],uH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(q.phase)||!A.includes(q.requestClass)||!S.includes(q.resource)||!I.includes(q.scope)||q.reason!==void 0&&!uH.includes(q.reason)||typeof q.queuePosition!=="number"||typeof q.queueDepth!=="number"||typeof q.inFlight!=="number"||typeof q.limit!=="number"||typeof q.waitMs!=="number"||typeof q.maxWaitMs!=="number"||q.recoveryRemainingMs!==void 0&&typeof q.recoveryRemainingMs!=="number")return;Y.providerAdmission({kind:"provider_admission",phase:q.phase,requestClass:q.requestClass,resource:q.resource,scope:q.scope,...q.reason!==void 0?{reason:q.reason}:{},queuePosition:q.queuePosition,queueDepth:q.queueDepth,inFlight:q.inFlight,limit:q.limit,waitMs:q.waitMs,maxWaitMs:q.maxWaitMs,...q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:q.recoveryRemainingMs}:{}})}),!U)await s.setSessionPermissionMode(G,z,R);let hH=U?!1:await _H.cancelPendingNonInteractive(z,G);if(U)Y.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??k(),isolation:B.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=r.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;Y.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let OH={messages:hH?await s.loadSessionModelContext(G,z):[...t],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:uJ()};W=await GH.create({sessionId:G,workspaceRoot:z,modelId:B.model,permissionMode:R,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?MH(B.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...t.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&W.getPendingSteeringCount()>0,h=M&&!g?await W.getGoal():null,O=h?.status==="active"||h?.status==="verifying",d=W.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!O&&d.state==="requires_attention")return Y.turnRecovery({kind:"turn_recovery",assessment:d}),Y.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!O?await W.getRecoveredFinalResponse():void 0;if(M&&!g&&!O){if(!b)throw Error("No unfinished turn or active goal to resume");let $=d;if($.state!=="none")Y.turnRecovery({kind:"turn_recovery",assessment:$});if(h)Y.goal({kind:"goal_updated",goal:h});if(b.structuredOutput&&b.structuredOutputSchemaDigest)Y.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else Y.content(b.content);return Y.phase("completed","done","Recovered headless run completed"),await E(0)}if(C!==void 0){let $=await W.executeUserShellCommand(C,{signal:P.signal,onEvent:async(q)=>{if(q.type==="started")Y.userShellStarted(q.executionId,q.command,q.auxiliary);else if(q.type==="output")Y.userShellOutput(q.executionId,q.stream,q.chunk,q.streamTruncated);await u()}});return Y.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let wH=B.maxTurns??W.getConfig().maxTurns,mH=U?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,cH=await EH.createWithRuntime(W,{sessionId:G,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:R,toolWhitelist:B.allowedTools,toolBlacklist:mH,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),w=await UH(cH.chatStream(_.content,OH,{stream:!0,signal:P.signal,maxTurns:B.maxTurns,builtinVerification:B.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:O,...wH===-1?{onTurnLimitReached:async($)=>{return Y.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||X==="jsonl")J.markAssistantContent();Y.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(Y.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let q=J.completeStream();Y.streamEnd(q.wroteAssistantContent,q.openedThinking);break}case"tool_start":{let q=$.toolCall;if(!("function"in q))break;if(q.function.name===m)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(q.function.name))break;try{let f=JSON.parse(q.function.arguments),A=PH(q.function.name,f),S=NH(q.function.name,f),I=vJ(q.function.name,A,S,Z);if(I.shouldLockTarget)Z.targetLocked=!0;Y.phase(I.phase,I.status,I.message,{toolName:q.function.name,target:S}),Y.toolStart(q.function.name,A,S,$.toolKind)}catch{Y.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${q.function.name}`:`Still searching: ${q.function.name}`,{toolName:q.function.name}),Y.toolStart(q.function.name,q.function.name,void 0,$.toolKind)}break}case"tool_progress":{let q=$.toolCall;if(!("function"in q))break;if(q.function.name===m)break;Y.toolProgress(q.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let q=$.toolCall;if(!("function"in q))break;if(q.function.name===m)break;let f;try{let S=JSON.parse(q.function.arguments);f=NH(q.function.name,S)}catch{f=void 0}let A=xH(FH(q.function.name,$.result),jH);if(Y.toolResult(q.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:gJ($.result.metadata)}),A.detail)Y.toolDetail(q.function.name,A.detail);break}case"token_usage":Y.tokenUsage($.usage);break;case"compaction":Y.compacting($);break;case"task_update":Y.taskUpdate($.tasks);break;case"goal_frontier_updated":Y.goalFrontier($);break;case"turn_recovery":Y.turnRecovery($);break;case"structured_output":Y.structuredOutput($);break;case"mcp_catalog_changed":Y.mcpCatalogChanged($);break;case"mcp_content_changed":Y.mcpContentChanged($);break;case"mcp_resource_updated":Y.mcpResourceUpdated($);break;case"mcp_connection_changed":Y.mcpConnectionChanged($);break;case"mcp_log":Y.mcpLog($);break;case"mcp_instructions_changed":Y.mcpInstructionsChanged($);break;case"mcp_task_changed":Y.mcpTaskChanged($);break;case"project_rules_loaded":Y.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":Y.goal($);break;case"subagent_spawned":case"subagent_completed":Y.subagent($);break;case"model_fallback":break;case"provider_admission":Y.providerAdmission($);break;case"provider_retry":Y.providerRetry($);break;case"provider_circuit":Y.providerCircuit($);break;case"provider_stall":Y.providerStall($);break;case"action_stationarity":Y.actionStationarity($);break;case"turn_start":if($.turn===1)Z.targetLocked=!1;Y.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let q=$}}await u()});if(w.metadata?.outputTruncated)Y.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(w.metadata?.recoveryAttention)return Y.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!w.success)return Y.error(`Error: ${w.error?.message??"Agent execution failed"}`),await E(1);return Y.phase("completed","done","Headless run completed"),await E(0)}catch(B){if(!T){if(J.hasOpenThinking()&&X==="text")c.stderr.write(`
|
|
6
|
-
`);Y.error(`Error: ${dJ(B)}`)}return await E(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),P.dispose()}}}async function AK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":X,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=zH,j=IJ(RJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([AH,fH,SH]);return mJ(j),await j.parse(),!0}export{lJ as runHeadless,AK as handleHeadlessMode,hJ as HeadlessOptionsSchema};
|
package/dist/chunk-acsfh1cw.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{$i as mf,_i as __,aj as qf,bj as T_,cj as Jf,ej as Wf,gj as If,ij as q,jj as Qf,lj as Df,mj as Kf,oj as s}from"./chunk-jb8stg10.js";import{wj as l}from"./chunk-g7h0peka.js";import{Aj as SE,Cj as jf}from"./chunk-s3a017q7.js";import{Fj as aE}from"./chunk-bdtpq7j9.js";var D_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},TE=(f)=>D_[f]||{};var H_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&H_.has(f)}function zT(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function $T(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function hE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let N=()=>{T.abort(x.reason);for(let[P,S]of h)P.removeEventListener("abort",S)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function ff(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let N,P=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(P),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var U_=l("Chat"),Y_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function xE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
|
-
`)}function b_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return U_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function B_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=B_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function tE(f,E,_){return Promise.all(f.map((T)=>T.type==="text"?Promise.resolve({type:"text",text:T.text}):E?c_(T.image_url.url,_):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function PE(f,E,_,T,h){let x=f.filter((A)=>A.role==="system").map((A)=>xE(A.content)).filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),N=[],P=E.input.includes("image");for(let A of f){if(A.role==="system")continue;if(A.role==="user"){let t=typeof A.content==="string"?A.content:await tE(A.content,P,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(A.role==="assistant"){let t=[];if(A.reasoningContent?.trim())t.push({type:"thinking",thinking:A.reasoningContent});let M=xE(A.content);if(M)t.push({type:"text",text:M});for(let I of A.tool_calls??[]){if(!("function"in I))continue;t.push({type:"toolCall",id:I.id,name:I.function.name,arguments:b_(I.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:Y_,stopReason:A.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:A.tool_call_id??"",toolName:A.name??"unknown",content:typeof A.content==="string"?[{type:"text",text:A.content}]:await tE(A.content,P,T),isError:!1,timestamp:Date.now()})}let S=_?.filter((A)=>!h||A.name===h).map((A)=>({name:A.name,description:A.description,parameters:A.parameters,constrainedSampling:A.constrainedSampling})).sort((A,t)=>A.name<t.name?-1:A.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...S?.length?{tools:S}:{}}}function ME(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let P=new Set(h.map((t)=>t.id)),S=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),A=new Set(S.map((t)=>t.tool_call_id));if(P.size===h.length&&S.length===P.size&&A.size===P.size)E.push(T,...S);_=N-1}return E}function AE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function NE(f,E){return{...f,...E.baseUrl?{baseUrl:SE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Xf(f){let E=f.modelCatalog??jf();return{models:E.models,model:NE(E.getModel(f.provider,f.model),f)}}function uE(f,E){let _=f.modelCatalog??jf();return NE(_.getModel(E.provider,E.model),f)}import{createHash as O_}from"node:crypto";var V_=32,j_=1000,X_=512,z_=2000,J_=0.1,W_=0.05,$_=0.9,k_=300000,L_=3600000;class zf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=G_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<j_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(z_,Math.max(X_,T.cacheReadTokens*J_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-W_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,S=_.toolsHash!==T.toolsHash,A=_.policyHash!==T.policyHash;if(!(N||P||S||A)&&_.promptTokens<T.promptTokens*$_)return;let M=Math.max(0,E-T.recordedAt),I=T.retention==="long"?L_:k_,Y=N?"model_changed":P?"system_prompt_changed":S?"tools_changed":A?"request_policy_changed":M>=I?"ttl_expired":"server_side",$=Z_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:M,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:S,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:N,requestPolicyChanged:A}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>V_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function G_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Ef(T.name),contractHash:Ef(_f(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Ef(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Ef(_f(_)),toolFingerprints:_,policyHash:Ef(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function Z_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${_f(E[_])}`).join(",")}}`}function Ef(f){return O_("sha256").update(f).digest("hex")}import{randomBytes as F_}from"node:crypto";import{createHmac as Q_}from"node:crypto";function K_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function C_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function Sf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),K_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",C_(f.customHeaders),_]);return Q_("sha256",Buffer.from(E)).update(T).digest("hex")}var o_=60000,s_=4,v_=0.8;var uf=300000,$f=600000;var IE=128,DE=256,w_=1800000,Nf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function kf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function a(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function p_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function m_(f,E){return Sf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function Tf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function HE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function UE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class bE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):F_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(a(f.maxEntries,IE),IE),maxWindowEntries:Math.min(a(f.maxWindowEntries,DE),DE),windowMs:a(f.windowMs,o_),minSamples:a(f.minSamples,s_),errorRateThreshold:p_(f.errorRateThreshold,v_),idleTtlMs:a(f.idleTtlMs,w_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#P();let E=this.#_();this.#b(E);let _=m_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#D();if(this.#x.size>=this.#T.maxEntries)return this.#P();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(uf,Math.min(a(E,uf),$f));return{preflight:()=>_.#M(f),check:()=>_.#B(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#N(h),snapshot:()=>_.#j(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#S(E),recordFailure:(E)=>f.#S(E),recordNeutral:(E)=>f.#S(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#M(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#u(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Nf)-E);return this.#U(f,Math.min(Nf,_))}#U(f,E){let{allowed:_,...T}=this.#A(f,E);return{eligible:!1,...T}}#B(f,E){let _=this.#_();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#u(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#A(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#c(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Nf)-_);return this.#A(f,Math.min(Nf,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#c(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#A(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#I(h,_,x,"reopened");return this.#O(h)}if(E==="neutral")return;if(this.#V(h,E==="failure",x),E!=="failure"||!_)return;let N=Tf(h.samples),P=h.samples.length===0?0:N/h.samples.length;if(h.samples.length>=this.#T.minSamples&&P>=this.#T.errorRateThreshold)return this.#I(h,_,x,"opened");return}#I(f,E,_,T){let h={reason:E.reason,...HE(E.statusCode)!==void 0?{statusCode:HE(E.statusCode)}:{},...UE(E.retryAfterMs)!==void 0?{retryAfterMs:UE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#O(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#V(f,E,_){if(this.#u(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#u(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#j(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:Tf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#b(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#D(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var YE;function BE(){return YE??=new bE,YE}import{randomBytes as q_}from"node:crypto";var g_=16,cE=128,OE=32,l_=3,VE=16,jE=96,XE=24,zE=12,JE=16,WE=4,$E=4,kE=67108864,LE=33554432,a_=12,y_=2,GE=2,ZE=1,oE=15000,QE=30000;function Lf(){return{foreground:0,background:0,internal:0}}function Gf(){return{inFlight:Lf(),queued:Lf(),pendingBytes:Lf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function KE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class xf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,P){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=N;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function tf(f){return f instanceof xf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function e_(f){let E=z(f.globalMaxInFlight,g_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,cE,cE),T=z(f.domainMaxPending,OE,OE),h=Math.min(z(f.ownerMaxInFlight,l_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,VE,VE),_),N=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(jE,Math.max(1,Math.floor(_*3/4))),jE),_),P=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(XE,Math.max(1,Math.floor(T*3/4))),XE),T),S=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),A=Math.min(z(f.internalGlobalMaxPending,Math.min(JE,Math.max(1,Math.floor(_/8))),JE),N),t=Math.min(z(f.internalDomainMaxPending,Math.min(WE,Math.max(1,Math.floor(T/8))),WE),P),M=Math.min(z(f.internalOwnerMaxPending,Math.min($E,Math.max(1,Math.floor(x/4))),$E),S),I=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,kE,kE),I),$=Math.min(z(f.ownerMaxPendingBytes,LE,LE),I),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(a_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(y_,h),h),h),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(GE,E),GE),E),Uf=z(f.internalDomainMaxInFlight,ZE,ZE),Rf=z(f.agingMs,QE,QE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:S,internalGlobalMaxPending:A,internalDomainMaxPending:t,internalOwnerMaxPending:M,globalMaxPendingBytes:I,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:Rf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function CE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function d_(f){if(CE(f.sessionId,"sessionId"),CE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>q)throw Error(`maxConcurrent must be between ${If} and ${q}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Zf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function n_(f,E){return Sf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class sE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Gf();#P=1;#S=0;#M=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):q_(32),this.#t=f.now??(()=>performance.now()),this.#f=e_(f)}admit(f){if(d_(f),this.#M)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Zf(f.signal);let E=n_(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#c();if(this.#_.length===0&&this.#A(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let I=this.#I(E,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(I),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#X("queue_full",f,N,this.#_.length);let P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let S,A,t=new Promise((I,Y)=>{S=I,A=Y});t.catch(()=>{return});let M={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:S,reject:A,settled:!1,admitted:!1};if(f.signal)M.abortListener=()=>this.#b(M,Zf(f.signal)),f.signal.addEventListener("abort",M.abortListener,{once:!0});return M.timer=setTimeout(()=>this.#j(M),f.maxWaitMs),M.timer.unref?.(),this.#_.push(M),this.#B(h,x,M),this.#N(),{ready:t,getSnapshot:()=>this.#$(M),cancel:(I)=>this.#b(M,Zf(f.signal,I))}}close(){if(this.#M)return;this.#M=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:W(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:W(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:W(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#M}}#U(f,E,_){let T=(t,M,I)=>M>=I?{scope:t,resource:"pending_count",inFlight:M,limit:I}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",W(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",W(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",W(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(t)return t}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),N=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),S=(t,M)=>f.pendingBytes>M-t,A=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),M=Math.max(1,Math.floor(N/4)),I=Math.max(1,Math.floor(P/4));if(S(this.#E.pendingBytes.internal,t)||S(_.counters.pendingBytes.internal,I)||S(E.counters.pendingBytes.internal,M))return A("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),M=Math.max(1,Math.floor(N*3/4)),I=Math.max(1,Math.floor(P/2));if(S(W(this.#E.pendingBytes),t)||S(W(_.counters.pendingBytes),I)||S(W(E.counters.pendingBytes),M))return A("class")}if(S(U(this.#E.pendingBytes),x))return A("global");if(S(U(_.counters.pendingBytes),P))return A("owner");if(S(U(E.counters.pendingBytes),N))return A("domain");return}#B(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Gf()}}#c(){return{order:this.#P,counters:Gf()}}#A(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#I(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#O(f,E,_)}}}#O(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#M)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,S]of this.#_.entries()){let A=this.#h.get(S.domainKey),t=this.#T.get(S.ownerId);if(A===void 0||t===void 0||!this.#A(A,t,S.requestClass))continue;let M=this.#V(S,f),I=E.get(S.ownerId);if(!I||M<I.rank||M===I.rank&&P<I.index)E.set(S.ownerId,{pending:S,rank:M,index:P})}let _=[...E.values()].filter(({pending:P})=>{let S=this.#h.get(P.domainKey),A=this.#T.get(P.ownerId);return S!==void 0&&A!==void 0&&this.#A(S,A,P.requestClass)}).map(({pending:P,rank:S})=>({pending:P,rank:S,order:this.#T.get(P.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((P)=>P.rank)),h=_.filter((P)=>P.rank===T),N=h.filter((P)=>P.order>this.#S).sort((P,S)=>P.order-S.order)[0]??h.sort((P,S)=>P.order-S.order)[0];this.#u(N.pending,N.order)}}#V(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=E;let _=this.#I(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#j(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#b(f,E){this.#D(f,E)}#D(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#N()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#J(T,h,f);if(this.#W(f),E)this.#z(f.domainKey,f.ownerId);return!0}#J(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,E){let _=this.#h.get(f);if(_&&KE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&KE(T.counters))this.#T.delete(E)}#$(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#L(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#k(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#X(f,E,_,T){return new xf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var FE;function vE(f={}){return FE??=new sE(f),FE}function wE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,N=0,P=!1,S=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},A=(t)=>{if(P)return;if(N+=1,N>T){S(_+1);return}if(t===null){S(4);return}switch(typeof t){case"string":S(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":S(8);return;case"boolean":S(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){S(32+t.byteLength);return}if(t instanceof ArrayBuffer){S(32+t.byteLength);return}if(t instanceof Date){S(40);return}if(t instanceof RegExp){S(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){S(32);for(let[M,I]of t)if(A(M),A(I),P)return;return}if(t instanceof Set){S(32);for(let M of t)if(A(M),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){S(32);return}if(Array.isArray(t)){S(16);for(let M of t)if(A(M),P)return;return}S(32);for(let M of Reflect.ownKeys(t)){if(typeof M!=="string")continue;let I=Object.getOwnPropertyDescriptor(t,M);if(!I?.enumerable||!("value"in I))continue;if(S(8+Buffer.byteLength(M,"utf8")),A(I.value),P)return}};return A(f),x}function pE(f){return wE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var mE=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class Cf extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var r_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],i_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],fT=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function qE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function ET(f){let E=qE(f);return i_.some((_)=>E.includes(_))}function Ff(f){if(f!==null&&typeof f==="object")mE.add(f)}function Ph(f){return f!==null&&typeof f==="object"&&mE.has(f)}function _T(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function TT(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function hT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function e(f,E){let _=qE(f),T=_T(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(r_.some((x)=>_.includes(x))||ET(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??TT(f)??hT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(fT.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function of(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function gE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=of(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,S=Math.min(500*2**N,P),A=Math.max(0,Math.min(1,_.random??Math.random())),t=S*(0.75+A*0.25);return Math.min(Math.round(t),h)}function yE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function xT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function sf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function tT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function RT(f,E,_,T){let h=T?void 0:xT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:tT(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function PT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function MT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;yE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function AT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(aE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}yE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function eE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:sf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(RT(x,E,f,h),PT(x,E.api,T?.toolChoice?.toolName),MT(x,E,f),AT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function lE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var ST=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function dE(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let P=new Headers(x.headers);_(lE(x.status,P)),await T?.(x,N)},!ST.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let P=await h(x,N);return _(lE(P.status,P.headers)),P}}function nE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,NT=30000;class rE extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class iE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function vf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function uT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function IT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:NT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function DT(f,E,_){if(_?.aborted)return Promise.reject(vf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",A)},P=(M)=>{if(x)return;x=!0,N(),T(M)},S=(M)=>{if(x)return;x=!0,N(),h(M instanceof Error?M:Error(String(M)))},A=()=>{if(_)S(vf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",A,{once:!0}),_?.aborted){A();return}f.then((M)=>P({kind:"next",result:M}),S)})}async function*HT(f,E,_){let T=uT(E),h=IT(T,E.stallWarningMs);if(E.signal?.aborted)throw vf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let A=await DT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(A.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return A.result}if(!P&&h!==void 0){_.stallCount++,P={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield P;continue}let t=new rE(T);throw E.abort?.(t),t}}async function*f_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),P=0,S=!1,A={stallCount:0,outputStarted:!1};try{while(!0){let t=HT(N,h,A),M=await t.next();while(!M.done)yield{providerStall:M.value},M=await t.next();let I=M.value;if(I.done)throw new iE;let Y=I.value;switch(Y.type){case"text_delta":A.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":A.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":A.outputStarted=!0,yield{toolCalls:[{index:P++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":S=!0,yield{finishReason:Y.reason,usage:nE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!S)Promise.resolve(N.return?.()).catch(()=>{return})}}var wf=l("Chat"),UT=1;function YT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function bT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function BT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=e(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=of(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function pf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class gf{config;models;model;promptCacheBreakMonitor=new zf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${UT++}`;constructor(f){let E=Xf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=E_(this.config),wf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],P,S;for await(let A of this.streamChat(f,E,_,T)){h+=A.content??"",x+=A.reasoningContent??"";for(let t of A.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);P=A.usage??P,S=A.finishReason??S}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,finishReason:S}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=ME(f);if(x.some((R)=>bT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||AE(x),P=await PE(x,this.model,E,_,h),S=(R,u)=>{let O=T?.providerSessionId;if(!O||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(O),R;let b=sf(this.config,u,O),H=this.promptCacheBreakMonitor.observe({sessionId:O,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,retention:b,contextEpoch:BT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:b,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!H)return R;return wf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:H}}},A=pE({messages:x,context:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!T_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,I=M?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(M?__:2),Q=M!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??BE(),Rf=this.config.providerCircuitBreakerOpenMs??Jf,h_=Math.max(uf,Math.min(this.config.streamIdleTimeout??Hf,$f)),lf=this.providerAdmissionScheduler,x_=this.config.providerRequestConcurrency??q,af=this.config.providerRequestAdmissionMs??Qf,t_=this.config.providerRequestPendingBytes??Kf,Yf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},R_=(R,u)=>Uf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Rf,probeLeaseMs:h_}),P_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:x_,maxPendingBytes:t_}),j=(R=Date.now())=>{if(!M)return;let u=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,R-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,M.budgetMs-u)}},v=()=>({mode:I,...j()??{}}),yf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},w=()=>{let R=j();return new y(M?.budgetMs??0,R?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,bf=(R,u)=>{let{state:O,...b}=u;return{phase:R,...b,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},ef=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),M_=async function*(R,u){if(!lf)return{release:()=>{return}};let O=j()?.recoveryRemainingMs,b=O!==void 0&&M?.startedAt!==void 0?Math.min(af,O):af,H;try{H=lf.admit({scope:P_(R,u),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:b,pendingBytes:A,signal:_})}catch(B){if(tf(B)){if(B.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(B)}}throw B}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:bf("queued",L)};let F=H.ready.then((B)=>({kind:"ready",permit:B}),(B)=>({kind:"error",error:B}));while(!0){let B=H.getSnapshot(),c=Math.max(1,Math.min(oE,Math.max(1,b-B.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),c),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:bf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(tf(G.error)){if(G.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(G.error)}}throw G.error}return yield{providerAdmission:bf("admitted",H.getSnapshot())},G.permit}},A_=(R,u)=>{if(!d())throw w();if(Q)K++;o=void 0;let O=new AbortController,b=_?hE(_,O.signal):O.signal,H=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,L;if(M?.startedAt!==void 0){let c=j()?.recoveryRemainingMs??0;if(c<=0)throw w();L={remainingMs:c,error:new y(M.budgetMs,M.budgetMs)}}let F=eE(u,R,b,T,N);dE(F,R,(c)=>{o=c});let B=f_(this.models,R,P,F,{idleTimeoutMs:u.streamIdleTimeout??Hf,signal:b,abort:(c)=>O.abort(c)});return async function*(){let c,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new Cf(H);c=setTimeout(()=>O.abort(X),H),c.unref?.()}if(L){let X=L;J=setTimeout(()=>O.abort(X.error),X.remainingMs),J.unref?.()}yield*B}finally{if(c)clearTimeout(c);if(J)clearTimeout(J)}}()},df=this,g=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),nf=(R,u)=>({phase:R,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),S_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Rf,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),Bf=(R,u,O)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:$,reason:u,...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}}),rf=async function*(R,u,O,b,H){let L,F=!1,B,c,J=R_(R,u);for(let X=0;X<=b;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(B=D.reason,c=D.statusCode,!M||!H){let C=nf("rejected",D);throw yield{providerCircuit:C},new hf(C)}yf();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:nf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),mf,V);if(await ff(m,_,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*M_(R,u)}catch(Z){if(Z instanceof y)yield Bf(Q?Math.max(0,K-1):X,B??"timeout",c);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let n=G.token;if(G.probe)yield{providerCircuit:S_(G)};try{let D=!1,k=!1;for await(let Z of A_(R,u)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&B&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(n);if(m)yield{providerCircuit:g(m)}}F=!0,O(),yield S(Z,R)}if(!k){let Z=J.recordSuccess(n);if(Z)yield{providerCircuit:g(Z)}}return}catch(D){if(p?.release(),L=D,df.logIdleTimeout(D,F,R),await df.handleAbort(_),D instanceof y){if(F)throw Ff(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B??"timeout",...c!==void 0?{statusCode:c}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=e(D,o);if(F)throw Ff(D),D;let Z=cT(D,o),V=Z?J.recordFailure(n,Z):o&&!pf(D)?J.recordNeutral(n):void 0;if(V)yield{providerCircuit:g(V)};if(!k.retryable||!k.reason){if(X>0&&B)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};throw D}B=k.reason,c=k.statusCode;let m=X<b&&d();if(V&&V.phase!=="closed"&&m&&(!M||!H)){let C={...g(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){yf();let C=Q?K:X+1,u_=gE(C,o,M?{maxDelayMs:qf,maxExponentialDelayMs:qf}:void 0),EE=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(M&&EE>0&&V)yield{providerCircuit:{...g(V),phase:"waiting"}};let I_=j(),Of=Math.max(u_,EE),r=M?Math.min(Of,I_?.recoveryRemainingMs??Of):Of,Mf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:r,nextRetryAt:Date.now()+r,...v()}},M){let i=r;while(i>0){let _E=Math.min(i,mf);if(await ff(_E,_,{throwOnAbort:!0}),i-=_E,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Mf,...v(),exhaustedBy:"recovery_budget"}},Af}if(i>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...g(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:r,nextRetryAt:Date.now()+i,...v()}}}}}else await ff(r,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...M&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(n),p?.release()}}throw L},cf,fE=!1,Pf=this.config.fallbackModels??[],N_=M&&Pf.length>0?Math.min(Y,$):$;try{for await(let R of rf(this.model,this.config,()=>{fE=!0},N_,Pf.length===0))yield R;return}catch(R){if(cf=R,fE||!tf(R)&&!kf(R)&&!pf(R)&&!e(R,o).retryable)throw R}for(let[R,u]of Pf.entries()){if(!d())break;yield{modelFallback:!0};let O=!1;try{let b=YT(this.config,u),H=uE(b,u),L=R===Pf.length-1,F=M&&!L?Math.min(Y,$):$;for await(let B of rf(H,b,()=>{O=!0},F,L))yield B;return}catch(b){if(cf=b,O||!tf(b)&&!kf(b)&&!pf(b)&&!e(b,o).retryable)throw b}}throw cf}async handleAbort(f){if(f?.aborted)await ff(0,f,{throwOnAbort:!0})}logIdleTimeout(f,E,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;wf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=Xf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=E_(this.config)}}function E_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return vE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??q,classLimitsEnabled:!1})}var OT=l("Service");async function Zh(f){let E=f;if(E.provider){let _=TE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},OT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return VT(E)}function VT(f){return new gf(f)}
|
|
5
|
-
export{zT as Xf,$T as Yf,hE as Zf,ff as _f,tf as $f,wE as ag,ET as bg,Ph as cg,e as dg,gE as eg,gf as fg,Zh as gg};
|
package/dist/chunk-as8stb2j.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-qjydadex.js";import"./chunk-1pmvyqed.js";import"./chunk-r51afpkk.js";import"./chunk-9z9v8v4j.js";import"./chunk-46jmq302.js";import"./chunk-g4vgnxh4.js";import"./chunk-sy0vxdc3.js";import"./chunk-24rsvr6e.js";import"./chunk-hx10bph0.js";import"./chunk-gq7fdc8c.js";import"./chunk-c5rfnzhf.js";import"./chunk-wzkh3e6a.js";import"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import{pf as R}from"./chunk-v2qxszks.js";import"./chunk-kbnxbb23.js";import{Lf as Q}from"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-acsfh1cw.js";import"./chunk-tev70rzj.js";import"./chunk-vvawhvea.js";import"./chunk-82x77b2p.js";import"./chunk-1cbaqh71.js";import"./chunk-5sknjz9b.js";import"./chunk-f7hsagj6.js";import"./chunk-sv5z5sna.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import"./chunk-mm1atkae.js";import"./chunk-gdnyt8a7.js";import"./chunk-vptn8fhx.js";import"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import"./chunk-bdtpq7j9.js";import{Kj as M}from"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-azaqc1b6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ib as a,Jb as b,Lb as c,Pb as d,Qb as e,Rb as f,Sb as g,Tb as h,Ub as i,Vb as j,Wb as k,bc as l,cc as m,dc as n,ec as o,gc as p,hc as q,ic as r}from"./chunk-c5rfnzhf.js";import"./chunk-wzkh3e6a.js";import"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import"./chunk-q0s3gcjm.js";import"./chunk-acsfh1cw.js";import"./chunk-vvawhvea.js";import"./chunk-5sknjz9b.js";import"./chunk-f7hsagj6.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import"./chunk-gdnyt8a7.js";import"./chunk-vptn8fhx.js";import"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.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};
|