blade-code 0.11.6 → 0.11.7
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-nneh4gkw.js → chunk-03ax0738.js} +1 -1
- package/dist/{chunk-mhv4q5sg.js → chunk-03hbrytg.js} +1 -1
- package/dist/{chunk-6sk6chsm.js → chunk-0w3h2qnk.js} +1 -1
- package/dist/{chunk-cfxs7jdk.js → chunk-1khsmsem.js} +1 -1
- package/dist/{chunk-xmp1ve8a.js → chunk-253fwyzb.js} +1 -1
- package/dist/{chunk-8d1vekke.js → chunk-29ek6raw.js} +1 -1
- package/dist/{chunk-nh301gpr.js → chunk-33sgdacd.js} +1 -1
- package/dist/{chunk-yh28byeh.js → chunk-37exmxas.js} +1 -1
- package/dist/{chunk-n32pbwyk.js → chunk-4mamvx8a.js} +3 -3
- package/dist/{chunk-0vw2xj0h.js → chunk-4rqen6w9.js} +1 -1
- package/dist/{chunk-nznd7549.js → chunk-4v28fy5p.js} +1 -1
- package/dist/{chunk-qfp7emtk.js → chunk-6f5gf32h.js} +1 -1
- package/dist/{chunk-vnxj21sa.js → chunk-6s4btp37.js} +99 -97
- package/dist/{chunk-qexnx2v2.js → chunk-70n8qq1r.js} +1 -1
- package/dist/{chunk-87bd1w02.js → chunk-9f99qxqc.js} +1 -1
- package/dist/{chunk-rgxknntk.js → chunk-9q7egv5e.js} +1 -1
- package/dist/{chunk-vgkcck5q.js → chunk-atjraymv.js} +1 -1
- package/dist/chunk-byrk9d45.js +1 -0
- package/dist/{chunk-acxyw1ej.js → chunk-chhf109c.js} +1 -1
- package/dist/{chunk-6jjpj5ge.js → chunk-d561qcwy.js} +1 -1
- package/dist/{chunk-8yh4mn8a.js → chunk-d9gdv6hv.js} +1 -1
- package/dist/chunk-drqv15xs.js +1 -0
- package/dist/{chunk-s2ner5gp.js → chunk-dtv22yvk.js} +1 -1
- package/dist/{chunk-ftk0ytf8.js → chunk-ep0g03gq.js} +1 -1
- package/dist/{chunk-t39n33ek.js → chunk-exp8ksxn.js} +1 -1
- package/dist/{chunk-zzacj0n9.js → chunk-f7nx3ewr.js} +1 -1
- package/dist/{chunk-hxwzdkwp.js → chunk-ghg7sbxt.js} +1 -1
- package/dist/{chunk-fprmcxd6.js → chunk-gt2wpeyx.js} +1 -1
- package/dist/{chunk-y7zh1sq6.js → chunk-hdbxph08.js} +1 -1
- package/dist/{chunk-6h1x1m4f.js → chunk-j4v5f56k.js} +1 -1
- package/dist/{chunk-vp4rdvvw.js → chunk-j6tm12ft.js} +1 -1
- package/dist/{chunk-bzwxh6nq.js → chunk-k17d0ysy.js} +1 -1
- package/dist/{chunk-avrnqtca.js → chunk-n90wq61v.js} +1 -1
- package/dist/{chunk-a1y938pg.js → chunk-ska66dmc.js} +1 -1
- package/dist/{chunk-sb12h5yv.js → chunk-vrk1p3p2.js} +1 -1
- package/dist/{chunk-aq7e74mn.js → chunk-wqk2nkm4.js} +2 -2
- package/dist/{chunk-yg81xx37.js → chunk-yeee0ac9.js} +1 -1
- package/dist/{chunk-5vh8zyjz.js → chunk-zhnctpb5.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2s1gmqh4.js +0 -1
- package/dist/chunk-p9dvggw1.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ac as En,xc as Ut,yc as fn,zc as yn}from"./chunk-9qxch6sy.js";import{Ah as xt}from"./chunk-
|
|
1
|
+
import{Ac as En,xc as Ut,yc as fn,zc as yn}from"./chunk-9qxch6sy.js";import{Ah as xt}from"./chunk-d9gdv6hv.js";import{$h as S,Gh as Ot,Hh as vi,Jh as en,Kh as Bt,Lh as U,Mh as sn,Nh as St,Oh as gt,Qh as rn,Rh as Tn,Sh as B,Th as on,Uh as dn,Vh as pn,Wh as Lt,Xh as cn,Yh as un,Zh as Mn,ci as wn,di as Vt,ei as lt,fi as h,gi as jt}from"./chunk-ep0g03gq.js";import{Zi as Zt}from"./chunk-b22ab7yw.js";import{Gj as X,Ij as g}from"./chunk-saz6mwpq.js";import{Xj as tn,Yj as nn}from"./chunk-k17d0ysy.js";import{Jk as ne}from"./chunk-gmpsfkgg.js";import{EventEmitter as be}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Yt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Ft(t,i){let n=X(t,i);if(n.success)return n.data;let e=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),s=e.length===1?`参数验证失败 [${e[0].field}]: ${e[0].message}`:`参数验证失败 (${e.length} 个错误):
|
|
2
2
|
${e.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Yt(s,e)}function et(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let e of n)et(e);else et(n)}function st(t){let i=JSON.parse(JSON.stringify(t,(n,e)=>n.startsWith("~")?void 0:e));return et(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,e,s,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=e;this.affectedPathsFn=s;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let e={signal:t,updateOutput:i,...n};return this.executeFn(this.params,e)}}function Jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=st(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{M as N,ka as _,la as z}from"./chunk-n32pbwyk.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-6jjpj5ge.js";import{Di as M,Ei as O}from"./chunk-ftk0ytf8.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
1
|
+
import{M as N,ka as _,la as z}from"./chunk-4mamvx8a.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-d561qcwy.js";import{Di as M,Ei as O}from"./chunk-ep0g03gq.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
2
2
|
export{C as w,k as x,T as y,a as z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as d,Zj as h}from"./chunk-
|
|
1
|
+
import{Xj as d,Zj as h}from"./chunk-k17d0ysy.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as xf,w as yf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{w as QH,x as YH,z as a}from"./chunk-
|
|
1
|
+
import{w as QH,x as YH,z as a}from"./chunk-9f99qxqc.js";import{A as uz,B as gz,C as cz,D as S}from"./chunk-gt2wpeyx.js";import{E as JH,F as Rz,G as Sz,H as Mz,I as Iz,J as hz}from"./chunk-03ax0738.js";import{$ as qz,Ea as yz,Fa as kz,Ga as Cz,Ha as fz,Q as R,_ as Ez,ha as Tz,ka as Pz,la as xz,oa as bz}from"./chunk-4mamvx8a.js";import"./chunk-nad5spvc.js";import{Va as HH}from"./chunk-70n8qq1r.js";import{$a as i,Xa as Oz,cb as r}from"./chunk-whxkwaz1.js";import{Rb as Nz,bc as Az,mc as l}from"./chunk-6s4btp37.js";import{xc as m}from"./chunk-9qxch6sy.js";import{$d as Fz,Hd as _z,Rd as I,Sd as d,Td as Vz,Yd as Dz,ae as Kz,ce as M,fe as jz,ke as wz,ne as K}from"./chunk-d561qcwy.js";import"./chunk-skktstg8.js";import{Le as Uz,Se as n,Te as Gz}from"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as ZH}from"./chunk-j4v5f56k.js";import"./chunk-crv3sghv.js";import{Zf as sz,_f as tz}from"./chunk-chhf109c.js";import{fg as zz}from"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import{kg as Bz}from"./chunk-1g7c3f82.js";import{sg as p}from"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import{xg as ez}from"./chunk-pm163dfm.js";import"./chunk-1khsmsem.js";import"./chunk-ska66dmc.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as zH}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-d9gdv6hv.js";import"./chunk-ys8gysg8.js";import{Ai as oz,xi as nz}from"./chunk-ep0g03gq.js";import{Zi as e}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import{Aj as v,wj as g,xj as Wz,zj as c}from"./chunk-m2x6pb4f.js";import{Ej as h}from"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import{Rj as rz,Uj as az}from"./chunk-0eajnhrj.js";import"./chunk-k17d0ysy.js";import"./chunk-asgmmaec.js";import{dk as Lz,ek as lz,ik as Hz,mk as Jz,nk as iz,ok as Qz}from"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import{Readable as NH,Writable as AH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as DH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as vz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function LH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function WH(z){let H={};for(let J of z){let Y=LH(J);if(Y)H[J.name]=Y}return H}function pz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function BH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:pz(z.content)}function _H(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function UH(z){if(!Bz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function GH(z){if(!(z instanceof vz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Vz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function VH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,J,Y,X={}){this.id=z;this.roots=H;this.connection=J;this.clientCapabilities=Y;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new hz({maxPendingItems:Rz,maxPendingBytes:Sz,writeTimeoutMs:Mz,signal:J.signal,sizeOf:(L)=>Buffer.byteLength(JSON.stringify(L)),write:async(L)=>{await J.sessionUpdate(L)},onFailure:(L)=>this.handleUpdateEgressFailure(L)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(J){if(!(J instanceof wz)&&J.code!=="ENOENT")throw J;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.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 bz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async($)=>{await this.sendUpdateAndWait($)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:($)=>this.requestPermission($)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?WH(this.options.mcpServers):void 0,Y=R.getTerminalService(this.id),X=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 Tz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...X?{workspace:X}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,_)=>{let U=await Y.execute($,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await kz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Nz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.roots.hostStateRoot)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="follow_up.queue.changed"){let _=i.safeParse($.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if($.type==="provider.recovery"){let _=p.safeParse($.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if($.type==="turn.activity"){let _=r.safeParse($.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=$.properties,T=$.properties.metadata;if($.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&qz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Ez(_,Lz()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Uz(H))continue;if(Kz(H)&&typeof H.content==="string"){if(!await this.sendUpdateAndWait({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
3
3
|
|
|
4
4
|
recap: ${H.content}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-hdbxph08.js";import"./chunk-k17d0ysy.js";import"./chunk-gmpsfkgg.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fg as G0}from"./chunk-x6k5ye1z.js";import{Hh as Y0,Ri as l,Ui as Z0,si as W}from"./chunk-ftk0ytf8.js";import{Zi as z0}from"./chunk-b22ab7yw.js";import{Qj as u}from"./chunk-xhwdac1j.js";import{devtools as B0,subscribeWithSelector as q0}from"zustand/middleware";import{createStore as D0}from"zustand/vanilla";var o=[{id:"ayu-dark",label:"Ayu Dark",theme:{name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:{name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:{name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},tags:["dark","classic"]},{id:"nord",label:"Nord",theme:{name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:{name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:{name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:{name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},tags:["dark","popular"]},{id:"github",label:"GitHub",theme:{name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:{name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:{name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:{name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:{name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:{name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},tags:["dark","japanese"]}];var a=o;var n={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},S={name:"default",colors:n,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},V0={...S,name:"dark",colors:{...n,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class s{currentTheme=S;themes=new Map;constructor(){this.themes.set("default",S),this.themes.set("dark",V0);for(let f of a)this.themes.set(f.id,f.theme)}setTheme(f){let y=this.themes.get(f);if(y)this.currentTheme=y;else throw Error(`Theme '${f}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(f){return this.themes.get(f)}hasTheme(f){return this.themes.has(f)}}var e=new s;var H0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,taskAttentionStatus:"idle",taskAttentionUnreadKeys:[],followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]},modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,reasoningEffort:"off",serviceTier:"auto",responseVerbosity:"auto",communicationStyle:"auto",subagentProgress:null,subagentProgresses:{},sideConversation:null,teams:[]},g=(f)=>({...H0,actions:{setInitializationStatus:(y)=>{f((b)=>({app:{...b.app,initializationStatus:y}}))},setInitializationError:(y)=>{f((b)=>({app:{...b.app,initializationError:y}}))},setActiveModal:(y)=>{f((b)=>({app:{...b.app,activeModal:y}}))},showSessionSelector:(y,b="resume")=>{f((x)=>({app:{...x.app,activeModal:"sessionSelector",sessionSelectorData:{intent:b,sessions:y},sessionHistoryViewerData:void 0}}))},showSessionHistoryViewer:(y,b="resume")=>{f((x)=>({app:{...x.app,activeModal:"sessionHistoryViewer",sessionSelectorData:void 0,sessionHistoryViewerData:{intent:b,session:y}}}))},showModelEditWizard:(y)=>{f((b)=>({app:{...b.app,activeModal:"modelEditWizard",modelEditorTarget:y}}))},closeModal:()=>{f((y)=>({app:{...y.app,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,modelEditorTarget:null}}))},setTasks:(y)=>{f((b)=>({app:{...b.app,tasks:y}}))},updateTask:(y)=>{f((b)=>({app:{...b.app,tasks:b.app.tasks.map((x)=>x.id===y.id?y:x)}}))},setAwaitingSecondCtrlC:(y)=>{f((b)=>({app:{...b.app,awaitingSecondCtrlC:y}}))},projectTaskAttentionState:(y,b,x)=>{f((p)=>({app:{...p.app,taskAttentionStatus:y,taskAttentionUnreadKeys:[...b],sessionSelectorData:y==="ready"&&p.app.activeModal==="sessionSelector"&&p.app.sessionSelectorData?{...p.app.sessionSelectorData,sessions:[...x]}:p.app.sessionSelectorData}}))},projectFollowUpQueue:(y,b)=>{f((x)=>{let p=[x.session.workspaceRoot,x.session.sessionId,""].join("\x00");if(b!==void 0&&!b.startsWith(p))return x;if(b!==void 0&&x.app.followUpQueueOwner!==null&&x.app.followUpQueueOwner!==b)return x;let h=x.app.followUpQueueMutation.supersededVersions??[];if(h.includes(y.version))return x;let F=x.app.followUpQueue&&x.app.followUpQueue.version!==y.version?[...h,x.app.followUpQueue.version].slice(-16):h;return{app:{...x.app,followUpQueue:y,followUpQueueOwner:b??x.app.followUpQueueOwner,followUpQueueMutation:{pending:x.app.followUpQueueMutation.pending,...x.app.followUpQueueMutation.messageId?{messageId:x.app.followUpQueueMutation.messageId}:{},supersededVersions:F}},command:{...x.command,followUpPresentations:Object.fromEntries(Object.entries(x.command.followUpPresentations).filter(([z])=>y.items.some((G)=>G.id===z)))}}})},claimFollowUpQueueOwner:(y)=>{f((b)=>{let x=[b.session.workspaceRoot,b.session.sessionId,""].join("\x00");if(!y.startsWith(x))return b;if(b.app.followUpQueueOwner===y)return b;return{app:{...b.app,followUpQueue:null,followUpQueueOwner:y,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...b.command,followUpPresentations:{}}}})},setFollowUpQueueMutation:(y,b)=>{f((x)=>{let p=[x.session.workspaceRoot,x.session.sessionId,""].join("\x00");if(b!==void 0&&!b.startsWith(p))return x;if(b!==void 0&&x.app.followUpQueueOwner!==null&&x.app.followUpQueueOwner!==b)return x;return{app:{...x.app,followUpQueueMutation:{...y,supersededVersions:y.supersededVersions??x.app.followUpQueueMutation.supersededVersions}}}})},clearFollowUpQueue:(y)=>{f((b)=>{if(y!==void 0&&b.app.followUpQueueOwner!==y)return b;return{app:{...b.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...b.command,followUpPresentations:{}}}})},setReasoningEffort:(y)=>{f((b)=>({app:{...b.app,reasoningEffort:y}}))},setServiceTier:(y)=>{f((b)=>({app:{...b.app,serviceTier:y}}))},setResponseVerbosity:(y)=>{f((b)=>({app:{...b.app,responseVerbosity:y}}))},setCommunicationStyle:(y)=>{f((b)=>({app:{...b.app,communicationStyle:y}}))},setThinkingModeEnabled:(y)=>{f((b)=>({app:{...b.app,reasoningEffort:y?"auto":"off"}}))},toggleThinkingMode:()=>{f((y)=>({app:{...y.app,reasoningEffort:y.app.reasoningEffort==="off"?"auto":"off"}}))},startSubagentProgress:(y,b,x)=>{f((p)=>({app:{...p.app,subagentProgresses:{...p.app.subagentProgresses,[y]:{id:y,type:b,description:x,status:"running",startTime:Date.now()}},subagentProgress:{id:y,type:b,description:x,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(y,b)=>{f((x)=>{let p=x.app.subagentProgresses[y];if(!p)return x;let h={...p,currentTool:b};return{app:{...x.app,subagentProgresses:{...x.app.subagentProgresses,[y]:h},subagentProgress:x.app.subagentProgress?.id===y?h:x.app.subagentProgress}}})},completeSubagentProgress:(y,b,x)=>{f((p)=>{let h=p.app.subagentProgresses[y];if(!h)return p;let F=x?.trim(),z={...h,status:b?"completed":"failed",currentTool:void 0,...!b&&F?{terminalSummary:F.slice(0,200)}:{}};return{app:{...p.app,subagentProgresses:{...p.app.subagentProgresses,[y]:z},subagentProgress:p.app.subagentProgress?.id===y?z:p.app.subagentProgress}}}),setTimeout(()=>{f((p)=>{let h=p.app.subagentProgresses[y];if(!h||h.status==="running")return p;let F={...p.app.subagentProgresses};delete F[y];let z=Object.values(F);return{app:{...p.app,subagentProgresses:F,subagentProgress:p.app.subagentProgress?.id===y?z[z.length-1]??null:p.app.subagentProgress}}})},1500)},startSideConversation:(y,b)=>{f((x)=>({app:{...x.app,sideConversation:{requestId:y,question:b,status:"loading"}}}))},completeSideConversation:(y,b)=>{f((x)=>{if(x.app.sideConversation?.requestId!==y)return x;return{app:{...x.app,sideConversation:{requestId:y,question:x.app.sideConversation.question,status:"completed",response:b.response,durationMs:b.durationMs}}}})},failSideConversation:(y,b)=>{f((x)=>{if(x.app.sideConversation?.requestId!==y)return x;return{app:{...x.app,sideConversation:{requestId:y,question:x.app.sideConversation.question,status:"error",error:b}}}})},dismissSideConversation:()=>{f((y)=>({app:{...y.app,sideConversation:null}}))},setTeams:(y)=>{f((b)=>({app:{...b.app,teams:y}}))}}});var U0={isProcessing:!1,abortController:null,followUpPresentations:{},recoveredSteeringCount:0},T=(f,y)=>({...U0,actions:{setProcessing:(b)=>{f((x)=>({command:{...x.command,isProcessing:b},...!b?{session:{...x.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}:{}}))},createAbortController:()=>{let b=y().command.abortController;if(b&&!b.signal.aborted)b.abort("interrupted-by-new-command");let x=new AbortController;return f((p)=>({command:{...p.command,abortController:x}})),x},getAbortController:()=>{return y().command.abortController},clearAbortController:(b)=>{let x=y().command.abortController;if(b!==void 0&&x!==b)return;f((p)=>({command:{...p.command,abortController:null}}))},abort:(b)=>{let{abortController:x}=y().command;if(x&&!x.signal.aborted)x.abort(b??"user-cancel");f((p)=>({command:{...p.command,isProcessing:!1},session:{...p.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}))},rememberFollowUpPresentation:(b,x)=>{f((p)=>({command:{...p.command,followUpPresentations:Object.fromEntries([...Object.entries(p.command.followUpPresentations),[b,x]].slice(-20))}}))},takeFollowUpPresentation:(b)=>{let x=y().command.followUpPresentations[b];if(!x)return;return f((p)=>({command:{...p.command,followUpPresentations:Object.fromEntries(Object.entries(p.command.followUpPresentations).filter(([h])=>h!==b))}})),x},clearFollowUpPresentations:()=>{f((b)=>({command:{...b.command,followUpPresentations:{}}}))},setRecoveredSteeringCount:(b)=>{f((x)=>({command:{...x.command,recoveredSteeringCount:Math.max(0,b)}}))}}});var j0={config:null},C=(f,y)=>({...j0,actions:{setConfig:(b)=>{u().configureModelProviders(b.modelProviders,b.models),f((x)=>({config:{...x.config,config:b}}))},updateConfig:(b)=>{let x=y().config.config;if(!x)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(b)}`);let p={...x,...b};if(b.modelProviders||b.models)u().configureModelProviders(p.modelProviders,p.models);f((h)=>({config:{...h.config,config:p}}))}}});var _0={currentFocus:"main-input",previousFocus:null},v=(f)=>({..._0,actions:{setFocus:(y)=>{f((b)=>({focus:{...b.focus,currentFocus:y,previousFocus:b.focus.currentFocus}}))},restorePreviousFocus:()=>{f((y)=>({focus:{...y.focus,currentFocus:y.focus.previousFocus||"main-input",previousFocus:null}}))}}});function I(f,y,b,x){let p=f.messages.find((F)=>F.id===y);if(p)return p;let h={id:y,role:b,content:"",timestamp:x};return f.messages.push(h),h}function t(f,y){let b=Date.parse(y.timestamp)||Date.now();switch(y.type){case"message_created":{let x=I(f,y.data.messageId,y.data.role,b),p=y.data.metadata;if(p&&typeof p==="object"&&!Array.isArray(p))x.metadata=p;return f}case"part_created":case"part_updated":{let{messageId:x,partType:p,payload:h,partId:F}=y.data,z=f.messages.find((G)=>G.id===x)??I(f,x,"assistant",b);if(p==="text"){let G=h.text??"";f.streamingText.delete(F),z.content=G}else if(p==="image")z.content=z.content?`${z.content}
|
|
1
|
+
import{fg as G0}from"./chunk-x6k5ye1z.js";import{Hh as Y0,Ri as l,Ui as Z0,si as W}from"./chunk-ep0g03gq.js";import{Zi as z0}from"./chunk-b22ab7yw.js";import{Qj as u}from"./chunk-xhwdac1j.js";import{devtools as B0,subscribeWithSelector as q0}from"zustand/middleware";import{createStore as D0}from"zustand/vanilla";var o=[{id:"ayu-dark",label:"Ayu Dark",theme:{name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:{name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:{name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},tags:["dark","classic"]},{id:"nord",label:"Nord",theme:{name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:{name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:{name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:{name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},tags:["dark","popular"]},{id:"github",label:"GitHub",theme:{name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:{name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:{name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:{name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:{name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:{name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},tags:["dark","japanese"]}];var a=o;var n={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},S={name:"default",colors:n,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},V0={...S,name:"dark",colors:{...n,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class s{currentTheme=S;themes=new Map;constructor(){this.themes.set("default",S),this.themes.set("dark",V0);for(let f of a)this.themes.set(f.id,f.theme)}setTheme(f){let y=this.themes.get(f);if(y)this.currentTheme=y;else throw Error(`Theme '${f}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(f){return this.themes.get(f)}hasTheme(f){return this.themes.has(f)}}var e=new s;var H0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,taskAttentionStatus:"idle",taskAttentionUnreadKeys:[],followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]},modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,reasoningEffort:"off",serviceTier:"auto",responseVerbosity:"auto",communicationStyle:"auto",subagentProgress:null,subagentProgresses:{},sideConversation:null,teams:[]},g=(f)=>({...H0,actions:{setInitializationStatus:(y)=>{f((b)=>({app:{...b.app,initializationStatus:y}}))},setInitializationError:(y)=>{f((b)=>({app:{...b.app,initializationError:y}}))},setActiveModal:(y)=>{f((b)=>({app:{...b.app,activeModal:y}}))},showSessionSelector:(y,b="resume")=>{f((x)=>({app:{...x.app,activeModal:"sessionSelector",sessionSelectorData:{intent:b,sessions:y},sessionHistoryViewerData:void 0}}))},showSessionHistoryViewer:(y,b="resume")=>{f((x)=>({app:{...x.app,activeModal:"sessionHistoryViewer",sessionSelectorData:void 0,sessionHistoryViewerData:{intent:b,session:y}}}))},showModelEditWizard:(y)=>{f((b)=>({app:{...b.app,activeModal:"modelEditWizard",modelEditorTarget:y}}))},closeModal:()=>{f((y)=>({app:{...y.app,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,modelEditorTarget:null}}))},setTasks:(y)=>{f((b)=>({app:{...b.app,tasks:y}}))},updateTask:(y)=>{f((b)=>({app:{...b.app,tasks:b.app.tasks.map((x)=>x.id===y.id?y:x)}}))},setAwaitingSecondCtrlC:(y)=>{f((b)=>({app:{...b.app,awaitingSecondCtrlC:y}}))},projectTaskAttentionState:(y,b,x)=>{f((p)=>({app:{...p.app,taskAttentionStatus:y,taskAttentionUnreadKeys:[...b],sessionSelectorData:y==="ready"&&p.app.activeModal==="sessionSelector"&&p.app.sessionSelectorData?{...p.app.sessionSelectorData,sessions:[...x]}:p.app.sessionSelectorData}}))},projectFollowUpQueue:(y,b)=>{f((x)=>{let p=[x.session.workspaceRoot,x.session.sessionId,""].join("\x00");if(b!==void 0&&!b.startsWith(p))return x;if(b!==void 0&&x.app.followUpQueueOwner!==null&&x.app.followUpQueueOwner!==b)return x;let h=x.app.followUpQueueMutation.supersededVersions??[];if(h.includes(y.version))return x;let F=x.app.followUpQueue&&x.app.followUpQueue.version!==y.version?[...h,x.app.followUpQueue.version].slice(-16):h;return{app:{...x.app,followUpQueue:y,followUpQueueOwner:b??x.app.followUpQueueOwner,followUpQueueMutation:{pending:x.app.followUpQueueMutation.pending,...x.app.followUpQueueMutation.messageId?{messageId:x.app.followUpQueueMutation.messageId}:{},supersededVersions:F}},command:{...x.command,followUpPresentations:Object.fromEntries(Object.entries(x.command.followUpPresentations).filter(([z])=>y.items.some((G)=>G.id===z)))}}})},claimFollowUpQueueOwner:(y)=>{f((b)=>{let x=[b.session.workspaceRoot,b.session.sessionId,""].join("\x00");if(!y.startsWith(x))return b;if(b.app.followUpQueueOwner===y)return b;return{app:{...b.app,followUpQueue:null,followUpQueueOwner:y,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...b.command,followUpPresentations:{}}}})},setFollowUpQueueMutation:(y,b)=>{f((x)=>{let p=[x.session.workspaceRoot,x.session.sessionId,""].join("\x00");if(b!==void 0&&!b.startsWith(p))return x;if(b!==void 0&&x.app.followUpQueueOwner!==null&&x.app.followUpQueueOwner!==b)return x;return{app:{...x.app,followUpQueueMutation:{...y,supersededVersions:y.supersededVersions??x.app.followUpQueueMutation.supersededVersions}}}})},clearFollowUpQueue:(y)=>{f((b)=>{if(y!==void 0&&b.app.followUpQueueOwner!==y)return b;return{app:{...b.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...b.command,followUpPresentations:{}}}})},setReasoningEffort:(y)=>{f((b)=>({app:{...b.app,reasoningEffort:y}}))},setServiceTier:(y)=>{f((b)=>({app:{...b.app,serviceTier:y}}))},setResponseVerbosity:(y)=>{f((b)=>({app:{...b.app,responseVerbosity:y}}))},setCommunicationStyle:(y)=>{f((b)=>({app:{...b.app,communicationStyle:y}}))},setThinkingModeEnabled:(y)=>{f((b)=>({app:{...b.app,reasoningEffort:y?"auto":"off"}}))},toggleThinkingMode:()=>{f((y)=>({app:{...y.app,reasoningEffort:y.app.reasoningEffort==="off"?"auto":"off"}}))},startSubagentProgress:(y,b,x)=>{f((p)=>({app:{...p.app,subagentProgresses:{...p.app.subagentProgresses,[y]:{id:y,type:b,description:x,status:"running",startTime:Date.now()}},subagentProgress:{id:y,type:b,description:x,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(y,b)=>{f((x)=>{let p=x.app.subagentProgresses[y];if(!p)return x;let h={...p,currentTool:b};return{app:{...x.app,subagentProgresses:{...x.app.subagentProgresses,[y]:h},subagentProgress:x.app.subagentProgress?.id===y?h:x.app.subagentProgress}}})},completeSubagentProgress:(y,b,x)=>{f((p)=>{let h=p.app.subagentProgresses[y];if(!h)return p;let F=x?.trim(),z={...h,status:b?"completed":"failed",currentTool:void 0,...!b&&F?{terminalSummary:F.slice(0,200)}:{}};return{app:{...p.app,subagentProgresses:{...p.app.subagentProgresses,[y]:z},subagentProgress:p.app.subagentProgress?.id===y?z:p.app.subagentProgress}}}),setTimeout(()=>{f((p)=>{let h=p.app.subagentProgresses[y];if(!h||h.status==="running")return p;let F={...p.app.subagentProgresses};delete F[y];let z=Object.values(F);return{app:{...p.app,subagentProgresses:F,subagentProgress:p.app.subagentProgress?.id===y?z[z.length-1]??null:p.app.subagentProgress}}})},1500)},startSideConversation:(y,b)=>{f((x)=>({app:{...x.app,sideConversation:{requestId:y,question:b,status:"loading"}}}))},completeSideConversation:(y,b)=>{f((x)=>{if(x.app.sideConversation?.requestId!==y)return x;return{app:{...x.app,sideConversation:{requestId:y,question:x.app.sideConversation.question,status:"completed",response:b.response,durationMs:b.durationMs}}}})},failSideConversation:(y,b)=>{f((x)=>{if(x.app.sideConversation?.requestId!==y)return x;return{app:{...x.app,sideConversation:{requestId:y,question:x.app.sideConversation.question,status:"error",error:b}}}})},dismissSideConversation:()=>{f((y)=>({app:{...y.app,sideConversation:null}}))},setTeams:(y)=>{f((b)=>({app:{...b.app,teams:y}}))}}});var U0={isProcessing:!1,abortController:null,followUpPresentations:{},recoveredSteeringCount:0},T=(f,y)=>({...U0,actions:{setProcessing:(b)=>{f((x)=>({command:{...x.command,isProcessing:b},...!b?{session:{...x.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}:{}}))},createAbortController:()=>{let b=y().command.abortController;if(b&&!b.signal.aborted)b.abort("interrupted-by-new-command");let x=new AbortController;return f((p)=>({command:{...p.command,abortController:x}})),x},getAbortController:()=>{return y().command.abortController},clearAbortController:(b)=>{let x=y().command.abortController;if(b!==void 0&&x!==b)return;f((p)=>({command:{...p.command,abortController:null}}))},abort:(b)=>{let{abortController:x}=y().command;if(x&&!x.signal.aborted)x.abort(b??"user-cancel");f((p)=>({command:{...p.command,isProcessing:!1},session:{...p.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}))},rememberFollowUpPresentation:(b,x)=>{f((p)=>({command:{...p.command,followUpPresentations:Object.fromEntries([...Object.entries(p.command.followUpPresentations),[b,x]].slice(-20))}}))},takeFollowUpPresentation:(b)=>{let x=y().command.followUpPresentations[b];if(!x)return;return f((p)=>({command:{...p.command,followUpPresentations:Object.fromEntries(Object.entries(p.command.followUpPresentations).filter(([h])=>h!==b))}})),x},clearFollowUpPresentations:()=>{f((b)=>({command:{...b.command,followUpPresentations:{}}}))},setRecoveredSteeringCount:(b)=>{f((x)=>({command:{...x.command,recoveredSteeringCount:Math.max(0,b)}}))}}});var j0={config:null},C=(f,y)=>({...j0,actions:{setConfig:(b)=>{u().configureModelProviders(b.modelProviders,b.models),f((x)=>({config:{...x.config,config:b}}))},updateConfig:(b)=>{let x=y().config.config;if(!x)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(b)}`);let p={...x,...b};if(b.modelProviders||b.models)u().configureModelProviders(p.modelProviders,p.models);f((h)=>({config:{...h.config,config:p}}))}}});var _0={currentFocus:"main-input",previousFocus:null},v=(f)=>({..._0,actions:{setFocus:(y)=>{f((b)=>({focus:{...b.focus,currentFocus:y,previousFocus:b.focus.currentFocus}}))},restorePreviousFocus:()=>{f((y)=>({focus:{...y.focus,currentFocus:y.focus.previousFocus||"main-input",previousFocus:null}}))}}});function I(f,y,b,x){let p=f.messages.find((F)=>F.id===y);if(p)return p;let h={id:y,role:b,content:"",timestamp:x};return f.messages.push(h),h}function t(f,y){let b=Date.parse(y.timestamp)||Date.now();switch(y.type){case"message_created":{let x=I(f,y.data.messageId,y.data.role,b),p=y.data.metadata;if(p&&typeof p==="object"&&!Array.isArray(p))x.metadata=p;return f}case"part_created":case"part_updated":{let{messageId:x,partType:p,payload:h,partId:F}=y.data,z=f.messages.find((G)=>G.id===x)??I(f,x,"assistant",b);if(p==="text"){let G=h.text??"";f.streamingText.delete(F),z.content=G}else if(p==="image")z.content=z.content?`${z.content}
|
|
2
2
|
[Image]`:"[Image]";return f}default:return f}}function x0(f,y){if(y.channel!=="content")return f;let b=f.messages.find((h)=>h.id===y.messageId)??I(f,y.messageId,"assistant",Date.now()),p=(f.streamingText.get(y.partId)?.text??"")+y.delta;return f.streamingText.set(y.partId,{messageId:y.messageId,text:p}),b.content=p,f}function b0(f,y,b,x=0,p=0,h){let F=u(),z=h?F.models.getModel(h,f):F.models.getModels().find(($)=>$.id===f);if(!z)return 0;let G=z.cost,Z=y/1e6*G.input+b/1e6*G.output+x/1e6*G.cacheRead+p/1e6*G.cacheWrite;return Math.round(Z*1e6)/1e6}var J={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,blockquote:/^(>+)\s?(.*)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/};function M0(f){let y=[],b=f.split(/\r?\n/),x=!1,p=[],h=null,F=0,z=!1,G=[],Z=[],$=!1,U=[],w=!1,Y=[],Q=0,X=!0;for(let j=0;j<b.length;j++){let H=b[j];if($){if(H.match(J.diffEnd)){try{let _=JSON.parse(U.join(`
|
|
3
3
|
`));y.push({type:"diff",content:"",diffData:{patch:_.patch,startLine:_.startLine,matchLine:_.matchLine}})}catch(_){y.push({type:"text",content:U.join(`
|
|
4
4
|
`)})}$=!1,U=[],X=!1;continue}U.push(H);continue}if(H.match(J.diffStart)){$=!0,U=[],X=!1;continue}if(x){let _=H.match(J.codeBlock),O=H.trim()==="```";if(_&&_[1])F++,p.push(H);else if(O)if(F>0)F--,p.push(H);else{let $0=p.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ae as O1,Be as n2,Ce as d2,De as J1,Ee as Q1,Fe as i2,Ge as Y1,He as V0,Ie as Z1,Je as G1,Le as r2,Se as o2,Te as Q0,_e as I_,af as V1,cf as a2,df as t2,ef as L1,ff as s2,ue as l2,ve as e,we as p2,xe as W1,ye as c2,ze as v}from"./chunk-s14zayxp.js";import{xg as h_}from"./chunk-pm163dfm.js";import{sh as l_}from"./chunk-1cy4ab77.js";import{Zi as f1}from"./chunk-b22ab7yw.js";import{Aj as E_,wj as u2,xj as h2,yj as F_,zj as r_}from"./chunk-m2x6pb4f.js";import{Ej as $0}from"./chunk-saz6mwpq.js";import{Rj as P_,Uj as u_}from"./chunk-0eajnhrj.js";import{Xj as __}from"./chunk-
|
|
1
|
+
import{Ae as O1,Be as n2,Ce as d2,De as J1,Ee as Q1,Fe as i2,Ge as Y1,He as V0,Ie as Z1,Je as G1,Le as r2,Se as o2,Te as Q0,_e as I_,af as V1,cf as a2,df as t2,ef as L1,ff as s2,ue as l2,ve as e,we as p2,xe as W1,ye as c2,ze as v}from"./chunk-s14zayxp.js";import{xg as h_}from"./chunk-pm163dfm.js";import{sh as l_}from"./chunk-1cy4ab77.js";import{Zi as f1}from"./chunk-b22ab7yw.js";import{Aj as E_,wj as u2,xj as h2,yj as F_,zj as r_}from"./chunk-m2x6pb4f.js";import{Ej as $0}from"./chunk-saz6mwpq.js";import{Rj as P_,Uj as u_}from"./chunk-0eajnhrj.js";import{Xj as __}from"./chunk-k17d0ysy.js";import{Ak as P,Bk as m,Ck as E1,Dk as F1,Ek as N_,Fk as z1,Gk as k1,Hk as L_,dk as l,nk as r,ok as p,pk as m2,qk as c,rk as n,sk as v2,tk as Z0,uk as $1,vk as P2,wk as H_,xk as G0,yk as g_,zk as T}from"./chunk-ed2hdrwe.js";import{readdir as D_,readFile as Z_,rm as R_,stat as L0}from"node:fs/promises";import*as N from"node:path";import{nanoid as i}from"nanoid";import{createHash as G4,randomUUID as V4}from"node:crypto";import*as $_ from"node:fs/promises";import*as n_ from"node:path";import L4 from"proper-lockfile";function nX(_){return Object.freeze({kind:"local",root:_})}function dX(_,X){let $=r(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function iX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function G_(_,X){if(_.kind==="local")return X(H_(_.root));return c(_.root,($)=>X(String($),$))}async function rX(_,X,$){return G_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:m(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:N_(_.root,X)}))}import{execFileSync as W4}from"node:child_process";import{createHash as O4}from"node:crypto";import{readFileSync as J4}from"node:fs";var Q4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&Q4.test(X.fingerprint)}var R1={readFile:(_)=>J4(_,"utf8"),execFile:(_,X)=>W4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},Y4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function F0(_,X){return{platform:_,fingerprint:O4("sha256").update(`${_}\x00${X}`).digest("hex")}}function Z4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function b_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return F0(X,Z4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?F0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?F0(X,J):void 0}}catch{return}return}function eX(_,X){return b_(_,X.platform)?.fingerprint===X.fingerprint}function _$(_,X,$=R1,W=Y4){if(!Number.isInteger(_)||_<=1)return!1;let J=b_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function B4(_,X){let $=G4("sha256").update(X).digest("hex");return n_.join(H_(_),".locks",`${$}.lock`)}function A_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function z0(_){try{let X=JSON.parse(await $_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(A_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await z0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),z0(_)}function U4(_){try{return process.kill(_,0),!0}catch(X){return!A_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await $_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
|
|
2
2
|
`,"utf8"),!0}catch(W){if(A_(W,"EEXIST"))return!1;if($)await $_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class X_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function b1(_,X,$=!1){let W,J;try{J=await L4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(A_(Q,"ELOCKED"))throw new X_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class h{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return h.acquire(_,X.root);return G_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return h.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return h.acquireAtPath(_,B4(X,_))}static async acquireRemote(_,X,$){let W=k1(X,_);try{await n(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await h.acquireAtPath(_,W);try{return await n(X,W),new h(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await $_.mkdir(n_.dirname(X),{recursive:!0,mode:448}),b1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:V4(),pid:process.pid,processIdentity:b_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new h(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new X_;if(U4(J.pid)){let O=J.processIdentity?b_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new X_(J.pid)}if($(),await $_.unlink(X).catch((O)=>{if(!A_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new h(X,W);throw new X_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>b1(this.filePath,async(X)=>{if((await z0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await $_.unlink(this.filePath).catch((W)=>{if(!A_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await G_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as d_}from"node:crypto";import{constants as C_,promises as W_}from"node:fs";import Y_ from"node:path";import{Mutex as H4}from"async-mutex";var y1=128,S1=67108864,N4=24576,g1=65536,R0=1,h1=/^[a-f0-9]{64}$/,C4=/^[a-f0-9]{64}\.txt$/,l1=64,q4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),o_=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -24,7 +24,7 @@ import{Eh as YO}from"./chunk-ys8gysg8.js";import{Zi as P}from"./chunk-b22ab7yw.j
|
|
|
24
24
|
`):void 0,warning:Z.length>0?Z.join(`
|
|
25
25
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
26
26
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
27
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await B.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((R)=>setTimeout(R,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let R=V.name==="AbortError"||V.code==="ABORT_ERR";if(R&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(R){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
27
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await B.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((R)=>setTimeout(R,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let R=V.name==="AbortError"||V.code==="ABORT_ERR";if(R&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(R){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-29ek6raw.js"),{createChatServiceAsync:W}=await import("./chunk-gwf872nm.js"),{resolveModelConfig:J}=await import("./chunk-eb10zapp.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-f7nx3ewr.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((R)=>R.id===O):F.config.models.find((R)=>R.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
28
28
|
|
|
29
29
|
`+`## 评估指令
|
|
30
30
|
${O.prompt}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{xf as a,yf as b}from"./chunk-9q7egv5e.js";import"./chunk-k17d0ysy.js";import"./chunk-gmpsfkgg.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-253fwyzb.js";import"./chunk-33sgdacd.js";import"./chunk-870szc6v.js";import"./chunk-9f99qxqc.js";import"./chunk-gt2wpeyx.js";import"./chunk-03ax0738.js";import"./chunk-4mamvx8a.js";import"./chunk-nad5spvc.js";import"./chunk-70n8qq1r.js";import"./chunk-whxkwaz1.js";import"./chunk-6s4btp37.js";import"./chunk-9qxch6sy.js";import"./chunk-d561qcwy.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as R}from"./chunk-j4v5f56k.js";import"./chunk-crv3sghv.js";import{_f as Q}from"./chunk-chhf109c.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import"./chunk-pm163dfm.js";import"./chunk-1khsmsem.js";import"./chunk-ska66dmc.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-d9gdv6hv.js";import"./chunk-ys8gysg8.js";import"./chunk-ep0g03gq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import{Xj as M}from"./chunk-k17d0ysy.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Zi as i}from"./chunk-b22ab7yw.js";import{$i as Kn,_i as rn,aj as Hn,ej as Yn,fj as _n,gj as Fn,hj as Vn,ij as qn,jj as ct,kj as Jn,lj as Qn,mj as Mn,nj as jn,oj as Wn,pj as Sn,qj as Zn,rj as kn,sj as ln,tj as yn,uj as vn,vj as te}from"./chunk-amabfzc8.js";import{wj as Pn,xj as xn}from"./chunk-m2x6pb4f.js";import{Ej as Ut,Gj as Lt,Hj as St,Ij as m}from"./chunk-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-
|
|
1
|
+
import{Zi as i}from"./chunk-b22ab7yw.js";import{$i as Kn,_i as rn,aj as Hn,ej as Yn,fj as _n,gj as Fn,hj as Vn,ij as qn,jj as ct,kj as Jn,lj as Qn,mj as Mn,nj as jn,oj as Wn,pj as Sn,qj as Zn,rj as kn,sj as ln,tj as yn,uj as vn,vj as te}from"./chunk-amabfzc8.js";import{wj as Pn,xj as xn}from"./chunk-m2x6pb4f.js";import{Ej as Ut,Gj as Lt,Hj as St,Ij as m}from"./chunk-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-k17d0ysy.js";import{ck as b}from"./chunk-asgmmaec.js";import{dk as It}from"./chunk-ed2hdrwe.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await I.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let t=_t.join(this.stateRoot,".oauth-credentials.lock"),n=Me(),e=Date.now()+Ee;while(Date.now()<e)try{let _=await I.open(t,rt.O_CREAT|rt.O_EXCL|rt.O_WRONLY,384);return await _.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:n,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await _.close(),async()=>{try{if(JSON.parse(await I.readFile(t,"utf8")).token===n)await I.unlink(t)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(_){if(!H(_,"EEXIST"))throw _;await this.removeDeadLock(t),await new Promise((r)=>setTimeout(r,ue))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(t){let n=await I.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&n.uid!==process.getuid()||(n.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await I.readFile(t,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Ae(e.pid))await I.unlink(t)}}var Nt="127.0.0.1",ft=7777,Pt="/oauth/callback",ie=300000;class ut extends Error{constructor(t){super(`MCP server "${t}" requires OAuth authorization; run "blade mcp login ${t}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ct extends Error{constructor(t){super(`MCP OAuth credentials are unavailable in this runtime for server "${t}"`);this.name="McpOAuthUnavailableError"}}function he(t){let n=t?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ea as I,Ga as K}from"./chunk-
|
|
1
|
+
import{Ea as I,Ga as K}from"./chunk-4mamvx8a.js";import{de as l,fe as V,ne as q}from"./chunk-d561qcwy.js";import{Yg as z}from"./chunk-ska66dmc.js";import{Zi as x}from"./chunk-b22ab7yw.js";async function J(){await z(x())}async function N(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(!G.isTTY){let b=[];for await(let F of G)b.push(F);return Buffer.concat(b).toString("utf-8").trim()}if(y.defaultMessage!==void 0)return y.defaultMessage;throw Error("No input provided")}async function W(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(G.isTTY)return;let b=[];for await(let O of G)b.push(Buffer.isBuffer(O)?O:Buffer.from(O));return Buffer.concat(b).toString("utf-8").trim()||void 0}async function X(y){if(!I(y))return{mode:"agent",content:y};let R=await K(y,{cwd:x(),surface:"headless",workspaceRoot:x()});if(!R.success)return{mode:"output",content:`Error: ${R.error||"未知错误"}`,exitCode:1};let G=R.data;if(G?.action==="invoke_skill"){let{skillName:b,skillArgs:F}=G;return{mode:"agent",content:F?`Please use the "${b}" skill to help me with: ${F}`:`Please use the "${b}" skill.`}}if(G?.action==="invoke_custom_command"||G?.action==="invoke_plugin_command"){let b=G.processedContent;return{mode:"agent",content:`# Custom Command: /${G.commandName}
|
|
2
2
|
|
|
3
3
|
${b}`}}return{mode:"output",content:R.content||R.message||"",exitCode:0}}async function m(y,R){let G=R&&y.getPendingSteeringCount()>0,b=R&&!G?await y.getGoal():null,F=b?.status==="active"||b?.status==="verifying",O=R&&!G&&!F,v=y.getTurnRecoveryAssessment?.()??{state:"none"},Z=O&&v.state!=="requires_attention"?await y.getRecoveredFinalResponse():void 0;return{pendingInputOnly:G,resumedGoal:b,goalContinuationOnly:F,finalRecovery:O,recoveryAssessment:v,recoveredFinalResponse:Z}}import{readFile as $,stat as L}from"node:fs/promises";import f from"node:path";function Q(y,R){let G;try{G=JSON.parse(y)}catch(b){throw Error(`Invalid JSON output schema from ${R}`,{cause:b})}return V(G).schema}async function _(y){if(y.jsonSchema!==void 0&&y.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(y.jsonSchema!==void 0)return Q(y.jsonSchema,"--json-schema");if(y.outputSchema===void 0)return;let R=f.resolve(y.outputSchema),G=await L(R);if(!G.isFile())throw Error(`Output schema path is not a regular file: ${R}`);if(G.size>l)throw Error(`Output schema exceeds ${l} bytes: ${R}`);return Q(await $(R,"utf8"),R)}function j(y){if(!(y instanceof Error))return!1;return y.message.includes("未找到会话")||y.message.includes("ENOENT")||y.message.includes("no such file")}async function A(y){try{return await q.loadSessionModelContext(y,x())}catch(R){if(j(R))return null;throw R}}async function C(y){if(y.resume===!0||y.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof y.resume==="string"&&y.resume.length>0){if(y.forkSession){let b=x(),F=await q.forkSession(y.resume,{newSessionId:y.sessionId,sourceProjectPath:b,targetProjectPath:b});return{...F,messages:await q.loadSessionModelContext(F.sessionId,b)}}let[R,G]=await Promise.all([q.loadSessionModelContext(y.resume),q.findSessionMetadata(y.resume)]);return{sessionId:y.resume,messages:R,metadata:G}}if(y.continue){let R=y.forkSession?await q.listSessions({cwd:x()}):await q.listSessions();if(R.length>0){let G=R[0].sessionId;if(y.forkSession){let b=x(),F=await q.forkSession(G,{newSessionId:y.sessionId,sourceProjectPath:b,targetProjectPath:b});return{...F,messages:await q.loadSessionModelContext(F.sessionId,b)}}return{sessionId:G,messages:await q.loadSessionModelContext(G),metadata:R[0]}}if(y.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(y.sessionId){let R=await A(y.sessionId);return{sessionId:y.sessionId,messages:R??[],...R?{metadata:await q.findSessionMetadata(y.sessionId,x())}:{}}}return{sessionId:`${y.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{J as p,N as q,W as r,X as s,m as t,_ as u,C as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ag as b,Bg as c,Cg as d,zg as a}from"./chunk-
|
|
1
|
+
import{Ag as b,Bg as c,Cg as d,zg as a}from"./chunk-1khsmsem.js";import"./chunk-ep0g03gq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-k17d0ysy.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$g as i,Tg as a,Ug as b,Vg as c,Wg as d,Xg as e,Yg as f,Zg as g,_g as h,ah as j,bh as k}from"./chunk-
|
|
1
|
+
import{$g as i,Tg as a,Ug as b,Vg as c,Wg as d,Xg as e,Yg as f,Zg as g,_g as h,ah as j,bh as k}from"./chunk-ska66dmc.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-d9gdv6hv.js";import"./chunk-ys8gysg8.js";import"./chunk-ep0g03gq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-k17d0ysy.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ia as p}from"./chunk-
|
|
1
|
+
import{ia as p}from"./chunk-4mamvx8a.js";import{Tb as _}from"./chunk-6s4btp37.js";import{Ed as N,Fd as U,Gd as I,Hd as A,Id as z,Td as q,ne as O}from"./chunk-d561qcwy.js";import{ze as o}from"./chunk-s14zayxp.js";import{fg as P}from"./chunk-x6k5ye1z.js";import{Gg as e}from"./chunk-ska66dmc.js";import{Ak as j}from"./chunk-ed2hdrwe.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
|
|
3
3
|
`).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
|
|
4
4
|
`)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
|