@hostclubeos/miraos 0.0.4-beta → 0.0.5-beta
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/bundled/bug-hunter/SKILL.md +7 -0
- package/chunks/{acpAgent-F4OT4AQQ.js → acpAgent-UHWDA3W7.js} +2 -2
- package/chunks/{chunk-ECNTMKHI.js → chunk-2GVKPBW5.js} +1 -1
- package/chunks/{chunk-HPGUQCRQ.js → chunk-2TDRP3IX.js} +1 -1
- package/chunks/{chunk-C24YTZET.js → chunk-4IVYVCCU.js} +1 -1
- package/chunks/{chunk-CKBEAZAV.js → chunk-62DMHXLL.js} +1 -1
- package/chunks/{chunk-AYU4PDSQ.js → chunk-744QTJR2.js} +2 -2
- package/chunks/{chunk-4XV2522J.js → chunk-D3YOXHQF.js} +1 -1
- package/chunks/{chunk-5SJFYZQJ.js → chunk-FRADUGRC.js} +1 -1
- package/chunks/{chunk-WDLXS4A3.js → chunk-FXANOHXI.js} +3 -3
- package/chunks/{chunk-JM46SKXF.js → chunk-MQWKOOSR.js} +1 -1
- package/chunks/{chunk-4TJKJ2LG.js → chunk-MUS4ADP7.js} +1 -1
- package/chunks/{chunk-FUIRLSNA.js → chunk-N4RIISOE.js} +1 -1
- package/chunks/{chunk-PUPIORBU.js → chunk-NKWATWMD.js} +1 -1
- package/chunks/{chunk-7LXU4NUI.js → chunk-NYM67KKZ.js} +1 -1
- package/chunks/{chunk-TIWH3MUJ.js → chunk-PXBJPUGN.js} +1 -1
- package/chunks/{chunk-LISKSG7B.js → chunk-QEIX42MZ.js} +1 -1
- package/chunks/{chunk-BZMSTSKY.js → chunk-RKFNQQNA.js} +1 -1
- package/chunks/{chunk-AXBNQS6C.js → chunk-SK3QOQR4.js} +1 -1
- package/chunks/{chunk-33G7MOU6.js → chunk-XZNF4YNN.js} +1 -1
- package/chunks/{daemon-status-provider-NBPLE4JN.js → daemon-status-provider-F6KB2LNG.js} +1 -1
- package/chunks/{fast-path-66F2TWKE.js → fast-path-DWPD5EGQ.js} +1 -1
- package/chunks/{llm-LZ3HARC2.js → llm-RBI7KXDE.js} +3 -3
- package/chunks/{local-6KBSW7N2.js → local-HSG47CNJ.js} +1 -1
- package/chunks/{managed-local-serve-2N3IAB3D.js → managed-local-serve-YE4JDFNP.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-M4P43K7W.js → managed-runtime-bootstrap-SHEXUEZN.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-WWZ7SJ7U.js → managed-runtime-ssh-worker-BZNJV7IB.js} +1 -1
- package/chunks/{memory-D62BXIJW.js → memory-JTDN5AEA.js} +1 -1
- package/chunks/{nonInteractiveCli-Z4A7THMG.js → nonInteractiveCli-BXHX6EIU.js} +1 -1
- package/chunks/{review-LM7KW6Y5.js → review-PC4IDLCG.js} +1 -1
- package/chunks/{run-qwen-serve-77UZS4JA.js → run-qwen-serve-XRWVWOZK.js} +1 -1
- package/chunks/{serve-RHO7RZ45.js → serve-JCUT4WK7.js} +1 -1
- package/chunks/{server-5HEOZG3T.js → server-HMTRZJF7.js} +1 -1
- package/chunks/{session-RT7VH6GE.js → session-RGLZU6KY.js} +1 -1
- package/chunks/{start-opentui-ui-I2XXWTJS.js → start-opentui-ui-YNTPK7LX.js} +1 -1
- package/chunks/{startInteractiveUI-774LJIJD.js → startInteractiveUI-MWA2VYTJ.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-633WYCVH.js → validateNonInterActiveAuth-3433WFLE.js} +1 -1
- package/chunks/{version-77KBVA2F.js → version-XCFKTEY3.js} +1 -1
- package/cli.js +1 -1
- package/package.json +2 -2
- package/bundled/bug-hunter/references/apk-redteam-pipeline/SKILL.md +0 -407
- package/bundled/bug-hunter/references/bb-local-toolkit/SKILL.md +0 -1558
- package/bundled/bug-hunter/references/bb-methodology/SKILL.md +0 -513
- package/bundled/bug-hunter/references/bug-bounty/SKILL.md +0 -1604
- package/bundled/bug-hunter/references/bugcrowd-reporting/SKILL.md +0 -331
- package/bundled/bug-hunter/references/cloud-iam-deep/SKILL.md +0 -521
- package/bundled/bug-hunter/references/enterprise-vpn-attack/SKILL.md +0 -356
- package/bundled/bug-hunter/references/evidence-hygiene/SKILL.md +0 -401
- package/bundled/bug-hunter/references/exploit-completion/SKILL.md +0 -155
- package/bundled/bug-hunter/references/hunt-api-misconfig/SKILL.md +0 -268
- package/bundled/bug-hunter/references/hunt-aspnet/SKILL.md +0 -277
- package/bundled/bug-hunter/references/hunt-ato/SKILL.md +0 -140
- package/bundled/bug-hunter/references/hunt-auth-bypass/SKILL.md +0 -449
- package/bundled/bug-hunter/references/hunt-brute-force/SKILL.md +0 -297
- package/bundled/bug-hunter/references/hunt-business-logic/SKILL.md +0 -237
- package/bundled/bug-hunter/references/hunt-cache-poison/SKILL.md +0 -338
- package/bundled/bug-hunter/references/hunt-captcha-bypass/SKILL.md +0 -92
- package/bundled/bug-hunter/references/hunt-cicd/SKILL.md +0 -267
- package/bundled/bug-hunter/references/hunt-clickjacking/SKILL.md +0 -66
- package/bundled/bug-hunter/references/hunt-cloud-misconfig/SKILL.md +0 -195
- package/bundled/bug-hunter/references/hunt-cors/SKILL.md +0 -291
- package/bundled/bug-hunter/references/hunt-csrf/SKILL.md +0 -374
- package/bundled/bug-hunter/references/hunt-deserialization/SKILL.md +0 -178
- package/bundled/bug-hunter/references/hunt-dispatch/SKILL.md +0 -380
- package/bundled/bug-hunter/references/hunt-dom/SKILL.md +0 -279
- package/bundled/bug-hunter/references/hunt-exceptional-conditions/SKILL.md +0 -67
- package/bundled/bug-hunter/references/hunt-file-upload/SKILL.md +0 -158
- package/bundled/bug-hunter/references/hunt-fintech-graphql/SKILL.md +0 -245
- package/bundled/bug-hunter/references/hunt-forgot-password/SKILL.md +0 -70
- package/bundled/bug-hunter/references/hunt-graphql/SKILL.md +0 -368
- package/bundled/bug-hunter/references/hunt-grpc/SKILL.md +0 -273
- package/bundled/bug-hunter/references/hunt-host-header/SKILL.md +0 -265
- package/bundled/bug-hunter/references/hunt-html-injection/SKILL.md +0 -62
- package/bundled/bug-hunter/references/hunt-http-smuggling/SKILL.md +0 -87
- package/bundled/bug-hunter/references/hunt-idor/SKILL.md +0 -389
- package/bundled/bug-hunter/references/hunt-jwt-crypto/SKILL.md +0 -177
- package/bundled/bug-hunter/references/hunt-k8s/SKILL.md +0 -293
- package/bundled/bug-hunter/references/hunt-laravel/SKILL.md +0 -211
- package/bundled/bug-hunter/references/hunt-ldap/SKILL.md +0 -307
- package/bundled/bug-hunter/references/hunt-lfi/SKILL.md +0 -266
- package/bundled/bug-hunter/references/hunt-llm-ai/SKILL.md +0 -245
- package/bundled/bug-hunter/references/hunt-mfa-bypass/SKILL.md +0 -134
- package/bundled/bug-hunter/references/hunt-misc/SKILL.md +0 -333
- package/bundled/bug-hunter/references/hunt-nextjs/SKILL.md +0 -255
- package/bundled/bug-hunter/references/hunt-nodejs/SKILL.md +0 -219
- package/bundled/bug-hunter/references/hunt-nosqli/SKILL.md +0 -166
- package/bundled/bug-hunter/references/hunt-ntlm-info/SKILL.md +0 -270
- package/bundled/bug-hunter/references/hunt-oauth/SKILL.md +0 -414
- package/bundled/bug-hunter/references/hunt-open-redirect/SKILL.md +0 -179
- package/bundled/bug-hunter/references/hunt-race-condition/SKILL.md +0 -485
- package/bundled/bug-hunter/references/hunt-rag-vector/SKILL.md +0 -167
- package/bundled/bug-hunter/references/hunt-rce/SKILL.md +0 -494
- package/bundled/bug-hunter/references/hunt-saml/SKILL.md +0 -112
- package/bundled/bug-hunter/references/hunt-session/SKILL.md +0 -298
- package/bundled/bug-hunter/references/hunt-shadow-api/SKILL.md +0 -153
- package/bundled/bug-hunter/references/hunt-sharepoint/SKILL.md +0 -437
- package/bundled/bug-hunter/references/hunt-source-leak/SKILL.md +0 -301
- package/bundled/bug-hunter/references/hunt-spa-api/SKILL.md +0 -123
- package/bundled/bug-hunter/references/hunt-springboot/SKILL.md +0 -241
- package/bundled/bug-hunter/references/hunt-sqli/SKILL.md +0 -422
- package/bundled/bug-hunter/references/hunt-ssrf/SKILL.md +0 -514
- package/bundled/bug-hunter/references/hunt-ssti/SKILL.md +0 -117
- package/bundled/bug-hunter/references/hunt-subdomain/SKILL.md +0 -335
- package/bundled/bug-hunter/references/hunt-tls-network/SKILL.md +0 -355
- package/bundled/bug-hunter/references/hunt-websocket/SKILL.md +0 -285
- package/bundled/bug-hunter/references/hunt-xss/SKILL.md +0 -450
- package/bundled/bug-hunter/references/hunt-xxe/SKILL.md +0 -422
- package/bundled/bug-hunter/references/ios-redteam-pipeline/SKILL.md +0 -287
- package/bundled/bug-hunter/references/m365-entra-attack/SKILL.md +0 -384
- package/bundled/bug-hunter/references/meme-coin-audit/SKILL.md +0 -358
- package/bundled/bug-hunter/references/mid-engagement-ir-detection/SKILL.md +0 -353
- package/bundled/bug-hunter/references/offensive-osint/README.md +0 -98
- package/bundled/bug-hunter/references/offensive-osint/SKILL.md +0 -399
- package/bundled/bug-hunter/references/offensive-osint/references/breach-and-credentials.md +0 -128
- package/bundled/bug-hunter/references/offensive-osint/references/dork-corpus.md +0 -180
- package/bundled/bug-hunter/references/offensive-osint/references/helpers-and-automation.md +0 -231
- package/bundled/bug-hunter/references/offensive-osint/references/identity-fabric.md +0 -305
- package/bundled/bug-hunter/references/offensive-osint/references/people-osint.md +0 -105
- package/bundled/bug-hunter/references/offensive-osint/references/probes-and-wordlists.md +0 -1266
- package/bundled/bug-hunter/references/offensive-osint/references/recon-stack.md +0 -282
- package/bundled/bug-hunter/references/offensive-osint/references/recon-techniques.md +0 -341
- package/bundled/bug-hunter/references/offensive-osint/references/saas-public-surfaces.md +0 -138
- package/bundled/bug-hunter/references/offensive-osint/references/secret-patterns.md +0 -67
- package/bundled/bug-hunter/references/offensive-osint/references/secret-validators.md +0 -329
- package/bundled/bug-hunter/references/offensive-osint/references/sector-notes.md +0 -72
- package/bundled/bug-hunter/references/offensive-osint/references/severity-matrix.md +0 -108
- package/bundled/bug-hunter/references/offensive-osint/references/specialized-osint.md +0 -199
- package/bundled/bug-hunter/references/offensive-osint/references/tooling-install.md +0 -188
- package/bundled/bug-hunter/references/offensive-osint/scripts/assets/FONT-LICENSE.txt +0 -13
- package/bundled/bug-hunter/references/offensive-osint/scripts/assets/archivo-black.woff2 +0 -0
- package/bundled/bug-hunter/references/offensive-osint/scripts/dashboard.py +0 -968
- package/bundled/bug-hunter/references/offensive-osint/scripts/h1_reference.py +0 -402
- package/bundled/bug-hunter/references/offensive-osint/scripts/secret_scan.py +0 -180
- package/bundled/bug-hunter/references/okta-attack/SKILL.md +0 -397
- package/bundled/bug-hunter/references/osint-methodology/README.md +0 -66
- package/bundled/bug-hunter/references/osint-methodology/SKILL.md +0 -1704
- package/bundled/bug-hunter/references/recon-scope-triage/SKILL.md +0 -89
- package/bundled/bug-hunter/references/redteam-mindset/SKILL.md +0 -401
- package/bundled/bug-hunter/references/redteam-report-template/SKILL.md +0 -347
- package/bundled/bug-hunter/references/regression-hunting/SKILL.md +0 -98
- package/bundled/bug-hunter/references/report-writing/SKILL.md +0 -568
- package/bundled/bug-hunter/references/security-arsenal/SKILL.md +0 -912
- package/bundled/bug-hunter/references/supply-chain-attack-recon/SKILL.md +0 -648
- package/bundled/bug-hunter/references/triage-validation/SKILL.md +0 -418
- package/bundled/bug-hunter/references/vmware-vcenter-attack/SKILL.md +0 -372
- package/bundled/bug-hunter/references/web2-recon/SKILL.md +0 -698
- package/bundled/bug-hunter/references/web3-audit/SKILL.md +0 -606
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-ECNTMKHI.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-LISKSG7B.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-PFKTTUGS.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
|
|
3
|
+
import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-2GVKPBW5.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-QEIX42MZ.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-PFKTTUGS.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
3
|
import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&§ion.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
|
|
4
|
-
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-
|
|
4
|
+
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-HSG47CNJ.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{GIT_COMMIT_INFO}from"./chunk-
|
|
3
|
+
import{GIT_COMMIT_INFO}from"./chunk-MQWKOOSR.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{getCliVersion}from"./chunk-D3YOXHQF.js";import{IdeClient}from"./chunk-PFKTTUGS.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function formatExecutionSandbox(config){const policy=config?.getShellExecutionSandbox?.();if(!policy)return void 0;const effective=policy.effectiveBackend??"unresolved";const enforcement=policy.enforcement?` (${policy.enforcement}${policy.landlockAbi?`, ABI ${policy.landlockAbi}`:""})`:"";return`tools / ${policy.requestedBackend??"auto"} \u2192 ${effective}${enforcement} / ${policy.filesystem} / command network: ${policy.network}`}__name(formatExecutionSandbox,"formatExecutionSandbox");import process from"node:process";import os from"node:os";import{execFile}from"node:child_process";var debugLogger=createDebugLogger("STATUS");var VERSION_PROBE_TIMEOUT_MS=5e3;function probeVersion(binary){return new Promise(resolve=>{execFile(binary,["--version"],{timeout:VERSION_PROBE_TIMEOUT_MS,encoding:"utf-8"},(err,stdout)=>{if(err){resolve("unknown");return}resolve(typeof stdout==="string"?stdout.trim():"unknown")})})}__name(probeVersion,"probeVersion");async function getNpmVersion(){return probeVersion("npm")}__name(getNpmVersion,"getNpmVersion");async function getGitVersion(){return probeVersion("git")}__name(getGitVersion,"getGitVersion");async function getIdeClientName(context){if(!context.services.config?.getIdeMode()){return""}try{const ideClient=await IdeClient.getInstance();return ideClient?.getDetectedIdeDisplayName()??""}catch{return""}}__name(getIdeClientName,"getIdeClientName");function getSandboxEnv(stripPrefix=false){const sandbox=process.env["SANDBOX"];if(!sandbox||sandbox==="sandbox-exec"){if(sandbox==="sandbox-exec"){const profile=process.env["SEATBELT_PROFILE"]||"unknown";return`sandbox-exec (${profile})`}return"no sandbox"}if(stripPrefix){return sandbox.replace(/^qwen-(?:code-)?/,"")}return sandbox}__name(getSandboxEnv,"getSandboxEnv");async function getSystemInfo(context){const osPlatform=process.platform;const osArch=process.arch;const osRelease=os.release();const nodeVersion=process.version;const executionSandbox=formatExecutionSandbox(context.services.config);const npmVersion=executionSandbox?"not probed (tool execution sandbox active)":await getNpmVersion();const sandboxEnv=executionSandbox??getSandboxEnv();const modelVersion=context.services.config?.getModel()||"Unknown";const cliVersion=await getCliVersion();const selectedAuthType=context.services.config?.getAuthType()||"";const ideClient=await getIdeClientName(context);const sessionId=context.services.config?.getSessionId()||"unknown";const proxy=context.services.config?.getProxy();return{cliVersion,osPlatform,osArch,osRelease,nodeVersion,npmVersion,sandboxEnv,modelVersion,selectedAuthType,ideClient,sessionId,proxy}}__name(getSystemInfo,"getSystemInfo");async function getExtendedSystemInfo(context){const baseInfo=await getSystemInfo(context);const memoryUsage=formatMemoryUsage(process.memoryUsage().rss);const sandboxEnv=formatExecutionSandbox(context.services.config)??getSandboxEnv(true);const contentGeneratorConfig=baseInfo.selectedAuthType==="openai"||baseInfo.selectedAuthType==="openai-responses"||baseInfo.selectedAuthType==="anthropic"?context.services.config?.getContentGeneratorConfig():void 0;const baseUrl=contentGeneratorConfig?.baseUrl;const apiKeyEnvKey=contentGeneratorConfig?.apiKeyEnvKey;const gitCommit=GIT_COMMIT_INFO&&!["N/A"].includes(GIT_COMMIT_INFO)?GIT_COMMIT_INFO:void 0;const fastModelSetting=context.services.settings?.merged?.fastModel||void 0;const fastModel=fastModelSetting?formatAuxModelSelectorForDisplay(fastModelSetting):void 0;const lspStatus=getLspStatus(context);return{...baseInfo,sandboxEnv,memoryUsage,baseUrl,apiKeyEnvKey,gitCommit,fastModel,lspStatus}}__name(getExtendedSystemInfo,"getExtendedSystemInfo");function getLspStatus(context){try{const snapshot=context.services.config?.getLspStatusSnapshot?.();if(!snapshot){return void 0}if(context.services.config?.getDebugMode?.()){debugLogger.debug("LSP status snapshot for /status:",snapshot)}return formatLspStatusSnapshot(snapshot)}catch(error){if(context.services.config?.getDebugMode?.()){debugLogger.debug("Unable to read LSP status snapshot for /status:",error)}return void 0}}__name(getLspStatus,"getLspStatus");function formatLspStatusSnapshot(snapshot){if(!snapshot.enabled){return"disabled"}if(snapshot.initializationError){return`enabled, initialization failed: ${snapshot.initializationError}`}if(snapshot.statusUnavailable){return"enabled, status unavailable"}if(snapshot.configuredServers===0){return"enabled, no servers configured"}const details=[snapshot.failedServers>0?`${snapshot.failedServers} failed`:"",snapshot.inProgressServers>0?`${snapshot.inProgressServers} starting`:"",snapshot.notStartedServers>0?`${snapshot.notStartedServers} not started`:""].filter(Boolean);const detailText=details.length>0?` (${details.join(", ")})`:"";return`enabled, ${snapshot.readyServers}/${snapshot.configuredServers} ready${detailText}`}__name(formatLspStatusSnapshot,"formatLspStatusSnapshot");export{formatExecutionSandbox,getNpmVersion,getGitVersion,getExtendedSystemInfo};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-PGKFDR73.js";import{JsonOutputAdapter}from"./chunk-
|
|
3
|
+
import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-PGKFDR73.js";import{JsonOutputAdapter}from"./chunk-62DMHXLL.js";import{StreamJsonOutputAdapter}from"./chunk-2TDRP3IX.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{handleAtCommand}from"./chunk-WC72OWF2.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-4IVYVCCU.js";import{formatDuration}from"./chunk-7VP4KALB.js";import{ModSession}from"./chunk-AE6E2YKY.js";import{frameModPrompt}from"./chunk-5KRYBTZV.js";import{cleanupReviewWorktreeLeases}from"./chunk-CUY6CVSL.js";import{RunBudgetEnforcer}from"./chunk-FXANOHXI.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-4KIFAVR2.js";import{t}from"./chunk-FK5L2WVV.js";import{isInlineModelOverrideAllowed}from"./chunk-YQXX44YA.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-3MBYQYPC.js";import{restoreWorktreeContext}from"./chunk-DVN6DAWO.js";import{executeToolCall}from"./chunk-ZOWMHZWO.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall,runAgentLoop}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-7Z2ZH5CW.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{clampInlineMediaPart}from"./chunk-Q6UAOTP3.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-JJAEIBSV.js";import{registerCleanup}from"./chunk-PFECH6U6.js";import{isWrappedSystemReminderPart}from"./chunk-DMM5LJWL.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{FatalInputError,getErrorType}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");async function waitForPendingMemoryTasks(client,signal,memoryWaitStopSignal){const promises=client.getPendingMemoryTaskPromises();if(promises.length===0)return;const pending=new Set(promises);const settled=Promise.allSettled(promises.map(promise=>promise.then(()=>{pending.delete(promise)},()=>{pending.delete(promise)})));let stopWaiting;const stopped=new Promise(resolve=>{stopWaiting=resolve});signal.addEventListener("abort",stopWaiting,{once:true});memoryWaitStopSignal?.addEventListener("abort",stopWaiting,{once:true});try{if(signal.aborted||memoryWaitStopSignal?.aborted){stopWaiting()}else{debugLogger.debug(`[runNonInteractive] Waiting for ${promises.length} tracked memory task(s)`)}await Promise.race([settled,stopped])}finally{signal.removeEventListener("abort",stopWaiting);memoryWaitStopSignal?.removeEventListener("abort",stopWaiting);client.removePendingMemoryTaskPromises(promises.filter(promise=>!pending.has(promise)))}if(signal.aborted){debugLogger.debug("[runNonInteractive] Abandoned memory wait after abort; tasks may still be running");signal.throwIfAborted()}if(pending.size>0&&memoryWaitStopSignal?.aborted){debugLogger.debug(`[runNonInteractive] Stopped waiting at the session EOF deadline; ${pending.size} tracked memory task(s) may still be running`);return}debugLogger.debug("[runNonInteractive] Tracked memory tasks settled")}__name(waitForPendingMemoryTasks,"waitForPendingMemoryTasks");var debugLogger2=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var ModTurnAbortedError=class extends TurnInterruptedError{static{__name(this,"ModTurnAbortedError")}constructor(){super();this.message="A Mod ended the turn."}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;var ONE_SHOT_MEMORY_WAIT_TIMEOUT_MS=5e3;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger2.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");var PROVIDER_DUPLICATE_ID_LOOP_STOP={loopType:"global_tool_call_duplicate",loopReason:"provider_duplicate_id"};function emitLoopDetectedMessage(config,stop){const message=formatLoopDetectedMessage(stop);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
|
|
4
4
|
`);return message}__name(emitLoopDetectedMessage,"emitLoopDetectedMessage");function emitNonInteractiveAssistantText(adapter,message){adapter.startAssistantMessage();adapter.processEvent({type:"content",value:message});adapter.finalizeAssistantMessage()}__name(emitNonInteractiveAssistantText,"emitNonInteractiveAssistantText");async function emitNonInteractiveFinalMessage(params){const{message,isError,adapter,config}=params;emitNonInteractiveAssistantText(adapter,message);const metrics=uiTelemetryService.getMetrics();const usage=computeUsageFromMetrics(metrics);const outputFormat=config.getOutputFormat();const stats=outputFormat==="json"?uiTelemetryService.getMetrics():void 0;await params.beforeEmit();adapter.emitResult({isError,durationMs:Date.now()-params.startTimeMs,apiDurationMs:0,numTurns:0,errorMessage:isError?message:void 0,usage,stats,summary:message})}__name(emitNonInteractiveFinalMessage,"emitNonInteractiveFinalMessage");function partitionHeadlessToolCalls(requests,config){let skillBefore=false;return partitionByConcurrencySafety(requests,request=>{const executionRequest=getHeadlessExecutionRequest(request,config);const canonicalName=canonicalToolName(executionRequest.name);const kind=config.getToolRegistry().getTool(canonicalName)?.kind;const inputMayChange=kind==="execute"&&(skillBefore||!config.getDisableAllHooks()&&(config.hasHooksForEvent("PreToolUse")||config.hasHooksForEvent("PermissionRequest")));skillBefore||=canonicalName===ToolNames.SKILL;return!inputMayChange&&isToolCallConcurrencySafe(executionRequest.name,kind,executionRequest.args)})}__name(partitionHeadlessToolCalls,"partitionHeadlessToolCalls");function getHeadlessExecutionRequest(request,config){if(canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const targetName=request.args["name"];let targetArgs=request.args["arguments"];if(typeof targetArgs==="string"){try{targetArgs=JSON.parse(targetArgs)}catch{return request}}if(typeof targetName!=="string"||typeof targetArgs!=="object"||targetArgs===null||Array.isArray(targetArgs)){return request}const registry=config.getToolRegistry();const target=registry.getTool(canonicalToolName(targetName));if(!target||!registry.isDeferredAndHidden(target.name)){return request}return{...request,name:target.name,args:targetArgs}}__name(getHeadlessExecutionRequest,"getHeadlessExecutionRequest");async function runNonInteractive(config,settings,input,prompt_id,options={}){return promptIdContext.run(prompt_id,async()=>{let adapter;const outputFormat=config.getOutputFormat();if(options.adapter){adapter=options.adapter}else if(outputFormat==="stream-json"){adapter=new StreamJsonOutputAdapter(config,config.getIncludePartialMessages())}else{adapter=new JsonOutputAdapter(config)}const ownsAdapter=options.adapter===void 0;const modSession=options.modSession??ModSession.create(config,settings,adapter);const ownsModSession=options.modSession===void 0;let modTurn;const unsubscribeRecordingFailure=ownsAdapter?subscribeToHeadlessChatRecordingFailures(config,adapter):void 0;let chatRecordingSettlement;const settleBeforeTerminalOutput=__name(()=>{chatRecordingSettlement??=(async()=>{await modTurn?.complete(abortController.signal.aborted&&!budgetEnforcer.getExceeded()?"aborted":"error");if(ownsModSession)await modSession?.close();modSession?.flushLogs();await settleChatRecording(config,{finalize:ownsAdapter})})();return chatRecordingSettlement},"settleBeforeTerminalOutput");const drainPendingMemoryTasks=__name((successTerminal=false)=>{const client=config.getLlmClient();if(options.memoryWaitStopSignal){return waitForPendingMemoryTasks(client,abortController.signal,options.memoryWaitStopSignal)}if(successTerminal){return waitForPendingMemoryTasks(client,abortController.signal)}const oneShotMemoryWindow=new AbortController;const oneShotMemoryWindowTimer=setTimeout(()=>oneShotMemoryWindow.abort(),ONE_SHOT_MEMORY_WAIT_TIMEOUT_MS);return waitForPendingMemoryTasks(client,abortController.signal,oneShotMemoryWindow.signal).finally(()=>clearTimeout(oneShotMemoryWindowTimer))},"drainPendingMemoryTasks");let resultEmitted=false;const emitResult=__name(async result=>{try{await settleBeforeTerminalOutput();adapter.emitResult(result);resultEmitted=true;options.onResultEmitted?.();await modSession?.flushOutput()}finally{await drainPendingMemoryTasks(!result.isError)}},"emitResult");const sessionId=config.getSessionId();const permissionMode=config.getApprovalMode();const cleanupReviewWorktrees=__name(gitTimeout=>{if(config.getShellExecutionSandbox?.())return;cleanupReviewWorktreeLeases({sessionId,promptId:prompt_id,repositoryRoot:config.getProjectRoot(),gitTimeout})},"cleanupReviewWorktrees");const unregisterReviewWorktreeCleanup=registerCleanup(()=>cleanupReviewWorktrees(1e3));let turnCount=0;let limitedTurnCount=0;let totalApiDurationMs=0;const startTime=Date.now();let activeInteractionPromptId=prompt_id;let activeInteractionOwner;const selectActiveInteraction=__name((promptId,startsInteraction=false)=>{if(startsInteraction||activeInteractionPromptId!==promptId){activeInteractionOwner=void 0}activeInteractionPromptId=promptId},"selectActiveInteraction");const captureActiveInteractionOwner=__name(()=>{activeInteractionOwner??=getActiveInteractionSpan(activeInteractionPromptId);return activeInteractionOwner},"captureActiveInteractionOwner");const endActiveInteraction=__name((status,metadata={})=>{const owner=captureActiveInteractionOwner();if(!owner||getActiveInteractionSpan(activeInteractionPromptId)!==owner){return}endInteractionSpan(status,{promptId:activeInteractionPromptId,...metadata})},"endActiveInteraction");const llmClient=config.getLlmClient();const abortController=options.abortController??new AbortController;const queuedGoalTurns=[];let activeGoalTurn;let goalRuntimeUnsubscribe;const emitGoalSnapshot=__name(snapshot=>{adapter.processEvent({type:"goal_state",value:snapshot})},"emitGoalSnapshot");const observeGoalRuntime=__name(runtime=>{goalRuntimeUnsubscribe??=runtime.subscribe(emitGoalSnapshot)},"observeGoalRuntime");const enforceSessionTurnLimit=__name(async isRuntimeGoalTurn=>{if(isRuntimeGoalTurn)return;limitedTurnCount++;const maxSessionTurns=config.getMaxSessionTurns();if(maxSessionTurns>=0&&limitedTurnCount>maxSessionTurns){await failClosedActiveGoalTurn("Headless Goal stopped after the session turn limit");await settleBeforeTerminalOutput();await handleMaxTurnsExceededError(config)}},"enforceSessionTurnLimit");let goalHostUnbind;const goalHost={startGoalTurn:__name(async input2=>{if(queuedGoalTurns.some(({permit:permit2})=>permit2.turnId===input2.permit.turnId)){return}const{permit,...continuation}=input2;queuedGoalTurns.push({permit:{...permit},turnKey:`goal-runtime:${permit.turnId}`,controller:new AbortController,origin:"runtime",...continuation})},"startGoalTurn"),preemptGoalTurn:__name(reason=>{for(const turn of queuedGoalTurns.splice(0)){turn.controller.abort(reason)}activeGoalTurn?.controller.abort(reason)},"preemptGoalTurn")};const bindGoalHost=__name(()=>{goalHostUnbind??=config.bindGoalTurnHost(goalHost)},"bindGoalHost");const markGoalTurnDelivered=__name(turn=>{try{config.getGoalRuntime().markTurnDelivered(turn.turnKey)}catch{}},"markGoalTurnDelivered");let settlingGoalTurn;let goalTurnSettlement;const failClosedActiveGoalTurn=__name((reason,pauseReason)=>{const turn=activeGoalTurn;if(!turn)return Promise.resolve();if(settlingGoalTurn===turn&&goalTurnSettlement){return goalTurnSettlement}settlingGoalTurn=turn;goalTurnSettlement=(async()=>{if(!turn.controller.signal.aborted){turn.controller.abort(reason)}try{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}if(runtime.getSnapshot().goal?.status==="active"){try{await runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:pauseReason??goalPauseReasonForHeadlessFailure(reason)})}catch(error){debugLogger2.warn("Failed to pause terminal headless Goal",error)}}try{await config.getChatRecordingService?.()?.flush()}catch(error){debugLogger2.warn("Failed to flush terminal headless Goal",error)}if(sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){await runtime.finishTurn(turn.permit)}}catch(error){debugLogger2.warn("Failed to close terminal headless Goal",error)}finally{if(activeGoalTurn===turn){activeGoalTurn=void 0}if(settlingGoalTurn===turn){settlingGoalTurn=void 0;goalTurnSettlement=void 0}}})();return goalTurnSettlement},"failClosedActiveGoalTurn");const finishGoalTurn=__name(async turn=>{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}let abortSettlement;const pauseOnAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();abortSettlement??=runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT}).then(()=>void 0).catch(error=>{debugLogger2.warn("Failed to pause aborted headless Goal",error)})},"pauseOnAbort");abortController.signal.addEventListener("abort",pauseOnAbort,{once:true});if(abortController.signal.aborted)pauseOnAbort();try{if(!abortController.signal.aborted){await runtime.finishTurn(turn.permit)}}finally{abortController.signal.removeEventListener("abort",pauseOnAbort);await abortSettlement}},"finishGoalTurn");const budgetEnforcer=new RunBudgetEnforcer({maxWallTimeSeconds:config.getMaxWallTimeSeconds(),maxToolCalls:config.getMaxToolCalls()},abortController);const stampBudgetAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();if(!exceeded)return;endActiveInteraction("error",{errorMessage:exceeded.message,errorType:"run_budget_exceeded"})},"stampBudgetAbort");abortController.signal.addEventListener("abort",stampBudgetAbort,{once:true});budgetEnforcer.start();let abortExitCommitted=false;const markAbortExitCommitted=__name(()=>{abortExitCommitted=true},"markAbortExitCommitted");const routeAbort=__name(async()=>{const exceeded=budgetEnforcer.getExceeded();endActiveInteraction(exceeded?"error":"cancelled",{...exceeded?{errorMessage:exceeded.message,errorType:"run_budget_exceeded"}:{}});await failClosedActiveGoalTurn(exceeded?.message??"Headless Goal execution was cancelled",exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT);await settleBeforeTerminalOutput();if(exceeded){await handleBudgetExceededError(config,exceeded,markAbortExitCommitted);throw new Error(exceeded.message)}const reason=abortController.signal.reason;if(reason instanceof TurnInterruptedError&&(options.recoverableCancellation===true||reason instanceof ModTurnAbortedError)){throw reason}await handleCancellationError(config,markAbortExitCommitted);throw new Error("Operation cancelled.")},"routeAbort");const localQueue=[];const pullModPrompts=__name(()=>{for(let prompt=modSession?.takeSubmittedPrompt();prompt;prompt=modSession?.takeSubmittedPrompt())localQueue.push({displayText:prompt.text,modelText:frameModPrompt(prompt),sendMessageType:"userQuery",modPrompt:prompt})},"pullModPrompts");const sdkOnlyMonitorQueue=[];const isCancelledMonitorEvent=__name(item=>Boolean(item.monitorId&&item.sdkNotification?.status==="running"&&config.getMonitorRegistry().get(item.monitorId)?.status==="cancelled"),"isCancelledMonitorEvent");const emitNotificationToSdk=__name(item=>{if(item.sendMessageType!=="notification")return;adapter.emitUserMessage([{text:item.displayText}]);if(item.sdkNotification){adapter.emitSystemMessage("task_notification",item.sdkNotification)}},"emitNotificationToSdk");const emitModPromptToSdk=__name(prompt=>{adapter.emitUserMessage([{text:prompt.text}]);adapter.emitSystemMessage("mod_prompt",{mod:prompt.plugin})},"emitModPromptToSdk");const flushQueuedNotificationsToSdk=__name(queue=>{while(queue.length>0){const item=queue.shift();if(!isCancelledMonitorEvent(item)){emitNotificationToSdk(item)}}},"flushQueuedNotificationsToSdk");let captureMonitorTurnsInLocalQueue=true;let oneShotMonitorsFinalized=false;const finalizeOneShotMonitors=__name(()=>{if(options.captureMonitorNotifications===false||oneShotMonitorsFinalized)return;oneShotMonitorsFinalized=true;captureMonitorTurnsInLocalQueue=false;config.getMonitorRegistry().abortAll();flushQueuedNotificationsToSdk(sdkOnlyMonitorQueue)},"finalizeOneShotMonitors");let pipeBroken=false;let workflowApprovalChannelRegistered=false;const stdoutErrorHandler=__name(err=>{if(err.code==="EPIPE"&&!pipeBroken){pipeBroken=true;process.stdout.destroy()}},"stdoutErrorHandler");const shutdownHandler=__name(()=>{debugLogger2.debug("[runNonInteractive] Shutdown signal received");abortController.abort()},"shutdownHandler");const pendingTeammateMessages=[];let boundManager=null;let approvalListener=null;const detachFromManager=__name(m=>{m.setLeaderMessageCallback(null);if(approvalListener){m.getEventEmitter().off("teammate_approval_request",approvalListener);approvalListener=null}},"detachFromManager");const onTeamManagerChangeHandler=__name(manager=>{if(boundManager&&boundManager!==manager){detachFromManager(boundManager)}boundManager=manager;if(manager){manager.setLeaderMessageCallback(formatted=>{pendingTeammateMessages.push(formatted)});if(options.controlService){approvalListener=__name(event=>{options.controlService.permission.handleTeammateApproval(event).catch(err=>{debugLogger2.warn("Teammate approval handling failed:",err)})},"approvalListener")}else{approvalListener=__name(event=>{const mode=config.getApprovalMode();const confirmationDetails=event.confirmationDetails;const requiresExplicitHostApproval=confirmationDetails?.type!=="plan"&&confirmationDetails!==void 0&&"hideAlwaysAllow"in confirmationDetails&&confirmationDetails.hideAlwaysAllow===true;if(mode==="yolo"&&!requiresExplicitHostApproval){event.respond("proceed_once").catch(err=>{debugLogger2.warn("Teammate approval ProceedOnce failed:",err)});return}const reason=requiresExplicitHostApproval?mode==="yolo"?`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface and cannot be bypassed by YOLO mode.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface, which is unavailable in non-stream-json mode with the current approval mode (${mode}). Use --input-format stream-json --output-format stream-json to review it.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": current approval mode (${mode}) cannot prompt in non-stream-json mode. Use --yolo or stream-json to allow teammate tool calls.`;process.stderr.write(`[team] ${reason}
|
|
5
5
|
`);pendingTeammateMessages.push(`<team_notice>
|
|
6
6
|
${reason}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{appEvents}from"./chunk-
|
|
3
|
+
import{appEvents}from"./chunk-FXANOHXI.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-SHKSVOTG.js";import{getMCPServerStatus}from"./chunk-MJEL7DIE.js";import{require_fast_deep_equal}from"./chunk-7LLG2W7I.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{createDaemonStatusProvider}from"./chunk-
|
|
3
|
+
import{createDaemonStatusProvider}from"./chunk-FRADUGRC.js";import"./chunk-RKFNQQNA.js";import"./chunk-MQWKOOSR.js";import"./chunk-YBIENZ5E.js";import"./chunk-EXVVGGII.js";import"./chunk-L42NTHIT.js";import"./chunk-JDHMSERR.js";import"./chunk-OFWAMIMB.js";import"./chunk-IFPLGH5C.js";import"./chunk-QDSIJTQB.js";import"./chunk-3Y4UVTLL.js";import"./chunk-2QYDBHYZ.js";import"./chunk-YCAEGUZI.js";import"./chunk-BVUZGX6E.js";import"./chunk-CVMEBFLL.js";import"./chunk-L5UULTGF.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-7JDZEB77.js";import"./chunk-3MBYQYPC.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-D3YOXHQF.js";import"./chunk-6KMPLONS.js";import"./chunk-TV5T4EZP.js";import"./chunk-MD3ZEOBX.js";import"./chunk-YLTVHXPO.js";import"./chunk-QPYXXB22.js";import"./chunk-DVN6DAWO.js";import"./chunk-46VUDNCL.js";import"./chunk-UNDRWCST.js";import"./chunk-KK6SQPYG.js";import"./chunk-TWJ4XBED.js";import"./chunk-4WYKHP7Q.js";import"./chunk-UNJYVYTC.js";import"./chunk-MUNBJIEX.js";import"./chunk-54CHQYA3.js";import"./chunk-4WMR7RZB.js";import"./chunk-HSN5QUS7.js";import"./chunk-KMAE5NUB.js";import"./chunk-ZOWMHZWO.js";import"./chunk-XWYUQMLN.js";import"./chunk-RKDS7A4H.js";import"./chunk-W6IOHGWW.js";import"./chunk-SXO35MFJ.js";import"./chunk-UGDAT4C4.js";import"./chunk-DECUAM3U.js";import"./chunk-MSAAQ2I7.js";import"./chunk-YU67VCCO.js";import"./chunk-PFKTTUGS.js";import"./chunk-R2EHHA2C.js";import"./chunk-MSIXO7NT.js";import"./chunk-ZIXAINJY.js";import"./chunk-HMCTSPVJ.js";import"./chunk-PHIPLV2I.js";import"./chunk-HW7ZRPZU.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-KZSUHQLD.js";import"./chunk-BTHQHTOB.js";import"./chunk-QVPT37XZ.js";import"./chunk-B5ZFH363.js";import"./chunk-DXUYBMFK.js";import"./chunk-BWTFZBMG.js";import"./chunk-HA7ADBWO.js";import"./chunk-I44IFX3I.js";import"./chunk-PSKT6KWO.js";import"./chunk-UJSVTVKB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-DNYXZVBT.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-NVXFGZ4Z.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-7Z2ZH5CW.js";import"./chunk-PNF77EBK.js";import"./chunk-YSZPZI2U.js";import"./chunk-QTJPOTU5.js";import"./chunk-G5PYYZMM.js";import"./chunk-TASTRW4D.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-IUVB7EIZ.js";import"./chunk-2BASBY3Z.js";import"./chunk-KYK53GFP.js";import"./chunk-T5XGTSQU.js";import"./chunk-JIQVUYBI.js";import"./chunk-THN4FBQ7.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-AV674UXZ.js";import"./chunk-KVSDMMDD.js";import"./chunk-744VRMDB.js";import"./chunk-EW3EVEYN.js";import"./chunk-IC42HQCH.js";import"./chunk-7UK4WJWS.js";import"./chunk-YIW3H46P.js";import"./chunk-6EDEOERB.js";import"./chunk-OV2J3OED.js";import"./chunk-AIGBQN6R.js";import"./chunk-4GNHXVJZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-NCBA52SB.js";import"./chunk-QTCO5I4C.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import"./chunk-C6KSOOGV.js";import"./chunk-2W7KMUTJ.js";import"./chunk-33P4RB6G.js";import"./chunk-RQHIWFQL.js";import"./chunk-BSFNCIBS.js";import"./chunk-DLFX4M6C.js";import"./chunk-VFB6Q74I.js";import"./chunk-NSZJIBK7.js";import"./chunk-PWRX5WNL.js";import"./chunk-3MG44MZK.js";import"./chunk-476F6QIM.js";import"./chunk-W2ZVZ6LS.js";import"./chunk-KP77CL5U.js";import"./chunk-AGEDDL7Z.js";import"./chunk-MJEL7DIE.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-FCQWRGW5.js";import"./chunk-6JHMYZNS.js";import"./chunk-Z6AR5XE5.js";import"./chunk-JWTMTDHE.js";import"./chunk-6QJWBGMS.js";import"./chunk-5PWKCDV6.js";import"./chunk-2GF3E5MI.js";import"./chunk-GJPZ5CKS.js";import"./chunk-UEWEDD5Y.js";import"./chunk-AJ75BPTA.js";import"./chunk-IDHSLPPU.js";import"./chunk-AIAYQAPA.js";import"./chunk-EV2CXPMN.js";import"./chunk-E5XJBLSO.js";import"./chunk-4ZBZL23U.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-BODSGVSR.js";import"./chunk-XMANRGPK.js";import"./chunk-JJAEIBSV.js";import"./chunk-KQX4H2D3.js";import"./chunk-BIOVWBME.js";import"./chunk-SW54YEPK.js";import"./chunk-7DOOXUDG.js";import"./chunk-RP57XAJ2.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import"./chunk-DBRQGEEI.js";import"./chunk-DMM5LJWL.js";import"./chunk-ZQMVXHGH.js";import"./chunk-4WFJ5OPA.js";import"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import"./chunk-JOJLS3IB.js";import"./chunk-D6CEQ2GY.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-H7OS7XH3.js";import"./chunk-7LLG2W7I.js";import"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{createDaemonStatusProvider};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
3
|
import{RUNTIME_STARTUP_CANCELLED_MESSAGE}from"./chunk-UKMS3RLB.js";import{getHeadlessYoloSafetyWarning}from"./chunk-Z57KDB5F.js";import{MAX_COMPACTED_REPLAY_MAX_BYTES,normalizeMaxRingBytes}from"./chunk-OFWAMIMB.js";import{isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{InvalidExecutionSandboxConfigError,assertExecutionSandboxSupported}from"./chunk-EKRCICRK.js";import"./chunk-ERGT5BD3.js";import{normalizeServeFastPathArgv}from"./chunk-X7QN6R6K.js";import"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var HELP_AND_VERSION_FLAGS=new Set(["--help","-h","--version","-v"]);var MCP_BUDGET_WARN_FRACTION=.75;var NUMBER_OPTIONS=new Map([["port","port"],["maxSessions","max-sessions"],["maxTotalSessions","max-total-sessions"],["maxPendingPromptsPerSession","max-pending-prompts-per-session"],["maxConnections","max-connections"],["eventRingSize","event-ring-size"],["eventRingMaxBytes","event-ring-max-bytes"],["compactedReplayMaxBytes","compacted-replay-max-bytes"],["maxJournalEvents","max-journal-events"],["maxJournalBytes","max-journal-bytes"],["mcp-client-budget","mcp-client-budget"],["memoryBudgetMb","memory-budget-mb"],["promptDeadlineMs","prompt-deadline-ms"],["writerIdleTimeoutMs","writer-idle-timeout-ms"],["channelIdleTimeoutMs","channel-idle-timeout-ms"],["initializeTimeoutMs","initialize-timeout-ms"],["sessionRestoreTimeoutMs","session-restore-timeout-ms"],["sessionReapIntervalMs","session-reap-interval-ms"],["sessionIdleTimeoutMs","session-idle-timeout-ms"],["sessionPromptSettledCloseGraceMs","session-prompt-settled-close-grace-ms"],["permissionResponseTimeoutMs","permission-response-timeout-ms"],["rateLimitPrompt","rate-limit-prompt"],["rateLimitMutation","rate-limit-mutation"],["rateLimitRead","rate-limit-read"],["rateLimitWindowMs","rate-limit-window-ms"]]);var NUMBER_OPTION_BY_FLAG=invertOptionMap(NUMBER_OPTIONS);var STRING_OPTION_BY_FLAG=new Map([["hostname","hostname"],["token","token"],["workspace","workspace"],["conversations-dir","conversationsDir"],["memory-project-scope","memoryProjectScope"],["tls-cert","tlsCert"],["tls-key","tlsKey"]]);var BOOLEAN_OPTION_BY_FLAG=new Map([["require-auth","requireAuth"],["enable-session-shell","enableSessionShell"],["web","serveWebShell"],["open","open"],["open-with-auth","open-with-auth"],["token-qr","tokenQr"],["http-bridge","http-bridge"],["allow-private-auth-base-url","allowPrivateAuthBaseUrl"],["experimental-lsp","experimentalLsp"],["restore-ask-user-question","restoreAskUserQuestion"],["rate-limit","rateLimit"]]);function invertOptionMap(source){const out=new Map;for(const[target,flag]of source){out.set(flag,target)}return out}__name(invertOptionMap,"invertOptionMap");function readOptionValue(argv,index,inlineValue){if(inlineValue!==void 0){return{value:inlineValue,nextIndex:index}}const value=argv[index+1];if(value===void 0||value.startsWith("-")){return null}return{value,nextIndex:index+1}}__name(readOptionValue,"readOptionValue");function parseNumber(value){if(value.trim()==="")return null;const parsed=Number(value);return Number.isNaN(parsed)?null:parsed}__name(parseNumber,"parseNumber");function parseBooleanValue(value){if(value==="true")return true;if(value==="false")return false;return null}__name(parseBooleanValue,"parseBooleanValue");function parsePositiveIntegerEnv(raw){if(raw===void 0||raw==="")return void 0;const trimmed=raw?.trim();if(!trimmed||!/^\d+$/.test(trimmed))return Number.NaN;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)&&parsed>0?parsed:Number.NaN}__name(parsePositiveIntegerEnv,"parsePositiveIntegerEnv");function isTruthyEnv(value){return value==="1"||value==="true"}__name(isTruthyEnv,"isTruthyEnv");function writeStderrLine(line){process.stderr.write(line.endsWith("\n")?line:`${line}
|
|
4
|
-
`)}__name(writeStderrLine,"writeStderrLine");function setServeOption(options,key,value){options[key]=value}__name(setServeOption,"setServeOption");function getRateLimitValidationError(options){for(const[name,value]of[["--rate-limit-prompt",options.rateLimitPrompt],["--rate-limit-mutation",options.rateLimitMutation],["--rate-limit-read",options.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){return`qwen serve: ${name} must be a positive integer.`}}if(options.rateLimitWindowMs!==void 0&&(!Number.isFinite(options.rateLimitWindowMs)||!Number.isInteger(options.rateLimitWindowMs)||options.rateLimitWindowMs<1e3)){return"qwen serve: --rate-limit-window-ms must be an integer >= 1000."}return null}__name(getRateLimitValidationError,"getRateLimitValidationError");function getServeFastPathValidationError(parsed){const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0&&(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0)){return"qwen serve: --mcp-client-budget must be a positive integer."}if(parsed.options.mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){return"qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."}const maxPendingPromptsPerSession=parsed.options.maxPendingPromptsPerSession;if(maxPendingPromptsPerSession!==void 0&&maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){return"qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."}try{normalizeMaxRingBytes(parsed.options.eventRingMaxBytes)}catch(error){return`qwen serve: ${error instanceof Error?error.message:String(error)}`}const compactedReplayMaxBytes=parsed.options.compactedReplayMaxBytes;if(compactedReplayMaxBytes!==void 0&&(!Number.isSafeInteger(compactedReplayMaxBytes)||compactedReplayMaxBytes<1||compactedReplayMaxBytes>MAX_COMPACTED_REPLAY_MAX_BYTES)){return`qwen serve: --compacted-replay-max-bytes must be a positive safe integer in [1, ${MAX_COMPACTED_REPLAY_MAX_BYTES}].`}const maxJournalEvents=parsed.options.maxJournalEvents;if(maxJournalEvents!==void 0&&(!Number.isSafeInteger(maxJournalEvents)||maxJournalEvents<1)){return"qwen serve: --max-journal-events must be a positive safe integer."}const maxJournalBytes=parsed.options.maxJournalBytes;if(maxJournalBytes!==void 0&&(!Number.isSafeInteger(maxJournalBytes)||maxJournalBytes<1)){return"qwen serve: --max-journal-bytes must be a positive safe integer."}const memoryBudgetMb=parsed.options.memoryBudgetMb;if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){return memoryBudgetRangeError()}return null}__name(getServeFastPathValidationError,"getServeFastPathValidationError");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");async function waitForServeRuntimeOrExit(handle){try{await handle.runtimeReady}catch(err){if(err instanceof Error&&err.message===RUNTIME_STARTUP_CANCELLED_MESSAGE){return}writeStderrLine(`qwen serve: runtime startup failed after listener was ready: ${err instanceof Error?err.message:String(err)}`);await handle.close().catch(()=>void 0);process.exit(1)}}__name(waitForServeRuntimeOrExit,"waitForServeRuntimeOrExit");function applyRateLimitEnvDefaults(options,env){if(options.rateLimit===void 0&&isTruthyEnv(env["QWEN_SERVE_RATE_LIMIT"])){options.rateLimit=true}if(options.rateLimit){options.rateLimitPrompt??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_PROMPT"]);options.rateLimitMutation??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_MUTATION"]);options.rateLimitRead??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_READ"]);options.rateLimitWindowMs??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_WINDOW_MS"])}}__name(applyRateLimitEnvDefaults,"applyRateLimitEnvDefaults");function discardRateLimitTuningWhenDisabled(options){if(options.rateLimit===true)return;delete options.rateLimitPrompt;delete options.rateLimitMutation;delete options.rateLimitRead;delete options.rateLimitWindowMs}__name(discardRateLimitTuningWhenDisabled,"discardRateLimitTuningWhenDisabled");async function bootstrapServeFastPathEnvironment(workspace){const{loadServeFastPathEnvironment,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}=await import("./fast-path-settings-QGSXJF45.js");preResolveServeFastPathHomeEnvOverrides();const workspaceDir=workspace??process.cwd();const settings=loadServeFastPathSettings(workspaceDir);loadServeFastPathEnvironment(settings,workspaceDir);return settings}__name(bootstrapServeFastPathEnvironment,"bootstrapServeFastPathEnvironment");function parseServeFastPathArgs(rawArgv,env=process.env){const argv=normalizeServeFastPathArgv(rawArgv);if(argv[0]!=="serve")return{kind:"fallback"};if(argv.some(arg=>HELP_AND_VERSION_FLAGS.has(arg))){return{kind:"fallback"}}const options={hostname:"127.0.0.1",mode:"http-bridge",port:4170};let open=false;let openWithAuth=false;let httpBridge=true;let mcpBudgetModeRaw;let mcpClientBudget;let explicitRateLimit;for(let i=1;i<argv.length;i++){const arg=argv[i];if(arg==="--")return{kind:"fallback"};if(!arg.startsWith("--"))return{kind:"fallback"};const withoutPrefix=arg.slice(2);const equalsIndex=withoutPrefix.indexOf("=");const rawFlag=equalsIndex===-1?withoutPrefix:withoutPrefix.slice(0,equalsIndex);const inlineValue=equalsIndex===-1?void 0:withoutPrefix.slice(equalsIndex+1);const negated=rawFlag.startsWith("no-");const flag=negated?rawFlag.slice(3):rawFlag;const booleanTarget=BOOLEAN_OPTION_BY_FLAG.get(flag);if(booleanTarget){let value=!negated;if(inlineValue!==void 0){const parsed=parseBooleanValue(inlineValue);if(parsed===null||negated)return{kind:"fallback"};value=parsed}if(booleanTarget==="open"){open=value}else if(booleanTarget==="open-with-auth"){openWithAuth=value}else if(booleanTarget==="http-bridge"){httpBridge=value}else{setServeOption(options,booleanTarget,value);if(booleanTarget==="rateLimit"){explicitRateLimit=value}}continue}if(negated)return{kind:"fallback"};const numberTarget=NUMBER_OPTION_BY_FLAG.get(flag);if(numberTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;const value=parseNumber(read.value);if(value===null)return{kind:"fallback"};if(numberTarget==="mcp-client-budget"){mcpClientBudget=value}else{setServeOption(options,numberTarget,value)}continue}const stringTarget=STRING_OPTION_BY_FLAG.get(flag);if(stringTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if((stringTarget==="workspace"||stringTarget==="conversationsDir")&&(options[stringTarget]!==void 0||read.value==="")){return{kind:"fallback"}}setServeOption(options,stringTarget,read.value);continue}if(flag==="memory-pressure-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"){return{kind:"fallback"}}options.memoryPressureMode=read.value;continue}if(flag==="child-heap-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"&&read.value!=="admit"&&read.value!=="enforce"){return{kind:"fallback"}}options.childHeapMode=read.value;continue}if(flag==="mcp-budget-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;mcpBudgetModeRaw=read.value;continue}if(flag==="allow-origin"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;options.allowOrigins=[...options.allowOrigins??[],read.value];continue}return{kind:"fallback"}}if(mcpBudgetModeRaw!==void 0&&mcpBudgetModeRaw!=="enforce"&&mcpBudgetModeRaw!=="warn"&&mcpBudgetModeRaw!=="off"){return{kind:"fallback"}}if(options.memoryProjectScope!==void 0&&options.memoryProjectScope!=="git-root"&&options.memoryProjectScope!=="workspace"){return{kind:"fallback"}}const mcpBudgetMode=mcpBudgetModeRaw??(mcpClientBudget!==void 0?"warn":"off");if(mcpClientBudget!==void 0)options.mcpClientBudget=mcpClientBudget;options.mcpBudgetMode=mcpBudgetMode;if(explicitRateLimit!==void 0){options.rateLimit=explicitRateLimit}applyRateLimitEnvDefaults(options,env);return{kind:"serve",open:open||openWithAuth,openWithAuth,httpBridge,options}}__name(parseServeFastPathArgs,"parseServeFastPathArgs");async function maybeOpenWebShellBrowser(handle,open,openWithAuth){if(!open)return;try{await handle.runtimeReady}catch{return}const{maybeOpenWebShellBrowser:openBrowser}=await import("./serve-RHO7RZ45.js");await openBrowser(handle,true,openWithAuth)}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function emitHeadlessYoloWarning(settings){if(!settings)return;const warning=getHeadlessYoloSafetyWarning({getApprovalMode:__name(()=>settings.tools?.approvalMode,"getApprovalMode"),getSandbox:__name(()=>settings.tools?.sandbox,"getSandbox"),getShellExecutionSandbox:__name(()=>settings.tools?.executionSandbox,"getShellExecutionSandbox")});if(warning){writeStderrLine(warning)}}__name(emitHeadlessYoloWarning,"emitHeadlessYoloWarning");function writeServeWarnings(parsed){if(!parsed.httpBridge){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(parsed.options.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0){const resolvedMcpMode=parsed.options.mcpBudgetMode??"warn";writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}}__name(writeServeWarnings,"writeServeWarnings");async function tryRunServeFastPath(rawArgv=process.argv.slice(2)){const parsed=parseServeFastPathArgs(rawArgv);if(parsed.kind==="fallback")return false;const validationError=getServeFastPathValidationError(parsed)||(parsed.options.rateLimit===true?getRateLimitValidationError(parsed.options):null);if(validationError){writeStderrLine(validationError);process.exit(1)}let settings;try{settings=await bootstrapServeFastPathEnvironment(parsed.options.workspace)}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: fast-path bootstrap failed, falling back to full startup: ${err instanceof Error?err.message:String(err)}`);return false}assertExecutionSandboxSupported(settings??{},"serve / ACP / web terminals");applyRateLimitEnvDefaults(parsed.options,process.env);discardRateLimitTuningWhenDisabled(parsed.options);const rateLimitError=getRateLimitValidationError(parsed.options);if(rateLimitError){writeStderrLine(rateLimitError);process.exit(1)}writeServeWarnings(parsed);if(parsed.openWithAuth){try{const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(parsed.options)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}}const{runQwenServe}=await import("./run-qwen-serve-77UZS4JA.js");let handle;try{handle=await runQwenServe(parsed.options,{updateRestartArgv:rawArgv,...settings?{bootSettings:settings}:{},resolveOnListen:true,deferRuntimeUntilFirstHealth:!parsed.open});try{emitHeadlessYoloWarning(settings)}catch{}await maybeOpenWebShellBrowser(handle,parsed.open,parsed.openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await waitForServeRuntimeOrExit(handle);await blockForever();return true}__name(tryRunServeFastPath,"tryRunServeFastPath");export{bootstrapServeFastPathEnvironment,parseServeFastPathArgs,tryRunServeFastPath,waitForServeRuntimeOrExit};
|
|
4
|
+
`)}__name(writeStderrLine,"writeStderrLine");function setServeOption(options,key,value){options[key]=value}__name(setServeOption,"setServeOption");function getRateLimitValidationError(options){for(const[name,value]of[["--rate-limit-prompt",options.rateLimitPrompt],["--rate-limit-mutation",options.rateLimitMutation],["--rate-limit-read",options.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){return`qwen serve: ${name} must be a positive integer.`}}if(options.rateLimitWindowMs!==void 0&&(!Number.isFinite(options.rateLimitWindowMs)||!Number.isInteger(options.rateLimitWindowMs)||options.rateLimitWindowMs<1e3)){return"qwen serve: --rate-limit-window-ms must be an integer >= 1000."}return null}__name(getRateLimitValidationError,"getRateLimitValidationError");function getServeFastPathValidationError(parsed){const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0&&(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0)){return"qwen serve: --mcp-client-budget must be a positive integer."}if(parsed.options.mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){return"qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."}const maxPendingPromptsPerSession=parsed.options.maxPendingPromptsPerSession;if(maxPendingPromptsPerSession!==void 0&&maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){return"qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."}try{normalizeMaxRingBytes(parsed.options.eventRingMaxBytes)}catch(error){return`qwen serve: ${error instanceof Error?error.message:String(error)}`}const compactedReplayMaxBytes=parsed.options.compactedReplayMaxBytes;if(compactedReplayMaxBytes!==void 0&&(!Number.isSafeInteger(compactedReplayMaxBytes)||compactedReplayMaxBytes<1||compactedReplayMaxBytes>MAX_COMPACTED_REPLAY_MAX_BYTES)){return`qwen serve: --compacted-replay-max-bytes must be a positive safe integer in [1, ${MAX_COMPACTED_REPLAY_MAX_BYTES}].`}const maxJournalEvents=parsed.options.maxJournalEvents;if(maxJournalEvents!==void 0&&(!Number.isSafeInteger(maxJournalEvents)||maxJournalEvents<1)){return"qwen serve: --max-journal-events must be a positive safe integer."}const maxJournalBytes=parsed.options.maxJournalBytes;if(maxJournalBytes!==void 0&&(!Number.isSafeInteger(maxJournalBytes)||maxJournalBytes<1)){return"qwen serve: --max-journal-bytes must be a positive safe integer."}const memoryBudgetMb=parsed.options.memoryBudgetMb;if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){return memoryBudgetRangeError()}return null}__name(getServeFastPathValidationError,"getServeFastPathValidationError");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");async function waitForServeRuntimeOrExit(handle){try{await handle.runtimeReady}catch(err){if(err instanceof Error&&err.message===RUNTIME_STARTUP_CANCELLED_MESSAGE){return}writeStderrLine(`qwen serve: runtime startup failed after listener was ready: ${err instanceof Error?err.message:String(err)}`);await handle.close().catch(()=>void 0);process.exit(1)}}__name(waitForServeRuntimeOrExit,"waitForServeRuntimeOrExit");function applyRateLimitEnvDefaults(options,env){if(options.rateLimit===void 0&&isTruthyEnv(env["QWEN_SERVE_RATE_LIMIT"])){options.rateLimit=true}if(options.rateLimit){options.rateLimitPrompt??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_PROMPT"]);options.rateLimitMutation??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_MUTATION"]);options.rateLimitRead??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_READ"]);options.rateLimitWindowMs??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_WINDOW_MS"])}}__name(applyRateLimitEnvDefaults,"applyRateLimitEnvDefaults");function discardRateLimitTuningWhenDisabled(options){if(options.rateLimit===true)return;delete options.rateLimitPrompt;delete options.rateLimitMutation;delete options.rateLimitRead;delete options.rateLimitWindowMs}__name(discardRateLimitTuningWhenDisabled,"discardRateLimitTuningWhenDisabled");async function bootstrapServeFastPathEnvironment(workspace){const{loadServeFastPathEnvironment,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}=await import("./fast-path-settings-QGSXJF45.js");preResolveServeFastPathHomeEnvOverrides();const workspaceDir=workspace??process.cwd();const settings=loadServeFastPathSettings(workspaceDir);loadServeFastPathEnvironment(settings,workspaceDir);return settings}__name(bootstrapServeFastPathEnvironment,"bootstrapServeFastPathEnvironment");function parseServeFastPathArgs(rawArgv,env=process.env){const argv=normalizeServeFastPathArgv(rawArgv);if(argv[0]!=="serve")return{kind:"fallback"};if(argv.some(arg=>HELP_AND_VERSION_FLAGS.has(arg))){return{kind:"fallback"}}const options={hostname:"127.0.0.1",mode:"http-bridge",port:4170};let open=false;let openWithAuth=false;let httpBridge=true;let mcpBudgetModeRaw;let mcpClientBudget;let explicitRateLimit;for(let i=1;i<argv.length;i++){const arg=argv[i];if(arg==="--")return{kind:"fallback"};if(!arg.startsWith("--"))return{kind:"fallback"};const withoutPrefix=arg.slice(2);const equalsIndex=withoutPrefix.indexOf("=");const rawFlag=equalsIndex===-1?withoutPrefix:withoutPrefix.slice(0,equalsIndex);const inlineValue=equalsIndex===-1?void 0:withoutPrefix.slice(equalsIndex+1);const negated=rawFlag.startsWith("no-");const flag=negated?rawFlag.slice(3):rawFlag;const booleanTarget=BOOLEAN_OPTION_BY_FLAG.get(flag);if(booleanTarget){let value=!negated;if(inlineValue!==void 0){const parsed=parseBooleanValue(inlineValue);if(parsed===null||negated)return{kind:"fallback"};value=parsed}if(booleanTarget==="open"){open=value}else if(booleanTarget==="open-with-auth"){openWithAuth=value}else if(booleanTarget==="http-bridge"){httpBridge=value}else{setServeOption(options,booleanTarget,value);if(booleanTarget==="rateLimit"){explicitRateLimit=value}}continue}if(negated)return{kind:"fallback"};const numberTarget=NUMBER_OPTION_BY_FLAG.get(flag);if(numberTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;const value=parseNumber(read.value);if(value===null)return{kind:"fallback"};if(numberTarget==="mcp-client-budget"){mcpClientBudget=value}else{setServeOption(options,numberTarget,value)}continue}const stringTarget=STRING_OPTION_BY_FLAG.get(flag);if(stringTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if((stringTarget==="workspace"||stringTarget==="conversationsDir")&&(options[stringTarget]!==void 0||read.value==="")){return{kind:"fallback"}}setServeOption(options,stringTarget,read.value);continue}if(flag==="memory-pressure-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"){return{kind:"fallback"}}options.memoryPressureMode=read.value;continue}if(flag==="child-heap-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"&&read.value!=="admit"&&read.value!=="enforce"){return{kind:"fallback"}}options.childHeapMode=read.value;continue}if(flag==="mcp-budget-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;mcpBudgetModeRaw=read.value;continue}if(flag==="allow-origin"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;options.allowOrigins=[...options.allowOrigins??[],read.value];continue}return{kind:"fallback"}}if(mcpBudgetModeRaw!==void 0&&mcpBudgetModeRaw!=="enforce"&&mcpBudgetModeRaw!=="warn"&&mcpBudgetModeRaw!=="off"){return{kind:"fallback"}}if(options.memoryProjectScope!==void 0&&options.memoryProjectScope!=="git-root"&&options.memoryProjectScope!=="workspace"){return{kind:"fallback"}}const mcpBudgetMode=mcpBudgetModeRaw??(mcpClientBudget!==void 0?"warn":"off");if(mcpClientBudget!==void 0)options.mcpClientBudget=mcpClientBudget;options.mcpBudgetMode=mcpBudgetMode;if(explicitRateLimit!==void 0){options.rateLimit=explicitRateLimit}applyRateLimitEnvDefaults(options,env);return{kind:"serve",open:open||openWithAuth,openWithAuth,httpBridge,options}}__name(parseServeFastPathArgs,"parseServeFastPathArgs");async function maybeOpenWebShellBrowser(handle,open,openWithAuth){if(!open)return;try{await handle.runtimeReady}catch{return}const{maybeOpenWebShellBrowser:openBrowser}=await import("./serve-JCUT4WK7.js");await openBrowser(handle,true,openWithAuth)}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function emitHeadlessYoloWarning(settings){if(!settings)return;const warning=getHeadlessYoloSafetyWarning({getApprovalMode:__name(()=>settings.tools?.approvalMode,"getApprovalMode"),getSandbox:__name(()=>settings.tools?.sandbox,"getSandbox"),getShellExecutionSandbox:__name(()=>settings.tools?.executionSandbox,"getShellExecutionSandbox")});if(warning){writeStderrLine(warning)}}__name(emitHeadlessYoloWarning,"emitHeadlessYoloWarning");function writeServeWarnings(parsed){if(!parsed.httpBridge){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(parsed.options.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0){const resolvedMcpMode=parsed.options.mcpBudgetMode??"warn";writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}}__name(writeServeWarnings,"writeServeWarnings");async function tryRunServeFastPath(rawArgv=process.argv.slice(2)){const parsed=parseServeFastPathArgs(rawArgv);if(parsed.kind==="fallback")return false;const validationError=getServeFastPathValidationError(parsed)||(parsed.options.rateLimit===true?getRateLimitValidationError(parsed.options):null);if(validationError){writeStderrLine(validationError);process.exit(1)}let settings;try{settings=await bootstrapServeFastPathEnvironment(parsed.options.workspace)}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: fast-path bootstrap failed, falling back to full startup: ${err instanceof Error?err.message:String(err)}`);return false}assertExecutionSandboxSupported(settings??{},"serve / ACP / web terminals");applyRateLimitEnvDefaults(parsed.options,process.env);discardRateLimitTuningWhenDisabled(parsed.options);const rateLimitError=getRateLimitValidationError(parsed.options);if(rateLimitError){writeStderrLine(rateLimitError);process.exit(1)}writeServeWarnings(parsed);if(parsed.openWithAuth){try{const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(parsed.options)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}}const{runQwenServe}=await import("./run-qwen-serve-XRWVWOZK.js");let handle;try{handle=await runQwenServe(parsed.options,{updateRestartArgv:rawArgv,...settings?{bootSettings:settings}:{},resolveOnListen:true,deferRuntimeUntilFirstHealth:!parsed.open});try{emitHeadlessYoloWarning(settings)}catch{}await maybeOpenWebShellBrowser(handle,parsed.open,parsed.openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await waitForServeRuntimeOrExit(handle);await blockForever();return true}__name(tryRunServeFastPath,"tryRunServeFastPath");export{bootstrapServeFastPathEnvironment,parseServeFastPathArgs,tryRunServeFastPath,waitForServeRuntimeOrExit};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2025 Qwen Team
|