blade-code 0.10.128 → 0.10.130
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-0z9nqbd0.js +2 -0
- package/dist/chunk-1bb4h5gf.js +1 -0
- package/dist/chunk-2bnpn8be.js +1 -0
- package/dist/{chunk-xzfc1s6k.js → chunk-2y1qngw7.js} +1 -1
- package/dist/{chunk-jy0vfp8a.js → chunk-42h7kj6p.js} +1 -1
- package/dist/{chunk-ted1hyvb.js → chunk-44jtpg8y.js} +1 -1
- package/dist/chunk-4sxxvtn4.js +1 -0
- package/dist/chunk-51qc7n8t.js +1 -0
- package/dist/{chunk-z3hpstky.js → chunk-53h87fmt.js} +1 -1
- package/dist/{chunk-y93nqyqd.js → chunk-55hq1ps4.js} +2 -2
- package/dist/{chunk-9n90djh7.js → chunk-5a17mdjd.js} +2 -2
- package/dist/{chunk-pq6g92cz.js → chunk-6p6ts4kv.js} +2 -2
- package/dist/{chunk-sca5q3tt.js → chunk-77efqpdc.js} +1 -1
- package/dist/chunk-7jj607dg.js +94 -0
- package/dist/{chunk-yqqeh12b.js → chunk-8a6nrqdc.js} +2 -2
- package/dist/{chunk-10w2pj3r.js → chunk-93x9xbew.js} +1 -1
- package/dist/{chunk-1aw643j2.js → chunk-9et78e3v.js} +2 -2
- package/dist/chunk-9gs4eqt8.js +1 -0
- package/dist/chunk-9s8saznq.js +1 -0
- package/dist/{chunk-fa0pyv9k.js → chunk-9yqadjea.js} +2 -2
- package/dist/{chunk-a7gghhvn.js → chunk-a4jetpj8.js} +18 -18
- package/dist/{chunk-yqpej45c.js → chunk-a60cmnmz.js} +2 -2
- package/dist/{chunk-8hd4vd20.js → chunk-aaxc81jc.js} +1 -1
- package/dist/{chunk-xejvs1fk.js → chunk-agda17kj.js} +1 -1
- package/dist/{chunk-c47db31j.js → chunk-ajsw4te2.js} +2 -2
- package/dist/{chunk-r04vwtej.js → chunk-ar5np5h5.js} +2 -2
- package/dist/chunk-b8m7zc7t.js +170 -0
- package/dist/chunk-bcre3557.js +1 -0
- package/dist/{chunk-atema2rc.js → chunk-dfjmvj3d.js} +2 -2
- package/dist/chunk-dkgaxmsp.js +10 -0
- package/dist/{chunk-mkvvyq49.js → chunk-e1d0e6t6.js} +2 -2
- package/dist/{chunk-s7axaw78.js → chunk-edtxcqxa.js} +1 -1
- package/dist/chunk-f8gb685p.js +2 -0
- package/dist/chunk-fjv2vede.js +1 -0
- package/dist/{chunk-zfyg3888.js → chunk-g4xny949.js} +1 -1
- package/dist/chunk-gfbkrk60.js +338 -0
- package/dist/{chunk-12hdakw4.js → chunk-gmqpfm52.js} +2 -2
- package/dist/{chunk-skv2gb99.js → chunk-grhsv55v.js} +2 -2
- package/dist/chunk-gzz0gnmv.js +1 -0
- package/dist/chunk-h1wphqkc.js +1 -0
- package/dist/{chunk-6v2hhgka.js → chunk-hhg1zcbq.js} +2 -2
- package/dist/{chunk-9hnfz9bx.js → chunk-hw1gbr11.js} +1 -1
- package/dist/{chunk-nx8xb7dm.js → chunk-jkfkyedn.js} +1 -1
- package/dist/chunk-kd3k1q9z.js +1 -0
- package/dist/{chunk-n8w1jxsh.js → chunk-kfkvdj49.js} +1 -1
- package/dist/chunk-m9mw8ppy.js +1 -0
- package/dist/{chunk-xshrj2nd.js → chunk-mdew58v9.js} +1 -1
- package/dist/{chunk-n4q6fvqe.js → chunk-mvm1rzc4.js} +2 -2
- package/dist/{chunk-qm632an7.js → chunk-p00f53yq.js} +1 -1
- package/dist/{chunk-p7349xay.js → chunk-p2sp2e0a.js} +2 -2
- package/dist/chunk-pj69j4zp.js +2 -0
- package/dist/{chunk-41byj2h8.js → chunk-pk11fexz.js} +2 -2
- package/dist/chunk-qahz5x5c.js +14 -0
- package/dist/{chunk-6m4sqwj0.js → chunk-qcvxff27.js} +2 -2
- package/dist/{chunk-p2rxrxct.js → chunk-r9tawy93.js} +3 -3
- package/dist/{chunk-rz2wc93t.js → chunk-s2atpv23.js} +4 -4
- package/dist/chunk-saedy6bj.js +1 -0
- package/dist/{chunk-fgbqm2jh.js → chunk-sfe4810k.js} +1 -1
- package/dist/{chunk-96w8ay2h.js → chunk-sj1dzeta.js} +1 -1
- package/dist/chunk-sn71fsm5.js +1 -0
- package/dist/{chunk-yysqw1cq.js → chunk-ss4sncn3.js} +2 -2
- package/dist/chunk-ss86eq2h.js +23 -0
- package/dist/{chunk-ektgnqmh.js → chunk-sx77dpxw.js} +1 -1
- package/dist/chunk-t4apxzp1.js +2 -0
- package/dist/chunk-te6203yf.js +1 -0
- package/dist/{chunk-gxwkwkhp.js → chunk-tkydv9k8.js} +1 -1
- package/dist/{chunk-60he05xs.js → chunk-tw5fr07c.js} +2 -2
- package/dist/{chunk-q3y3s16v.js → chunk-v52wc8yg.js} +2 -2
- package/dist/{chunk-b408cqg1.js → chunk-v5hzk7j2.js} +2 -2
- package/dist/{chunk-v4nqv1pr.js → chunk-v94ztjtp.js} +385 -385
- package/dist/{chunk-85jv1sr7.js → chunk-xa9k5pjt.js} +2 -2
- package/dist/{chunk-mvgmsjwq.js → chunk-z03dtyh6.js} +1 -1
- package/dist/{chunk-jxc67ydz.js → chunk-zc91c7b5.js} +2 -2
- package/dist/{chunk-mm05y2c5.js → chunk-zkzhm39s.js} +1 -1
- package/dist/{chunk-1xg7qx35.js → chunk-zwjrensv.js} +1 -1
- package/dist/web/assets/ChatView-Bg36FUaj.js +53 -0
- package/dist/web/assets/{CodeBlockHighlighter-0VOa5Mes.js → CodeBlockHighlighter-D5rB73Eo.js} +2 -2
- package/dist/web/assets/FilePreview-BxaBSmap.js +65 -0
- package/dist/web/assets/KanbanBoard-B4gx3JMo.js +16 -0
- package/dist/web/assets/{MarkdownRenderer-3g4TPTeI.js → MarkdownRenderer-BRH7LHhN.js} +3 -3
- package/dist/web/assets/ScrollArea-DikU3QeQ.js +1 -0
- package/dist/web/assets/SessionHistorySurface-DG80d6-F.js +6 -0
- package/dist/web/assets/{SettingsModal-3GMy6V-E.js → SettingsModal-Bxqkok81.js} +3 -3
- package/dist/web/assets/Sidebar-DGaHGcHx.js +31 -0
- package/dist/web/assets/TaskSwitcher-DOnLPurk.js +26 -0
- package/dist/web/assets/TerminalPanel-BzhCF9vw.js +6 -0
- package/dist/web/assets/archive-BiDGrqry.js +6 -0
- package/dist/web/assets/{arrow-left-03GxbYI7.js → arrow-left-BY-esOAP.js} +1 -1
- package/dist/web/assets/{calendar-clock-8W4ostX1.js → calendar-clock-BCyxvfVt.js} +1 -1
- package/dist/web/assets/chevron-right-Bg-10yuN.js +6 -0
- package/dist/web/assets/{chevrons-up-down-BboZzEAk.js → chevrons-up-down-M5SAJq7T.js} +1 -1
- package/dist/web/assets/{clock-3-aXgeptZP.js → clock-3-v-nHTA0A.js} +1 -1
- package/dist/web/assets/copy-p1zc_rjZ.js +6 -0
- package/dist/web/assets/download-D_-kbJXR.js +6 -0
- package/dist/web/assets/{external-link-UkIIC2ds.js → external-link-wSGTIqe3.js} +1 -1
- package/dist/web/assets/{folder-BOCc5dv2.js → folder-Ltm9jCS5.js} +1 -1
- package/dist/web/assets/index-B4186fIT.css +1 -0
- package/dist/web/assets/index-_xnlrekR.js +210 -0
- package/dist/web/assets/{pause-DVIT6IIr.js → pause-_LvCZkxM.js} +1 -1
- package/dist/web/assets/pencil-DB6ICr_h.js +6 -0
- package/dist/web/assets/{play-DsdF5dji.js → play-BRXP1rHJ.js} +1 -1
- package/dist/web/assets/plus-BqvjEpLw.js +6 -0
- package/dist/web/assets/session-events-AGMXvPey.js +22 -0
- package/dist/web/assets/settings-LfQbDvBA.js +6 -0
- package/dist/web/assets/teamService-B5FnUcet.js +1 -0
- package/dist/web/assets/terminal-By4sO9Gw.js +6 -0
- package/dist/web/assets/vendor-radix-D6QrtXqd.js +45 -0
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/dist/chunk-0ktte40x.js +0 -185
- package/dist/chunk-1acb8fwq.js +0 -120
- package/dist/chunk-3pwqqk7w.js +0 -1
- package/dist/chunk-3q7g9206.js +0 -1
- package/dist/chunk-562w5zc6.js +0 -2
- package/dist/chunk-5x56nka1.js +0 -1
- package/dist/chunk-7hajkvde.js +0 -1
- package/dist/chunk-9wptwfmg.js +0 -1
- package/dist/chunk-ap01rwg0.js +0 -169
- package/dist/chunk-cm8fy1jn.js +0 -1
- package/dist/chunk-dp4r5bay.js +0 -1
- package/dist/chunk-dtxza4zh.js +0 -1
- package/dist/chunk-hd7bxzvy.js +0 -1
- package/dist/chunk-hks48s9k.js +0 -1
- package/dist/chunk-hmncnf7p.js +0 -1
- package/dist/chunk-j6fj679p.js +0 -10
- package/dist/chunk-m8czdpyg.js +0 -1
- package/dist/chunk-p5awnndq.js +0 -8
- package/dist/chunk-s7peh6kf.js +0 -2
- package/dist/chunk-ws6gtw33.js +0 -1
- package/dist/chunk-wtmhqy5s.js +0 -1
- package/dist/chunk-xnstybjm.js +0 -2
- package/dist/chunk-xpdtg9h9.js +0 -23
- package/dist/chunk-z2jwm4s8.js +0 -1
- package/dist/web/assets/ChatView-DCHnicTP.js +0 -58
- package/dist/web/assets/FilePreview-C_3KHzzj.js +0 -65
- package/dist/web/assets/KanbanBoard-D_NTkUnD.js +0 -16
- package/dist/web/assets/TaskSwitcher-eCdxu5Eo.js +0 -26
- package/dist/web/assets/TerminalPanel-9q9Trmv9.js +0 -6
- package/dist/web/assets/index-DGf6Z2kM.css +0 -1
- package/dist/web/assets/index-DaiT-mmo.js +0 -275
- package/dist/web/assets/session-events-CWzF04l4.js +0 -22
- package/dist/web/assets/teamService-BliaDj1Z.js +0 -1
- package/dist/web/assets/vendor-radix-Bc1_Q9tz.js +0 -45
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-qahz5x5c.js";import"./chunk-t4apxzp1.js";import"./chunk-grhsv55v.js";import"./chunk-xa9k5pjt.js";import"./chunk-5a17mdjd.js";import"./chunk-9yqadjea.js";import"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import"./chunk-tw5fr07c.js";import"./chunk-v52wc8yg.js";import"./chunk-s2atpv23.js";import"./chunk-77efqpdc.js";import"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{hf as n}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Df as s}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{wj as N,zj as M}from"./chunk-tkydv9k8.js";import{Mj as H}from"./chunk-pj69j4zp.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
|
|
2
2
|
`,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
|
|
3
|
-
export{K as
|
|
3
|
+
export{K as qj,X as rj,J as sj,L as tj,hu as uj};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-qahz5x5c.js";import"./chunk-t4apxzp1.js";import"./chunk-grhsv55v.js";import"./chunk-xa9k5pjt.js";import"./chunk-5a17mdjd.js";import"./chunk-9yqadjea.js";import"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import"./chunk-tw5fr07c.js";import"./chunk-v52wc8yg.js";import"./chunk-s2atpv23.js";import"./chunk-77efqpdc.js";import"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{hf as R}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Df as Q}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Cj as M}from"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
+
____ _ _
|
|
3
|
+
| __ )| | __ _ __| | ___
|
|
4
|
+
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
+
| |_) | | (_| | (_| | __/
|
|
6
|
+
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
+
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
+
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
+
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
+
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{q as
|
|
1
|
+
import{Cj as d,Ej as h}from"./chunk-v5hzk7j2.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
|
+
export{q as af,w as bf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as cg,g as dg};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{cf as a,df as b,ef as c}from"./chunk-pk11fexz.js";import"./chunk-gmqpfm52.js";import"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-93x9xbew.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -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 fh,F as gh,R as hh,v as ih};
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import{Te as b0}from"./chunk-0z9nqbd0.js";import{ih as OT}from"./chunk-g4xny949.js";import{oj as yT}from"./chunk-ar5np5h5.js";import{$j as wT,Mj as X0,Uj as E,Wj as D,Xj as i,Zj as c,_j as j0,ak as ST,bk as fT,fk as k,hk as D0,ik as a,qk as RT}from"./chunk-pj69j4zp.js";import{rk as Z0}from"./chunk-zkzhm39s.js";import{createHash as C_}from"node:crypto";import{readdir as k0,stat as A0}from"node:fs/promises";import G0 from"node:path";import{createHash as tT,randomBytes as u0}from"node:crypto";import{chmod as p0,link as oT,lstat as p,mkdir as rT,open as l,readdir as l0,realpath as v0,unlink as U0}from"node:fs/promises";import K from"node:path";function cT(){return typeof globalThis.Bun<"u"}function dT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function sT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}var aT=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
|
+
`);async function t(T){try{let $;if(cT()){let{Database:G}=await import("bun:sqlite");$=sT(new G(T))}else{let X=(await import("better-sqlite3")).default;$=dT(new X(T))}return $.exec(aT),$}catch{return null}}var eT="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,T$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,$$=1024,_$=".surface-workspaces-v1.capacity.sqlite",i0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class M extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var P,o=new Map;function c0(T){return K.join(String(T),eT)}async function d0(T,$){let _=D($);if(i(_.collisionIdentity)!==String(T))throw new M("session_surface_state_invalid");let G=a0(_.exactIdentity),X=c0(T);return await X$(T,X),G$(X,()=>Y$(X,async()=>{await V$(X);let Y=await s0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=$$)throw new M("session_surface_capacity");let Z=K.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=H$();if(U.has(g))continue;return L$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new M("session_surface_state_invalid")}))}async function G$(T,$){let _=o.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);o.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),o.get(T)===Y)o.delete(T)}}async function X$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof M)throw _;throw new M("session_surface_state_invalid")}try{await rT($,{recursive:!1,mode:448})}catch(G){if(x(G)!=="EEXIST")throw new M("session_surface_state_invalid")}await V0($,String(T)),await h(String(T))}}async function Y$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Q$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await P?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await Z$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new M("session_surface_state_invalid");if(X instanceof M)throw X;if(X!==void 0||!Q)throw new M("session_surface_state_invalid");return Q.value}async function Q$(T){let $=K.join(T,_$),_=null,G;try{let X=!1;try{let Q=await l($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(x(Q)!=="EEXIST")throw Q}if(await m($,T),X)await h(T);G=await l($,"r"),await n(G,$,T);let Y=await G.stat({bigint:!0});if(_=await t($),!_)throw new M("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA journal_mode=DELETE;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await p0($,384);return await n(G,$,T),await U$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof M)throw X;throw new M("session_surface_state_invalid")}}async function Z$(T){await n(T.identityHandle,T.path,K.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!B0(T.identity,$))throw new M("session_surface_state_invalid")}async function U$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await p0(G,384);await m(G,$)}catch(X){if(x(X)!=="ENOENT"){if(X instanceof M)throw X;throw new M("session_surface_state_invalid")}}}}async function V$(T){let $=await l0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!i0.test(G.name))continue;let X=K.join(T,G.name);await m(X,T),await U0(X),_=!0}if(_)await h(T)}async function s0(T,$,_){try{await V0($,String(T))}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof M)throw Q;throw new M("session_surface_state_invalid")}let G;try{G=await l0($,{withFileTypes:!0})}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new M("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(i0.test(Q.name)){await m(K.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=K.basename(Q.name,".json");if(!n0.test(Z))throw new M("session_surface_state_invalid");let U=K.join($,Q.name),V=await B$(U,$);if(V.exactIdentityDigest!==Z)throw new M("session_surface_state_invalid");if(X.has(Z))throw new M("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new M("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function B$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return g$(G)}catch(G){if(G instanceof M&&G.code==="session_surface_not_found")throw G;if(x(G)==="ENOENT")throw new M("session_surface_not_found");throw new M("session_surface_state_invalid")}finally{await _?.close()}}function g$(T){let $;try{$=JSON.parse(T)}catch{throw new M("session_surface_state_invalid")}if(!M$($))throw new M("session_surface_state_invalid");return $}function M$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&n0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&T$.test($.workspaceRef)}function a0(T){return tT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function H$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function O$(){return`.tmp-acp-remote-workspace-${process.pid}-${u0(16).toString("hex")}.pending`}async function V0(T,$){if(K.dirname(T)!==$)throw new M("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isDirectory())throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new M("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==448)throw new M("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function m(T,$){if(K.dirname(T)!==$)throw new M("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isFile())throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new M("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==384)throw new M("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function n(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),p($,{bigint:!0})]);if(K.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new M("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new M("session_surface_state_invalid");await g0($,_,K.basename($))}async function g0(T,$,_){let G=await v0(T),X=await v0($);if(G!==K.join(X,_))throw new M("session_surface_state_invalid")}async function h(T){if(!C$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await F$(T)}catch{throw new M("session_surface_state_invalid")}}function C$(T){return T!=="win32"}async function F$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function L$(T,$,_,G,X){let Y=K.join($,O$()),Q,Z,U=!1,V=!1,g,H;try{Q=await l(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await n(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await P?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await oT(Y,_),U=!0}catch(O){if(x(O)!=="EEXIST")throw O;g=await J$(T,G)}if(U){let O=await p(_,{bigint:!0});if(!Z||!B0(Z,O))throw new M("session_surface_state_invalid");await m(_,$),await h($),V=!0,g=X.workspaceRef;try{await P?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(O){H=O}finally{await Q?.close().catch(()=>{return})}if(H!==void 0&&U&&!V&&Z)try{let O=await p(_,{bigint:!0});if(B0(Z,O))await U0(_),await h($)}catch{}try{if(await U0(Y),!V)await h($)}catch(O){if(x(O)!=="ENOENT"&&H===void 0&&!V)H=O}if(H instanceof M)throw H;if(H!==void 0||g===void 0)throw new M("session_surface_state_invalid");return g}async function J$(T,$){let _=c0(T),G=await s0(T,_,!0),X=a0(D($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new M("session_surface_state_invalid");return Y.workspaceRef}function B0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function x(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function t0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as f from"node:path";var $T=50,_T=100,z$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),N$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,I$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,K$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&I$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&K$.test(T)}function W$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||o0(_.cwd))||!XT(_.lastMessageTime)||!o0(_.projectPath)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:f.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:f.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function A$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||r0(_.exactIdentity))||!XT(_.lastMessageTime)||!r0(_.workspaceIdentity)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function v(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function x$(T){if(!T.cursor)return;let $=k$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function E$(T){if(!T.cursor)return;let $=A$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function l_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!f.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:f.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function n_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function i_(T={}){let $=e0(T.taskStatus,z$,"task status"),_=e0(T.taskPriority,N$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return q$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function e0(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function TT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function q$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function D$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function c_(T,$){let _=[...T],G=x$($);if(G)_=_.filter((Q)=>D$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:W$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function d_(T,$){let _=[...T],G=E$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:j$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function w$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function M0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function H0(T,$){let _=T.find((G)=>M0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:YT(T,$),createdAt:_.data.createdAt}}function YT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function QT(T,$){H0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!w$(Q)})}function u(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(H0($,_.data.targetMessageId),_.data.mode!=="code")$=QT($,_.data.targetMessageId)}return $}function a_(T){let $=u(T);return $.filter(M0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function t_(T,$){let _=u(T),G=H0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:QT(_,$),removedTurns:Y.filter(M0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as n$}from"node:crypto";var r_={clientVisible:!1};function ZT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as R$}from"node:string_decoder";var T1=1048576;function O0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class C0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=O0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=O0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=O0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var r={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},R={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},UT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},S$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},f$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:r,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:r,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:R,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:UT},{pattern:/^git\s+(status|branch|remote)/i,config:R},{pattern:/^git\s+(log|diff|show)/i,config:UT},{pattern:/^(ls|dir|tree)\s+/i,config:R,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:r,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:r,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:R,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:R,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function VT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class F0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of f$)if($.test(T))return{config:_,summaryTemplate:G};return{config:S$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
|
|
3
|
+
`),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
|
|
4
|
+
`);if(V+=`
|
|
5
|
+
|
|
6
|
+
... (${U} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${Y} total) ...
|
|
7
|
+
|
|
8
|
+
`,V+=Z.join(`
|
|
9
|
+
`),V.length>$.maxChars){let H=Math.floor($.maxChars/2)-50,O=VT(V,0,H),I=VT(V,V.length-H);V=`${O}
|
|
10
|
+
|
|
11
|
+
... (content truncated to ${$.maxChars} chars) ...
|
|
12
|
+
|
|
13
|
+
${I}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
|
|
14
|
+
|
|
15
|
+
[Summary: ${g}]`;return{content:V,truncated:!0,originalLines:Y,originalChars:G,summary:g}}static truncateForLLM(T,$,_){let G=this.truncate(T,_),X=this.truncate($,_),Y;if(G.truncated||X.truncated){let Q=[];if(G.truncated)Q.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
|
|
16
|
+
`).length} lines`);if(X.truncated)Q.push(`stderr: ${X.originalLines} lines -> ${X.content.split(`
|
|
17
|
+
`).length} lines`);Y=`Output truncated: ${Q.join(", ")}`}return{stdout:G.content,stderr:X.content,truncationInfo:Y}}static shouldTruncate(T,$){let{config:_}=this.getConfigForCommand($);return T.split(`
|
|
18
|
+
`).length>_.maxLines||T.length>_.maxChars}static getStats(T){return{lines:T.split(`
|
|
19
|
+
`).length,chars:T.length,words:T.split(/\s+/).filter(Boolean).length}}}var BT=32768,y$=1048576,h$=65536,P$=3600000,gT=4096,m$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function Z1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class L0{stream;executionId;onEvent;output=new C0(y$/2);decoder=new R$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(T,$,_){this.stream=T;this.executionId=$;this.onEvent=_}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<gT){let G=$.subarray(0,Math.min($.length,gT-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let _=MT(this.decoder.write($));this.output.append(_),this.emit(_)}finish(){if(this.binary)return;let T=MT(this.decoder.end());this.output.append(T),this.emit(T)}snapshot(){let T=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:T.content,omittedBytes:T.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(T){if(!T||!this.onEvent||this.streamTruncated)return;let $=h$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=v$(T,$);if(this.streamedBytes+=Buffer.byteLength(_),_.length<T.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:_,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function MT(T){return T.replace(m$,"")}function v$(T,$){let _=Buffer.from(T);if(_.length<=$)return T;let G=$;while(G>0&&(_[G]&192)===128)G-=1;return _.subarray(0,G).toString("utf8")}function HT(T){return T.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function u$(T){let $=T.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>BT)throw Error(`User shell command exceeds ${BT} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function p$(){return{execute(T,$){return new Promise((_)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",X=process.platform==="win32"?["/d","/s","/c",T]:["-l","-c",T],{child:Y,processTree:Q}=OT(G,X,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),Z="",U="",V=!1,g=!1,H=!1,O,I=()=>{return O??=Q.terminate(),O},B=setTimeout(()=>{V=!0,I()},$.timeoutMs),L=()=>{g=!0,I()};if($.signal.addEventListener("abort",L,{once:!0}),$.signal.aborted)L();Y.stdout?.on("data",(F)=>{$.onOutput?.("stdout",F)}),Y.stderr?.on("data",(F)=>{$.onOutput?.("stderr",F)});let N=async(F)=>{if(H)return;if(H=!0,clearTimeout(B),$.signal.removeEventListener("abort",L),V||g)await I();_({...F,stdout:"",stderr:"",timedOut:V,aborted:g})};Y.once("error",(F)=>{N({exitCode:null,error:F.message})}),Y.once("close",(F)=>{N({exitCode:F})})})}}}async function U1(T,$){let _=u$(T),G=$.timeoutMs??P$,X=new L0("stdout",$.executionId,$.onEvent),Y=new L0("stderr",$.executionId,$.onEvent),Q=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:_});let Z,U=!1,V=!1;try{Z=await($.executor??p$()).execute(_,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(L,N)=>{if(L==="stdout")U=!0;else V=!0;(L==="stdout"?X:Y).append(N)}})}catch(L){Z={exitCode:null,stdout:"",stderr:"",error:L instanceof Error?L.message:String(L)}}if(!U)X.append(Z.stdout);if(!V)Y.append(Z.stderr);X.finish(),Y.finish(),await Promise.all([X.flushEvents(),Y.flushEvents()]);let g=X.snapshot(),H=Y.snapshot(),O=F0.truncateForLLM(g.content.trim(),H.content.trim(),_),I=Z.aborted||$.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",B={version:1,command:_,status:I,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-Q),stdout:O.stdout,stderr:Z.error?[O.stderr,Z.error].filter(Boolean).join(`
|
|
20
|
+
`):O.stderr,stdoutOmittedBytes:g.omittedBytes,stderrOmittedBytes:H.omittedBytes,binaryOutput:g.binary||H.binary,truncated:Boolean(O.truncationInfo)||g.omittedBytes>0||H.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:B}),B}function V1(T){let $=[T.stdout?`stdout:
|
|
21
|
+
${T.stdout}`:"",T.stderr?`stderr:
|
|
22
|
+
${T.stderr}`:""].filter(Boolean).join(`
|
|
23
|
+
`);return["<user_shell_command>",`<command>${HT(T.command)}</command>`,"<result>",`Status: ${T.status}`,`Exit code: ${T.exitCode??"null"}`,`Duration: ${(T.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
24
|
+
${HT($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
25
|
+
`)}function CT(T){let $=[T.stdout,T.stderr?`stderr:
|
|
26
|
+
${T.stderr}`:""].filter(Boolean).join(`
|
|
27
|
+
`);return[`! ${T.command}`,$||"(no output)"].join(`
|
|
28
|
+
`)}function l$(T){if(!T||typeof T!=="object"||Array.isArray(T))return;let $=T;if($.version!==1||typeof $.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String($.status))||$.exitCode!==null&&typeof $.exitCode!=="number"||typeof $.durationMs!=="number"||typeof $.stdout!=="string"||typeof $.stderr!=="string"||typeof $.stdoutOmittedBytes!=="number"||typeof $.stderrOmittedBytes!=="number"||typeof $.binaryOutput!=="boolean"||typeof $.truncated!=="boolean")return;return $}function FT(T){if(!T||typeof T!=="object"||Array.isArray(T))return;return l$(T.userShellCommand)}var i$=262144,c$="session-surface-message\x00",IT="[private state path]",e="[content truncated]",LT=`
|
|
29
|
+
${e}`,T0=String.fromCharCode(27),d$=String.fromCharCode(7),s$=String.fromCharCode(157),a$=String.fromCharCode(156),t$=String.fromCharCode(155),o$=new RegExp(`(?:${b(T0)}\\]|${b(s$)})[\\s\\S]*?(?:${b(d$)}|${b(T0)}\\\\|${b(a$)})`,"g"),r$=new RegExp(`(?:${b(T0)}\\[|${b(t$)})[0-?]*[ -/]*[@-~]`,"g");function J0(T,$){let _={privateRoots:[T],privateValues:[$.exactIdentity,$.collisionIdentity]};if($.style==="win32")_.caseInsensitivePrivateRoots=[$.wirePath];else _.privateRoots=[T,$.wirePath];return _}class J extends Error{code="session_surface_state_invalid";constructor(){super("session surface projection state is invalid");this.name="SessionSurfaceProjectionError"}}function KT(T,$){let _=g_($.maxContentBytes),{privateRoots:G,caseInsensitivePrivateRoots:X}=WT($),Y=jT($.privateValues??[]),Q=u(T),Z=new Map;for(let V of Q){if(I0(V.seq),V.type==="message_created"){Z.set(V.data.messageId,{event:V,orderedPartIds:[],partsById:new Map});continue}if(V.type!=="part_created"&&V.type!=="part_updated")continue;let g=Z.get(V.data.messageId);if(!g)continue;__(g,V)}let U=[];for(let V of Z.values()){let g=T_(V,G,X,Y,_);if(g)U.push(g)}return U}function e$(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function b(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_(T,$,_,G,X){let Y=T.event.data.role;if(Y!=="user"&&Y!=="assistant")return;let Q=$_(T),Z=AT(Q),U={role:Y,content:Z,...T.event.data.metadata!==void 0?{metadata:T.event.data.metadata}:{}};if(!ZT(U))return;let V=Y_(T.event.data.createdAt),H=kT($0($0(Z,_,!0),$),G).trim();if(!H)return;let O=V_(H,X),I=X_(T.event);if(O.truncated)return{id:I,role:Y,content:O.content,timestamp:V,truncated:!0};return{id:I,role:Y,content:O.content,timestamp:V}}function z0(T,$){let{privateRoots:_,caseInsensitivePrivateRoots:G}=WT($);return kT($0($0(AT(T),G,!0),_),jT($.privateValues??[]))}function $_(T){let $=FT(T.event.data.metadata);if($)return CT($);return T.orderedPartIds.map((_)=>T.partsById.get(_)).flatMap((_)=>_?[_.content]:[]).join("")}function __(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:G_($.data.payload)}:{partId:$.data.partId,type:"image",content:"[Image]"};if(!T.partsById.has($.data.partId))T.orderedPartIds.push($.data.partId);T.partsById.set($.data.partId,_)}function G_(T){if(!e$(T))return"";let $=T.text;return typeof $==="string"?$:""}function X_(T){let $=I0(T.seq);return N0($,T.data.messageId)}function N0(T,$){let _=I0(T),G=n$("sha256").update(c$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function Y_(T){let $=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(T);if(!$)throw new J;let _=Number($[1]),G=Number($[2]),X=Number($[3]),Y=Number($[4]),Q=Number($[5]),Z=Number($[6]),U=$[8],V=new Date(Date.UTC(_,G,0)).getUTCDate(),g=U==="Z"||U!==void 0&&Number(U.slice(1,3))<=23&&Number(U.slice(4,6))<=59;if(G<1||G>12||X<1||X>V||Y>23||Q>59||Z>59||!g||!Number.isFinite(Date.parse(T)))throw new J;return T}function JT(T,$){return[...new Set([...T,...$].filter(Boolean))].sort((_,G)=>G.length-_.length)}function zT(T){return/^[A-Za-z]:[\\/]/.test(T)||/^\\\\/.test(T)}function WT(T){let $=JT(T.privateRoots,T.bladeStorageRoots??[]);return{privateRoots:$.filter((_)=>!zT(_)),caseInsensitivePrivateRoots:JT([...T.caseInsensitivePrivateRoots??[],...$.filter(zT)],[])}}function jT(T){return[...new Set(T.filter(Boolean))].sort(($,_)=>_.length-$.length)}function kT(T,$){let _=T;for(let G of $)_=_.split(G).join(IT);return _}function $0(T,$,_=!1){let G=T;for(let X of $)G=Q_(G,X,_);return G}function Q_(T,$,_){if(!$)return T;let G=0,X="",Y=_?new RegExp($.split(/[\\/]+/).map((Q)=>b(Q)).join("[\\\\/]+"),"i"):void 0;while(G<T.length){let Q=Y?.exec(T.slice(G)),Z=Y?Q?G+Q.index:-1:T.indexOf($,G);if(Z<0){X+=T.slice(G);break}X+=T.slice(G,Z);let U=Q?.[0].length??$.length,V=Z_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=IT,G=V}return X}function Z_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!U_(X)&&!NT(X))return $;let Y=G;while(Y<T.length){let Q=T[Y];if(Q===void 0||NT(Q))break;Y+=1}return Y}function U_(T){return T==="/"||T==="\\"}function NT(T){return T===" "||T==="\t"||T===`
|
|
30
|
+
`||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function AT(T){return[...T.replace(/\r\n?/g,`
|
|
31
|
+
`).replace(o$,"").replace(r$,"").split(`${T0}\\`).join("")].filter((G)=>{let X=G.charCodeAt(0);return!(X===0||X>=1&&X<=8||X===11||X===12||X>=14&&X<=31||X>=127&&X<=159)}).join("")}function V_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=B_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${xT(T,X)}${_}`,truncated:!0}}function xT(T,$){if($<=0)return"";let _=Buffer.from(T,"utf8");if(_.length<=$)return T;let G=_.subarray(0,$).toString("utf8");while(Buffer.byteLength(G,"utf8")>$)G=G.slice(0,-1);return G.replace(/\uFFFD$/,"")}function B_(T){let $=Buffer.byteLength(LT,"utf8");if(T>=$)return LT;let _=Buffer.byteLength(e,"utf8");if(T>=_)return e;return xT(e,T)}function g_(T){let $=T??i$;if(!Number.isSafeInteger($)||$<=0)throw new J;return $}function I0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new J;return $}import*as A from"node:fs";import{createReadStream as M_}from"node:fs";import*as z from"node:fs/promises";import*as K0 from"node:path";import{createInterface as H_}from"node:readline";var ET=65536;function _0(T){let $=T.data;if($===null||typeof $!=="object"||Array.isArray($))throw Error("Session event data must be a JSON object");return JSON.stringify(T)}function O_(T,$,_){let G=T.trim();if(!G)return;try{return JSON.parse(G)}catch(X){throw Error(`Invalid session JSONL in ${_} at line ${$}`,{cause:X})}}function d(T,$="session transcript"){let _=T.split(`
|
|
32
|
+
`),G=!T.endsWith(`
|
|
33
|
+
`),X=[];for(let[Y,Q]of _.entries())try{let Z=O_(Q,Y+1,$);if(Z){if(typeof Z.seq!=="number")Z.seq=X.length+1;X.push(Z)}}catch(Z){if(G&&Y===_.length-1)break;throw Z}return X}class j{static appendQueues=new Map;filePath;constructor(T){this.filePath=T}static maxSeq(T){let $=0;for(let _ of T)if(typeof _.seq==="number"&&_.seq>$)$=_.seq;return $}static stampSeqFrom(T,$){let _=$;return T.map((G)=>{if(typeof G.seq==="number"){if(G.seq>_)_=G.seq;return G}return _+=1,{...G,seq:_}})}static stampSeq(T,$){return j.stampSeqFrom(T,j.maxSeq($))}async append(T){try{let[$]=await this.appendEntries([T]);return $}catch($){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,$),$}}async appendBatch(T){try{return await this.appendEntries(T)}catch($){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,$),$}}async appendEntries(T){if(T.length===0)return[];return this.enqueue(async()=>{await z.mkdir(K0.dirname(this.filePath),{recursive:!0,mode:493});let $=await z.open(this.filePath,"a+",384);try{let _=await this.repairIncompleteTail($),G=await this.readTailSeq($),X=j.stampSeqFrom(T,G),Y=`${X.map(_0).join(`
|
|
34
|
+
`)}
|
|
35
|
+
`;return await $.appendFile(_+Y,"utf8"),await $.sync(),X}finally{await $.close()}})}async createExclusive(T){if(T.length===0)throw Error("Cannot create an empty session transcript");await z.mkdir(K0.dirname(this.filePath),{recursive:!0,mode:493});let $;try{$=await z.open(this.filePath,"wx",384);let G=`${j.stampSeq(T,[]).map(_0).join(`
|
|
36
|
+
`)}
|
|
37
|
+
`;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await z.unlink(this.filePath).catch(()=>{return});throw _}finally{await $?.close()}}async readAll(T={}){if(T.signal?.throwIfAborted(),!A.existsSync(this.filePath))return[];let $=await z.readFile(this.filePath,{encoding:"utf-8",signal:T.signal});return d($,this.filePath)}async readStream(T){return new Promise(($,_)=>{if(!A.existsSync(this.filePath)){$();return}let G=M_(this.filePath,"utf-8"),X=H_({input:G,crlfDelay:Number.POSITIVE_INFINITY}),Y=0;X.on("line",async(Q)=>{let Z=Q.trim();if(Z.length===0)return;try{let U=JSON.parse(Z);if(Y+=1,typeof U.seq!=="number")U.seq=Y;await T(U)}catch(U){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Z}`,U)}}),X.on("close",()=>$()),X.on("error",_),G.on("error",_)})}async filter(T){let $=[];return await this.readStream((_)=>{if(T(_))$.push(_)}),$}async readLast(T){return(await this.readAll()).slice(-T)}async readFromSeq(T){return(await this.readAll()).filter((_)=>(_.seq??0)>=T)}async getStats(){try{if(!A.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let T=await z.stat(this.filePath),_=(await z.readFile(this.filePath,"utf-8")).split(`
|
|
38
|
+
`).filter((G)=>G.trim().length>0).length;return{exists:!0,size:T.size,lineCount:_}}catch(T){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,T),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await z.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await z.unlink(this.filePath),!0}catch(T){if(T.code==="ENOENT")return!1;throw T}})}catch(T){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,T),T}}async deleteValidated(T){return this.enqueue(async()=>{let $;try{$=await z.open(this.filePath,"r")}catch(G){if(G.code==="ENOENT")return!1;throw G}let _;try{_=d(await $.readFile("utf8"),"session transcript")}finally{await $.close()}if(!T(_))return!1;try{return await z.unlink(this.filePath),!0}catch(G){if(G.code==="ENOENT")return!1;throw G}})}async appendValidated(T,$={}){return this.appendValidatedAsync(async(_)=>T(_),$)}async appendValidatedBatch(T,$={}){return this.appendValidatedBatchAsync(async(_)=>T(_),$)}async appendValidatedBatchAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?A.constants.O_RDWR|(A.constants.O_NOFOLLOW??0):"r+",G=await z.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X);if(Z.length===0)return[];let U=j.stampSeq(Z,X),V=`${U.map(_0).join(`
|
|
39
|
+
`)}
|
|
40
|
+
`;return await G.write(Y+V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async appendValidatedAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?A.constants.O_RDWR|(A.constants.O_NOFOLLOW??0):"r+",G=await z.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X),[U]=j.stampSeq([Z],X),V=`${Y}${_0(U)}
|
|
41
|
+
`;return await G.write(V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async readAllValidated(T={}){T.signal?.throwIfAborted();let $=T.noFollow?A.constants.O_RDONLY|(A.constants.O_NOFOLLOW??0):"r",_;try{_=await z.open(this.filePath,$)}catch(G){if(T.signal?.throwIfAborted(),G.code==="ENOENT")return[];throw G}try{await T.validateHandle?.(_),T.signal?.throwIfAborted();let G=d(await _.readFile({encoding:"utf8",signal:T.signal}),"session transcript");return T.signal?.throwIfAborted(),await T.validateHandle?.(_),T.signal?.throwIfAborted(),G}finally{await _.close()}}getFilePath(){return this.filePath}async enqueue(T){let _=(j.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(T),G=_.then(()=>{return},()=>{return});j.appendQueues.set(this.filePath,G);try{return await _}finally{if(j.appendQueues.get(this.filePath)===G)j.appendQueues.delete(this.filePath)}}async readCommittedState(T,$=this.filePath){let _=await this.repairIncompleteTail(T),G=await T.readFile("utf8"),X=d(G,$),{size:Y}=await T.stat();return{entries:X,separator:_,size:Y}}async readTailSeq(T){let{size:$}=await T.stat();if($===0)return 0;let _=Math.max(0,$-ET),G=Buffer.allocUnsafe($-_);await T.read(G,0,G.length,_);let X=G.toString("utf8").split(`
|
|
42
|
+
`);for(let Q=X.length-1;Q>=0;Q--){let Z=X[Q].trim();if(!Z)continue;if(Q===0&&_>0)break;try{let U=JSON.parse(Z).seq;if(typeof U==="number")return U}catch{}break}let Y=await T.readFile("utf8");return j.maxSeq(d(Y,this.filePath))}async repairIncompleteTail(T){let{size:$}=await T.stat();if($===0)return"";let _=Buffer.allocUnsafe(1);if(await T.read(_,0,1,$-1),_[0]===10)return"";let G=await this.findTailStart(T,$),X=Buffer.allocUnsafe($-G);await T.read(X,0,X.length,G);try{return JSON.parse(X.toString("utf8").trim()),`
|
|
43
|
+
`}catch{return await T.truncate(G),""}}async findTailStart(T,$){let _=$;while(_>0){let G=Math.max(0,_-ET),X=Buffer.allocUnsafe(_-G);await T.read(X,0,X.length,G);let Y=X.lastIndexOf(10);if(Y>=0)return G+Y+1;_=G}return 0}}function qT(T){let $=Number(T.pragma("user_version")??0);if($===7)return;if($>0&&$!==7)T.exec(`
|
|
44
|
+
DROP TABLE IF EXISTS parts_fts;
|
|
45
|
+
DROP TABLE IF EXISTS surface_messages;
|
|
46
|
+
DROP TABLE IF EXISTS parts;
|
|
47
|
+
DROP TABLE IF EXISTS sessions;
|
|
48
|
+
DROP TABLE IF EXISTS projection_state;
|
|
49
|
+
DROP TABLE IF EXISTS surface_projection_meta;
|
|
50
|
+
`);T.exec(`
|
|
51
|
+
CREATE TABLE IF NOT EXISTS surface_projection_meta (
|
|
52
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
|
|
53
|
+
catalog_revision INTEGER NOT NULL DEFAULT 0 CHECK(catalog_revision >= 0)
|
|
54
|
+
);
|
|
55
|
+
INSERT OR IGNORE INTO surface_projection_meta (singleton, catalog_revision)
|
|
56
|
+
VALUES (1, 0);
|
|
57
|
+
|
|
58
|
+
CREATE TABLE IF NOT EXISTS projection_state (
|
|
59
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
60
|
+
project_path TEXT NOT NULL,
|
|
61
|
+
session_id TEXT NOT NULL,
|
|
62
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
63
|
+
file_size INTEGER NOT NULL DEFAULT 0,
|
|
64
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
65
|
+
stat_fingerprint TEXT NOT NULL DEFAULT '',
|
|
66
|
+
PRIMARY KEY (source_kind, project_path, session_id)
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
70
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
71
|
+
project_path TEXT NOT NULL,
|
|
72
|
+
session_id TEXT NOT NULL,
|
|
73
|
+
root_id TEXT,
|
|
74
|
+
parent_id TEXT,
|
|
75
|
+
relation_type TEXT,
|
|
76
|
+
title TEXT,
|
|
77
|
+
agent_type TEXT,
|
|
78
|
+
model TEXT,
|
|
79
|
+
task_status TEXT,
|
|
80
|
+
task_priority TEXT,
|
|
81
|
+
task_kind TEXT,
|
|
82
|
+
task_due_at TEXT,
|
|
83
|
+
archived_at TEXT,
|
|
84
|
+
last_message_time TEXT,
|
|
85
|
+
project_sort_key TEXT NOT NULL,
|
|
86
|
+
public_workspace_ref TEXT,
|
|
87
|
+
public_workspace_sort_key TEXT NOT NULL,
|
|
88
|
+
session_sort_key TEXT NOT NULL,
|
|
89
|
+
first_message_time TEXT,
|
|
90
|
+
message_count INTEGER NOT NULL DEFAULT 0,
|
|
91
|
+
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
92
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
93
|
+
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
94
|
+
metadata_json TEXT NOT NULL,
|
|
95
|
+
surface_digest TEXT NOT NULL,
|
|
96
|
+
PRIMARY KEY (source_kind, project_path, session_id)
|
|
97
|
+
);
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
99
|
+
last_message_time DESC,
|
|
100
|
+
source_kind DESC,
|
|
101
|
+
public_workspace_sort_key ASC,
|
|
102
|
+
session_sort_key ASC
|
|
103
|
+
);
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
105
|
+
source_kind,
|
|
106
|
+
archived_at,
|
|
107
|
+
project_path,
|
|
108
|
+
parent_id
|
|
109
|
+
);
|
|
110
|
+
-- 任务看板过滤/排序:按项目锁定后再按状态、优先级、截止时间收敛。
|
|
111
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_board ON sessions(
|
|
112
|
+
project_path,
|
|
113
|
+
task_status,
|
|
114
|
+
task_priority,
|
|
115
|
+
task_due_at,
|
|
116
|
+
source_kind
|
|
117
|
+
);
|
|
118
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_status ON sessions(
|
|
119
|
+
task_status,
|
|
120
|
+
project_path,
|
|
121
|
+
source_kind
|
|
122
|
+
);
|
|
123
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_priority ON sessions(
|
|
124
|
+
task_priority,
|
|
125
|
+
task_due_at,
|
|
126
|
+
source_kind
|
|
127
|
+
) WHERE task_priority IS NOT NULL;
|
|
128
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_due_at ON sessions(
|
|
129
|
+
task_due_at,
|
|
130
|
+
source_kind
|
|
131
|
+
) WHERE task_due_at IS NOT NULL;
|
|
132
|
+
|
|
133
|
+
CREATE TABLE IF NOT EXISTS parts (
|
|
134
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
135
|
+
project_path TEXT NOT NULL,
|
|
136
|
+
session_id TEXT NOT NULL,
|
|
137
|
+
part_id TEXT NOT NULL,
|
|
138
|
+
message_id TEXT,
|
|
139
|
+
part_type TEXT,
|
|
140
|
+
role TEXT,
|
|
141
|
+
seq INTEGER,
|
|
142
|
+
timestamp TEXT,
|
|
143
|
+
text TEXT,
|
|
144
|
+
PRIMARY KEY (source_kind, project_path, session_id, part_id)
|
|
145
|
+
);
|
|
146
|
+
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(
|
|
147
|
+
source_kind, project_path, session_id
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
CREATE TABLE IF NOT EXISTS surface_messages (
|
|
151
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
152
|
+
project_path TEXT NOT NULL,
|
|
153
|
+
session_id TEXT NOT NULL,
|
|
154
|
+
message_seq INTEGER NOT NULL CHECK(message_seq >= 0),
|
|
155
|
+
message_id TEXT NOT NULL,
|
|
156
|
+
message_json TEXT NOT NULL,
|
|
157
|
+
byte_count INTEGER NOT NULL CHECK(byte_count >= 0),
|
|
158
|
+
PRIMARY KEY (
|
|
159
|
+
source_kind, project_path, session_id, message_seq, message_id
|
|
160
|
+
)
|
|
161
|
+
);
|
|
162
|
+
CREATE INDEX IF NOT EXISTS idx_surface_messages_history ON surface_messages(
|
|
163
|
+
source_kind, project_path, session_id, message_seq DESC, message_id DESC
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
167
|
+
text,
|
|
168
|
+
source_kind UNINDEXED,
|
|
169
|
+
project_path UNINDEXED,
|
|
170
|
+
session_id UNINDEXED,
|
|
171
|
+
part_id UNINDEXED,
|
|
172
|
+
role UNINDEXED,
|
|
173
|
+
timestamp UNINDEXED,
|
|
174
|
+
seq UNINDEXED,
|
|
175
|
+
tokenize = 'unicode61'
|
|
176
|
+
);
|
|
177
|
+
`),T.exec("PRAGMA user_version=7;")}var F_=yT("Service"),L_="session-surface-projection-v1\x00",x0=524288,J_=3,z_=new AbortController().signal,N_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,hT=`WITH RECURSIVE archive_members(
|
|
178
|
+
source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
|
|
179
|
+
effective_archived_at, depth
|
|
180
|
+
) AS (
|
|
181
|
+
SELECT source_kind, project_path, public_workspace_ref, session_id, session_id,
|
|
182
|
+
archived_at, 0
|
|
183
|
+
FROM sessions
|
|
184
|
+
WHERE archived_at IS NOT NULL
|
|
185
|
+
UNION ALL
|
|
186
|
+
SELECT child.source_kind, child.project_path, child.public_workspace_ref,
|
|
187
|
+
child.session_id, parent.archive_root_id, parent.effective_archived_at,
|
|
188
|
+
parent.depth + 1
|
|
189
|
+
FROM sessions child
|
|
190
|
+
JOIN archive_members parent
|
|
191
|
+
ON child.source_kind = parent.source_kind
|
|
192
|
+
AND child.project_path = parent.project_path
|
|
193
|
+
AND child.public_workspace_ref IS parent.public_workspace_ref
|
|
194
|
+
AND child.parent_id = parent.session_id
|
|
195
|
+
WHERE parent.depth < 128
|
|
196
|
+
),
|
|
197
|
+
ranked_archive AS (
|
|
198
|
+
SELECT source_kind, project_path, public_workspace_ref, session_id,
|
|
199
|
+
archive_root_id, effective_archived_at,
|
|
200
|
+
ROW_NUMBER() OVER (
|
|
201
|
+
PARTITION BY source_kind, project_path, public_workspace_ref, session_id
|
|
202
|
+
ORDER BY depth ASC, archive_root_id ASC
|
|
203
|
+
) AS rank
|
|
204
|
+
FROM archive_members
|
|
205
|
+
)`,PT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>wT($,T.getFilePath(),G)}):T.readAll({signal:_})}},w0=PT;function R1(T){w0=T}function y1(){w0=PT}function h1(){return x0}var s;function mT(){return G0.join(X0(),"index.db")}async function I_(){let T=mT();if(s&&s.path===T)return s.db;let $=(async()=>{let _=await t(T);if(!_)return null;try{return qT(_),_}catch{return null}})();return s={path:T,db:$},$}function K_(){s=void 0}function W_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function j_(T,$,_,G,X){T.prepare("DELETE FROM parts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),T.prepare("DELETE FROM parts_fts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G);let Y=new Map;for(let U of X)if(U.type==="message_created")Y.set(U.data.messageId,U.data.role);let Q=T.prepare(`INSERT OR REPLACE INTO parts
|
|
206
|
+
(source_kind, project_path, session_id, part_id, message_id, part_type, role,
|
|
207
|
+
seq, timestamp, text)
|
|
208
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
|
|
209
|
+
(text, source_kind, project_path, session_id, part_id, role, timestamp, seq)
|
|
210
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=W_(U.data.payload);if(V===null)continue;let g=Y.get(U.data.messageId)??"assistant",H=U.seq??0;if(Q.run($,_,G,U.data.partId,U.data.messageId,U.data.partType,g,H,U.timestamp,V),g==="user"||g==="assistant")Z.run(V,$,_,G,U.data.partId,g,U.timestamp,H)}}function k_(T,$,_,G){let{metadata:X,publicWorkspaceRef:Y}=_,Q=v(Y??X.projectPath);T.prepare(`INSERT INTO sessions
|
|
211
|
+
(source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
|
|
212
|
+
agent_type, model, task_status, task_priority, task_kind, task_due_at,
|
|
213
|
+
archived_at, last_message_time, project_sort_key,
|
|
214
|
+
public_workspace_ref, public_workspace_sort_key, session_sort_key,
|
|
215
|
+
first_message_time, message_count, has_errors, is_subagent, metadata_json,
|
|
216
|
+
surface_digest)
|
|
217
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
218
|
+
ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
|
|
219
|
+
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
220
|
+
relation_type=excluded.relation_type, title=excluded.title,
|
|
221
|
+
agent_type=excluded.agent_type, model=excluded.model,
|
|
222
|
+
task_status=excluded.task_status, task_priority=excluded.task_priority,
|
|
223
|
+
task_kind=excluded.task_kind, task_due_at=excluded.task_due_at,
|
|
224
|
+
archived_at=excluded.archived_at,
|
|
225
|
+
last_message_time=excluded.last_message_time,
|
|
226
|
+
project_sort_key=excluded.project_sort_key,
|
|
227
|
+
public_workspace_ref=excluded.public_workspace_ref,
|
|
228
|
+
public_workspace_sort_key=excluded.public_workspace_sort_key,
|
|
229
|
+
session_sort_key=excluded.session_sort_key,
|
|
230
|
+
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
231
|
+
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
232
|
+
metadata_json=excluded.metadata_json, surface_digest=excluded.surface_digest`).run($,X.projectPath,X.sessionId,X.rootId,X.parentId??null,X.relationType??null,X.title??null,X.agentType??null,X.model??null,X.taskStatus,X.taskPriority??null,X.taskKind??null,X.taskDueAt??null,X.archivedAt??null,X.lastMessageTime,v(X.projectPath),Y??null,Q,v(X.sessionId),X.firstMessageTime,X.messageCount,X.hasErrors?1:0,X.relationType==="subagent"?1:0,JSON.stringify(X),G)}function q(T){T.prepare(`UPDATE surface_projection_meta
|
|
233
|
+
SET catalog_revision=catalog_revision + 1 WHERE singleton=1`).run()}function A_(T,$,_,G,X,Y){T.prepare(`DELETE FROM surface_messages
|
|
234
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);let Q=new Map;for(let U of X)if(U.type==="message_created"&&typeof U.seq==="number")Q.set(U.seq,U.data.messageId);let Z=T.prepare(`INSERT INTO surface_messages
|
|
235
|
+
(source_kind, project_path, session_id, message_seq, message_id,
|
|
236
|
+
message_json, byte_count)
|
|
237
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=b0.parse(U),g=vT(V.id),H=Q.get(g);if(!H)throw new J;let O=JSON.stringify(V);Z.run($,_,G,g,H,O,Buffer.byteLength(O))}}function vT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new J;return _}function x_(T){let{metadata:$}=T,_={locator:T.publicWorkspaceRef===void 0?{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}}:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:T.publicWorkspaceRef}},...uT($,T.publicWorkspaceRef)};return C_("sha256").update(L_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function uT(T,$){let _=T.remoteWorkspace===void 0?void 0:D(T.remoteWorkspace);if(_===void 0!==($===void 0)||_&&i(_.collisionIdentity)!==T.projectPath||!k(T.sessionId)||!k(T.rootId)||T.parentId!==void 0&&!k(T.parentId)||T.relationType!==void 0&&T.relationType!=="subagent"&&T.relationType!=="fork"||!["queued","running","completed","failed","cancelled","interrupted"].includes(T.taskStatus)||!Number.isSafeInteger(T.messageCount)||T.messageCount<0||!T.firstMessageTime||!T.lastMessageTime||T.archivedAt!==void 0&&!T.archivedAt||T.selectedModelId!==void 0&&!T.selectedModelId)throw new J;let G={..._?J0(T.projectPath,_):{privateRoots:[]},bladeStorageRoots:[X0()]},X=T.relationType,Y=T.taskStatus;return{displayCwd:_?.wirePath??T.projectPath,..._?{pathStyle:_.style}:{},...T.title!==void 0?{title:z0(T.title,G)}:{},rootId:T.rootId,...T.parentId!==void 0?{parentId:T.parentId}:{},...X!==void 0?{relationType:X}:{},taskStatus:Y,messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:z0(T.selectedModelId,G)}:{}}}function E_(T,$,_,G){return T.prepare(`SELECT EXISTS(
|
|
238
|
+
SELECT 1 FROM sessions
|
|
239
|
+
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
240
|
+
UNION ALL
|
|
241
|
+
SELECT 1 FROM surface_messages
|
|
242
|
+
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
243
|
+
) AS present`).get($,_,G,$,_,G)?.present===1}function S0(T,$,_,G){let X=E_(T,$,_,G);for(let Y of["surface_messages","sessions","parts","parts_fts"])T.prepare(`DELETE FROM ${Y} WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);return X}function w(T,$,_,G){let X=S0(T,$,_,G);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),X}function q_(T,$,_){let G=T.prepare(`SELECT project_path, session_id FROM sessions
|
|
244
|
+
WHERE source_kind=? AND json_extract(metadata_json, '$.filePath')=?`).all($,_),X=!1;for(let Y of G)X=S0(T,$,Y.project_path,Y.session_id)||X;return X}function W0(T,$,_,G,X,Y,Q,Z){T.prepare(`INSERT INTO projection_state
|
|
245
|
+
(source_kind, project_path, session_id, last_seq, file_size, mtime_ms,
|
|
246
|
+
stat_fingerprint)
|
|
247
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
248
|
+
ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
|
|
249
|
+
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
250
|
+
mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,_,G,X,Y,Q,Z)}function y(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function DT(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return c(_,async(Z)=>{let U=a(Z,$),V=X??U;if(V!==U)throw new E("remote-session-file-path");return E0(T,$,_,G,V,Y,Z,Q)});return E0(T,$,_,G,X??D0(_,$),Y,void 0,Q)}async function E0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new E("remote-session-scope");try{await j0(Q,X),Z?.throwIfAborted()}catch(C){if(Z?.aborted)throw C;if(C.code!=="ENOENT")throw C;return Z?.throwIfAborted(),T.transaction(()=>{if(w(T,Y,_,$))q(T)}),!0}}let U;try{U=await A0(X,{bigint:!0}),Z?.throwIfAborted()}catch(C){if(Z?.aborted)throw C;let W=C.code;if(Y==="acp-remote"&&W!=="ENOENT")throw C;return T.transaction(()=>{if(w(T,Y,_,$))q(T)}),!0}let V=T.prepare(`SELECT last_seq, file_size, mtime_ms, stat_fingerprint FROM projection_state
|
|
251
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,_,$);if(Y==="local"&&V&&V.stat_fingerprint===y(U))return!1;let g=new j(X),H;try{let C=U,W;for(let P0=0;P0<J_;P0+=1){Z?.throwIfAborted();let m0=await w0.readSession(g,Q,Z??z_);Z?.throwIfAborted();let Q0=await A0(X,{bigint:!0});if(Z?.throwIfAborted(),y(C)===y(Q0)){H=m0,U=Q0,W=m0;break}C=Q0}if(!W)throw new J;H=W}catch(C){if(Z?.aborted)throw C;let W=C.code;if(W!=="ENOENT"){if(Y==="acp-remote"){if(C instanceof E)throw C;if(W!==void 0)throw new E("remote-session-read")}throw C}return T.transaction(()=>{if(w(T,Y,_,$))q(T)}),!0}if(Y==="acp-remote"&&H.length===0){try{await j0(Q,X)}catch(C){if(Z?.aborted)throw C;if(C.code==="ENOENT")return T.transaction(()=>{if(w(T,Y,_,$))q(T)}),!0;throw C}throw new E("remote-session-empty")}Z?.throwIfAborted();let O=Y==="local"?H.find((C)=>C.type==="session_created"):void 0,I=Y==="local"&&O!==void 0&&Object.hasOwn(O.data,"remoteWorkspace"),B=null;if(Y==="acp-remote"){let C=ST(H,$,_);B=D(C.data.remoteWorkspace)}else if(I)D(O.data.remoteWorkspace);let L=H.reduce((C,W)=>typeof W.seq==="number"&&W.seq>C?W.seq:C,0),N=u(H),F=I?null:G(H,$,_,Y,X),S=F?.remoteWorkspace;if(Y==="acp-remote"){if(!F||F.sessionId!==$||F.projectPath!==_||S===void 0)throw new E("remote-session-metadata");let C=D(S);if(!B||C.style!==B.style||C.wirePath!==B.wirePath||C.exactIdentity!==B.exactIdentity||C.collisionIdentity!==B.collisionIdentity)throw new E("remote-session-descriptor");if(i(C.collisionIdentity)!==_)throw new E("remote-session-project-path")}if(H.length===0||!F||Y==="local"&&S!==void 0)return Z?.throwIfAborted(),T.transaction(()=>{let C;if(I)C=q_(T,Y,X),C=w(T,Y,_,$)||C;else C=S0(T,Y,_,$),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U));if(C)q(T)}),!0;let f0=B&&Q?await d0(Q,B):void 0;Z?.throwIfAborted();let R0=KT(H,{...B?J0(_,B):{privateRoots:[]},bladeStorageRoots:[X0()]}),y0={metadata:F,...f0!==void 0?{publicWorkspaceRef:f0}:{},surfaceMessages:R0},h0=x_(y0),Y0=T.prepare(`SELECT last_message_time FROM sessions
|
|
252
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId),nT=Y==="acp-remote"&&Q?a(Q,F.sessionId):D0(F.projectPath,F.sessionId),iT=G0.resolve(X)===G0.resolve(nT);if(Y0&&!iT&&typeof Y0.last_message_time==="string"&&Y0.last_message_time>F.lastMessageTime)return Z?.throwIfAborted(),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U)),!0;return Z?.throwIfAborted(),T.transaction(()=>{let W=T.prepare(`SELECT surface_digest FROM sessions
|
|
253
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId)?.surface_digest!==h0;if(k_(T,Y,y0,h0),j_(T,Y,F.projectPath,F.sessionId,N),A_(T,Y,F.projectPath,F.sessionId,N,R0),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U)),W)q(T)}),!0}var bT=new WeakMap;function q0(T,$,_,G){let X=T.prepare(`SELECT session_id FROM projection_state
|
|
254
|
+
WHERE source_kind=? AND project_path=?
|
|
255
|
+
UNION
|
|
256
|
+
SELECT session_id FROM sessions
|
|
257
|
+
WHERE source_kind=? AND project_path=?
|
|
258
|
+
UNION
|
|
259
|
+
SELECT session_id FROM parts
|
|
260
|
+
WHERE source_kind=? AND project_path=?
|
|
261
|
+
UNION
|
|
262
|
+
SELECT session_id FROM parts_fts
|
|
263
|
+
WHERE source_kind=? AND project_path=?
|
|
264
|
+
UNION
|
|
265
|
+
SELECT session_id FROM surface_messages
|
|
266
|
+
WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(w(T,$,_,Y.session_id))q(T)}}async function D_(T,$,_,G){G?.throwIfAborted();try{await c(_,async(X)=>{let Y=(await k0(String(X))).flatMap((V)=>{if(!V.endsWith(".jsonl"))return[];let g=V.slice(0,-6);if(!k(g))return[];return[{filePath:a(X,g),sessionId:g}]});G?.throwIfAborted();let Q=new Set(Y.map((V)=>V.sessionId)),Z=Math.min(32,Y.length),U=0;await Promise.all(Array.from({length:Z},async()=>{while(U<Y.length){G?.throwIfAborted();let V=Y[U++];if(!V)continue;await E0(T,V.sessionId,_,$,V.filePath,"acp-remote",X,G)}})),G?.throwIfAborted(),T.transaction(()=>{q0(T,"acp-remote",_,Q)})})}catch(X){if(G?.aborted)throw X;if(X.code!=="ENOENT")throw X;T.transaction(()=>{q0(T,"acp-remote",_,new Set)})}}async function P1(T,$,_){_?.throwIfAborted();let G=await fT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await D_(T,$,String(Q),_);let X=new Set(G.map(String)),Y=T.prepare(`SELECT project_path FROM projection_state WHERE source_kind='acp-remote'
|
|
267
|
+
UNION
|
|
268
|
+
SELECT project_path FROM sessions WHERE source_kind='acp-remote'
|
|
269
|
+
UNION
|
|
270
|
+
SELECT project_path FROM parts WHERE source_kind='acp-remote'
|
|
271
|
+
UNION
|
|
272
|
+
SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
|
|
273
|
+
UNION
|
|
274
|
+
SELECT project_path FROM surface_messages WHERE source_kind='acp-remote'`).all();for(let Q of Y)if(_?.throwIfAborted(),!X.has(Q.project_path))T.transaction(()=>{q0(T,"acp-remote",Q.project_path,new Set)})}async function b_(T,$,_=0){let G=bT.get(T)??{};if(bT.set(T,G),G.inFlight)return G.inFlight;if(_>0&&G.lastCompletedAt!==void 0&&Date.now()-G.lastCompletedAt<=_)return;let X=w_(T,$);G.inFlight=X;try{await X,G.lastCompletedAt=Date.now()}finally{if(G.inFlight===X)G.inFlight=void 0}}async function w_(T,$){let _=new Set,G=await RT(),Y=(await Promise.all(G.map(async(B)=>{if(B.kind==="local")try{return(await k0(B.storagePath)).flatMap((N)=>{if(!N.endsWith(".jsonl"))return[];let F=N.slice(0,-6);if(!k(F))return[];return[{kind:"local",filePath:G0.join(B.storagePath,N),projectPath:B.projectPath,sessionId:F}]})}catch{return[]}return c(B.storagePath,async(L)=>{return(await k0(String(L))).flatMap((F)=>{if(!F.endsWith(".jsonl"))return[];let S=F.slice(0,-6);if(!k(S))return[];return[{kind:"acp-remote",filePath:a(L,S),projectPath:B.projectPath,sessionId:S}]})})}))).flat();for(let B of Y)_.add(`${B.kind}\x00${B.projectPath}\x00${B.sessionId}`);let Q=T.prepare(`SELECT source_kind, project_path, session_id, last_seq, file_size, mtime_ms,
|
|
275
|
+
stat_fingerprint
|
|
276
|
+
FROM projection_state`).all(),Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`,B])),U=[],V=Math.min(128,Y.length),g=0;await Promise.all(Array.from({length:V},async()=>{while(g<Y.length){let B=Y[g++];if(!B)continue;if(B.kind==="acp-remote"){U.push(B);continue}try{let L=await A0(B.filePath,{bigint:!0}),N=Z.get(`${B.kind}\x00${B.projectPath}\x00${B.sessionId}`);if(N&&N.stat_fingerprint===y(L))continue}catch(L){if(L.code!=="ENOENT")throw L}U.push(B)}}));let H=Math.min(32,U.length),O=0;await Promise.all(Array.from({length:H},async()=>{while(O<U.length){let B=U[O++];if(!B)continue;try{if(B.kind==="acp-remote")await DT(T,B.sessionId,B.projectPath,$,B.filePath,"acp-remote");else await DT(T,B.sessionId,B.projectPath,$,B.filePath,"local")}catch(L){let N=L.code;if(B.kind==="acp-remote"){if(N==="ENOENT")continue;throw L}if(N==="acp_remote_workspace_state_invalid")throw L;if(N!=="ENOENT")F_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let I=T.prepare(`SELECT source_kind, project_path, session_id FROM projection_state
|
|
277
|
+
UNION
|
|
278
|
+
SELECT source_kind, project_path, session_id FROM sessions
|
|
279
|
+
WHERE source_kind='acp-remote'
|
|
280
|
+
UNION
|
|
281
|
+
SELECT source_kind, project_path, session_id FROM parts
|
|
282
|
+
WHERE source_kind='acp-remote'
|
|
283
|
+
UNION
|
|
284
|
+
SELECT source_kind, project_path, session_id FROM parts_fts
|
|
285
|
+
WHERE source_kind='acp-remote'
|
|
286
|
+
UNION
|
|
287
|
+
SELECT source_kind, project_path, session_id FROM surface_messages
|
|
288
|
+
WHERE source_kind='acp-remote'`).all();for(let B of I)if(!_.has(`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(w(T,B.source_kind,B.project_path,B.session_id))q(T)})}function m1(T,$,_,G="local"){T.transaction(()=>{if(w(T,G,_,$))q(T)})}async function v1(T){let{rm:$}=await import("node:fs/promises");K_();let _=mT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await I_();if(!G)return null;return await b_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function pT(T){try{let $=JSON.parse(T.metadata_json);if(!$||typeof $!=="object"||Array.isArray($))throw new J;let _=$,G=v(T.public_workspace_ref??T.project_path);if(_.sessionId!==T.session_id||_.projectPath!==T.project_path||_.rootId!==T.root_id||(_.parentId??null)!==T.parent_id||(_.relationType??null)!==T.relation_type||_.taskStatus!==T.task_status||T.relation_type!==null&&T.relation_type!=="subagent"&&T.relation_type!=="fork"||!Number.isSafeInteger(T.message_count)||T.message_count<0||T.has_errors!==0&&T.has_errors!==1||T.is_subagent!==0&&T.is_subagent!==1||_.firstMessageTime!==T.first_message_time||_.lastMessageTime!==T.last_message_time||(_.title??null)!==T.title||(_.archivedAt??null)!==T.archived_at||_.messageCount!==T.message_count||Number(_.hasErrors)!==T.has_errors||Number(_.relationType==="subagent")!==T.is_subagent||T.public_workspace_sort_key!==G||T.session_sort_key!==v(T.session_id)||!/^[a-f0-9]{64}$/.test(T.surface_digest)||!T.stat_fingerprint||T.source_kind==="local"&&(T.public_workspace_ref!==null||_.remoteWorkspace!==void 0)||T.source_kind==="acp-remote"&&(T.public_workspace_ref===null||!N_.test(T.public_workspace_ref)||_.remoteWorkspace===void 0))throw new J;let X=T.effective_archived_at?{..._,archivedAt:T.effective_archived_at,archivedBySessionId:T.archive_root_id}:_,Y=uT(X,T.public_workspace_ref??void 0);return{sourceKind:T.source_kind,projectPath:T.project_path,sessionId:T.session_id,...T.public_workspace_ref===null?{}:{publicWorkspaceRef:T.public_workspace_ref},publicWorkspaceSortKey:T.public_workspace_sort_key,surfaceDigest:T.surface_digest,transcriptFingerprint:T.stat_fingerprint,lastMessageTime:T.last_message_time,sessionSortKey:T.session_sort_key,summary:Y}}catch{throw new J}}function u1(T,$){if(!k($))throw new J;try{return T.prepare(`${hT}
|
|
289
|
+
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
290
|
+
s.relation_type, s.task_status, s.first_message_time,
|
|
291
|
+
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
292
|
+
s.has_errors,
|
|
293
|
+
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
294
|
+
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
295
|
+
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
296
|
+
s.metadata_json
|
|
297
|
+
FROM sessions s
|
|
298
|
+
JOIN projection_state p USING (source_kind, project_path, session_id)
|
|
299
|
+
LEFT JOIN ranked_archive a
|
|
300
|
+
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
301
|
+
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
302
|
+
AND a.session_id=s.session_id AND a.rank=1
|
|
303
|
+
WHERE s.session_id=?
|
|
304
|
+
ORDER BY s.source_kind DESC, s.public_workspace_sort_key ASC,
|
|
305
|
+
s.session_sort_key ASC`).all($).map(pT)}catch{throw new J}}function S_(T){let $=T.prepare("SELECT catalog_revision FROM surface_projection_meta WHERE singleton=1").get()?.catalog_revision;if(!Number.isSafeInteger($)||$===void 0||$<0)throw new J;return $}function p1(T,$){return lT($.limit),T.transaction(()=>{let _=[],G=["s.is_subagent=0",$.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"];if($.workspaceKind!==void 0)G.push("s.source_kind=?"),_.push($.workspaceKind);if($.boundary!==void 0)G.push(`(s.last_message_time < ?
|
|
306
|
+
OR (s.last_message_time = ? AND s.source_kind < ?)
|
|
307
|
+
OR (s.last_message_time = ? AND s.source_kind = ?
|
|
308
|
+
AND s.public_workspace_sort_key > ?)
|
|
309
|
+
OR (s.last_message_time = ? AND s.source_kind = ?
|
|
310
|
+
AND s.public_workspace_sort_key = ? AND s.session_sort_key > ?))`),_.push($.boundary.lastMessageTime,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.sessionSortKey);_.push($.limit+1);let X=S_(T),Y=T.prepare(`${hT}
|
|
311
|
+
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
312
|
+
s.relation_type, s.task_status, s.first_message_time,
|
|
313
|
+
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
314
|
+
s.has_errors,
|
|
315
|
+
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
316
|
+
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
317
|
+
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
318
|
+
s.metadata_json
|
|
319
|
+
FROM sessions s
|
|
320
|
+
JOIN projection_state p USING (source_kind, project_path, session_id)
|
|
321
|
+
LEFT JOIN ranked_archive a
|
|
322
|
+
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
323
|
+
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
324
|
+
AND a.session_id=s.session_id AND a.rank=1
|
|
325
|
+
WHERE ${G.join(" AND ")}
|
|
326
|
+
ORDER BY s.last_message_time DESC, s.source_kind DESC,
|
|
327
|
+
s.public_workspace_sort_key ASC, s.session_sort_key ASC
|
|
328
|
+
LIMIT ?`).all(..._),Q=Y.slice(0,$.limit),Z=Q.map(pT),U=Y.length>$.limit?Q.at(-1):void 0;return{revision:X,sessions:Z,...U?{nextBoundary:{lastMessageTime:U.last_message_time,sourceKind:U.source_kind,publicWorkspaceSortKey:U.public_workspace_sort_key,sessionSortKey:U.session_sort_key}}:{}}})}function l1(T,$){if(lT($.limit),$.beforeSequence!==void 0&&(!Number.isSafeInteger($.beforeSequence)||$.beforeSequence<0))throw new J;let _=$.maxBytes??x0;if(!Number.isSafeInteger(_)||_<1)throw new J;let G=Math.min(_,x0);return T.transaction(()=>{let X=T.prepare(`SELECT surface_digest, stat_fingerprint FROM sessions
|
|
329
|
+
JOIN projection_state USING (source_kind, project_path, session_id)
|
|
330
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get($.sourceKind,$.projectPath,$.sessionId);if(!X)throw new J;if(!/^[a-f0-9]{64}$/.test(X.surface_digest)||!X.stat_fingerprint)throw new J;let Y=$.beforeSequence===void 0?"":"AND message_seq < ?",Q=[$.sourceKind,$.projectPath,$.sessionId,...$.beforeSequence===void 0?[]:[$.beforeSequence],$.limit+1],Z=T.prepare(`SELECT message_seq, message_id, message_json, byte_count
|
|
331
|
+
FROM surface_messages
|
|
332
|
+
WHERE source_kind=? AND project_path=? AND session_id=? ${Y}
|
|
333
|
+
ORDER BY message_seq DESC, message_id DESC LIMIT ?`).all(...Q),U=[],V=2;for(let O of Z.slice(0,$.limit)){let I=U.length===0?0:1;if(U.length>0&&V+I+O.byte_count>G)break;U.push(O),V+=I+O.byte_count}let g=U.map((O)=>f_(O)).reverse(),H=Z.length>U.length;return{messages:g,hasOlder:H,...H&&U.length>0?{nextSequence:U.at(-1).message_seq}:{},transcriptFingerprint:X.stat_fingerprint,surfaceDigest:X.surface_digest}})}function f_(T){try{if(Buffer.byteLength(T.message_json)!==T.byte_count)throw new J;let $=b0.parse(JSON.parse(T.message_json));if($.id!==N0(T.message_seq,T.message_id)||vT($.id)!==T.message_seq)throw new J;return $}catch{throw new J}}function lT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new J}function n1(T,$,_,G){let X=$.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!X)return[];let Y=`"${X}"*`,Q=_?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
334
|
+
WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
|
|
335
|
+
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
336
|
+
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
337
|
+
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
338
|
+
export{d0 as _d,u as $d,a_ as ae,t_ as be,d as ce,j as de,v as ee,x$ as fe,E$ as ge,l_ as he,n_ as ie,i_ as je,D$ as ke,b$ as le,c_ as me,d_ as ne,r_ as oe,ZT as pe,T1 as qe,C0 as re,F0 as se,Z1 as te,U1 as ue,V1 as ve,CT as we,FT as xe,J0 as ye,KT as ze,R1 as Ae,y1 as Be,h1 as Ce,mT as De,I_ as Ee,K_ as Fe,uT as Ge,DT as He,D_ as Ie,P1 as Je,b_ as Ke,m1 as Le,v1 as Me,u1 as Ne,S_ as Oe,p1 as Pe,l1 as Qe,n1 as Re};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{bh as Q}from"./chunk-93x9xbew.js";import{Ji as F,Li as k,Oi as G}from"./chunk-sj1dzeta.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as ff};
|