blade-code 0.10.97 → 0.10.98
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-8htbttg5.js → chunk-0bsn86gg.js} +1 -1
- package/dist/{chunk-q5t2rnx0.js → chunk-17ck16tq.js} +1 -1
- package/dist/{chunk-2mwgykjs.js → chunk-1j3mmdbt.js} +1 -1
- package/dist/{chunk-csr9d8yx.js → chunk-3wjb3bhw.js} +2 -2
- package/dist/{chunk-88mf53ak.js → chunk-4004spc1.js} +1 -1
- package/dist/{chunk-88ykfsbv.js → chunk-4crf8nvz.js} +2 -2
- package/dist/chunk-4n7zxjk0.js +1 -0
- package/dist/{chunk-0v74fhhc.js → chunk-4ytvrkks.js} +1 -1
- package/dist/{chunk-zvms9ap7.js → chunk-54syvhtz.js} +2 -2
- package/dist/{chunk-t5es94zk.js → chunk-63wahkkf.js} +1 -1
- package/dist/chunk-6b232wd7.js +1 -0
- package/dist/chunk-78bmtbzh.js +1 -0
- package/dist/chunk-7k38nj7a.js +23 -0
- package/dist/{chunk-s47ypj8n.js → chunk-7kbtqzy0.js} +3 -3
- package/dist/{chunk-sdvfyzv0.js → chunk-7wgtj7w4.js} +2 -2
- package/dist/{chunk-630jj776.js → chunk-7yn3d4cf.js} +1 -1
- package/dist/{chunk-7wtbhnfr.js → chunk-8dtggj9c.js} +1 -1
- package/dist/{chunk-2c2cxrc0.js → chunk-8jtwm19d.js} +1 -1
- package/dist/{chunk-dsnz4a1d.js → chunk-8v8frtnd.js} +1 -1
- package/dist/{chunk-qm83ezt6.js → chunk-9qqhkwbw.js} +1 -1
- package/dist/{chunk-t5y1ebdn.js → chunk-a7hz8scf.js} +1 -1
- package/dist/{chunk-31g86axj.js → chunk-a9ek5zt1.js} +2 -2
- package/dist/{chunk-23qhbq46.js → chunk-azcca8bk.js} +1 -1
- package/dist/{chunk-bztsz28c.js → chunk-b4ahgdtn.js} +2 -2
- package/dist/chunk-d1je4wzc.js +2 -0
- package/dist/{chunk-g2yaghbk.js → chunk-d2f41jxt.js} +1 -1
- package/dist/chunk-d3z12cgn.js +1 -0
- package/dist/chunk-d62jkv36.js +1 -0
- package/dist/chunk-dc3k9999.js +1 -0
- package/dist/{chunk-qhsmhx0y.js → chunk-dp9xbrjy.js} +2 -2
- package/dist/{chunk-p5ewrebt.js → chunk-drqezf1p.js} +1 -1
- package/dist/{chunk-ps2rv1gg.js → chunk-e6wgta3m.js} +1 -1
- package/dist/{chunk-xjyr40bn.js → chunk-e99cqtmv.js} +2 -2
- package/dist/{chunk-3saxqsn7.js → chunk-ef5b0ysc.js} +1 -1
- package/dist/{chunk-c6p5mj1k.js → chunk-fra0nwzj.js} +2 -2
- package/dist/{chunk-9mnspb2d.js → chunk-gaj6kkb6.js} +1 -1
- package/dist/{chunk-3229684w.js → chunk-gcy8nczq.js} +1 -1
- package/dist/{chunk-xtm0sp0k.js → chunk-h1wvtdh4.js} +1 -1
- package/dist/{chunk-p87j2g40.js → chunk-hdhxzmw7.js} +1 -1
- package/dist/chunk-hdrap16m.js +1 -0
- package/dist/{chunk-6qxzcx0a.js → chunk-hmgxkjbx.js} +2 -2
- package/dist/{chunk-g2hxj68b.js → chunk-hphdt9ph.js} +2 -2
- package/dist/chunk-hvz0wk1j.js +1 -0
- package/dist/{chunk-825r9sfe.js → chunk-hy9tkb5x.js} +3 -3
- package/dist/{chunk-mybhqpc7.js → chunk-j0ndrqv6.js} +1 -1
- package/dist/{chunk-zyfacwgn.js → chunk-j9cnp8ms.js} +1 -1
- package/dist/{chunk-fm93hym6.js → chunk-krhr8xbg.js} +2 -2
- package/dist/{chunk-ycr6tsfs.js → chunk-ks3f9h9n.js} +2 -2
- package/dist/chunk-kv6w817v.js +10 -0
- package/dist/chunk-m4bg4jp9.js +1 -0
- package/dist/{chunk-21ycnzsv.js → chunk-mf2s05b7.js} +1 -1
- package/dist/chunk-mpm2kdf6.js +1 -0
- package/dist/{chunk-qeznbnd1.js → chunk-my7nr1sx.js} +2 -2
- package/dist/{chunk-s36efnxd.js → chunk-nvypaz88.js} +1 -1
- package/dist/{chunk-vchv2x9y.js → chunk-p47hbq3a.js} +2 -2
- package/dist/{chunk-jy4s51bt.js → chunk-ps9vc0m3.js} +2 -2
- package/dist/{chunk-j1t2qedg.js → chunk-q74f1pj9.js} +1 -1
- package/dist/{chunk-n407vvwt.js → chunk-qb1wev32.js} +1 -1
- package/dist/{chunk-cvpvncza.js → chunk-qdf2a3vf.js} +1 -1
- package/dist/{chunk-nxmn37zx.js → chunk-rmkw6dpm.js} +1 -1
- package/dist/{chunk-dretwm9j.js → chunk-rzcm8hw3.js} +1 -1
- package/dist/chunk-rztsp1jj.js +1 -0
- package/dist/{chunk-h5xw792m.js → chunk-s6n0cgg5.js} +2 -2
- package/dist/{chunk-fbs90qgx.js → chunk-szccdrah.js} +1 -1
- package/dist/{chunk-v2bvrk83.js → chunk-tae9c030.js} +2 -2
- package/dist/{chunk-n7p994w1.js → chunk-v2p30pe1.js} +1 -1
- package/dist/{chunk-m67hdwk8.js → chunk-vw2j0avq.js} +1 -1
- package/dist/{chunk-z6we2tr8.js → chunk-wkfhpjkf.js} +1 -1
- package/dist/chunk-wq8zryfj.js +1 -0
- package/dist/{chunk-a1vhp8sa.js → chunk-wzgdm617.js} +2 -2
- package/dist/{chunk-7bhk8qk5.js → chunk-wzx5s1dm.js} +2 -2
- package/dist/chunk-ysckkpw0.js +1 -0
- package/dist/chunk-zppdqh51.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-0p6qkcft.js +0 -1
- package/dist/chunk-0pdkfzgc.js +0 -1
- package/dist/chunk-2vt67deg.js +0 -1
- package/dist/chunk-64kpbdpc.js +0 -1
- package/dist/chunk-6tzphr1p.js +0 -10
- package/dist/chunk-7t2nf0rz.js +0 -1
- package/dist/chunk-ah15z613.js +0 -1
- package/dist/chunk-b9thsjxh.js +0 -2
- package/dist/chunk-cp9mj5he.js +0 -1
- package/dist/chunk-g7yfjy30.js +0 -1
- package/dist/chunk-krym2q8y.js +0 -23
- package/dist/chunk-perp57h6.js +0 -1
- package/dist/chunk-pxmfnkf3.js +0 -1
- package/dist/chunk-qkmsw3km.js +0 -1
- package/dist/chunk-s91r4emx.js +0 -1
- package/dist/chunk-wgg7ysqn.js +0 -1
- package/dist/chunk-zr27h1p0.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{qi as o}from"./chunk-krhr8xbg.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e,i as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{qe as s}from"./chunk-b4ahgdtn.js";import{Je as o}from"./chunk-p47hbq3a.js";import{$g as R,Tg as y,Ug as D,Wg as N,Yg as j,Zg as F,dh as E,eh as _,fh as f,gh as C,ih as S,jh as m,nh as c,sh as l,th as n}from"./chunk-4crf8nvz.js";import{uh as Y}from"./chunk-4ytvrkks.js";import{Bh as Z,wh as x,yh as k}from"./chunk-nvypaz88.js";import{Ih as X}from"./chunk-j0ndrqv6.js";import{$h as M,Mh as h,Nh as A,Th as P,Uh as T,Wh as $,Xh as U,Yh as G,_h as L,bi as O,ci as I}from"./chunk-8jtwm19d.js";import{ki as d}from"./chunk-54syvhtz.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
5
5
|
`),process.exit(1)}};function r(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Ak=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
|
|
6
|
-
export{Dk as
|
|
6
|
+
export{Dk as ne,hk as oe,Ak as pe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
|
|
2
|
-
export{B as
|
|
2
|
+
export{B as Ze};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Fi as C,Gi as I}from"./chunk-zyfacwgn.js";import{Pi as _}from"./chunk-h5xw792m.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
1
|
+
import{Gi as C,Hi as I}from"./chunk-j9cnp8ms.js";import{Qi as _}from"./chunk-s6n0cgg5.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
2
|
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as
|
|
3
|
+
export{R as Di,t as Ei,x as Fi};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{bh as H,ch as I}from"./chunk-4crf8nvz.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as mg,F as ng,R as og,v as pg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{g as i}from"./chunk-
|
|
1
|
+
import{g as i}from"./chunk-mf2s05b7.js";import{Kh as s}from"./chunk-j0ndrqv6.js";import"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Di as a,Ei as b,Fi as c}from"./chunk-fra0nwzj.js";import"./chunk-j9cnp8ms.js";import"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as
|
|
1
|
+
import{$d as l_,Ud as l,Vd as M$,Wd as h_,Xd as F$,Yd as j,Zd as c_,_d as D$,ae as z$,be as n_,ce as p_,ee as i0,he as i_,ie as f$}from"./chunk-wzx5s1dm.js";import{nf as F0}from"./chunk-4004spc1.js";import{dg as D0}from"./chunk-gaj6kkb6.js";import{pg as a1}from"./chunk-h1wvtdh4.js";import{Ch as A$,Dh as E$,Eh as T0,Fh as S0,Gh as B0}from"./chunk-d1je4wzc.js";import{Kh as T1}from"./chunk-j0ndrqv6.js";import{ki as u0}from"./chunk-54syvhtz.js";import{ri as E0,ui as M0}from"./chunk-63wahkkf.js";import{yi as t}from"./chunk-tae9c030.js";import{Ii as U$,Ji as Z0,Ki as K$,Li as x,Mi as u,Oi as K0,Pi as a,Qi as k}from"./chunk-s6n0cgg5.js";import{readdir as v_,readFile as W0,rm as G0,stat as d0}from"node:fs/promises";import*as Z from"node:path";import{nanoid as P}from"nanoid";import{createHash as P$,randomUUID as u$}from"node:crypto";import*as h from"node:fs/promises";import*as w0 from"node:path";import{execFileSync as g$}from"node:child_process";import{createHash as j$}from"node:crypto";import{readFileSync as y$}from"node:fs";var I$=/^[a-f0-9]{64}$/;function R1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&I$.test($.fingerprint)}var W1={readFile:(_)=>y$(_,"utf8"),execFile:(_,$)=>g$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},m$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function W_(_,$){return{platform:_,fingerprint:j$("sha256").update(`${_}\x00${$}`).digest("hex")}}function v$(_,$){let O=$.readFile(`/proc/${_}/stat`).trim(),R=O.lastIndexOf(")");if(R<0)throw Error("Invalid /proc process stat");let W=O.slice(R+2).split(/\s+/)[19];if(!W||!/^\d+$/.test(W))throw Error("Missing process start ticks");return W}function f0(_,$=process.platform,O=W1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return W_($,v$(_,O));if($==="darwin"){let R=O.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return R?W_($,R):void 0}if($==="win32"){let R=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,L=O.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",R]).trim();return L?W_($,L):void 0}}catch{return}return}function L1(_,$){return f0(_,$.platform)?.fingerprint===$.fingerprint}function k4(_,$,O=W1,R=m$){if(!Number.isInteger(_)||_<=1)return!1;let L=f0(_,$.platform,O);if(L)return L.fingerprint===$.fingerprint;return!R(_)}var G1=1;function h$(_,$){let O=P$("sha256").update($).digest("hex");return w0.join(Z0(_),".locks",`${O}.lock`)}function x0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==G1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!R1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function X1(_){let $=await L_(_);if($)return $;return await new Promise((O)=>setTimeout(O,10)),L_(_)}function c$(_){try{return process.kill(_,0),!0}catch($){return x0($,"EPERM")}}async function B1(_,$){let O;try{return O=await h.open(_,"wx",384),await O.writeFile(`${JSON.stringify($)}
|
|
2
2
|
`,"utf8"),!0}catch(R){if(x0(R,"EEXIST"))return!1;if(O)await h.unlink(_).catch(()=>{return});throw R}finally{await O?.close().catch(()=>{return})}}class d 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"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=T1()){let O=h$($,_),R={version:G1,sessionId:_,ownerId:u$(),pid:process.pid,processIdentity:f0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(w0.dirname(O),{recursive:!0,mode:448}),await B1(O,R))return new o(O,R);let L=await X1(O);if(L&&c$(L.pid)&&(!L.processIdentity||L1(L.pid,L.processIdentity)))throw new d(L.pid);if(await h.unlink(O).catch((W)=>{if(!x0(W,"ENOENT"))throw W}),await B1(O,R))return new o(O,R);throw new d((await X1(O))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!x0($,"ENOENT"))throw $})}}import{createHash as b0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var J1=128,C1=67108864,n$=24576,V1=65536,B_=1,H1=/^[a-f0-9]{64}$/,p$=/^[a-f0-9]{64}\.txt$/,U1=64,i$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),g0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -115,4 +115,4 @@ ${[...L0,...X0].join(`
|
|
|
115
115
|
s.project_sort_key ASC,
|
|
116
116
|
s.session_sort_key ASC
|
|
117
117
|
LIMIT ?`).all(...L,_.limit+1),X=await Promise.all(W.map(async(G)=>{let J=JSON.parse(G.metadata_json);if(G.archive_root_id&&G.effective_archived_at)return this.reconcileInterruptedTask({...J,archivedAt:G.effective_archived_at,archivedBySessionId:G.archive_root_id});let{archivedAt:V,archivedBySessionId:T,...C}=J;return this.reconcileInterruptedTask(C)})),B=p_(X,_);return{sessions:B.sessions.map((G)=>this.toPublicMetadata(G)),nextCursor:B.nextCursor}}catch{return null}}static async listSessions(_={}){let $=l_(_),O=z$(_),R=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived,O),L=new Set;return R.sort(n_).flatMap((W)=>{let X=`${W.projectPath}\x00${W.sessionId}`;if(L.has(X))return[];return L.add(X),[this.toPublicMetadata(W)]})}static async collectStaleEmptySessions(_={}){let $=_.now??Date.now(),O=_.olderThanMs??W4;if(!Number.isFinite(O)||O<0)throw Error("Stale empty session age must be a non-negative number");let R=_.projectPath?[{storagePath:Z0(this.resolveCatalogWorkspace(_.projectPath)),projectPath:this.resolveCatalogWorkspace(_.projectPath)}]:await this.listAllProjectStorageDirectories(),L=0;for(let W of R){let X;try{X=await v_(W.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of X){if(!B.endsWith(".jsonl"))continue;let G=B.slice(0,-6);if(!K$(G))continue;let J=Z.join(W.storagePath,B);try{let T=await d0(J);if($-T.mtimeMs<O)continue;if(await Promise.all([d0(Z.join(W.storagePath,`${G}.inbox.json`)).then(()=>!0).catch(()=>!1),d0(K0(W.projectPath,G)).then(()=>!0).catch(()=>!1)]).then((Y)=>Y.some(Boolean)))continue}catch(T){if(T.code==="ENOENT")continue;throw T}let V;try{V=await o.acquire(G,W.projectPath)}catch(T){if(T instanceof d)continue;throw T}try{if(!await new j(J).deleteValidated((C)=>C.length===1&&C[0]?.type==="session_created"&&C[0].data.relationType!=="subagent"))continue;L++,await G0(Z.join(W.storagePath,`${G}.inbox.json`),{force:!0}),await G0(K0(W.projectPath,G),{force:!0}),await this.removeFromProjection(G,W.projectPath)}catch(T){U0.warn(`[SessionService] Skipping stale empty session cleanup: ${G}`,T)}finally{await V.release()}}}return L}static async findSessionMetadata(_,$){if(x(_),$!==void 0){if(!Z.isAbsolute($))throw Error("Session catalog cwd must be absolute");let R=Z.resolve($),L=this.getSessionFilePath(R,_);try{let W=await this.readStoredSessionMetadata(L,_,R);if(W.projectPath!==R)return;if(!W.parentId||W.archivedAt)return this.toPublicMetadata(u_([W],null)[0]??W);let X=await this.scanStoredSessions(R,!0,0,null);return this.toPublicMetadata(X.find((B)=>B.sessionId===_)??W)}catch(W){if(W.code==="ENOENT")return;throw W}}let O=(await this.scanStoredSessions(void 0,!0,0,null)).filter((R)=>R.sessionId===_);if(O.length===0)return;if(O.length>1)throw Error(`Ambiguous session ID: ${_}`);return this.toPublicMetadata(O[0])}static async loadSession(_,$){try{if($){if(!Z.isAbsolute($))throw Error("Session catalog cwd must be absolute");let R=Z.resolve($),L=this.getSessionFilePath(R,_);try{return await this.loadSessionFromFile(L,_,R)}catch(W){if(W.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw W}}let O=(await this.scanStoredSessions(void 0,!0,0,null)).find((R)=>R.sessionId===_);if(!O)throw Error(`未找到会话: ${_}`);return await this.loadSessionFromFile(O.filePath,_)}catch(O){throw U0.error(`[SessionService] 加载会话失败 (${_}):`,O),O}}static async loadSessionModelContext(_,$){try{if($){if(!Z.isAbsolute($))throw Error("Session catalog cwd must be absolute");let R=Z.resolve($),L=this.getSessionFilePath(R,_);try{return await this.loadSessionModelContextFromFile(L,_,R)}catch(W){if(W.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw W}}let O=(await this.scanStoredSessions(void 0,!0,0,null)).find((R)=>R.sessionId===_);if(!O)throw Error(`未找到会话: ${_}`);return await this.loadSessionModelContextFromFile(O.filePath,_)}catch(O){throw U0.error(`[SessionService] 加载模型上下文失败 (${_}):`,O),O}}static async exportSessionMarkdown(_,$,O={}){x(_);let R=this.resolveCatalogWorkspace($),L=u(R,_),W;try{W=await this.readStableSessionSnapshot(L,_)}catch(G){throw this.sanitizeStoredSessionError(G,_)}let X=this.projectMetadataFromEntries(W,_,R,L);if(X.projectPath!==R)throw Error(`Session export workspace mismatch: ${_}`);let B=X.archivedAt;if(!B&&X.parentId)B=(await this.findArchivedAncestor(X.parentId,R))?.archivedAt;return $$(W,{...X,archivedAt:B},O)}static async listRewindCheckpoints(_,$){x(_);let O=this.resolveCatalogWorkspace($),R=u(O,_),L=await this.readStableSessionSnapshot(R,_);this.validateSessionWorkspace(L,_,O);let W=new h0({sessionId:_,workspaceRoot:O});await W.initialize();let X=M$(L),B=[];for(let G of X){let J=h_(L,G.messageId),V=await W.previewRewind(J.snapshotMessageIds);B.push({...G,fileCount:V.files.length})}return B}static async rewindSession(_,$,O){x(_);let R=this.resolveCatalogWorkspace($);await this.assertSessionWritable(_,R);let L=u(R,_),W=new j(L),X;try{await W.appendValidatedAsync(async(B)=>{this.validateSessionWorkspace(B,_,R);let G=h_(B,O.targetMessageId),J=new h0({sessionId:_,workspaceRoot:R});await J.initialize();let V=await J.previewRewind(G.snapshotMessageIds),T=O.mode==="conversation"?await J.commitSnapshots(G.snapshotMessageIds):await J.rewindSnapshots(G.snapshotMessageIds),C=new Date().toISOString(),Y={id:P(),sessionId:_,timestamp:C,type:"session_rewound",cwd:R,gitBranch:a(R),version:t(),data:{rewindId:P(),targetMessageId:O.targetMessageId,mode:O.mode,restoredFiles:O.mode==="conversation"?[]:T.files,createdAt:C}},Q=l([...B,Y]);return X={checkpoint:{...G.checkpoint,fileCount:V.files.length},mode:O.mode,removedTurns:G.removedTurns,restoredFiles:Y.data.restoredFiles,messages:this.convertJSONLToMessages(Q)},Y})}catch(B){throw this.sanitizeStoredSessionError(B,_)}if(!X)throw Error(`Session rewind did not produce a result: ${_}`);for(let B of X.restoredFiles)r.getInstance().clearFileRecord(B);return X}static async forkSession(_,$){x(_);let O=$.newSessionId??`fork-${Date.now()}-${P(8)}`;x(O);let R=this.resolveForkWorkspace($.sourceProjectPath),L=this.resolveForkWorkspace($.targetProjectPath);if(R!==L)throw Error("Session forks must stay in the source workspace");let W=u(R,_),X=await this.readStableSessionSnapshot(W,_),B=this.getSessionCreatedEntry(X,_);if(B.data.sessionId!==_)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!Z.isAbsolute(B.cwd)||Z.resolve(B.cwd)!==R)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let G=this.projectMetadataFromEntries(X,_,R,W);if(G.archivedAt)throw new J0(_,_);if(G.parentId){let U=await this.findArchivedAncestor(G.parentId,R);if(U)throw new J0(_,U.sessionId)}let J=l(X),V=new Date().toISOString(),T=B.data.rootId||_,C=a(L),Y=t(),{status:Q,taskStatus:A,taskStatusReason:b,taskFailure:E,taskStartedAt:L0,taskCompletedAt:X0,taskOwnerPid:y,taskPromptSummary:I,taskPriority:z,taskKind:D,taskDueAt:w,taskDispatch:q,taskModelId:f,taskRetriedFrom:r_,taskDelivery:a_,taskIsolation:t_,taskSourceProjectPath:t0,taskWorktree:s_,taskDiffStat:e_,taskQueuePosition:_1,taskQueueDepth:$1,taskConcurrencyLimit:O1,pendingInteraction:s0,...e0}=B.data,__={id:P(),sessionId:O,timestamp:V,type:"session_created",cwd:L,gitBranch:C,version:Y,data:{...e0,sessionId:O,rootId:T,parentId:_,relationType:"fork",taskStatus:"completed",taskCompletedAt:V,taskIsolation:"local",taskSourceProjectPath:L,createdAt:V,updatedAt:V}},$_=J.filter((U)=>U.type!=="session_created"&&U.type!=="token_budget_handoff_recorded"&&U.type!=="inbox_acknowledged"&&U.type!=="interaction_requested"&&U.type!=="interaction_responded"&&U.type!=="interaction_recovered"&&U.type!=="review_started"&&U.type!=="review_completed").map((U)=>{let m={...U,id:P(),sessionId:O,cwd:L,gitBranch:C,version:Y};if(U.type==="session_updated"){let{status:F,taskStatus:Y0,taskStatusReason:B4,taskFailure:T4,taskStartedAt:G4,taskCompletedAt:J4,taskOwnerPid:C4,taskPromptSummary:V4,taskPriority:Y4,taskKind:Z4,taskDueAt:Q4,taskDispatch:N4,taskModelId:q4,taskRetriedFrom:H4,taskDelivery:U4,taskIsolation:K4,taskSourceProjectPath:A4,taskWorktree:E4,taskDiffStat:M4,taskQueuePosition:F4,taskQueueDepth:D4,taskConcurrencyLimit:z4,pendingInteraction:f4,...S$}=U.data;return{...m,type:"session_updated",data:{...S$,sessionId:O,rootId:T,parentId:_,relationType:"fork"}}}if(U.type==="message_created"){let{inboxMessageId:F,...Y0}=U.data;return{...m,type:"message_created",data:Y0}}return m}),O_={id:P(),sessionId:O,timestamp:V,type:"session_updated",cwd:L,gitBranch:C,version:Y,data:{sessionId:O,rootId:T,parentId:_,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:V,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:L,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:V}},C0=[__,...$_,O_],V0=u(L,O),z0=!1;try{await new j(V0).createExclusive(C0),z0=!0;let U=K1(J.flatMap((m)=>m.type==="message_created"?[m.data.metadata]:[]));if(U.length>0){let m=new e(R,_,{storageRoot:k()}),F=new e(L,O,{storageRoot:k()});await m.copyReferencedTo(U,F)}}catch(U){if(z0)await new j(V0).delete().catch(()=>{return}),await new e(L,O,{storageRoot:k()}).removeAll().catch(()=>{return});if(U.code==="EEXIST")throw Error(`Fork session already exists: ${O}`,{cause:U});throw U}let R_=this.projectMetadataFromEntries(C0,O,L,V0);return{sessionId:O,parentSessionId:_,projectPath:L,messages:this.convertJSONLToMessages(C0),metadata:this.toPublicMetadata(R_)}}static async deleteSession(_,$){if(x(_),$){if(!Z.isAbsolute($))throw Error("Session catalog cwd must be absolute");let R=Z.resolve($),L=this.getSessionFilePath(R,_),W=new j(L),X;try{X=await W.deleteValidated((B)=>{return this.projectMetadataFromEntries(B,_,R,L).projectPath===R})}catch(B){if(!this.isCorruptSessionJSONLError(B))throw B;X=await W.delete()}if(!X)return 0;return await G0(Z.join(Z.dirname(L),`${_}.inbox.json`),{force:!0}),await G0(K0(R,_),{force:!0}),await new e(R,_,{storageRoot:k()}).removeAll(),await Z_(R,_,k()),await this.removeFromProjection(_,R),1}let O=(await this.scanStoredSessions(void 0,!0)).filter((R)=>R.sessionId===_);if(O.length===0)return 0;return await Promise.all(O.map(async(R)=>{await new j(R.filePath).delete(),await G0(Z.join(Z.dirname(R.filePath),`${R.sessionId}.inbox.json`),{force:!0}),await G0(K0(R.projectPath,R.sessionId),{force:!0}),await new e(R.projectPath,R.sessionId,{storageRoot:k()}).removeAll(),await Z_(R.projectPath,R.sessionId,k()),await this.removeFromProjection(R.sessionId,R.projectPath)})),O.length}static async removeFromProjection(_,$){try{let O=await i0();if(O)f$(O,_,$)}catch{}}static validateTaskMetadataUpdate(_,$){if(_.taskPromptSummary!==void 0&&_.taskPromptSummary!==null&&(!_.taskPromptSummary.trim()||_.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(_.taskPriority!==void 0&&_.taskPriority!==null&&!r0.has(_.taskPriority))throw Error("Invalid session task priority");if(_.taskKind!==void 0&&_.taskKind!==null&&!a0.has(_.taskKind))throw Error("Invalid session task kind");if(_.taskDueAt!==void 0&&_.taskDueAt!==null&&!Number.isFinite(Date.parse(_.taskDueAt)))throw Error("Invalid session task due date");if(_.taskFailure!==void 0&&_.taskFailure!==null&&!D_(_.taskFailure))throw Error("Invalid session task failure");if(_.taskDispatch!==void 0&&_.taskDispatch!==null&&!N$(_.taskDispatch))throw Error("Invalid durable task dispatch");if(_.taskModelId!==void 0&&_.taskModelId!==null&&(!_.taskModelId.trim()||_.taskModelId.length>500))throw Error("Invalid session task model ID");if(_.selectedModelId!==void 0&&_.selectedModelId!==null&&(!_.selectedModelId.trim()||_.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(_.permissionMode!==void 0&&_.permissionMode!==null&&!o0(_.permissionMode))throw Error("Invalid session permission mode");if(_.reasoningEffort!==void 0&&_.reasoningEffort!==null&&!F0(_.reasoningEffort))throw Error("Invalid session reasoning effort");if(_.serviceTier!==void 0&&_.serviceTier!==null&&!M0(_.serviceTier))throw Error("Invalid session service tier");if(_.responseVerbosity!==void 0&&_.responseVerbosity!==null&&!E0(_.responseVerbosity))throw Error("Invalid session response verbosity");if(_.communicationStyle!==void 0&&_.communicationStyle!==null&&!D0(_.communicationStyle))throw Error("Invalid session communication style");if(_.communicationStyleDigest!==void 0&&_.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(_.communicationStyleDigest))throw Error("Invalid session communication style digest");if(_.projectInstructionsDigest!==void 0&&_.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(_.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(_.taskRetriedFrom!==void 0&&_.taskRetriedFrom!==null&&!q$(_.taskRetriedFrom))throw Error("Invalid session task retry source");if(_.taskDelivery!==void 0&&_.taskDelivery!==null&&!Z$(_.taskDelivery))throw Error("Invalid session task delivery");if(_.taskIsolation!==void 0&&_.taskIsolation!==null&&!d_.has(_.taskIsolation))throw Error(`Invalid session task isolation: ${String(_.taskIsolation)}`);if(_.taskSourceProjectPath!==void 0&&_.taskSourceProjectPath!==null&&!Z.isAbsolute(_.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(_.taskWorktree!==void 0&&_.taskWorktree!==null){let O=Y$(_.taskWorktree);if(!O||O.sessionId!==$||![O.repositoryRoot,O.originalWorkspaceRoot,O.worktreeRoot,O.workspaceRoot].every((R)=>Z.isAbsolute(R)))throw Error("Invalid session task worktree metadata")}if(_.taskDiffStat!==void 0&&_.taskDiffStat!==null&&!Q$(_.taskDiffStat))throw Error("Invalid session task diff stat");if(_.taskQueuePosition!==void 0&&_.taskQueuePosition!==null&&(!Number.isInteger(_.taskQueuePosition)||_.taskQueuePosition<1))throw Error("Invalid session task queue position");if(_.taskQueueDepth!==void 0&&_.taskQueueDepth!==null&&(!Number.isInteger(_.taskQueueDepth)||_.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(_.taskConcurrencyLimit!==void 0&&_.taskConcurrencyLimit!==null&&(!Number.isInteger(_.taskConcurrencyLimit)||_.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof _.taskQueuePosition==="number"&&typeof _.taskQueueDepth==="number"&&_.taskQueuePosition>_.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(_,$,O={}){x(_),K.validateTaskMetadataUpdate(O,_);let R=K.resolveCatalogWorkspace($);if(O.taskWorktree&&Z.resolve(O.taskWorktree.workspaceRoot)!==R)throw Error("Session task worktree must match the catalog workspace");let L=new Date().toISOString(),W={id:P(),sessionId:_,timestamp:L,type:"session_created",cwd:R,gitBranch:a(R),version:t(),data:{sessionId:_,rootId:_,...O.title!==void 0?{title:O.title}:{},taskStatus:O.taskStatus??"queued",...O.taskPromptSummary!==void 0?{taskPromptSummary:O.taskPromptSummary}:{},...O.taskPriority!==void 0?{taskPriority:O.taskPriority}:{},...O.taskKind!==void 0?{taskKind:O.taskKind}:{},...typeof O.taskDueAt==="string"?{taskDueAt:new Date(O.taskDueAt).toISOString()}:{},...O.taskDispatch!==void 0?{taskDispatch:O.taskDispatch}:{},...O.taskModelId!==void 0?{taskModelId:O.taskModelId}:{},...O.taskRetriedFrom!==void 0?{taskRetriedFrom:O.taskRetriedFrom}:{},...O.taskIsolation!==void 0?{taskIsolation:O.taskIsolation}:{},...O.taskSourceProjectPath!==void 0?{taskSourceProjectPath:O.taskSourceProjectPath}:{},...O.taskWorktree!==void 0?{taskWorktree:O.taskWorktree}:{},...O.selectedModelId!==void 0?{selectedModelId:O.selectedModelId}:{},...O.permissionMode!==void 0?{permissionMode:O.permissionMode}:{},...O.reasoningEffort!==void 0?{reasoningEffort:O.reasoningEffort}:{},...O.serviceTier!==void 0?{serviceTier:O.serviceTier}:{},...O.responseVerbosity!==void 0?{responseVerbosity:O.responseVerbosity}:{},...O.communicationStyle!==void 0?{communicationStyle:O.communicationStyle}:{},...O.communicationStyleDigest!==void 0?{communicationStyleDigest:O.communicationStyleDigest}:{},...O.projectInstructionsDigest!==void 0?{projectInstructionsDigest:O.projectInstructionsDigest}:{},createdAt:L,updatedAt:L}},X=K.getSessionFilePath(R,_);return await new j(X).createExclusive([W]),K.toPublicMetadata(K.projectMetadataFromEntries([W],_,R,X))}static async assertSessionWritable(_,$){let O=await this.findSessionMetadata(_,$);if(!O)throw Error(`Session not found: ${_}`);if(O.archivedAt)throw new J0(_,O.archivedBySessionId??_);return O}static async findArchivedAncestor(_,$){let O=new Set,R=_;while(R){if(O.has(R))throw Error("Session lineage contains a cycle");O.add(R),x(R);let L=u($,R),W;try{W=await W0(L,"utf8")}catch(B){if(B.code==="ENOENT")return;throw B}let X=this.projectMetadataFromEntries(this.parseStoredSession(W,R),R,$,L);if(X.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(X.archivedAt)return{sessionId:X.sessionId,archivedAt:X.archivedAt};R=X.parentId}return}static async listSessionArchiveMembers(_,$){x(_);let O=this.resolveCatalogWorkspace($),R=await this.scanStoredSessions(O,!0,0,null);if(!R.some((X)=>X.sessionId===_))throw Error(`Session not found: ${_}`);let L=new Set([_]),W=!0;while(W){W=!1;for(let X of R)if(X.parentId&&L.has(X.parentId)&&!L.has(X.sessionId))L.add(X.sessionId),W=!0}return R.filter((X)=>L.has(X.sessionId)).sort((X,B)=>X.sessionId.localeCompare(B.sessionId)).map((X)=>this.toPublicMetadata(X))}static async archiveSession(_,$){x(_);let O=this.resolveCatalogWorkspace($),R=await this.findSessionMetadata(_,O);if(!R)throw Error(`Session not found: ${_}`);if(R.archivedAt)return R;let L=await this.listSessionArchiveMembers(_,O),W=L.find((B)=>B.taskStatus==="queued"||B.taskStatus==="running");if(W)throw new p(`Stop session ${W.sessionId} before archiving this session tree`);let X=[];try{for(let V of L)X.push(await o.acquire(V.sessionId,O));let B=u(O,_),G=new j(B),J=[];return await G.appendValidated((V)=>{let T=this.projectMetadataFromEntries(V,_,O,B);if(T.archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);if(T.taskStatus==="queued"||T.taskStatus==="running")throw new p(`Stop session ${_} before archiving it`);let C=new Date().toISOString(),Y={id:P(),sessionId:_,timestamp:C,type:"session_updated",cwd:O,gitBranch:a(O),version:t(),data:{sessionId:_,archivedAt:C,updatedAt:C}};return J=[...V,Y],Y}),this.toPublicMetadata({...this.projectMetadataFromEntries(J,_,O,B),archivedBySessionId:_})}catch(B){if(B instanceof p)throw B;if(B instanceof d)throw new p(B.message);throw this.sanitizeStoredSessionError(B,_)}finally{for(let B of X.reverse())await B.release()}}static async unarchiveSession(_,$){x(_);let O=this.resolveCatalogWorkspace($),R=await this.findSessionMetadata(_,O);if(!R)throw Error(`Session not found: ${_}`);if(!R.archivedAt)return R;if(R.archivedBySessionId&&R.archivedBySessionId!==_)throw new p(`Unarchive ancestor ${R.archivedBySessionId} to restore session ${_}`);let L;try{L=await o.acquire(_,O);let W=u(O,_),X=new j(W),B=[];return await X.appendValidated((G)=>{if(!this.projectMetadataFromEntries(G,_,O,W).archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);let V=new Date().toISOString(),T={id:P(),sessionId:_,timestamp:V,type:"session_updated",cwd:O,gitBranch:a(O),version:t(),data:{sessionId:_,archivedAt:null,updatedAt:V}};return B=[...G,T],T}),this.toPublicMetadata(this.projectMetadataFromEntries(B,_,O,W))}catch(W){if(W instanceof p)throw W;if(W instanceof d)throw new p(W.message);throw this.sanitizeStoredSessionError(W,_)}finally{await L?.release()}}static async updateSessionMetadata(_,$,O){if(x(_),K.validateTaskMetadataUpdate(O,_),O.taskStatus!==void 0&&!C$.has(O.taskStatus))throw Error(`Invalid session task status: ${String(O.taskStatus)}`);if(O.taskOwnerPid!==void 0&&O.taskOwnerPid!==null&&(!Number.isInteger(O.taskOwnerPid)||O.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let R=K.resolveCatalogWorkspace($);if(O.taskWorktree&&Z.resolve(O.taskWorktree.workspaceRoot)!==R)throw Error("Session task worktree must match the catalog workspace");let L=K.getSessionFilePath(R,_),W=new j(L),X=[];try{await W.appendValidatedAsync(async(B)=>{let G=K.getSessionCreatedEntry(B,_);if(G.data.sessionId!==_)throw Error(`Session metadata creation record sessionId mismatch: ${_}`);if(!Z.isAbsolute(G.cwd)||Z.resolve(G.cwd)!==R)throw Error(`Session metadata creation record cwd mismatch: ${_}`);let J=K.projectMetadataFromEntries(B,_,R,L);if(J.archivedAt)throw new J0(_,_);if(J.parentId){let C=await K.findArchivedAncestor(J.parentId,R);if(C)throw new J0(_,C.sessionId)}let V=new Date().toISOString(),T={id:P(),sessionId:_,timestamp:V,type:"session_updated",cwd:R,gitBranch:a(R),version:t(),data:{sessionId:_,...O.title!==void 0?{title:O.title}:{},...O.taskStatus!==void 0?{taskStatus:O.taskStatus}:{},...O.taskStatusReason!==void 0?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure!==void 0?{taskFailure:O.taskFailure}:{},...O.taskStartedAt!==void 0?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt!==void 0?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskOwnerPid!==void 0?{taskOwnerPid:O.taskOwnerPid}:{},...O.taskPromptSummary!==void 0?{taskPromptSummary:O.taskPromptSummary}:{},...O.taskPriority!==void 0?{taskPriority:O.taskPriority}:{},...O.taskKind!==void 0?{taskKind:O.taskKind}:{},...O.taskDueAt!==void 0?{taskDueAt:O.taskDueAt===null?null:new Date(O.taskDueAt).toISOString()}:{},...O.taskDispatch!==void 0?{taskDispatch:O.taskDispatch}:{},...O.taskModelId!==void 0?{taskModelId:O.taskModelId}:{},...O.taskRetriedFrom!==void 0?{taskRetriedFrom:O.taskRetriedFrom}:{},...O.taskDelivery!==void 0?{taskDelivery:O.taskDelivery}:{},...O.taskIsolation!==void 0?{taskIsolation:O.taskIsolation}:{},...O.taskSourceProjectPath!==void 0?{taskSourceProjectPath:O.taskSourceProjectPath}:{},...O.taskWorktree!==void 0?{taskWorktree:O.taskWorktree}:{},...O.taskDiffStat!==void 0?{taskDiffStat:O.taskDiffStat}:{},...O.taskQueuePosition!==void 0?{taskQueuePosition:O.taskQueuePosition}:{},...O.taskQueueDepth!==void 0?{taskQueueDepth:O.taskQueueDepth}:{},...O.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:O.taskConcurrencyLimit}:{},...O.selectedModelId!==void 0?{selectedModelId:O.selectedModelId}:{},...O.permissionMode!==void 0?{permissionMode:O.permissionMode}:{},...O.reasoningEffort!==void 0?{reasoningEffort:O.reasoningEffort}:{},...O.serviceTier!==void 0?{serviceTier:O.serviceTier}:{},...O.responseVerbosity!==void 0?{responseVerbosity:O.responseVerbosity}:{},...O.communicationStyle!==void 0?{communicationStyle:O.communicationStyle}:{},...O.communicationStyleDigest!==void 0?{communicationStyleDigest:O.communicationStyleDigest}:{},...O.projectInstructionsDigest!==void 0?{projectInstructionsDigest:O.projectInstructionsDigest}:{},updatedAt:V}};return X=[...B,T],T})}catch(B){throw K.sanitizeStoredSessionError(B,_)}return K.toPublicMetadata(K.projectMetadataFromEntries(X,_,R,L))}static async setSessionPermissionMode(_,$,O){if(x(_),!o0(O))throw Error("Invalid session permission mode");let R=K.resolveCatalogWorkspace($),L=await K.findSessionMetadata(_,R);if(L?.permissionMode===O)return L;if(L)return K.updateSessionMetadata(_,R,{permissionMode:O});try{return await K.createSessionMetadata(_,R,{taskStatus:"completed",permissionMode:O})}catch(W){if(W.code!=="EEXIST")throw W;return K.updateSessionMetadata(_,R,{permissionMode:O})}}static async findSessionTaskWorktree(_,$){x(_);let O=K.resolveCatalogWorkspace($),R=K.getSessionFilePath(O,_);try{return(await K.readStoredSessionMetadata(R,_,O)).taskWorktree}catch(L){if(L.code==="ENOENT")return;throw K.sanitizeStoredSessionError(L,_)}}static async findSessionTaskDispatch(_,$){x(_);let O=K.resolveCatalogWorkspace($),R=K.getSessionFilePath(O,_);try{return(await K.readStoredSessionMetadata(R,_,O)).taskDispatch}catch(L){if(L.code==="ENOENT")return;throw K.sanitizeStoredSessionError(L,_)}}static async loadSessionFromFile(_,$,O){let R=await W0(_,"utf-8"),L=this.parseStoredSession(R,$);if(O!==void 0){if(this.projectMetadataFromEntries(L,$,O,_).projectPath!==O)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(L)}static async loadSessionModelContextFromFile(_,$,O){let R=await W0(_,"utf-8"),L=this.parseStoredSession(R,$);if(O!==void 0){if(this.projectMetadataFromEntries(L,$,O,_).projectPath!==O)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToModelContext(L)}static convertJSONLToModelContext(_){let $=l(_),O=-1,R;for(let W=0;W<$.length;W++){let X=$[W];if(X?.type!=="part_created"||X.data.partType!=="summary")continue;let B=X.data.payload;if(O=W,R=I0(B.replacementMessages),!R)R=[{role:"user",content:B.text??"",metadata:X.data.payload}]}if(O<0||!R)return this.convertJSONLToMessages($,{includeTokenBudgetHandoffs:!0});let L=this.convertJSONLToMessages($.slice(O+1),{includeTokenBudgetHandoffs:!0});return[...R,...L]}static convertJSONLToMessages(_,$={}){let O=[],R=new Map,L=new Map,W=new Map,X=new Map,B=new Map,G=l(_),J=$.includeTokenBudgetHandoffs?I1(G):{kind:"none"},V=new Set;for(let T of G){if(T.type==="token_budget_handoff_recorded"){if(J.kind==="valid"&&J.event.id===T.id){let C=m1(T);if(C)O.push(C)}continue}if(T.type==="message_created"){let C=T.data.metadata&&typeof T.data.metadata==="object"&&!Array.isArray(T.data.metadata)?T.data.metadata:void 0,Y=C?.codeReview&&typeof C.codeReview==="object"&&!Array.isArray(C.codeReview)?C.codeReview:void 0;if(Y?.phase==="completed"&&typeof Y.reviewId==="string")V.add(Y.reviewId);let Q=T.data.role==="assistant"&&T.data.parentMessageId?W.get(T.data.parentMessageId):void 0,A=Q??{role:T.data.role,content:"",...T.data.metadata||T.data.inboxMessageId?{metadata:{...T.data.metadata&&typeof T.data.metadata==="object"&&!Array.isArray(T.data.metadata)?T.data.metadata:{},...T.data.inboxMessageId?{inboxMessageId:T.data.inboxMessageId}:{}}}:{}};if(R.set(T.data.messageId,A),L.set(T.data.messageId,[]),!Q)O.push(A)}if(T.type==="part_created"){if(T.data.partType==="reasoning"){let C=R.get(T.data.messageId);if(C){let Y=T.data.payload;C.reasoningContent=(C.reasoningContent??"")+(Y.text??"")}}if(T.data.partType==="text"){let C=R.get(T.data.messageId);if(C){let Y=T.data.payload,Q=L.get(T.data.messageId);if(Q)Q.push({type:"text",text:Y.text??""}),C.content=H$(Q);else C.content=Y.text??""}}if(T.data.partType==="image"){let C=R.get(T.data.messageId);if(C){let Y=T.data.payload,Q=L.get(T.data.messageId);if(Q&&Y.dataUrl)Q.push({type:"image_url",image_url:{url:Y.dataUrl}}),C.content=H$(Q)}}if(T.data.partType==="tool_call"){let C=R.get(T.data.messageId);if(C?.role!=="assistant"){if(C=W.get(T.data.messageId),!C)C={role:"assistant",content:"",tool_calls:[]},W.set(T.data.messageId,C),O.push(C)}if(C.role==="assistant"){let Y=T.data.payload,Q=Y.toolCallId??T.data.partId;X.set(T.data.partId,Q),B.set(Q,C),C.tool_calls??=[],C.tool_calls.push({id:Q,type:"function",function:{name:Y.toolName??"unknown",arguments:JSON.stringify(Y.input??{})}})}}if(T.data.partType==="tool_result"){let C=T.data.payload,Y=c1(C),Q=Y.error?`Error: ${Y.error.message}`:typeof Y.llmContent==="string"?Y.llmContent:JSON.stringify(Y.llmContent),A=C;O.push({role:"tool",content:Q,tool_call_id:X.get(T.data.messageId)??C.toolCallId,name:C.toolName,metadata:A})}if(T.data.partType==="summary"){let C=T.data.payload,Y=T.data.payload;O.push({role:"system",content:C.text??"",metadata:Y})}if(T.data.partType==="subtask_ref"){let C=R.get(T.data.messageId)??B.get(T.data.messageId);if(C){let Y=T.data.payload,Q=C.metadata??{};C.metadata={...Q,subtaskRef:Y}}}}}for(let T of m0(G)){if(T.completion===void 0||V.has(T.start.reviewId))continue;O.push({role:"assistant",content:k1(T.start,T.completion),metadata:{codeReview:{...S1(T.start,T.completion),synthetic:!0}}})}return O}static projectionDeriver(){return(_,$,O)=>{try{let R=u(O,$);return this.projectMetadataFromEntries(_,$,O,R)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(_,$,O=0,R=!1,L={}){try{let W=await i0();if(!W)return null;await i_(W,this.projectionDeriver(),O);let X=[],B=[];if(_!==void 0)X.push("project_path=?"),B.push(_);_4(L,"",X,B);let G=X.length>0?` WHERE ${X.join(" AND ")}`:"",J=W.prepare(`SELECT metadata_json, is_subagent FROM sessions${G}`).all(...B),V=[];for(let C of J){if(!$&&C.is_subagent===1)continue;try{let Y=JSON.parse(C.metadata_json);if(_!==void 0&&Y.projectPath!==_)continue;V.push(Y)}catch{}}let T=await Promise.all(V.map((C)=>this.reconcileInterruptedTask(C)));return u_(T.filter((C)=>x$(C,L)),R)}catch{return null}}static async scanStoredSessions(_,$=!1,O=0,R=!1,L={}){let W=_?Z.resolve(_):void 0,X=await this.scanStoredSessionsFromProjection(W,$,O,R,L);if(X)return X;let B=W?[{storagePath:Z0(W),projectPath:W}]:await this.listAllProjectStorageDirectories(),G=[];for(let J of B){let V;try{V=await v_(J.storagePath)}catch(T){if(T.code==="ENOENT")continue;throw T}for(let T of V){if(!T.endsWith(".jsonl"))continue;let C=T.slice(0,-6),Y=Z.join(J.storagePath,T);try{let Q=await this.readStoredSessionMetadata(Y,C,J.projectPath);if(W!==void 0&&Q.projectPath!==W){U0.warn(`[SessionService] Skipping out-of-scope session transcript: ${C}`);continue}if(!$&&Q.relationType==="subagent")continue;if(!$4(Q,L))continue;G.push(Q)}catch(Q){let A=Q.code;if(A==="ENOENT")continue;if(A)throw Q;U0.warn(`[SessionService] Skipping invalid session transcript: ${C}`)}}}return u_(G,R)}static async listAllProjectStorageDirectories(){let _=Z.join(k(),"projects"),$;try{$=await v_(_,{withFileTypes:!0,encoding:"utf8"})}catch(O){if(O.code==="ENOENT")return[];throw O}return $.filter((O)=>O.isDirectory()).map((O)=>({storagePath:Z.join(_,O.name),projectPath:U$(O.name)}))}static async readStoredSessionMetadata(_,$,O){let R=await W0(_,"utf-8"),L=this.parseStoredSession(R,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(L,$,O,_))}static async reconcileInterruptedTask(_){let $=_.taskOwnerPid;if(_.taskStatus!=="running"||$===void 0||V$($))return _;let O;try{O=await o.acquire(_.sessionId,_.projectPath)}catch(W){if(!(W instanceof d))throw W;let X=await W0(_.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(X,_.sessionId),_.sessionId,_.projectPath,_.filePath)}let R=new j(_.filePath),L;try{try{await R.appendValidated((W)=>{let X=this.projectMetadataFromEntries(W,_.sessionId,_.projectPath,_.filePath);if(X.taskStatus!=="running"||X.taskOwnerPid!==$||V$($))throw new o_;let B=new Date().toISOString(),G={id:P(),sessionId:_.sessionId,timestamp:B,type:"session_updated",cwd:_.projectPath,gitBranch:a(_.projectPath),version:t(),data:{sessionId:_.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:B,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:B}};return L=[...W,G],G})}catch(W){if(!(W instanceof o_))throw W}if(!L){let W=await W0(_.filePath,"utf-8");L=this.parseStoredSession(W,_.sessionId)}return this.projectMetadataFromEntries(L,_.sessionId,_.projectPath,_.filePath)}finally{await O.release()}}static projectMetadataFromEntries(_,$,O,R){if(_.length===0)throw Error(`Empty session transcript: ${$}`);let L=this.getSessionCreatedEntry(_,$),W=_.reduce((F,Y0)=>Y0.type==="session_updated"?{...F,...Y0.data}:F,{...L.data}),X=l(_),B=b1(w1(X)),J=m0(X).at(-1),V=X.findLastIndex((F)=>F.type==="review_started"&&F.data.reviewId===J?.start.reviewId||F.type==="review_completed"&&F.data.reviewId===J?.start.reviewId),T=X.findLastIndex((F)=>(F.type==="session_created"||F.type==="session_updated")&&Object.hasOwn(F.data,"taskStatus")),C=J!==void 0&&V>T,Y=C?J.completion===void 0?"running":J.completion.status==="completed"||J.completion.status==="stale"?"completed":J.completion.status==="aborted"?"cancelled":J.completion.status==="interrupted"?"interrupted":"failed":void 0,Q=X.filter((F)=>F.type==="message_created"&&["user","assistant"].includes(F.data.role)).length,A=X.some((F)=>F.type==="part_created"&&F.data.partType==="tool_result"&&typeof F.data.payload.error==="string"),b=C$.has(W.taskStatus)?W.taskStatus:void 0,E=Y??b??(A?"failed":"completed"),L0=typeof W.taskOwnerPid==="number"&&Number.isInteger(W.taskOwnerPid)&&W.taskOwnerPid>0?W.taskOwnerPid:void 0,X0=d_.has(W.taskIsolation)?W.taskIsolation:void 0,y=typeof W.taskSourceProjectPath==="string"&&Z.isAbsolute(W.taskSourceProjectPath)?Z.resolve(W.taskSourceProjectPath):void 0,I=L.cwd;if(I!==void 0&&!Z.isAbsolute(I))throw Error(`Session catalog cwd must be absolute: ${$}`);let z=I===void 0?O:Z.resolve(I),D=Y$(W.taskWorktree),w=D?.sessionId===$&&Z.resolve(D.workspaceRoot)===z?D:void 0,q=Q$(W.taskDiffStat),f=N$(W.taskDispatch),r_=r0.has(W.taskPriority)?W.taskPriority:f?.taskPriority,a_=a0.has(W.taskKind)?W.taskKind:f?.taskKind,t_=typeof W.taskDueAt==="string"&&Number.isFinite(Date.parse(W.taskDueAt))?new Date(W.taskDueAt).toISOString():f?.taskDueAt,t0=typeof W.taskModelId==="string"&&W.taskModelId.trim()?W.taskModelId:f?.modelId,s_=typeof W.selectedModelId==="string"&&W.selectedModelId.trim()?W.selectedModelId:t0,e_=o0(W.permissionMode)?W.permissionMode:f?.permissionMode,_1=F0(W.reasoningEffort)?W.reasoningEffort:f?.reasoningEffort,$1=M0(W.serviceTier)?W.serviceTier:f?.serviceTier,O1=E0(W.responseVerbosity)?W.responseVerbosity:f?.responseVerbosity,s0=D0(W.communicationStyle)?W.communicationStyle:f?.communicationStyle,e0=Object.hasOwn(W,"communicationStyleDigest")?typeof W.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(W.communicationStyleDigest)?W.communicationStyleDigest:void 0:s0===f?.communicationStyle?f?.communicationStyleDigest:void 0,__=Object.hasOwn(W,"projectInstructionsDigest")?typeof W.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(W.projectInstructionsDigest)?W.projectInstructionsDigest:void 0:f?.projectInstructionsDigest,$_=k$(W.archivedAt)?W.archivedAt:void 0,O_=q$(W.taskRetriedFrom),C0=Z$(W.taskDelivery),V0=typeof W.taskQueuePosition==="number"&&Number.isInteger(W.taskQueuePosition)&&W.taskQueuePosition>0?W.taskQueuePosition:void 0,z0=typeof W.taskQueueDepth==="number"&&Number.isInteger(W.taskQueueDepth)&&W.taskQueueDepth>=0?W.taskQueueDepth:void 0,R_=typeof W.taskConcurrencyLimit==="number"&&Number.isInteger(W.taskConcurrencyLimit)&&W.taskConcurrencyLimit>0?W.taskConcurrencyLimit:void 0,U=C?J?.completion?J.completion.status==="completed"?void 0:`Code review ${N_(J.completion.status)}`:`Reviewing ${J?.start.target.label??"changes"}`:void 0,m=C?E==="failed"&&U?F_(U):void 0:D_(W.taskFailure)?W.taskFailure:E==="failed"&&typeof W.taskStatusReason==="string"?F_(W.taskStatusReason):void 0;return{sessionId:$,projectPath:z,gitBranch:L.gitBranch,rootId:W.rootId||$,parentId:W.parentId,relationType:W.relationType,resumedFrom:W.resumedFrom,rootAgentId:W.rootAgentId,resumeDepth:W.resumeDepth,title:W.title,agentType:W.agentType,model:W.model,selectedModelId:s_,permissionMode:e_,reasoningEffort:_1,serviceTier:$1,responseVerbosity:O1,communicationStyle:s0,communicationStyleDigest:e0,projectInstructionsDigest:__,pendingInteraction:B,taskStatus:E,taskStatusReason:m?.message??U??(typeof W.taskStatusReason==="string"?W.taskStatusReason:void 0),taskFailure:m,taskStartedAt:C?J?.start.startedAt:typeof W.taskStartedAt==="string"?W.taskStartedAt:void 0,taskCompletedAt:C?J?.completion?.completedAt:typeof W.taskCompletedAt==="string"?W.taskCompletedAt:void 0,taskPromptSummary:C?J?L4(J.start.target):"/review uncommitted":typeof W.taskPromptSummary==="string"?W.taskPromptSummary:void 0,taskPriority:r_,taskKind:a_,taskDueAt:t_,taskModelId:t0,taskRetryAvailable:f!==void 0,taskRetriedFrom:O_,taskDelivery:C0,taskIsolation:X0,taskSourceProjectPath:y,taskWorktreePath:w?.worktreeRoot,taskWorktreeBranch:w?.branch,taskBaseCommit:w?.baseCommit,taskDiffStat:q,taskQueuePosition:V0,taskQueueDepth:z0,taskConcurrencyLimit:R_,archivedAt:$_,taskOwnerPid:C?void 0:L0,taskWorktree:w,taskDispatch:f,messageCount:Q,firstMessageTime:_[0].timestamp,lastMessageTime:_.at(-1).timestamp,hasErrors:A||E==="failed",filePath:R}}static toPublicMetadata(_){let{filePath:$,taskOwnerPid:O,taskWorktree:R,taskDispatch:L,...W}=_;return W}static getSessionFilePath(_,$){return u(_,$)}static getSessionCreatedEntry(_,$){let O=_.find((R)=>R.type==="session_created");if(!O)throw new b$($);return O}static resolveCatalogWorkspace(_){if(!Z.isAbsolute(_))throw Error("Session catalog cwd must be absolute");return Z.resolve(_)}static validateSessionWorkspace(_,$,O){let R=this.getSessionCreatedEntry(_,$);if(R.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!Z.isAbsolute(R.cwd)||Z.resolve(R.cwd)!==O)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(_){if(!Z.isAbsolute(_))throw Error("Fork workspace paths must be absolute");return Z.resolve(_)}static parseStoredSession(_,$){return F$(_,`session ${$}`)}static isCorruptSessionJSONLError(_){return _ instanceof Error&&_.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(_,$){if(!this.isCorruptSessionJSONLError(_)||!(_ instanceof Error))return _;let O=_.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${O?` at line ${O}`:""}`,{cause:_.cause})}static async readStableSessionSnapshot(_,$,O=3){for(let R=0;R<O;R+=1){let L=await A0.stat(_),W=await A0.readFile(_),X=this.parseStoredSession(W,$),B=await A0.stat(_);if(L.size===B.size&&L.mtimeNs===B.mtimeNs&&L.dev===B.dev&&L.ino===B.ino)return X}throw Error("Session changed while creating fork; retry the operation")}}function H$(_){if(_.length===1&&_[0]?.type==="text")return _[0].text;return[..._]}
|
|
118
|
-
export{V_ as ac,z_ as bc,R1 as cc,f0 as dc,L1 as ec,k4 as fc,d as gc,o as hc,n$ as ic,V1 as jc,e as kc,a4 as lc,t4 as mc,s4 as nc,e4 as oc,_O as pc,$O as qc,OO as rc,RO as sc,WO as tc,LO as uc,XO as vc,BO as wc,TO as xc,GO as yc,JO as zc,CO as Ac,VO as Bc,YO as Cc,ZO as Dc,QO as Ec,NO as Fc,qO as Gc,HO as Hc,UO as Ic,KO as Jc,AO as Kc,EO as Lc,MO as Mc,FO as Nc,DO as Oc,zO as Pc,M1 as Qc,O2 as Rc,Z_ as Sc,z1 as Tc,SO as Uc,gO as Vc,w1 as Wc,IO as Xc,m0 as Yc,vO as Zc,N_ as _c,k1 as $c,S1 as ad,hO as bd,cO as cd,lO as dd,Z2 as ed,I1 as fd,m1 as gd,Q2 as hd,nO as id,E_ as jd,F_ as kd,
|
|
118
|
+
export{V_ as ac,z_ as bc,R1 as cc,f0 as dc,L1 as ec,k4 as fc,d as gc,o as hc,n$ as ic,V1 as jc,e as kc,a4 as lc,t4 as mc,s4 as nc,e4 as oc,_O as pc,$O as qc,OO as rc,RO as sc,WO as tc,LO as uc,XO as vc,BO as wc,TO as xc,GO as yc,JO as zc,CO as Ac,VO as Bc,YO as Cc,ZO as Dc,QO as Ec,NO as Fc,qO as Gc,HO as Hc,UO as Ic,KO as Jc,AO as Kc,EO as Lc,MO as Mc,FO as Nc,DO as Oc,zO as Pc,M1 as Qc,O2 as Rc,Z_ as Sc,z1 as Tc,SO as Uc,gO as Vc,w1 as Wc,IO as Xc,m0 as Yc,vO as Zc,N_ as _c,k1 as $c,S1 as ad,hO as bd,cO as cd,lO as dd,Z2 as ed,I1 as fd,m1 as gd,Q2 as hd,nO as id,E_ as jd,F_ as kd,D_ as ld,r as md,h0 as nd,LR as od,XR as pd,BR as qd,TR as rd,c1 as sd,GR as td,CR as ud,l1 as vd,YR as wd,k_ as xd,S_ as yd,KR as zd,AR as Ad,t1 as Bd,l0 as Cd,fR as Dd,G$ as Ed,O$ as Fd,kR as Gd,J$ as Hd,SR as Id,W4 as Jd,GW as Kd,JW as Ld,b$ as Md,J0 as Nd,p as Od,K as Pd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as E4}from"./chunk-8hprmrd5.js";import{Dd as I0,Fd as V6,Gd as R1,Hd as K6,Od as n$,Sc as kJ,Uc as CJ,Vc as vJ,Wc as d2,Xc as m2,bc as X$,bd as IJ,cd as S4,dd as T4,ed as v2,fd as x1,gd as M4,hd as R4,id as E1,ld as UJ,td as V1}from"./chunk-6qxzcx0a.js";import{Td as F0,Wd as _J,Xd as k0}from"./chunk-7bhk8qk5.js";import{Ye as tJ}from"./chunk-3saxqsn7.js";import{$e as O4,Ze as _4,_e as i0,af as HJ,df as b1,ef as Y6,ff as zJ,gf as BJ,if as jJ}from"./chunk-31g86axj.js";import{$f as X4,Tf as J$,Uf as r0,Xf as b4}from"./chunk-q5t2rnx0.js";import{kg as A$}from"./chunk-s47ypj8n.js";import{uh as rJ}from"./chunk-0v74fhhc.js";import{Jh as H0}from"./chunk-mybhqpc7.js";import{ji as h0}from"./chunk-zvms9ap7.js";import{xi as xJ}from"./chunk-v2bvrk83.js";import{Ii as _$,Ki as i6,Li as y0,Mi as M1,Oi as MJ,Pi as RJ,Qi as hJ}from"./chunk-h5xw792m.js";import{Ri as G8}from"./chunk-g2yaghbk.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
|
|
1
|
+
import{$b as E4}from"./chunk-8hprmrd5.js";import{Ed as I0,Gd as V6,Hd as R1,Id as K6,Pd as n$,Sc as kJ,Uc as CJ,Vc as vJ,Wc as d2,Xc as m2,bc as X$,bd as IJ,cd as S4,dd as T4,ed as v2,fd as x1,gd as M4,hd as R4,id as E1,md as UJ,ud as V1}from"./chunk-hmgxkjbx.js";import{Ud as F0,Xd as _J,Yd as k0}from"./chunk-wzx5s1dm.js";import{Ze as tJ}from"./chunk-ef5b0ysc.js";import{$e as i0,_e as _4,af as O4,bf as HJ,ef as b1,ff as Y6,gf as zJ,hf as BJ,jf as jJ}from"./chunk-a9ek5zt1.js";import{Uf as J$,Vf as r0,Yf as b4,ag as X4}from"./chunk-17ck16tq.js";import{lg as A$}from"./chunk-7kbtqzy0.js";import{vh as rJ}from"./chunk-4ytvrkks.js";import{Kh as H0}from"./chunk-j0ndrqv6.js";import{ki as h0}from"./chunk-54syvhtz.js";import{yi as xJ}from"./chunk-tae9c030.js";import{Ji as _$,Li as i6,Mi as y0,Ni as M1,Pi as MJ,Qi as RJ,Ri as hJ}from"./chunk-s6n0cgg5.js";import{Si as G8}from"./chunk-d2f41jxt.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",r6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class N$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)b5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function x0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function n6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",O2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function o6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function f2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function N1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function o$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function U0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await x0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as Q6}from"node:crypto";import{promises as m5}from"node:fs";import c5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var a6={enabled:!0,maxIndexLines:200};var E5="memory",s6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=_$($);this.memoryDir=B$.join(W,E5)}this.config={...a6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,s6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import E8 from"node:path";import{nanoid as S8}from"nanoid";import*as M0 from"node:fs/promises";import*as bJ from"node:path";import{Mutex as j8}from"async-mutex";import U8 from"write-file-atomic";var PJ=120,k2=128;function $1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function B8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];let Z=$1(J.inputMessageIds),W=$1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function S1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=B8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((K)=>V.has(K))}var T1=1,J1=8388608;function NJ($,J){let Z={version:T1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
85
85
|
`}function C2($,J){return $ instanceof Error&&"code"in $&&$.code===J}function D8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function w8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==T1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!D8(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?R1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:T1,sessionId:Z,messages:Y}}function q8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return S1($,Z);return[]}))}class h1{workspaceRoot;sessionId;filePath;mutex=new j8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new h1($,J,M1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=NJ(this.sessionId,Z);if(Buffer.byteLength(W)>J1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:T1,sessionId:this.sessionId,messages:[]};try{if((await M0.stat(this.filePath)).size>J1)throw Error(`Steering inbox exceeds ${J1} bytes: ${this.filePath}`);await M0.chmod(this.filePath,384),$=w8(await M0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!C2(Y,"ENOENT"))throw Y}let J=y0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=q8(_J(await M0.readFile(J,"utf8"),J))}catch(Y){if(!C2(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await M0.mkdir(bJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await M0.unlink(this.filePath).catch((W)=>{if(!C2(W,"ENOENT"))throw W});return}let Z=J??NJ(this.sessionId,$);if(Buffer.byteLength(Z)>J1)throw Error(`Steering inbox exceeds ${J1} bytes: ${this.filePath}`);await U8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as v0 from"node:fs/promises";import*as uJ from"node:path";import{nanoid as K0}from"nanoid";var EJ=256;class D0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new k0(y0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=D0.instances.get(Z);if(!W)W=new D0($,J),D0.instances.set(Z,W),D0.pruneIdleInstances(Z);else D0.instances.delete(Z),D0.instances.set(Z,W);return W}static release($,J){D0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(D0.instances.size<=EJ)return;for(let[J,Z]of D0.instances){if(J===$||Z.subscribers.size>0)continue;if(D0.instances.delete(J),D0.instances.size<=EJ)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),D0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(v2(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(v2($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function M$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class C0 extends Error{}var F8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function I2($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function SJ($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=k2)W.push(K)}return[...new Set(W)]}function gJ($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1)return;let J="inputMessageIds"in $?$1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;return{inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function pJ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return S1($,Z);return[]}))}function dJ($,J,Z=[]){let W=gJ(J.data.recovery);if(!W)return;let Y=pJ($);for(let K of Z)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K));if(V.length===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function u2($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=dJ($,Z);if(W)return W}return}var L8=1e4,O8=1e5,f8=2592000000,TJ=128,y8=1e6,A8=256;function P8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>TJ||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>y8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>TJ||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function mJ($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,B=Array.isArray(K)?K.filter((z)=>typeof z==="string"&&z.length>0&&z.length<=k2):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>PJ||B.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>L8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>O8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>f8)return;let j;if("goalFinalization"in Y){if(j=P8(Y.goalFinalization),!j)return}return{turnId:V,inputMessageIds:[...new Set(B)],turnsCount:Q,toolCallsCount:X,durationMs:H,...j?{goalFinalization:j}:{}}}function N8($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=mJ(Y,J);if(V)return V}return}function _8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=mJ(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function Z1($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},B=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(B,{toolCallId:B,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(B),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(B)&&H.error===null)V.add(B)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class A0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;initializedSessions=new Set;constructor($=H0(),J=100,Z=xJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:K0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:MJ(this.projectPath),version:this.version,data:Z}}log($){return D0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=y0(this.projectPath,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=A0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),A0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(A0.sessionInitializationRuns.get(Z)===W)A0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>A8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await new k0(J).readAll()).length>0)return;let V=new Date().toISOString(),K={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:V,updatedAt:V},Q=this.createEvent("session_created",$,K);await this.log($).commit(Q)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=CJ;return J}async initialize(){try{let $=_$(this.projectPath);await v0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=K0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},B=this.createEvent("message_created",$,H),j=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],z=typeof Z==="string"?[this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:b8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([B,...j,...z]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=Y.some((z)=>z.type==="inbox_acknowledged"&&z.data.messageIds.includes(J.inboxMessageId)),K=Y.find((z)=>z.type==="message_created"&&z.data.inboxMessageId===J.inboxMessageId),Q=Y.findLast((z)=>{if(z.type!=="part_created"||z.data.partType!=="tool_call"||!z.data.payload||typeof z.data.payload!=="object"||Array.isArray(z.data.payload))return!1;let U=z.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let A=U.input,b=A.resume_from??A.resume;return A.run_in_background===!0&&A.subagent_session_id===J.childSessionId&&A.description===J.subagentRef.subagentDescription&&(A.subagent_type===void 0||A.subagent_type===J.subagentRef.subagentType)&&(A.resume_from===void 0||A.resume===void 0||A.resume_from===A.resume)&&(b===void 0?J.subagentRef.subagentResumedFrom===void 0:b===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let X=Y.find((z)=>z.type==="part_created"&&z.data.partType==="subtask_ref"&&z.data.payload!==null&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)&&z.data.payload.childSessionId===J.childSessionId&&z.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),B=K?.data.messageId??K0(),j=[];if(!K){let z={messageId:B,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};j.push(this.createEvent("message_created",$,z)),j.push(this.createEvent("part_created",$,{partId:K0(),messageId:B,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let z=Y.findLast((A)=>A.type==="part_created"&&A.data.partType==="subtask_ref"&&A.data.messageId===Q.data.messageId&&A.data.payload!==null&&typeof A.data.payload==="object"&&!Array.isArray(A.data.payload)&&A.data.payload.childSessionId===J.childSessionId),U=z?.data.payload&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)?z.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:K0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:B},j}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=F0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new C0;let Y=M$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof C0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new C0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=M$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof C0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=$1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=F0(X),B=pJ(H),j=H.findLast((g)=>(g.type==="turn_completed"||g.type==="turn_aborted")&&g.data.turnId===J.turnId);if(j){if(j.type==="turn_completed")throw K=void 0,Q=[],new C0;let g=gJ(j.data.recovery),Z0=g?V.filter((w0)=>g.inputMessageIds.includes(w0)):[],P0=Z0.filter((w0)=>!B.has(w0));if(Q=Z0,K=dJ(H,j,Z0),P0.length===0)throw new C0;return[this.createEvent("inbox_acknowledged",$,{messageIds:P0,acknowledgedAt:J.abortedAt})]}let z=M$(H).active;if(!z||z.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=Z1(H,z.turnId),A=SJ(H,z.turnId),b=u2(H),M=new Set(J.recovery?.inputMessageIds??[]),R=b?b.inputMessageIds.filter((g)=>M.has(g)):[],x=[...new Set([...A,...R])],P={version:1,inputMessageIds:x,hadSuccessfulToolResult:U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:I2(H,z.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:P.inputMessageIds,hadSuccessfulToolResult:P.hadSuccessfulToolResult,emptyFinalCorrectionSpent:P.emptyFinalCorrectionSpent};let v=V.filter((g)=>x.includes(g)),u=v.filter((g)=>!B.has(g));Q=v;let q=new Set(B);for(let g of v)q.add(g);let d=P.inputMessageIds.filter((g)=>!q.has(g));K=d.length>0?{turnId:J.turnId,outcome:"aborted",inputMessageIds:d,hadSuccessfulToolResult:P.hadSuccessfulToolResult,emptyFinalCorrectionSpent:P.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:u0,...Q0}=J;return[this.createEvent("turn_aborted",$,{...Q0,...v.length>0?{acknowledgedInputMessageIds:v}:{},recovery:P}),...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof C0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=F0(J),W=M$(Z).active;return W?Z1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=F0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=M$(Y).active,K=Z1(Y);if(!V&&K.orphaned.length===0){if(Z=u2(Y),Z)return[];throw new C0}let Q=V?N8(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let P=Z1(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:P.hadSuccessfulResult,emptyFinalCorrectionSpent:I2(Y,V.turnId),finalization:Q};let v=new Set(Y.flatMap((d)=>d.type==="inbox_acknowledged"?d.data.messageIds:[])),u=Q.inputMessageIds.filter((d)=>!v.has(d)),q=new Date().toISOString();return[...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:q})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:q,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?Z1(Y,V.turnId):void 0,H=X?.orphaned.some((P)=>{let v=J.adoptedToolResults?.get(P.toolCallId);return v?.toolCallId===P.toolCallId&&v.toolName===P.toolName&&v.error===void 0})??!1,B=new Set(V?.inputMessageIds??[]),j=V?u2(Y):void 0,z=j?j.inputMessageIds.filter((P)=>B.has(P)):[],U=z.length>0,A=V?SJ(Y,V.turnId):[];Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...A,...z])],hadSuccessfulToolResult:(X?.hadSuccessfulResult??!1)||H||U&&j?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:I2(Y,V.turnId)||U&&j?.emptyFinalCorrectionSpent===!0}:void 0;let b=V?X?.all.length??0:0,M=new Date().toISOString(),R=V?Date.parse(V.startedAt):Number.NaN,x=K.orphaned.flatMap((P)=>{let v=J.adoptedToolResults?.get(P.toolCallId),u=v?.toolCallId===P.toolCallId&&v.toolName===P.toolName?v:void 0,q=this.createEvent("part_created",$,{partId:P.toolCallId,messageId:u?P.messageId:P.toolCallId,partType:"tool_result",payload:u?{toolCallId:P.toolCallId,toolName:P.toolName,output:u.output,error:u.error??null,...u.metadata===void 0?{}:{metadata:u.metadata}}:{toolCallId:P.toolCallId,toolName:P.toolName,output:null,error:F8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:M});if(!u?.subagentRef)return[q];let d=u.subagentRef;return[q,this.createEvent("part_created",$,{partId:K0(),messageId:P.messageId,partType:"subtask_ref",payload:{childSessionId:d.subagentSessionId,agentType:d.subagentType,description:d.subagentDescription??"",status:d.subagentStatus,summary:d.subagentSummary??"",resumedFrom:d.subagentResumedFrom??null,rootAgentId:d.subagentRootId??d.subagentSessionId,resumeDepth:d.subagentResumeDepth??0,verificationVerdict:d.verificationVerdict??null,startedAt:M,finishedAt:M},createdAt:M})]});return V?[...x,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:M,turnsCount:0,toolCallsCount:b,durationMs:Number.isFinite(R)?Math.max(0,Date.now()-R):0,recovery:Z?{version:1,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof C0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?_8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??K0(),X=[];if(!W){let j={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,j))}let H=V??K0(),B={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,B)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,z=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,U=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(z&&U){let A={partId:K0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:z,agentType:U,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,A))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),B=Y??K0();return await this.log($).commitValidatedBatch((j)=>{let z=Q?.subagentStatus==="running"?F0(j).findLast((x)=>x.type==="part_created"&&x.data.partType==="subtask_ref"&&x.data.payload!==null&&typeof x.data.payload==="object"&&!Array.isArray(x.data.payload)&&x.data.payload.childSessionId===Q.subagentSessionId&&(x.data.payload.status==="completed"||x.data.payload.status==="failed"||x.data.payload.status==="cancelled")):void 0,U=z?.data.payload,A=X&&typeof X==="object"&&!Array.isArray(X)?X:{},b=U?{...A,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,M=[];if(!Y){let x={messageId:B,role:"assistant",parentMessageId:void 0,createdAt:H};M.push(this.createEvent("message_created",$,x))}let R={partId:J,messageId:B,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,...b===void 0?{}:{metadata:b}},createdAt:H};if(M.push(this.createEvent("part_created",$,R)),Q&&!z){let x=Q.subagentStatus==="running"?null:H,P={partId:K0(),messageId:B,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:x},createdAt:H};M.push(this.createEvent("part_created",$,P))}return M}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=K0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:K0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:vJ(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=x1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=x1(F0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${IJ}${K0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=x1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=y0(this.projectPath,$),W=await new k0(J).readAll();return W.length>0?F0(W):null}catch{return null}}async loadSession($){try{let J=y0(this.projectPath,$),Z=new k0(J),W=F0(await Z.readAll());if(W.length===0)return null;let Y=W.find((V)=>V.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=y0(this.projectPath,$),Z=new k0(J),W=F0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let X of W){if(X.type==="message_created")Y.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let H=Y.get(X.data.messageId);if(H){let B=X.data.payload;H.content=B.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let H=Y.get(X.data.messageId);if(H)H.content=H.content?`${H.content}
|
|
86
|
-
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=_$(this.projectPath);return(await v0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=y0(this.projectPath,$),Z=new k0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=F0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=y0(this.projectPath,$);await new k0(J).delete(),await v0.unlink(M1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await kJ(this.projectPath,$,RJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
86
|
+
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=_$(this.projectPath);return(await v0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=y0(this.projectPath,$),Z=new k0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=F0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=y0(this.projectPath,$);await new k0(J).delete(),await v0.unlink(M1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await kJ(this.projectPath,$,RJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-m4bg4jp9.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=y0(this.projectPath,Z),V=await new k0(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=_$(this.projectPath);await v0.mkdir($,{recursive:!0,mode:493});let J=uJ.join($,".health-check");return await v0.writeFile(J,"test","utf-8"),await v0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return hJ()}}function b8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var cJ=131072,g2=new rJ;function p2($,J){return`${E8.resolve($)}\x00${J}`}function c2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>cJ)throw Error(`${J} exceeds ${cJ} bytes`);return JSON.parse(Z)}function lJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function T8($,J){return JSON.stringify($)===JSON.stringify(J)}function M8($,J){if($.request.interactionType!=="elicitation")return c2(J,"Interaction response");return c2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function iJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function R8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function h8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
87
87
|
`)}function x8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=h8(J);return{toolOutput:`User answers:
|
|
88
88
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${K}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ie as a,Je as b,Ke as c,Le as d,Me as e,Ne as f,Oe as g,Pe as h,Qe as i,Re as j,Se as k,Te as l,Ue as m,Ve as n,We as o,Xe as p,Ye as q}from"./chunk-p47hbq3a.js";import"./chunk-v508x7cg.js";import"./chunk-ef5b0ysc.js";import"./chunk-4crf8nvz.js";import"./chunk-4ytvrkks.js";import"./chunk-nvypaz88.js";import"./chunk-d1je4wzc.js";import"./chunk-j0ndrqv6.js";import"./chunk-8jtwm19d.js";import"./chunk-54syvhtz.js";import"./chunk-krhr8xbg.js";import"./chunk-63wahkkf.js";import"./chunk-tae9c030.js";import"./chunk-fra0nwzj.js";import"./chunk-j9cnp8ms.js";import"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|