@code-yeongyu/senpi 2026.10.24-3 → 2026.10.24-4

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundle/chunks/{args-6T5EQVY3.js → args-JXULI4EH.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-VUKNGMDT.js → chunk-3LNSLJ7N.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-MRN6IKOQ.js → chunk-3VOG6WFU.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-GOB5BLDV.js → chunk-42OY5SZZ.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-4TRKE3ZC.js → chunk-BMYNMUVZ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-JAXZOEJE.js → chunk-BWA4FVFW.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-AGQSRWNN.js → chunk-EHQXLHRB.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-YJA2B7FQ.js → chunk-FDL4CF6F.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-DITSGW4R.js → chunk-GVJ76VQI.js} +38 -38
  11. package/dist/bundle/chunks/{chunk-HCF5M6NA.js → chunk-GXY5JEI5.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-CYG4LS4S.js → chunk-HKUXKTFW.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-AVLYZET7.js → chunk-IUHU5PEC.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-LR6Z6V54.js → chunk-NQC7MI2G.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-DYWHYQUD.js → chunk-PXKF2RHD.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-H6IG2ITJ.js → chunk-QH2HSCMX.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-CZYADQ2E.js → chunk-SGDOZT6B.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-BZ75DRZB.js → chunk-U67ML6CQ.js} +4 -2
  19. package/dist/bundle/chunks/{chunk-I5NIJZDY.js → chunk-UT6AJHPK.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-CZR7C6CY.js → chunk-VOBD6FQG.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-SGATKHO4.js → chunk-Y5OTHMXO.js} +1 -1
  22. package/dist/bundle/chunks/{cli-main-BOYWBHOB.js → cli-main-UH3MAREK.js} +1 -1
  23. package/dist/bundle/chunks/{dispatch-KQEGIXQW.js → dispatch-DEP4PEDZ.js} +3 -2
  24. package/dist/bundle/chunks/{help-fast-path-6PVN7WI5.js → help-fast-path-ZHZGXAUG.js} +1 -1
  25. package/dist/bundle/chunks/{host-command-7MAXSZIH.js → host-command-OQR4RDTM.js} +1 -1
  26. package/dist/bundle/chunks/{host-session-command-L2UTORL5.js → host-session-command-IGB27ZPJ.js} +1 -1
  27. package/dist/bundle/chunks/{interactive-mode-NVBFOE5R.js → interactive-mode-R5RCSJ2F.js} +1 -1
  28. package/dist/bundle/chunks/{list-tips-BO5RP34W.js → list-tips-CREX4IXZ.js} +1 -1
  29. package/dist/bundle/chunks/{multi-session-host-3TVASSQD.js → multi-session-host-YZEMYUFY.js} +2 -2
  30. package/dist/bundle/chunks/{package-manager-cli-5BHVDVJC.js → package-manager-cli-5FOXDKUA.js} +1 -1
  31. package/dist/bundle/chunks/{role-BHA5ROSF.js → role-M2MTVACJ.js} +1 -1
  32. package/dist/bundle/chunks/{rotation-stream-RXMCJJUL.js → rotation-stream-U7YQMC7H.js} +1 -1
  33. package/dist/bundle/chunks/{rpc-mode-LPP46I7H.js → rpc-mode-6K62CZBW.js} +1 -1
  34. package/dist/bundle/chunks/{schedule-command-QW67J57R.js → schedule-command-XBW4EOG5.js} +1 -1
  35. package/dist/bundle/chunks/{session-control-endpoint-QQBBY5AT.js → session-control-endpoint-54TMCS7Q.js} +1 -1
  36. package/dist/bundle/chunks/{session-picker-HIC5ZTE6.js → session-picker-P2VUU2MQ.js} +1 -1
  37. package/dist/bundle/chunks/session-worker.js +56 -53
  38. package/dist/bundle/cli.js +2 -2
  39. package/dist/bundle/index.js +1 -1
  40. package/dist/bundle/rpc-entry.js +1 -1
  41. package/dist/bundle/runtime-manifest.json +1 -1
  42. package/dist/cli/args.d.ts +2 -0
  43. package/dist/cli/args.js +27 -0
  44. package/dist/core/agent-session.js +1 -1
  45. package/dist/core/extensions/builtin/anthropic-subscription/index.js +4 -2
  46. package/dist/core/extensions/builtin/anthropic-subscription/options.js +2 -1
  47. package/dist/core/extensions/builtin/anthropic-subscription/sdk-boundary.js +9 -2
  48. package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.d.ts +3 -0
  49. package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.js +9 -0
  50. package/dist/core/extensions/builtin/anthropic-subscription/settings.d.ts +1 -1
  51. package/dist/core/extensions/builtin/anthropic-subscription/settings.js +3 -1
  52. package/dist/core/extensions/builtin/anthropic-subscription/stream.js +4 -1
  53. package/dist/core/extensions/builtin/btw/index.js +4 -1
  54. package/dist/core/extensions/builtin/compaction/lane-policy.js +3 -1
  55. package/dist/core/extensions/builtin/look-at/runner.js +1 -0
  56. package/dist/core/extensions/builtin/mcp/connection-types.d.ts +2 -0
  57. package/dist/core/extensions/builtin/mcp/connection.js +3 -0
  58. package/dist/core/extensions/builtin/mcp/elicitation.d.ts +5 -2
  59. package/dist/core/extensions/builtin/mcp/elicitation.js +57 -11
  60. package/dist/core/extensions/builtin/mcp/index.js +1 -1
  61. package/dist/core/extensions/builtin/mcp/modern/dispatch.js +6 -9
  62. package/dist/core/extensions/builtin/mcp/service-connection.d.ts +1 -0
  63. package/dist/core/extensions/builtin/mcp/service-connection.js +1 -0
  64. package/dist/core/extensions/builtin/mcp/service.js +1 -0
  65. package/dist/core/extensions/builtin/mcp/transport-sdk.d.ts +1 -0
  66. package/dist/core/extensions/builtin/mcp/transport-sdk.js +5 -5
  67. package/dist/core/extensions/builtin/mcp/transport.d.ts +1 -0
  68. package/dist/core/extensions/builtin/mcp/transport.js +1 -0
  69. package/dist/core/external-admission.d.ts +4 -1
  70. package/dist/core/external-admission.js +18 -2
  71. package/dist/core/lifecycle-session-binding.js +20 -0
  72. package/dist/core/sdk.js +1 -0
  73. package/dist/core/session-spawned-by.d.ts +4 -0
  74. package/dist/core/session-spawned-by.js +16 -0
  75. package/dist/main.js +7 -2
  76. package/dist/modes/rpc/session-router-open-profile.js +2 -10
  77. package/docs/usage.md +14 -0
  78. package/package.json +6 -6
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
2
  import{TOOL_CHILD_ROLE_ENV,channelEnvPresent}from"./chunk-V3CK2AVC.js";var role=process.env[TOOL_CHILD_ROLE_ENV];if(role!==void 0&&role!==""){if(role==="launch-shim"){let{runLaunchShimRole}=await import("./launch-shim-role-Q6NG2YCV.js");runLaunchShimRole()}role!=="tool-child"&&(process.stderr.write(`senpi: unknown internal role ${JSON.stringify(role)}
3
3
  `),process.exit(70)),channelEnvPresent(process.env)||(process.stderr.write(`tool-child: channel unavailable
4
- `),process.exit(70));let{runToolChildRole}=await import("./role-BHA5ROSF.js");await runToolChildRole()}
4
+ `),process.exit(70));let{runToolChildRole}=await import("./role-M2MTVACJ.js");await runToolChildRole()}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{Text}from"./chunk-YJA2B7FQ.js";import{getShellConfig}from"./chunk-JAXZOEJE.js";import{HOST_CALL_KINDS,TOOL_CHILD_LIMITS,connectChannel,isRefId}from"./chunk-V3CK2AVC.js";import{typebox_exports}from"./chunk-MIENF2YK.js";import{TOOL_CHILD_LEDGER_ENV,TOOL_CHILD_REENTRY_ENV,TOOL_CHILD_REFS_ROOT_ENV,rememberToolChildReentry,scrubToolChildEnv,toolChildReentry}from"./chunk-OXNWERO4.js";import{BACKGROUND_START_GRACE_MS,DEFAULT_COLS,DEFAULT_MAX_SESSIONS,DEFAULT_ROWS,FOREGROUND_ENV_OVERRIDES,KILLED_SESSION_EXIT_GRACE_MS,TERMINAL_BASH_TOOL,TERMINAL_INPUT_TOOL,TERMINAL_KILL_TOOL,TERMINAL_OUTPUT_TOOL,TERMINAL_RESIZE_TOOL,encodeKeys,loadPty,safeRegExp}from"./chunk-NTK2MHJ5.js";import{processIsLive,processStartTimeMs,readProcessStartTime,sameProcessStartMs}from"./chunk-7ASLQ243.js";var ToolChildJobError=class extends Error{constructor(code,message){super(message),this.code=code,this.name="ToolChildJobError"}};var WakeAdmissionError=class extends Error{constructor(bytes){super(`wake_too_large: ${bytes} bytes exceeds the ${TOOL_CHILD_LIMITS.wakePendingBytes}-byte pending budget`),this.code="wake_too_large",this.name="WakeAdmissionError"}},WakeAdmission=class{#pending=new Map;#blocked=[];#pendingBytes=0;get pending(){return this.#pending.size}get blocked(){return this.#blocked.length}send(wakeId,bytes){return bytes>TOOL_CHILD_LIMITS.wakePendingBytes?Promise.reject(new WakeAdmissionError(bytes)):this.#blocked.length===0&&this.#fits(bytes)?(this.#admit(wakeId,bytes),Promise.resolve()):new Promise(release=>{this.#blocked.push({wakeId,bytes,release})})}ack(wakeId){let bytes=this.#pending.get(wakeId);if(bytes!==void 0){this.#pending.delete(wakeId),this.#pendingBytes-=bytes;for(let next=this.#blocked[0];next!==void 0&&this.#fits(next.bytes);next=this.#blocked[0])this.#blocked.shift(),this.#admit(next.wakeId,next.bytes),next.release()}}#fits(bytes){return this.#pending.size<TOOL_CHILD_LIMITS.wakePending&&this.#pendingBytes+bytes<=TOOL_CHILD_LIMITS.wakePendingBytes}#admit(wakeId,bytes){this.#pending.set(wakeId,bytes),this.#pendingBytes+=bytes}};function hostCallCapacity(){return TOOL_CHILD_LIMITS.HOST_CALL_ACTIVE+TOOL_CHILD_LIMITS.HOST_CALL_WAITING}var HostCallAdmission=class{#active=new Set;#waiting=[];get active(){return this.#active.size}get waiting(){return this.#waiting.length}submit(callId){return this.#active.has(callId)||this.#waiting.includes(callId)?refuse(callId,"host_call_duplicate"):this.#active.size<TOOL_CHILD_LIMITS.HOST_CALL_ACTIVE&&this.#waiting.length===0?(this.#active.add(callId),{state:"active"}):this.#active.size+this.#waiting.length>=hostCallCapacity()?refuse(callId,"host_call_capacity"):(this.#waiting.push(callId),{state:"waiting"})}settle(callId){if(!this.#active.delete(callId)){let index=this.#waiting.indexOf(callId);index>=0&&this.#waiting.splice(index,1);return}let next=this.#waiting.shift();return next!==void 0&&this.#active.add(next),next}};function refuse(callId,code){return{state:"refused",frame:{type:"host_call_refused",callId,code}}}import{createHash,randomBytes}from"node:crypto";import{createReadStream}from"node:fs";import{mkdir,readFile,rm as rm2,stat,writeFile}from"node:fs/promises";import{dirname}from"node:path";import{readdir,rm}from"node:fs/promises";import{join}from"node:path";function refGenerationDir(root,generation){return join(root,`gen-${generation}`)}function refFilePath(root,ref){if(!isRefId(ref.refId))throw new Error(`invalid ref id: ${JSON.stringify(ref.refId)}`);return join(refGenerationDir(root,ref.generation),"refs",ref.refId)}async function teardownRefGeneration(root,generation){await rm(refGenerationDir(root,generation),{recursive:!0,force:!0})}var PayloadRefError=class extends Error{constructor(code,message,reason){super(`${code}: ${message}`),this.name="PayloadRefError",this.code=code,this.reason=reason}},PayloadRefWriter=class{#root;#now;#pending=new Map;#ownedBytes=0;constructor(options){this.generation=options.generation,this.budget=options.budget??TOOL_CHILD_LIMITS.refsBudget,this.#root=options.root,this.#now=options.now??Date.now}get ownedBytes(){return this.#ownedBytes}async create(payload){let size=payload.byteLength;if(this.#ownedBytes+size>this.budget)throw new PayloadRefError("ref_budget_exceeded",`${size} bytes on top of ${this.#ownedBytes} owned exceeds ${this.budget}`);this.#ownedBytes+=size;let ref={refId:randomBytes(12).toString("hex"),generation:this.generation,bytes:size,sha256:createHash("sha256").update(payload).digest("hex")},path=refFilePath(this.#root,ref);try{await mkdir(dirname(path),{recursive:!0,mode:448}),await writeFile(path,payload,{flag:"wx",mode:384})}catch(error){throw this.#ownedBytes-=size,await rm2(path,{force:!0}),error}return this.#pending.set(ref.refId,{bytes:size,createdAtMs:this.#now()}),ref}async handle(control){let pending=this.#pending.get(control.refId);pending!==void 0&&(this.#pending.delete(control.refId),this.#ownedBytes-=pending.bytes,control.type==="ref_nack"&&await rm2(refFilePath(this.#root,{refId:control.refId,generation:this.generation}),{force:!0}))}pendingIds(){return[...this.#pending.keys()]}overdue(){let deadline=this.#now()-TOOL_CHILD_LIMITS.refAckMs;return[...this.#pending].filter(([,ref])=>ref.createdAtMs<=deadline).map(([refId])=>refId)}async teardown(){this.#pending.clear(),this.#ownedBytes=0,await teardownRefGeneration(this.#root,this.generation)}},isMissingFile=error=>error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR");async function hashFile(path,signal){let hash=createHash("sha256");for await(let chunk of createReadStream(path)){if(signal?.aborted)return"cancelled";hash.update(chunk)}return hash.digest("hex")}var PayloadRefReader=class{#root;#generation;#budget;#send;#owned=new Map;#ownedBytes=0;constructor(options){this.#root=options.root,this.#generation=options.generation,this.#budget=options.budget??TOOL_CHILD_LIMITS.refsBudget,this.#send=options.send}async accept(ref,signal){let reason=await this.#verify(ref,signal);return reason!==void 0?(this.refuse(ref,reason),{ok:!1,reason}):(this.#owned.set(ref.refId,ref),this.#ownedBytes+=ref.bytes,this.#send({type:"ref_ack",refId:ref.refId}),{ok:!0})}refuse(ref,reason){this.#owned.has(ref.refId)||this.#send({type:"ref_nack",refId:ref.refId,reason})}async consume(refId){let ref=this.#owned.get(refId);if(ref===void 0)throw new PayloadRefError("ref_not_owned",`ref ${refId} is not owned by this side`);let path=refFilePath(this.#root,ref),bytes=await readFile(path);return await rm2(path,{force:!0}),this.#owned.delete(refId),this.#ownedBytes-=ref.bytes,bytes}ownedIds(){return[...this.#owned.keys()]}async#verify(ref,signal){if(signal?.aborted)return"cancelled";if(ref.generation!==this.#generation||!isRefId(ref.refId)||this.#owned.has(ref.refId))return"foreign";if(this.#ownedBytes+ref.bytes>this.#budget)return"budget";let path=refFilePath(this.#root,ref);try{if((await stat(path)).size!==ref.bytes)return"corrupt";let digest=await hashFile(path,signal);return digest==="cancelled"?"cancelled":digest===ref.sha256?void 0:"corrupt"}catch(error){if(isMissingFile(error))return"missing";throw error}}};async function packPayload(value,writer){let normalized=value===void 0?null:value,json=JSON.stringify(normalized);return json===void 0||Buffer.byteLength(json,"utf8")<=TOOL_CHILD_LIMITS.REF_THRESHOLD?{inline:!0,value:normalized}:{inline:!1,ref:await writer.create(Buffer.from(json,"utf8"))}}async function unpackPayload(ref,reader,signal){let acceptance=await reader.accept(ref,signal);if(!acceptance.ok)throw new PayloadRefError("ref_rejected",`ref ${ref.refId} was refused (${acceptance.reason})`,acceptance.reason);let bytes=await reader.consume(ref.refId);return JSON.parse(Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength).toString("utf8"))}var ChildHostCalls=class{#channel;#admissions=new Map;#pending=new Map;#refs;#next=0;constructor(channel,refs){this.#channel=channel,this.#refs=refs}load(jobId){let admission=this.#admissions.get(jobId);return{active:admission?.active??0,waiting:admission?.waiting??0}}async call(jobId,target,signal){let label=target.name??target.kind;if(signal.aborted)throw new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`);let callId=`h${++this.#next}`,packed=target.args===void 0||this.#refs===void 0?{inline:!0,value:target.args}:await packPayload(target.args,this.#refs.writer),frame={type:"host_call",callId,jobId,kind:target.kind,...target.name===void 0?{}:{name:target.name},...packed.inline?packed.value===void 0?{}:{args:packed.value}:{argsRef:packed.ref}};if(signal.aborted)throw this.#releaseUnsent(frame),new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`);return new Promise((resolve,reject)=>{let decision=this.#admission(jobId).submit(callId);if(decision.state==="refused"){this.#forgetIdle(jobId),this.#releaseUnsent(frame),reject(new ToolChildJobError(decision.frame.code,`${label}: host call ${callId} refused`));return}let pending={frame,resolve,reject,sent:!1};this.#pending.set(callId,pending),signal.addEventListener("abort",()=>this.#settle(callId,call=>{call.sent||this.#releaseUnsent(call.frame),call.reject(new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`))}),{once:!0}),decision.state==="active"&&this.#send(pending)})}handle(frame){if(frame.type==="host_reply"){let{valueRef}=frame;return this.#settle(frame.callId,call=>{frame.error!==void 0?call.reject(new ToolChildJobError("host_call_failed",frame.error)):valueRef===void 0?call.resolve(frame.value??null):this.#refs===void 0?call.reject(new ToolChildJobError("host_call_failed","a valueRef reply on a side that reads no refs")):unpackPayload(valueRef,this.#refs.reader).then(call.resolve,error=>call.reject(new ToolChildJobError("host_call_failed",error instanceof Error?error.message:String(error))))}),!0}return frame.type==="host_call_refused"?(this.#settle(frame.callId,call=>call.reject(new ToolChildJobError(frame.code,`host call ${frame.callId} refused by the server`))),!0):!1}close(){for(let callId of[...this.#pending.keys()])this.#settle(callId,call=>call.reject(new ToolChildJobError("tool_child_exited","the channel closed")))}#admission(jobId){let admission=this.#admissions.get(jobId);return admission===void 0&&(admission=new HostCallAdmission,this.#admissions.set(jobId,admission)),admission}#forgetIdle(jobId){let admission=this.#admissions.get(jobId);admission!==void 0&&admission.active===0&&admission.waiting===0&&this.#admissions.delete(jobId)}#send(call){call.sent=!0,this.#channel.send(call.frame)}#releaseUnsent(frame){frame.argsRef!==void 0&&this.#refs?.writer.handle({type:"ref_nack",refId:frame.argsRef.refId,reason:"cancelled"})}#settle(callId,apply){let call=this.#pending.get(callId);if(call===void 0)return;this.#pending.delete(callId);let{jobId}=call.frame,promoted=this.#admissions.get(jobId)?.settle(callId);if(this.#forgetIdle(jobId),apply(call),promoted!==void 0){let next=this.#pending.get(promoted);next!==void 0&&this.#send(next)}}};var JobUpdates=class{#jobId;#channel;#writer;#window;#nextSeq=0;#acked=0;#waiters=[];#ended=!1;#tail=Promise.resolve();constructor(options){this.#jobId=options.jobId,this.#channel=options.channel,this.#writer=options.writer,this.#window=options.window??TOOL_CHILD_LIMITS.updatesInFlight}update(value){let sent=this.#tail.then(()=>this.#send(value));return this.#tail=sent.catch(()=>{}),sent}async#send(value){for(;!this.#ended&&this.#nextSeq-this.#acked>=this.#window;)await new Promise(resolve=>this.#waiters.push(resolve));if(this.#ended)throw new Error(`update after job ${this.#jobId} ended`);let packed=this.#writer===void 0?{inline:!0,value}:await packPayload(value,this.#writer);if(this.#ended)throw new Error(`update after job ${this.#jobId} ended`);let seq=++this.#nextSeq;this.#channel.send(packed.inline?{type:"update",jobId:this.#jobId,seq,...packed.value===void 0?{}:{value:packed.value}}:{type:"update",jobId:this.#jobId,seq,valueRef:packed.ref})}acked(seq){seq<=this.#acked||(this.#acked=Math.min(seq,this.#nextSeq),this.#wake())}end(){this.#ended=!0,this.#wake()}#wake(){for(let resolve of this.#waiters.splice(0))resolve()}};var BarrierClock=class _BarrierClock{constructor(buffer){if(buffer.byteLength%Int32Array.BYTES_PER_ELEMENT!==0)throw new Error("barrier clock buffer is misaligned");let length=buffer.byteLength/Int32Array.BYTES_PER_ELEMENT;if(length<5||(length-1)%4!==0)throw new Error("barrier clock buffer has no slots");this.buffer=buffer,this.cells=new Int32Array(buffer),this.slots=(length-1)/4}static create(slots=256){if(!Number.isInteger(slots)||slots<1)throw new Error(`barrier clock needs at least one slot, got ${slots}`);return new _BarrierClock(new SharedArrayBuffer((1+slots*4)*Int32Array.BYTES_PER_ELEMENT))}tick(){return Atomics.add(this.cells,0,1)+1}claimSlot(){for(let slot=0;slot<this.slots;slot++)if(Atomics.compareExchange(this.cells,this.index(slot,3),0,1)===0)return Atomics.store(this.cells,this.index(slot,0),0),Atomics.store(this.cells,this.index(slot,1),0),Atomics.store(this.cells,this.index(slot,2),0),slot}releaseSlot(slot){Atomics.store(this.cells,this.index(slot,3),0)}recordAck(slot){let tick=this.tick();return Atomics.store(this.cells,this.index(slot,0),tick),Atomics.notify(this.cells,this.index(slot,0)),tick}recordInvoke(slot){let ackTick=Atomics.load(this.cells,this.index(slot,0)),invokeTick=this.tick();return Atomics.store(this.cells,this.index(slot,1),invokeTick),Atomics.add(this.cells,this.index(slot,2),1),{ackTick:ackTick===0?null:ackTick,invokeTick}}waitForAck(slot,timeoutMs=Number.POSITIVE_INFINITY){let at=this.index(slot,0);for(;Atomics.load(this.cells,at)===0;)if(Atomics.wait(this.cells,at,0,timeoutMs)==="timed-out")return"timed-out";return"acked"}read(slot){let ackTick=Atomics.load(this.cells,this.index(slot,0)),invokeTick=Atomics.load(this.cells,this.index(slot,1));return{ackTick:ackTick===0?null:ackTick,invokeTick:invokeTick===0?null:invokeTick,invocations:Atomics.load(this.cells,this.index(slot,2))}}index(slot,field){if(!Number.isInteger(slot)||slot<0||slot>=this.slots)throw new Error(`no barrier slot ${slot}`);return 1+slot*4+field}};function proofIsOrdered(proof){return proof.ackTick!==null&&proof.ackTick<proof.invokeTick}import{randomUUID}from"node:crypto";import{existsSync,readdirSync,rmSync,watch}from"node:fs";import{writeFile as writeFile2}from"node:fs/promises";import{join as join2}from"node:path";var PREFIX="SENPI_TOOL_CHILD_TEST_",TEST_CONTROL_DIR_ENV=`${PREFIX}CONTROL_DIR`;function readTestControls(env){let dir=env[TEST_CONTROL_DIR_ENV],value=name=>{let raw=env[`${PREFIX}${name}`];return raw===void 0||raw===""||raw==="0"?void 0:raw};return{enabled:name=>value(name)!==void 0,value,released:file=>dir===void 0?Promise.reject(new Error(`${TEST_CONTROL_DIR_ENV} is not set`)):waitForFile(dir,file),watchPrefix:(prefix,onFile)=>dir===void 0?{ready:Promise.reject(new Error(`${TEST_CONTROL_DIR_ENV} is not set`)),close:()=>{}}:watchPrefix(dir,prefix,onFile)}}function watchPrefix(dir,prefix,onFile){let seen=new Set,report=name=>{!name.startsWith(prefix)||seen.has(name)||(seen.add(name),onFile(name))},sentinel=`.watch-${process.pid}-${randomUUID()}`,resend,live=!1,markReady=()=>{},failReady=()=>{},ready=new Promise((resolve,reject)=>{markReady=resolve,failReady=reject}),watcher=watch(dir,(_event,name)=>{if(name!==null){if(name===sentinel){live=!0,clearTimeout(resend),rmSync(join2(dir,sentinel),{force:!0});for(let existing of readdirSync(dir))report(existing);markReady();return}existsSync(join2(dir,name))&&report(name)}}),touch=()=>{live||writeFile2(join2(dir,sentinel),String(Date.now())).then(()=>{live||(resend=setTimeout(touch,50))},error=>failReady(error))};return touch(),{ready,close:()=>{live=!0,clearTimeout(resend),watcher.close(),rmSync(join2(dir,sentinel),{force:!0})}}}function waitForFile(dir,file){let path=join2(dir,file),sentinel=join2(dir,`.watch-${process.pid}-${randomUUID()}`);return new Promise((resolve,reject)=>{let done=!1,resend,finish=()=>{done||(done=!0,clearTimeout(resend),watcher.close(),rmSync(sentinel,{force:!0}),resolve())},watcher=watch(dir,(_event,name)=>{if(existsSync(path)){finish();return}name!==null&&join2(dir,name)===sentinel&&clearTimeout(resend)}),touch=()=>{done||writeFile2(sentinel,String(Date.now())).then(()=>{done||(existsSync(path)?finish():resend=setTimeout(touch,50))},error=>{done||(done=!0,watcher.close(),reject(error))})};touch()})}var WindowsJobError=class extends Error{constructor(step,win32Error){super(`tool_child_job_assign_failed: ${step} failed (win32 error ${win32Error})`),this.code="tool_child_job_assign_failed",this.name="WindowsJobError",this.win32Error=win32Error}};function extendedLimitInformation(){let info=new Uint8Array(144);return new DataView(info.buffer).setUint32(16,10240,!0),info}var WindowsJob=class _WindowsJob{constructor(kernel,handle){this.closed=!1,this.kernel=kernel,this.handle=handle}static create(kernel){let handle=kernel.CreateJobObjectW(null,null);if(!handle)throw new WindowsJobError("CreateJobObjectW",kernel.GetLastError());let info=extendedLimitInformation();if(kernel.SetInformationJobObject(handle,9,info,info.byteLength)===0){let error=kernel.GetLastError();throw kernel.CloseHandle(handle),new WindowsJobError("SetInformationJobObject",error)}return new _WindowsJob(kernel,handle)}assign(pid){let process2=this.kernel.OpenProcess(4353,0,pid);if(!process2)throw new WindowsJobError("OpenProcess",this.kernel.GetLastError());try{if(this.kernel.AssignProcessToJobObject(this.handle,process2)===0)throw new WindowsJobError("AssignProcessToJobObject",this.kernel.GetLastError());let inJob=new Uint8Array(4);if(this.kernel.IsProcessInJob(process2,this.handle,inJob)===0||new DataView(inJob.buffer).getInt32(0,!0)===0)throw new WindowsJobError("IsProcessInJob",this.kernel.GetLastError())}finally{this.kernel.CloseHandle(process2)}}memberPids(){let list=new Uint8Array(8200);if(this.kernel.QueryInformationJobObject(this.handle,3,list,list.byteLength,null)===0)return[];let view=new DataView(list.buffer),count=Math.min(view.getUint32(4,!0),1024);return Array.from({length:count},(_,index)=>Number(view.getBigUint64(8+index*8,!0)))}terminate(exitCode=1){this.closed||this.kernel.TerminateJobObject(this.handle,exitCode)}close(){this.closed||(this.closed=!0,this.kernel.CloseHandle(this.handle))}};function loadKernel32Job(){if(process.platform!=="win32")return;let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return;let lib=ffi.dlopen("kernel32.dll",{CreateJobObjectW:{args:["ptr","ptr"],returns:"ptr"},SetInformationJobObject:{args:["ptr","i32","ptr","u32"],returns:"i32"},QueryInformationJobObject:{args:["ptr","i32","ptr","u32","ptr"],returns:"i32"},OpenProcess:{args:["u32","i32","u32"],returns:"ptr"},AssignProcessToJobObject:{args:["ptr","ptr"],returns:"i32"},IsProcessInJob:{args:["ptr","ptr","ptr"],returns:"i32"},TerminateJobObject:{args:["ptr","u32"],returns:"i32"},CloseHandle:{args:["ptr"],returns:"i32"},GetLastError:{args:[],returns:"u32"},GetCurrentProcess:{args:[],returns:"ptr"}}),call=(name,...args)=>{let fn=lib.symbols[name];if(fn===void 0)throw new Error(`kernel32 has no ${name}`);return fn(...args.map(arg=>arg instanceof Uint8Array?ffi.ptr(arg):arg))};return{CreateJobObjectW:()=>call("CreateJobObjectW",null,null),SetInformationJobObject:(job,infoClass,info,length)=>Number(call("SetInformationJobObject",job,infoClass,info,length)),QueryInformationJobObject:(job,infoClass,info,length)=>Number(call("QueryInformationJobObject",job,infoClass,info,length,null)),OpenProcess:(access,inherit,pid)=>call("OpenProcess",access,inherit,pid),AssignProcessToJobObject:(job,process2)=>Number(call("AssignProcessToJobObject",job,process2)),IsProcessInJob:(process2,job,result)=>Number(call("IsProcessInJob",process2,job,result)),TerminateJobObject:(job,exitCode)=>Number(call("TerminateJobObject",job,exitCode)),CloseHandle:handle=>Number(call("CloseHandle",handle)),GetLastError:()=>Number(call("GetLastError")),GetCurrentProcess:()=>call("GetCurrentProcess")}}var defaultInJob;function currentProcessInJob(kernel){if(kernel!==void 0)return queryInJob(kernel);if(defaultInJob===void 0){let loaded=loadKernel32Job();defaultInJob=loaded===void 0?!1:queryInJob(loaded)}return defaultInJob}function queryInJob(kernel){let result=new Uint8Array(4);return kernel.IsProcessInJob(kernel.GetCurrentProcess(),null,result)!==0&&new DataView(result.buffer).getInt32(0,!0)!==0}var FINISHED_SLOT_STATES=256,LaunchGateError=class extends Error{constructor(code,message){super(`${code}: ${message}`),this.name="LaunchGateError",this.code=code}},LaunchGate=class{#channel;#slots=new Map;#finished=new Map;#controls;#next=0;constructor(channel,clock=BarrierClock.create(),env=process.env,creatorInJob=currentProcessInJob){this.#channel=channel,this.clock=clock,this.#controls=readTestControls(env),this.#creatorInJob=creatorInJob}#creatorInJob;started(launchId,pid,breakaway=!1){this.#slots.has(launchId)&&this.#channel.send({type:"command_started",launchId,pid,startedAtMs:Date.now(),creatorInJob:this.#creatorInJob(),breakaway})}get skipsAckWait(){return this.#controls.enabled("SKIP_ACK_WAIT")}request(request){let slot=this.clock.claimSlot();if(slot===void 0)throw new LaunchGateError("tool_child_launch_capacity",`${this.clock.slots} launches in flight`);let launchId=`L${process.pid}-${++this.#next}`,ack,acked=new Promise(resolve=>{ack=resolve});return this.#slots.set(launchId,{slot,ack,lifetime:request.lifetime,request}),this.#channel.send({type:"launch",launchId,...request}),this.#controls.enabled("STOP_AFTER_SPAWN")&&process.kill(process.pid,"SIGSTOP"),{launchId,slot,acked}}adopt(launchId,slot,request){this.#slots.set(launchId,{slot,ack:()=>{},lifetime:request.lifetime,request}),this.#channel.send({type:"launch",launchId,...request})}handleWorker(message){message.kind==="launch"?this.adopt(message.launchId,message.slot,message.request):message.kind==="invoking"?this.invoking(message.launchId):message.kind==="started"?this.started(message.launchId,message.pid,message.breakaway):this.done(message.launchId,{...message.exitCode===void 0?{}:{exitCode:message.exitCode},...message.signal===void 0?{}:{signal:message.signal}})}handle(message){if(message.type==="launch_ack"){let entry=this.#slots.get(message.launchId);return entry!==void 0&&(this.clock.recordAck(entry.slot),entry.ack()),!0}if(message.type==="slot_query"){let entry=this.#slots.get(message.launchId),state=entry===void 0?this.#finished.get(message.launchId)??{ackTick:null,invokeTick:null,invocations:0}:this.clock.read(entry.slot);return this.#channel.send({type:"slot_state",launchId:message.launchId,...state}),!0}return!1}invokeNow(launchId){let entry=this.#slots.get(launchId);if(entry===void 0)throw new LaunchGateError("tool_child_launch_unknown",launchId);this.clock.recordInvoke(entry.slot),this.invoking(launchId)}invoking(launchId){let entry=this.#slots.get(launchId);if(entry===void 0)return;let state=this.clock.read(entry.slot),invokeTick=state.invokeTick;if(invokeTick===null)return;let send=()=>this.#channel.send({type:"launch_proof",launchId,ackTick:state.ackTick,invokeTick}),hold=this.#controls.value("HOLD_LAUNCH_PROOF");if(hold!==void 0&&(hold!=="detached"||entry.lifetime==="detached")){this.#controls.released(`release-proof-${launchId}`).then(send);return}send()}endJobGroups(jobId){let ended=[];for(let[launchId,{request}]of this.#slots)if(!(request.jobId!==jobId||request.lifetime!=="owned"||request.containment!=="own-group")&&!(request.pgid===void 0||request.pgid<=1))try{process.kill(-request.pgid,"SIGKILL"),ended.push({launchId,pgid:request.pgid})}catch{}for(let{launchId}of ended)this.done(launchId,{signal:"SIGKILL"});return ended.map(({pgid})=>pgid)}done(launchId,outcome){let entry=this.#slots.get(launchId);entry!==void 0&&(this.#slots.delete(launchId),this.#finished.set(launchId,this.clock.read(entry.slot)),this.#finished.size>FINISHED_SLOT_STATES&&this.#finished.delete(this.#finished.keys().next().value??""),this.clock.releaseSlot(entry.slot),this.#channel.send({type:"launch_done",launchId,...outcome.exitCode===void 0?{}:{exitCode:outcome.exitCode},...outcome.signal===void 0?{}:{signal:outcome.signal}}))}};import{mkdir as mkdir3,readdir as readdir2,readFile as readFile3,rm as rm4,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";import{appendFile,mkdir as mkdir2,open,readFile as readFile2,rm as rm3}from"node:fs/promises";import{dirname as dirname2,join as join3}from"node:path";function generationLedgerPath(dir,generation){return join3(dir,`g${generation}`,"descendants.ledger")}var DescendantsLedger=class{#path;#durableDir=!1;#entries=new Map;constructor(path){this.#path=path}get path(){return this.#path}entries(){return[...this.#entries.values()]}async append(entry){if(!this.#durableDir){let directory=dirname2(this.#path);await mkdir2(directory,{recursive:!0,mode:448}),await(await open(this.#path,"a",384)).close(),await syncDirectory(directory),await syncDirectory(dirname2(directory)),this.#durableDir=!0}let handle=await open(this.#path,"a",384);try{await handle.write(`${JSON.stringify(entry)}
2
+ import{Text}from"./chunk-FDL4CF6F.js";import{getShellConfig}from"./chunk-BWA4FVFW.js";import{HOST_CALL_KINDS,TOOL_CHILD_LIMITS,connectChannel,isRefId}from"./chunk-V3CK2AVC.js";import{typebox_exports}from"./chunk-MIENF2YK.js";import{TOOL_CHILD_LEDGER_ENV,TOOL_CHILD_REENTRY_ENV,TOOL_CHILD_REFS_ROOT_ENV,rememberToolChildReentry,scrubToolChildEnv,toolChildReentry}from"./chunk-OXNWERO4.js";import{BACKGROUND_START_GRACE_MS,DEFAULT_COLS,DEFAULT_MAX_SESSIONS,DEFAULT_ROWS,FOREGROUND_ENV_OVERRIDES,KILLED_SESSION_EXIT_GRACE_MS,TERMINAL_BASH_TOOL,TERMINAL_INPUT_TOOL,TERMINAL_KILL_TOOL,TERMINAL_OUTPUT_TOOL,TERMINAL_RESIZE_TOOL,encodeKeys,loadPty,safeRegExp}from"./chunk-NTK2MHJ5.js";import{processIsLive,processStartTimeMs,readProcessStartTime,sameProcessStartMs}from"./chunk-7ASLQ243.js";var ToolChildJobError=class extends Error{constructor(code,message){super(message),this.code=code,this.name="ToolChildJobError"}};var WakeAdmissionError=class extends Error{constructor(bytes){super(`wake_too_large: ${bytes} bytes exceeds the ${TOOL_CHILD_LIMITS.wakePendingBytes}-byte pending budget`),this.code="wake_too_large",this.name="WakeAdmissionError"}},WakeAdmission=class{#pending=new Map;#blocked=[];#pendingBytes=0;get pending(){return this.#pending.size}get blocked(){return this.#blocked.length}send(wakeId,bytes){return bytes>TOOL_CHILD_LIMITS.wakePendingBytes?Promise.reject(new WakeAdmissionError(bytes)):this.#blocked.length===0&&this.#fits(bytes)?(this.#admit(wakeId,bytes),Promise.resolve()):new Promise(release=>{this.#blocked.push({wakeId,bytes,release})})}ack(wakeId){let bytes=this.#pending.get(wakeId);if(bytes!==void 0){this.#pending.delete(wakeId),this.#pendingBytes-=bytes;for(let next=this.#blocked[0];next!==void 0&&this.#fits(next.bytes);next=this.#blocked[0])this.#blocked.shift(),this.#admit(next.wakeId,next.bytes),next.release()}}#fits(bytes){return this.#pending.size<TOOL_CHILD_LIMITS.wakePending&&this.#pendingBytes+bytes<=TOOL_CHILD_LIMITS.wakePendingBytes}#admit(wakeId,bytes){this.#pending.set(wakeId,bytes),this.#pendingBytes+=bytes}};function hostCallCapacity(){return TOOL_CHILD_LIMITS.HOST_CALL_ACTIVE+TOOL_CHILD_LIMITS.HOST_CALL_WAITING}var HostCallAdmission=class{#active=new Set;#waiting=[];get active(){return this.#active.size}get waiting(){return this.#waiting.length}submit(callId){return this.#active.has(callId)||this.#waiting.includes(callId)?refuse(callId,"host_call_duplicate"):this.#active.size<TOOL_CHILD_LIMITS.HOST_CALL_ACTIVE&&this.#waiting.length===0?(this.#active.add(callId),{state:"active"}):this.#active.size+this.#waiting.length>=hostCallCapacity()?refuse(callId,"host_call_capacity"):(this.#waiting.push(callId),{state:"waiting"})}settle(callId){if(!this.#active.delete(callId)){let index=this.#waiting.indexOf(callId);index>=0&&this.#waiting.splice(index,1);return}let next=this.#waiting.shift();return next!==void 0&&this.#active.add(next),next}};function refuse(callId,code){return{state:"refused",frame:{type:"host_call_refused",callId,code}}}import{createHash,randomBytes}from"node:crypto";import{createReadStream}from"node:fs";import{mkdir,readFile,rm as rm2,stat,writeFile}from"node:fs/promises";import{dirname}from"node:path";import{readdir,rm}from"node:fs/promises";import{join}from"node:path";function refGenerationDir(root,generation){return join(root,`gen-${generation}`)}function refFilePath(root,ref){if(!isRefId(ref.refId))throw new Error(`invalid ref id: ${JSON.stringify(ref.refId)}`);return join(refGenerationDir(root,ref.generation),"refs",ref.refId)}async function teardownRefGeneration(root,generation){await rm(refGenerationDir(root,generation),{recursive:!0,force:!0})}var PayloadRefError=class extends Error{constructor(code,message,reason){super(`${code}: ${message}`),this.name="PayloadRefError",this.code=code,this.reason=reason}},PayloadRefWriter=class{#root;#now;#pending=new Map;#ownedBytes=0;constructor(options){this.generation=options.generation,this.budget=options.budget??TOOL_CHILD_LIMITS.refsBudget,this.#root=options.root,this.#now=options.now??Date.now}get ownedBytes(){return this.#ownedBytes}async create(payload){let size=payload.byteLength;if(this.#ownedBytes+size>this.budget)throw new PayloadRefError("ref_budget_exceeded",`${size} bytes on top of ${this.#ownedBytes} owned exceeds ${this.budget}`);this.#ownedBytes+=size;let ref={refId:randomBytes(12).toString("hex"),generation:this.generation,bytes:size,sha256:createHash("sha256").update(payload).digest("hex")},path=refFilePath(this.#root,ref);try{await mkdir(dirname(path),{recursive:!0,mode:448}),await writeFile(path,payload,{flag:"wx",mode:384})}catch(error){throw this.#ownedBytes-=size,await rm2(path,{force:!0}),error}return this.#pending.set(ref.refId,{bytes:size,createdAtMs:this.#now()}),ref}async handle(control){let pending=this.#pending.get(control.refId);pending!==void 0&&(this.#pending.delete(control.refId),this.#ownedBytes-=pending.bytes,control.type==="ref_nack"&&await rm2(refFilePath(this.#root,{refId:control.refId,generation:this.generation}),{force:!0}))}pendingIds(){return[...this.#pending.keys()]}overdue(){let deadline=this.#now()-TOOL_CHILD_LIMITS.refAckMs;return[...this.#pending].filter(([,ref])=>ref.createdAtMs<=deadline).map(([refId])=>refId)}async teardown(){this.#pending.clear(),this.#ownedBytes=0,await teardownRefGeneration(this.#root,this.generation)}},isMissingFile=error=>error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR");async function hashFile(path,signal){let hash=createHash("sha256");for await(let chunk of createReadStream(path)){if(signal?.aborted)return"cancelled";hash.update(chunk)}return hash.digest("hex")}var PayloadRefReader=class{#root;#generation;#budget;#send;#owned=new Map;#ownedBytes=0;constructor(options){this.#root=options.root,this.#generation=options.generation,this.#budget=options.budget??TOOL_CHILD_LIMITS.refsBudget,this.#send=options.send}async accept(ref,signal){let reason=await this.#verify(ref,signal);return reason!==void 0?(this.refuse(ref,reason),{ok:!1,reason}):(this.#owned.set(ref.refId,ref),this.#ownedBytes+=ref.bytes,this.#send({type:"ref_ack",refId:ref.refId}),{ok:!0})}refuse(ref,reason){this.#owned.has(ref.refId)||this.#send({type:"ref_nack",refId:ref.refId,reason})}async consume(refId){let ref=this.#owned.get(refId);if(ref===void 0)throw new PayloadRefError("ref_not_owned",`ref ${refId} is not owned by this side`);let path=refFilePath(this.#root,ref),bytes=await readFile(path);return await rm2(path,{force:!0}),this.#owned.delete(refId),this.#ownedBytes-=ref.bytes,bytes}ownedIds(){return[...this.#owned.keys()]}async#verify(ref,signal){if(signal?.aborted)return"cancelled";if(ref.generation!==this.#generation||!isRefId(ref.refId)||this.#owned.has(ref.refId))return"foreign";if(this.#ownedBytes+ref.bytes>this.#budget)return"budget";let path=refFilePath(this.#root,ref);try{if((await stat(path)).size!==ref.bytes)return"corrupt";let digest=await hashFile(path,signal);return digest==="cancelled"?"cancelled":digest===ref.sha256?void 0:"corrupt"}catch(error){if(isMissingFile(error))return"missing";throw error}}};async function packPayload(value,writer){let normalized=value===void 0?null:value,json=JSON.stringify(normalized);return json===void 0||Buffer.byteLength(json,"utf8")<=TOOL_CHILD_LIMITS.REF_THRESHOLD?{inline:!0,value:normalized}:{inline:!1,ref:await writer.create(Buffer.from(json,"utf8"))}}async function unpackPayload(ref,reader,signal){let acceptance=await reader.accept(ref,signal);if(!acceptance.ok)throw new PayloadRefError("ref_rejected",`ref ${ref.refId} was refused (${acceptance.reason})`,acceptance.reason);let bytes=await reader.consume(ref.refId);return JSON.parse(Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength).toString("utf8"))}var ChildHostCalls=class{#channel;#admissions=new Map;#pending=new Map;#refs;#next=0;constructor(channel,refs){this.#channel=channel,this.#refs=refs}load(jobId){let admission=this.#admissions.get(jobId);return{active:admission?.active??0,waiting:admission?.waiting??0}}async call(jobId,target,signal){let label=target.name??target.kind;if(signal.aborted)throw new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`);let callId=`h${++this.#next}`,packed=target.args===void 0||this.#refs===void 0?{inline:!0,value:target.args}:await packPayload(target.args,this.#refs.writer),frame={type:"host_call",callId,jobId,kind:target.kind,...target.name===void 0?{}:{name:target.name},...packed.inline?packed.value===void 0?{}:{args:packed.value}:{argsRef:packed.ref}};if(signal.aborted)throw this.#releaseUnsent(frame),new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`);return new Promise((resolve,reject)=>{let decision=this.#admission(jobId).submit(callId);if(decision.state==="refused"){this.#forgetIdle(jobId),this.#releaseUnsent(frame),reject(new ToolChildJobError(decision.frame.code,`${label}: host call ${callId} refused`));return}let pending={frame,resolve,reject,sent:!1};this.#pending.set(callId,pending),signal.addEventListener("abort",()=>this.#settle(callId,call=>{call.sent||this.#releaseUnsent(call.frame),call.reject(new ToolChildJobError("tool_child_cancelled",`${label}: job cancelled`))}),{once:!0}),decision.state==="active"&&this.#send(pending)})}handle(frame){if(frame.type==="host_reply"){let{valueRef}=frame;return this.#settle(frame.callId,call=>{frame.error!==void 0?call.reject(new ToolChildJobError("host_call_failed",frame.error)):valueRef===void 0?call.resolve(frame.value??null):this.#refs===void 0?call.reject(new ToolChildJobError("host_call_failed","a valueRef reply on a side that reads no refs")):unpackPayload(valueRef,this.#refs.reader).then(call.resolve,error=>call.reject(new ToolChildJobError("host_call_failed",error instanceof Error?error.message:String(error))))}),!0}return frame.type==="host_call_refused"?(this.#settle(frame.callId,call=>call.reject(new ToolChildJobError(frame.code,`host call ${frame.callId} refused by the server`))),!0):!1}close(){for(let callId of[...this.#pending.keys()])this.#settle(callId,call=>call.reject(new ToolChildJobError("tool_child_exited","the channel closed")))}#admission(jobId){let admission=this.#admissions.get(jobId);return admission===void 0&&(admission=new HostCallAdmission,this.#admissions.set(jobId,admission)),admission}#forgetIdle(jobId){let admission=this.#admissions.get(jobId);admission!==void 0&&admission.active===0&&admission.waiting===0&&this.#admissions.delete(jobId)}#send(call){call.sent=!0,this.#channel.send(call.frame)}#releaseUnsent(frame){frame.argsRef!==void 0&&this.#refs?.writer.handle({type:"ref_nack",refId:frame.argsRef.refId,reason:"cancelled"})}#settle(callId,apply){let call=this.#pending.get(callId);if(call===void 0)return;this.#pending.delete(callId);let{jobId}=call.frame,promoted=this.#admissions.get(jobId)?.settle(callId);if(this.#forgetIdle(jobId),apply(call),promoted!==void 0){let next=this.#pending.get(promoted);next!==void 0&&this.#send(next)}}};var JobUpdates=class{#jobId;#channel;#writer;#window;#nextSeq=0;#acked=0;#waiters=[];#ended=!1;#tail=Promise.resolve();constructor(options){this.#jobId=options.jobId,this.#channel=options.channel,this.#writer=options.writer,this.#window=options.window??TOOL_CHILD_LIMITS.updatesInFlight}update(value){let sent=this.#tail.then(()=>this.#send(value));return this.#tail=sent.catch(()=>{}),sent}async#send(value){for(;!this.#ended&&this.#nextSeq-this.#acked>=this.#window;)await new Promise(resolve=>this.#waiters.push(resolve));if(this.#ended)throw new Error(`update after job ${this.#jobId} ended`);let packed=this.#writer===void 0?{inline:!0,value}:await packPayload(value,this.#writer);if(this.#ended)throw new Error(`update after job ${this.#jobId} ended`);let seq=++this.#nextSeq;this.#channel.send(packed.inline?{type:"update",jobId:this.#jobId,seq,...packed.value===void 0?{}:{value:packed.value}}:{type:"update",jobId:this.#jobId,seq,valueRef:packed.ref})}acked(seq){seq<=this.#acked||(this.#acked=Math.min(seq,this.#nextSeq),this.#wake())}end(){this.#ended=!0,this.#wake()}#wake(){for(let resolve of this.#waiters.splice(0))resolve()}};var BarrierClock=class _BarrierClock{constructor(buffer){if(buffer.byteLength%Int32Array.BYTES_PER_ELEMENT!==0)throw new Error("barrier clock buffer is misaligned");let length=buffer.byteLength/Int32Array.BYTES_PER_ELEMENT;if(length<5||(length-1)%4!==0)throw new Error("barrier clock buffer has no slots");this.buffer=buffer,this.cells=new Int32Array(buffer),this.slots=(length-1)/4}static create(slots=256){if(!Number.isInteger(slots)||slots<1)throw new Error(`barrier clock needs at least one slot, got ${slots}`);return new _BarrierClock(new SharedArrayBuffer((1+slots*4)*Int32Array.BYTES_PER_ELEMENT))}tick(){return Atomics.add(this.cells,0,1)+1}claimSlot(){for(let slot=0;slot<this.slots;slot++)if(Atomics.compareExchange(this.cells,this.index(slot,3),0,1)===0)return Atomics.store(this.cells,this.index(slot,0),0),Atomics.store(this.cells,this.index(slot,1),0),Atomics.store(this.cells,this.index(slot,2),0),slot}releaseSlot(slot){Atomics.store(this.cells,this.index(slot,3),0)}recordAck(slot){let tick=this.tick();return Atomics.store(this.cells,this.index(slot,0),tick),Atomics.notify(this.cells,this.index(slot,0)),tick}recordInvoke(slot){let ackTick=Atomics.load(this.cells,this.index(slot,0)),invokeTick=this.tick();return Atomics.store(this.cells,this.index(slot,1),invokeTick),Atomics.add(this.cells,this.index(slot,2),1),{ackTick:ackTick===0?null:ackTick,invokeTick}}waitForAck(slot,timeoutMs=Number.POSITIVE_INFINITY){let at=this.index(slot,0);for(;Atomics.load(this.cells,at)===0;)if(Atomics.wait(this.cells,at,0,timeoutMs)==="timed-out")return"timed-out";return"acked"}read(slot){let ackTick=Atomics.load(this.cells,this.index(slot,0)),invokeTick=Atomics.load(this.cells,this.index(slot,1));return{ackTick:ackTick===0?null:ackTick,invokeTick:invokeTick===0?null:invokeTick,invocations:Atomics.load(this.cells,this.index(slot,2))}}index(slot,field){if(!Number.isInteger(slot)||slot<0||slot>=this.slots)throw new Error(`no barrier slot ${slot}`);return 1+slot*4+field}};function proofIsOrdered(proof){return proof.ackTick!==null&&proof.ackTick<proof.invokeTick}import{randomUUID}from"node:crypto";import{existsSync,readdirSync,rmSync,watch}from"node:fs";import{writeFile as writeFile2}from"node:fs/promises";import{join as join2}from"node:path";var PREFIX="SENPI_TOOL_CHILD_TEST_",TEST_CONTROL_DIR_ENV=`${PREFIX}CONTROL_DIR`;function readTestControls(env){let dir=env[TEST_CONTROL_DIR_ENV],value=name=>{let raw=env[`${PREFIX}${name}`];return raw===void 0||raw===""||raw==="0"?void 0:raw};return{enabled:name=>value(name)!==void 0,value,released:file=>dir===void 0?Promise.reject(new Error(`${TEST_CONTROL_DIR_ENV} is not set`)):waitForFile(dir,file),watchPrefix:(prefix,onFile)=>dir===void 0?{ready:Promise.reject(new Error(`${TEST_CONTROL_DIR_ENV} is not set`)),close:()=>{}}:watchPrefix(dir,prefix,onFile)}}function watchPrefix(dir,prefix,onFile){let seen=new Set,report=name=>{!name.startsWith(prefix)||seen.has(name)||(seen.add(name),onFile(name))},sentinel=`.watch-${process.pid}-${randomUUID()}`,resend,live=!1,markReady=()=>{},failReady=()=>{},ready=new Promise((resolve,reject)=>{markReady=resolve,failReady=reject}),watcher=watch(dir,(_event,name)=>{if(name!==null){if(name===sentinel){live=!0,clearTimeout(resend),rmSync(join2(dir,sentinel),{force:!0});for(let existing of readdirSync(dir))report(existing);markReady();return}existsSync(join2(dir,name))&&report(name)}}),touch=()=>{live||writeFile2(join2(dir,sentinel),String(Date.now())).then(()=>{live||(resend=setTimeout(touch,50))},error=>failReady(error))};return touch(),{ready,close:()=>{live=!0,clearTimeout(resend),watcher.close(),rmSync(join2(dir,sentinel),{force:!0})}}}function waitForFile(dir,file){let path=join2(dir,file),sentinel=join2(dir,`.watch-${process.pid}-${randomUUID()}`);return new Promise((resolve,reject)=>{let done=!1,resend,finish=()=>{done||(done=!0,clearTimeout(resend),watcher.close(),rmSync(sentinel,{force:!0}),resolve())},watcher=watch(dir,(_event,name)=>{if(existsSync(path)){finish();return}name!==null&&join2(dir,name)===sentinel&&clearTimeout(resend)}),touch=()=>{done||writeFile2(sentinel,String(Date.now())).then(()=>{done||(existsSync(path)?finish():resend=setTimeout(touch,50))},error=>{done||(done=!0,watcher.close(),reject(error))})};touch()})}var WindowsJobError=class extends Error{constructor(step,win32Error){super(`tool_child_job_assign_failed: ${step} failed (win32 error ${win32Error})`),this.code="tool_child_job_assign_failed",this.name="WindowsJobError",this.win32Error=win32Error}};function extendedLimitInformation(){let info=new Uint8Array(144);return new DataView(info.buffer).setUint32(16,10240,!0),info}var WindowsJob=class _WindowsJob{constructor(kernel,handle){this.closed=!1,this.kernel=kernel,this.handle=handle}static create(kernel){let handle=kernel.CreateJobObjectW(null,null);if(!handle)throw new WindowsJobError("CreateJobObjectW",kernel.GetLastError());let info=extendedLimitInformation();if(kernel.SetInformationJobObject(handle,9,info,info.byteLength)===0){let error=kernel.GetLastError();throw kernel.CloseHandle(handle),new WindowsJobError("SetInformationJobObject",error)}return new _WindowsJob(kernel,handle)}assign(pid){let process2=this.kernel.OpenProcess(4353,0,pid);if(!process2)throw new WindowsJobError("OpenProcess",this.kernel.GetLastError());try{if(this.kernel.AssignProcessToJobObject(this.handle,process2)===0)throw new WindowsJobError("AssignProcessToJobObject",this.kernel.GetLastError());let inJob=new Uint8Array(4);if(this.kernel.IsProcessInJob(process2,this.handle,inJob)===0||new DataView(inJob.buffer).getInt32(0,!0)===0)throw new WindowsJobError("IsProcessInJob",this.kernel.GetLastError())}finally{this.kernel.CloseHandle(process2)}}memberPids(){let list=new Uint8Array(8200);if(this.kernel.QueryInformationJobObject(this.handle,3,list,list.byteLength,null)===0)return[];let view=new DataView(list.buffer),count=Math.min(view.getUint32(4,!0),1024);return Array.from({length:count},(_,index)=>Number(view.getBigUint64(8+index*8,!0)))}terminate(exitCode=1){this.closed||this.kernel.TerminateJobObject(this.handle,exitCode)}close(){this.closed||(this.closed=!0,this.kernel.CloseHandle(this.handle))}};function loadKernel32Job(){if(process.platform!=="win32")return;let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return;let lib=ffi.dlopen("kernel32.dll",{CreateJobObjectW:{args:["ptr","ptr"],returns:"ptr"},SetInformationJobObject:{args:["ptr","i32","ptr","u32"],returns:"i32"},QueryInformationJobObject:{args:["ptr","i32","ptr","u32","ptr"],returns:"i32"},OpenProcess:{args:["u32","i32","u32"],returns:"ptr"},AssignProcessToJobObject:{args:["ptr","ptr"],returns:"i32"},IsProcessInJob:{args:["ptr","ptr","ptr"],returns:"i32"},TerminateJobObject:{args:["ptr","u32"],returns:"i32"},CloseHandle:{args:["ptr"],returns:"i32"},GetLastError:{args:[],returns:"u32"},GetCurrentProcess:{args:[],returns:"ptr"}}),call=(name,...args)=>{let fn=lib.symbols[name];if(fn===void 0)throw new Error(`kernel32 has no ${name}`);return fn(...args.map(arg=>arg instanceof Uint8Array?ffi.ptr(arg):arg))};return{CreateJobObjectW:()=>call("CreateJobObjectW",null,null),SetInformationJobObject:(job,infoClass,info,length)=>Number(call("SetInformationJobObject",job,infoClass,info,length)),QueryInformationJobObject:(job,infoClass,info,length)=>Number(call("QueryInformationJobObject",job,infoClass,info,length,null)),OpenProcess:(access,inherit,pid)=>call("OpenProcess",access,inherit,pid),AssignProcessToJobObject:(job,process2)=>Number(call("AssignProcessToJobObject",job,process2)),IsProcessInJob:(process2,job,result)=>Number(call("IsProcessInJob",process2,job,result)),TerminateJobObject:(job,exitCode)=>Number(call("TerminateJobObject",job,exitCode)),CloseHandle:handle=>Number(call("CloseHandle",handle)),GetLastError:()=>Number(call("GetLastError")),GetCurrentProcess:()=>call("GetCurrentProcess")}}var defaultInJob;function currentProcessInJob(kernel){if(kernel!==void 0)return queryInJob(kernel);if(defaultInJob===void 0){let loaded=loadKernel32Job();defaultInJob=loaded===void 0?!1:queryInJob(loaded)}return defaultInJob}function queryInJob(kernel){let result=new Uint8Array(4);return kernel.IsProcessInJob(kernel.GetCurrentProcess(),null,result)!==0&&new DataView(result.buffer).getInt32(0,!0)!==0}var FINISHED_SLOT_STATES=256,LaunchGateError=class extends Error{constructor(code,message){super(`${code}: ${message}`),this.name="LaunchGateError",this.code=code}},LaunchGate=class{#channel;#slots=new Map;#finished=new Map;#controls;#next=0;constructor(channel,clock=BarrierClock.create(),env=process.env,creatorInJob=currentProcessInJob){this.#channel=channel,this.clock=clock,this.#controls=readTestControls(env),this.#creatorInJob=creatorInJob}#creatorInJob;started(launchId,pid,breakaway=!1){this.#slots.has(launchId)&&this.#channel.send({type:"command_started",launchId,pid,startedAtMs:Date.now(),creatorInJob:this.#creatorInJob(),breakaway})}get skipsAckWait(){return this.#controls.enabled("SKIP_ACK_WAIT")}request(request){let slot=this.clock.claimSlot();if(slot===void 0)throw new LaunchGateError("tool_child_launch_capacity",`${this.clock.slots} launches in flight`);let launchId=`L${process.pid}-${++this.#next}`,ack,acked=new Promise(resolve=>{ack=resolve});return this.#slots.set(launchId,{slot,ack,lifetime:request.lifetime,request}),this.#channel.send({type:"launch",launchId,...request}),this.#controls.enabled("STOP_AFTER_SPAWN")&&process.kill(process.pid,"SIGSTOP"),{launchId,slot,acked}}adopt(launchId,slot,request){this.#slots.set(launchId,{slot,ack:()=>{},lifetime:request.lifetime,request}),this.#channel.send({type:"launch",launchId,...request})}handleWorker(message){message.kind==="launch"?this.adopt(message.launchId,message.slot,message.request):message.kind==="invoking"?this.invoking(message.launchId):message.kind==="started"?this.started(message.launchId,message.pid,message.breakaway):this.done(message.launchId,{...message.exitCode===void 0?{}:{exitCode:message.exitCode},...message.signal===void 0?{}:{signal:message.signal}})}handle(message){if(message.type==="launch_ack"){let entry=this.#slots.get(message.launchId);return entry!==void 0&&(this.clock.recordAck(entry.slot),entry.ack()),!0}if(message.type==="slot_query"){let entry=this.#slots.get(message.launchId),state=entry===void 0?this.#finished.get(message.launchId)??{ackTick:null,invokeTick:null,invocations:0}:this.clock.read(entry.slot);return this.#channel.send({type:"slot_state",launchId:message.launchId,...state}),!0}return!1}invokeNow(launchId){let entry=this.#slots.get(launchId);if(entry===void 0)throw new LaunchGateError("tool_child_launch_unknown",launchId);this.clock.recordInvoke(entry.slot),this.invoking(launchId)}invoking(launchId){let entry=this.#slots.get(launchId);if(entry===void 0)return;let state=this.clock.read(entry.slot),invokeTick=state.invokeTick;if(invokeTick===null)return;let send=()=>this.#channel.send({type:"launch_proof",launchId,ackTick:state.ackTick,invokeTick}),hold=this.#controls.value("HOLD_LAUNCH_PROOF");if(hold!==void 0&&(hold!=="detached"||entry.lifetime==="detached")){this.#controls.released(`release-proof-${launchId}`).then(send);return}send()}endJobGroups(jobId){let ended=[];for(let[launchId,{request}]of this.#slots)if(!(request.jobId!==jobId||request.lifetime!=="owned"||request.containment!=="own-group")&&!(request.pgid===void 0||request.pgid<=1))try{process.kill(-request.pgid,"SIGKILL"),ended.push({launchId,pgid:request.pgid})}catch{}for(let{launchId}of ended)this.done(launchId,{signal:"SIGKILL"});return ended.map(({pgid})=>pgid)}done(launchId,outcome){let entry=this.#slots.get(launchId);entry!==void 0&&(this.#slots.delete(launchId),this.#finished.set(launchId,this.clock.read(entry.slot)),this.#finished.size>FINISHED_SLOT_STATES&&this.#finished.delete(this.#finished.keys().next().value??""),this.clock.releaseSlot(entry.slot),this.#channel.send({type:"launch_done",launchId,...outcome.exitCode===void 0?{}:{exitCode:outcome.exitCode},...outcome.signal===void 0?{}:{signal:outcome.signal}}))}};import{mkdir as mkdir3,readdir as readdir2,readFile as readFile3,rm as rm4,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";import{appendFile,mkdir as mkdir2,open,readFile as readFile2,rm as rm3}from"node:fs/promises";import{dirname as dirname2,join as join3}from"node:path";function generationLedgerPath(dir,generation){return join3(dir,`g${generation}`,"descendants.ledger")}var DescendantsLedger=class{#path;#durableDir=!1;#entries=new Map;constructor(path){this.#path=path}get path(){return this.#path}entries(){return[...this.#entries.values()]}async append(entry){if(!this.#durableDir){let directory=dirname2(this.#path);await mkdir2(directory,{recursive:!0,mode:448}),await(await open(this.#path,"a",384)).close(),await syncDirectory(directory),await syncDirectory(dirname2(directory)),this.#durableDir=!0}let handle=await open(this.#path,"a",384);try{await handle.write(`${JSON.stringify(entry)}
3
3
  `),await handle.datasync()}finally{await handle.close()}this.#entries.set(entry.launchId,entry)}static async readPersisted(path){let text;try{text=await readFile2(path,"utf8")}catch{return[]}let entries=[];for(let line of text.split(`
4
4
  `))if(line.trim()!=="")try{entries.push(JSON.parse(line))}catch{}return entries}async remove(){this.#entries.clear(),await rm3(this.#path,{force:!0})}};async function syncDirectory(directory){if(process.platform==="win32")return;let handle=await open(directory,"r");try{await handle.sync()}finally{await handle.close()}}var LaunchLog=class{#path;#chain=Promise.resolve();#failedWrites=0;constructor(path){this.#path=path}get path(){return this.#path}get failedWrites(){return this.#failedWrites}settled(){return this.#chain}record(record){let line=`${JSON.stringify({atMs:Date.now(),...record})}
5
5
  `;return this.#chain=this.#chain.then(async()=>{try{await mkdir2(dirname2(this.#path),{recursive:!0,mode:448}),await appendFile(this.#path,line,{mode:384})}catch{this.#failedWrites+=1}}),this.#chain}};import{execFile}from"node:child_process";async function classifyGroup(group,ownGroup,probes){if(group.lifetime==="detached")return"detached";if(ownGroup===void 0||group.pgid===ownGroup||group.pgid<=1)return"own-group";if(!probes.groupHasMembers(group.pgid))return"empty";if(!probes.isAlive(group.pgid))return"sweep";let observed=await probes.startOf(group.pgid).catch(()=>{}),recorded=group.leaderStart===void 0?void 0:processStartTimeMs(group.leaderStart);return sameProcessStartMs(recorded,observed===void 0?void 0:processStartTimeMs(observed))?"sweep":"leader-reused"}async function sweepGroups(groups,options,probes=defaultGroupProbes){let ownGroup=await probes.ownGroup(),verdicts=await Promise.all(groups.map(async group=>({group,verdict:await classifyGroup(group,ownGroup,probes)}))),targets=verdicts.filter(entry=>entry.verdict==="sweep").map(entry=>entry.group.pgid);for(let pgid of targets)probes.signalGroup(pgid,"SIGTERM");let remaining=await drain(targets,options.graceMs,options.pollMs??25,probes);for(let pgid of remaining)probes.signalGroup(pgid,"SIGKILL");return remaining=await drain(remaining,options.killWaitMs,options.pollMs??25,probes),verdicts.map(({group,verdict})=>({launchId:group.launchId,pgid:group.pgid,verdict,...verdict==="sweep"?{survived:remaining.includes(group.pgid)}:{}}))}async function drain(pgids,budgetMs,pollMs,probes){let remaining=pgids.filter(pgid=>probes.groupHasMembers(pgid));for(let waited=0;remaining.length>0&&waited<budgetMs;waited+=pollMs)await probes.wait(pollMs),remaining=remaining.filter(pgid=>probes.groupHasMembers(pgid));return remaining}function processGroupOf(pid){return process.platform==="win32"?Promise.resolve(void 0):new Promise(resolve=>{execFile("ps",["-o","pgid=","-p",String(pid)],{timeout:2e3},(error,stdout)=>{let text=String(stdout).trim();resolve(error===null&&/^\d+$/u.test(text)?Number(text):void 0)})})}function groupHasMembers(pgid){try{return process.kill(-pgid,0),!0}catch(error){return error instanceof Error&&"code"in error&&error.code==="EPERM"}}var defaultGroupProbes={groupHasMembers,isAlive:processIsLive,startOf:pid=>readProcessStartTime(pid),ownGroup:()=>processGroupOf(process.pid),signalGroup:(pgid,signal)=>{try{process.kill(-pgid,signal)}catch{}},wait:ms=>new Promise(resolve=>setTimeout(resolve,ms))};var SWEEP_TIMING={graceMs:500,killWaitMs:1e3};async function sweepLedger(path){let groups=(await DescendantsLedger.readPersisted(path)).flatMap(entry=>entry.pgid===void 0?[]:[{launchId:entry.launchId,pgid:entry.pgid,leaderStart:entry.leaderStart,lifetime:entry.lifetime}]);return groups.length===0?[]:sweepGroups(groups,SWEEP_TIMING)}var GENERATION_CHILD_FILE="child.pid";async function recordGenerationChild(dir,generation,pid){let generationDir=dirname3(generationLedgerPath(dir,generation));await mkdir3(generationDir,{recursive:!0,mode:448}),await writeFile3(join4(generationDir,GENERATION_CHILD_FILE),String(pid),{mode:384})}async function childAlive(file){let pid=Number(await readFile3(file,"utf8").catch(()=>""));if(!Number.isSafeInteger(pid)||pid<=1)return!1;try{return process.kill(pid,0),!0}catch(error){return Reflect.get(Object(error),"code")==="EPERM"}}async function sweepStaleGenerations(dir){let names=await readdir2(dir).catch(()=>[]),outcomes=[];for(let name of names){let generation=/^g(\d+)$/.exec(name)?.[1];generation!==void 0&&(await childAlive(join4(dir,name,GENERATION_CHILD_FILE))||(outcomes.push(...await sweepLedger(generationLedgerPath(dir,Number(generation)))),await rm4(join4(dir,name),{recursive:!0,force:!0})))}return outcomes}var TOOL_CHILD_GENERATION_ENV="SENPI_TOOL_CHILD_GENERATION",TOOL_CHILD_PROTOCOL_VERSION=2,NEVER_CANCELLED=new AbortController().signal;async function runToolChild(options){let env={...options.env??process.env},exit=options.exit??(code=>process.exit(code)),generation=Number(env[TOOL_CHILD_GENERATION_ENV]);(!Number.isSafeInteger(generation)||generation<0)&&(process.stderr.write(`tool-child: invalid generation
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,SUMMARIZATION_MAX_DURATION_CAP_MS,SUMMARIZATION_TOTAL_BUDGET_MS,clientMessageIdentity,isAbortGraceInRange}from"./chunk-GY5MR5KR.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{DETACH_CONNECTION_CAPABILITY}from"./chunk-4TRKE3ZC.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-II22E3CV.js";import{ORIGIN_HOST_INSTANCE_FIELD,attachJsonlLineReader,originHostInstance,serializeJsonLine}from"./chunk-RVYSJBZ7.js";import{fuzzyFilter}from"./chunk-YJA2B7FQ.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";var COMMAND_TOKEN=/^\/[A-Za-z][A-Za-z0-9:_-]*$/,MAX_SUGGESTIONS=3,UnknownCommandError=class extends Error{constructor(command,suggestions,reason){super(formatUnknownCommandMessage(command,suggestions,reason)),this.name="UnknownCommandError",this.command=command,this.suggestions=suggestions,this.reason=reason}};function formatUnknownCommandMessage(command,suggestions,reason){if(reason==="interactive_only")return`/${command} is an interactive command and cannot be sent as a prompt.`;let hint=suggestions.length===0?"":` Did you mean ${suggestions.map(name=>`/${name}`).join(", ")}?`;return`Unknown command /${command}.${hint}`}var UNKNOWN_COMMAND_CONFIRM_HINT='Resend with "unknownCommandAsText": true to send it as text.';function unknownCommandErrorFromWire(data){if(typeof data!="object"||data===null)return;let command=Reflect.get(data,"command"),suggestions=Reflect.get(data,"suggestions"),reason=Reflect.get(data,"reason");if(typeof command!="string"||!Array.isArray(suggestions)||reason!=="unknown"&&reason!=="interactive_only")return;let names=suggestions.filter(name=>typeof name=="string");return new UnknownCommandError(command,names,reason)}function commandShapedName(text){let token=text.trim().split(/\s/,1)[0]??"";return COMMAND_TOKEN.test(token)?token.slice(1):void 0}function findUnknownCommand(text,catalog){let command=commandShapedName(text);if(command===void 0||catalog.promptCommands.has(command))return;if(catalog.interactiveCommands.has(command))return new UnknownCommandError(command,[],"interactive_only");let known=[...new Set([...catalog.promptCommands,...catalog.interactiveCommands])],suggestions=fuzzyFilter(known,command,name=>name).slice(0,MAX_SUGGESTIONS);return new UnknownCommandError(command,suggestions,"unknown")}import{existsSync}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
2
+ import{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,SUMMARIZATION_MAX_DURATION_CAP_MS,SUMMARIZATION_TOTAL_BUDGET_MS,clientMessageIdentity,isAbortGraceInRange}from"./chunk-GY5MR5KR.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{DETACH_CONNECTION_CAPABILITY}from"./chunk-BMYNMUVZ.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-II22E3CV.js";import{ORIGIN_HOST_INSTANCE_FIELD,attachJsonlLineReader,originHostInstance,serializeJsonLine}from"./chunk-RVYSJBZ7.js";import{fuzzyFilter}from"./chunk-FDL4CF6F.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";var COMMAND_TOKEN=/^\/[A-Za-z][A-Za-z0-9:_-]*$/,MAX_SUGGESTIONS=3,UnknownCommandError=class extends Error{constructor(command,suggestions,reason){super(formatUnknownCommandMessage(command,suggestions,reason)),this.name="UnknownCommandError",this.command=command,this.suggestions=suggestions,this.reason=reason}};function formatUnknownCommandMessage(command,suggestions,reason){if(reason==="interactive_only")return`/${command} is an interactive command and cannot be sent as a prompt.`;let hint=suggestions.length===0?"":` Did you mean ${suggestions.map(name=>`/${name}`).join(", ")}?`;return`Unknown command /${command}.${hint}`}var UNKNOWN_COMMAND_CONFIRM_HINT='Resend with "unknownCommandAsText": true to send it as text.';function unknownCommandErrorFromWire(data){if(typeof data!="object"||data===null)return;let command=Reflect.get(data,"command"),suggestions=Reflect.get(data,"suggestions"),reason=Reflect.get(data,"reason");if(typeof command!="string"||!Array.isArray(suggestions)||reason!=="unknown"&&reason!=="interactive_only")return;let names=suggestions.filter(name=>typeof name=="string");return new UnknownCommandError(command,names,reason)}function commandShapedName(text){let token=text.trim().split(/\s/,1)[0]??"";return COMMAND_TOKEN.test(token)?token.slice(1):void 0}function findUnknownCommand(text,catalog){let command=commandShapedName(text);if(command===void 0||catalog.promptCommands.has(command))return;if(catalog.interactiveCommands.has(command))return new UnknownCommandError(command,[],"interactive_only");let known=[...new Set([...catalog.promptCommands,...catalog.interactiveCommands])],suggestions=fuzzyFilter(known,command,name=>name).slice(0,MAX_SUGGESTIONS);return new UnknownCommandError(command,suggestions,"unknown")}import{existsSync}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
3
3
  Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
4
4
  Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
5
5
  ${issue.sessionCwd}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-6AOVUTUR.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-7YO7VQZW.js";function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.includes(value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
2
+ import{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-6AOVUTUR.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-7YO7VQZW.js";function isSpawnedBy(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&"parentSessionId"in value&&typeof value.parentSessionId=="string"&&value.parentSessionId.length>0&&"rootSessionId"in value&&typeof value.rootSessionId=="string"&&value.rootSessionId.length>0&&"taskId"in value&&typeof value.taskId=="string"&&value.taskId.length>0}function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.includes(value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--spawned-by"){let value=args[i+1];if(value===void 0||value.startsWith("-"))result.diagnostics.push({type:"error",message:"--spawned-by requires a JSON object"});else{i++;try{let ancestry=JSON.parse(value);isSpawnedBy(ancestry)?result.spawnedBy=ancestry:result.diagnostics.push({type:"error",message:"--spawned-by requires non-empty parentSessionId, rootSessionId, and taskId strings"})}catch(error){if(!(error instanceof SyntaxError))throw error;result.diagnostics.push({type:"error",message:"--spawned-by must be valid JSON"})}}}else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
3
3
  ${source_default.bold("Extension CLI Flags:")}
4
4
  ${extensionFlags.map(flag=>{let value=flag.type==="string"?" <value>":"",description=flag.description??`Registered by ${flag.extensionPath}`;return` --${flag.name}${value}`.padEnd(30)+description}).join(`
5
5
  `)}
@@ -40,6 +40,8 @@ ${source_default.bold("Options:")}
40
40
  --resume, -r Select a session to resume
41
41
  --session <path|id> Use specific session file or partial UUID
42
42
  --session-id <id> Use exact project session ID, creating it if missing
43
+ --spawned-by <json> Fresh session ancestry: parentSessionId, rootSessionId, taskId
44
+ Ignored with a warning when resuming or forking
43
45
  --fork <path|id> Fork specific session file or partial UUID into a new session
44
46
  --rebind <path|id> Move a session from a moved or re-cloned repository into this directory and continue it
45
47
  --session-dir <dir> Directory for session storage and lookup
@@ -214,4 +216,4 @@ ${source_default.bold("Built-in Tool Names:")}
214
216
  grep - Search file contents (read-only, off by default)
215
217
  find - Find files by glob pattern (read-only, off by default)
216
218
  ls - List directory contents (read-only, off by default)
217
- `)}export{isToolRuntimeKind,toolRuntimeCapabilities,isHostOwnedToolRuntimeCapability,toolRuntimeCapability,TOOL_RUNTIME_UNSUPPORTED_HOST,toolRuntimeHostRefusal,ToolRuntimeUnsupportedHostError,resolveToolRuntime,isSessionRuntimeKind,resolveSessionRuntime,isValidThinkingLevel,normalizeSessionName,parseArgs,printHelp};
219
+ `)}export{isSpawnedBy,isToolRuntimeKind,toolRuntimeCapabilities,isHostOwnedToolRuntimeCapability,toolRuntimeCapability,TOOL_RUNTIME_UNSUPPORTED_HOST,toolRuntimeHostRefusal,ToolRuntimeUnsupportedHostError,resolveToolRuntime,isSessionRuntimeKind,resolveSessionRuntime,isValidThinkingLevel,normalizeSessionName,parseArgs,printHelp};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-AVLYZET7.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-6T5EQVY3.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{enableStartupCompileCache};
2
+ import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-IUHU5PEC.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-JXULI4EH.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{enableStartupCompileCache};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import{advanceSessionFence}from"./chunk-SOMFLLPD.js";import{killWindowsProcessTree}from"./chunk-JAXZOEJE.js";import{APP_NAME}from"./chunk-7YO7VQZW.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{processStartTimeMs,sameProcessStartMs}from"./chunk-7ASLQ243.js";import{randomUUID}from"node:crypto";import{mkdir,readdir,readFile,rename,rm,stat,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";var InvalidScheduledJobError=class extends Error{constructor(message){super(message),this.name="InvalidScheduledJobError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requireString(raw,key){let value=raw[key];if(typeof value!="string"||value.length===0)throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a non-empty string`);return value}function requireCount(raw,key){let value=raw[key];if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a non-negative integer`);return value}function nullableCount(raw,key){return raw[key]===null||raw[key]===void 0?null:requireCount(raw,key)}function nullableString(raw,key){let value=raw[key];if(value==null)return null;if(typeof value!="string")throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a string`);return value}function parseScheduledJob(raw){if(!isRecord(raw))throw new InvalidScheduledJobError("scheduled job must be a JSON object");if(raw.version!==1)throw new InvalidScheduledJobError(`unsupported scheduled job version: ${JSON.stringify(raw.version)}`);let id=requireString(raw,"id");if(!/^sch_[a-z0-9]{12}$/.test(id))throw new InvalidScheduledJobError(`invalid scheduled job id: ${id}`);let everyMs=nullableCount(raw,"everyMs");if(everyMs!==null&&everyMs<60*1e3)throw new InvalidScheduledJobError("scheduled job recurrence must be at least 60s");if(everyMs!==null&&everyMs>316224e5)throw new InvalidScheduledJobError("scheduled job recurrence must be at most 366 days");let prompt=requireString(raw,"prompt");if(Buffer.byteLength(prompt,"utf8")>16384)throw new InvalidScheduledJobError("scheduled job prompt exceeds 16384 bytes");let createdAt=requireCount(raw,"createdAt"),dueAt=requireCount(raw,"dueAt");return{version:1,id,sessionId:requireString(raw,"sessionId"),sessionFile:nullableString(raw,"sessionFile"),cwd:requireString(raw,"cwd"),prompt,createdAt,dueAt,everyMs,fireCount:requireCount(raw,"fireCount"),lastFiredAt:nullableCount(raw,"lastFiredAt"),lastError:nullableString(raw,"lastError")}}function nextRecurringDueAt(dueAt,everyMs,now){if(dueAt>now)return dueAt;let missed=Math.floor((now-dueAt)/everyMs)+1;return dueAt+missed*everyMs}function formatScheduledMessage(job,firedAt){let recurrence=job.everyMs===null?"":`, repeats every ${Math.round(job.everyMs/1e3)}s`;return`[Scheduled prompt ${job.id}: created ${new Date(job.createdAt).toISOString()}, due ${new Date(job.dueAt).toISOString()}, fired ${new Date(firedAt).toISOString()}${recurrence}]
2
+ import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import{advanceSessionFence}from"./chunk-SOMFLLPD.js";import{killWindowsProcessTree}from"./chunk-BWA4FVFW.js";import{APP_NAME}from"./chunk-7YO7VQZW.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{processStartTimeMs,sameProcessStartMs}from"./chunk-7ASLQ243.js";import{randomUUID}from"node:crypto";import{mkdir,readdir,readFile,rename,rm,stat,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";var InvalidScheduledJobError=class extends Error{constructor(message){super(message),this.name="InvalidScheduledJobError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requireString(raw,key){let value=raw[key];if(typeof value!="string"||value.length===0)throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a non-empty string`);return value}function requireCount(raw,key){let value=raw[key];if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a non-negative integer`);return value}function nullableCount(raw,key){return raw[key]===null||raw[key]===void 0?null:requireCount(raw,key)}function nullableString(raw,key){let value=raw[key];if(value==null)return null;if(typeof value!="string")throw new InvalidScheduledJobError(`scheduled job field "${key}" must be a string`);return value}function parseScheduledJob(raw){if(!isRecord(raw))throw new InvalidScheduledJobError("scheduled job must be a JSON object");if(raw.version!==1)throw new InvalidScheduledJobError(`unsupported scheduled job version: ${JSON.stringify(raw.version)}`);let id=requireString(raw,"id");if(!/^sch_[a-z0-9]{12}$/.test(id))throw new InvalidScheduledJobError(`invalid scheduled job id: ${id}`);let everyMs=nullableCount(raw,"everyMs");if(everyMs!==null&&everyMs<60*1e3)throw new InvalidScheduledJobError("scheduled job recurrence must be at least 60s");if(everyMs!==null&&everyMs>316224e5)throw new InvalidScheduledJobError("scheduled job recurrence must be at most 366 days");let prompt=requireString(raw,"prompt");if(Buffer.byteLength(prompt,"utf8")>16384)throw new InvalidScheduledJobError("scheduled job prompt exceeds 16384 bytes");let createdAt=requireCount(raw,"createdAt"),dueAt=requireCount(raw,"dueAt");return{version:1,id,sessionId:requireString(raw,"sessionId"),sessionFile:nullableString(raw,"sessionFile"),cwd:requireString(raw,"cwd"),prompt,createdAt,dueAt,everyMs,fireCount:requireCount(raw,"fireCount"),lastFiredAt:nullableCount(raw,"lastFiredAt"),lastError:nullableString(raw,"lastError")}}function nextRecurringDueAt(dueAt,everyMs,now){if(dueAt>now)return dueAt;let missed=Math.floor((now-dueAt)/everyMs)+1;return dueAt+missed*everyMs}function formatScheduledMessage(job,firedAt){let recurrence=job.everyMs===null?"":`, repeats every ${Math.round(job.everyMs/1e3)}s`;return`[Scheduled prompt ${job.id}: created ${new Date(job.createdAt).toISOString()}, due ${new Date(job.dueAt).toISOString()}, fired ${new Date(firedAt).toISOString()}${recurrence}]
3
3
  ${job.prompt}`}var STATE_DIRS=["pending","firing","failed"],JOB_ID=/^sch_[a-z0-9]{12}$/,RECORD_FILE=/^(sch_[a-z0-9]{12})(?:@(\d+)(?:~(\d+)-(\d+))?)?\.json$/;function scheduleDir(agentDir){return join(agentDir,"schedule")}function isScheduledJobId(id){return JOB_ID.test(id)}function isFileSystemError(error,code){return error instanceof Error&&"code"in error&&error.code===code}async function ensureDir(dir){await mkdir(dir,{recursive:!0,mode:448})}async function writeAtomic(filePath,contents){await ensureDir(dirname(filePath));let tempPath=join(dirname(filePath),`.schedule-${randomUUID()}.tmp`);try{await writeFile(tempPath,contents,{encoding:"utf8",mode:384}),await rename(tempPath,filePath)}catch(error){throw await rm(tempPath,{force:!0}),error}}function serialize(job){return`${JSON.stringify(job,null,2)}
4
4
  `}async function readJobFile(path,expectedId){if((await stat(path)).size>65536)throw new InvalidScheduledJobError(`scheduled job file exceeds ${65536} bytes`);let parsed;try{parsed=JSON.parse(await readFile(path,"utf8"))}catch(error){throw isFileSystemError(error,"ENOENT")?error:new InvalidScheduledJobError("scheduled job file is not valid JSON")}let job=parseScheduledJob(parsed);if(job.id!==expectedId)throw new InvalidScheduledJobError(`scheduled job id ${job.id} does not match its file`);return job}async function listScheduledJobs(dir){let jobs=[],invalid=[];for(let state of STATE_DIRS){let names;try{names=await readdir(join(dir,state))}catch(error){if(isFileSystemError(error,"ENOENT"))continue;throw error}for(let name of names.sort()){let match=RECORD_FILE.exec(name);if(match===null)continue;let[,id,occurrence,pid,startedAt]=match,file=join(state,name);if(!(state==="pending"?occurrence===void 0:state==="firing"?pid!==void 0:occurrence!==void 0&&pid===void 0)||id===void 0){invalid.push({state,file,error:`unexpected record name for ${state}/`});continue}try{let job=await readJobFile(join(dir,file),id);jobs.push({state,job,file,...occurrence===void 0?{}:{occurrence:Number(occurrence)},...pid===void 0||startedAt===void 0?{}:{owner:{pid:Number(pid),processStartedAtMs:Number(startedAt)}}})}catch(error){if(isFileSystemError(error,"ENOENT"))continue;invalid.push({state,file,error:error instanceof Error?error.message:String(error)})}}}return jobs.sort((a,b)=>a.job.dueAt-b.job.dueAt),{jobs,invalid}}async function createScheduledJob(dir,input,now){let job=parseScheduledJob({version:1,id:`sch_${randomUUID().replace(/-/g,"").slice(0,12)}`,...input,createdAt:now,fireCount:0,lastFiredAt:null});return await writeAtomic(join(dir,"pending",`${job.id}.json`),serialize(job)),job}function tombstonePath(dir,id){return join(dir,"cancelled",id)}async function isCancelled(dir,id){try{return await stat(tombstonePath(dir,id)),!0}catch(error){if(isFileSystemError(error,"ENOENT"))return!1;throw error}}function runnersDir(dir){return join(dir,"runners")}import{randomUUID as randomUUID2}from"node:crypto";import{link,readdir as readdir2,rename as rename2,rm as rm2,stat as stat2,writeFile as writeFile2}from"node:fs/promises";import{join as join2}from"node:path";var TOMBSTONE_RETENTION_MS=1440*60*1e3;async function cancelScheduledJob(dir,id,options={}){if(!isScheduledJobId(id))return;let records=(await listScheduledJobs(dir)).jobs.filter(record=>record.job.id===id),representative=records.find(record=>record.state==="pending")??records[0];if(representative===void 0||options.sessionId!==void 0&&representative.job.sessionId!==options.sessionId)return;await writeAtomic(tombstonePath(dir,id),`${new Date().toISOString()}
5
5
  `);let inFlight=(await occurrenceNumbers(dir,"firing",id)).length>0;await rm2(join2(dir,"pending",`${id}.json`),{force:!0});let failed=records.filter(record=>record.state==="failed");for(let record of failed)await rm2(join2(dir,record.file),{force:!0});return{job:representative.job,inFlight,removedFailed:failed.length}}function occurrenceFile(id,occurrence,owner){return join2("firing",`${id}@${occurrence}~${owner.pid}-${owner.processStartedAtMs}.json`)}async function restorePending(dir,record,id){let pending=join2(dir,"pending",`${id}.json`);try{await link(join2(dir,record),pending)}catch(error){if(!isFileSystemError(error,"EEXIST"))throw error}await rm2(join2(dir,record),{force:!0}),await isCancelled(dir,id)&&await rm2(pending,{force:!0})}async function claimOccurrence(dir,job,owner){let record=occurrenceFile(job.id,job.fireCount+1,owner);await ensureDir(join2(dir,"firing"));try{await rename2(join2(dir,"pending",`${job.id}.json`),join2(dir,record))}catch(error){if(isFileSystemError(error,"ENOENT"))return;throw error}if(await isCancelled(dir,job.id)){await rm2(join2(dir,record),{force:!0});return}if((await readJobFile(join2(dir,record),job.id)).fireCount!==job.fireCount){await restorePending(dir,record,job.id);return}return record}async function rearmRecurringJob(dir,next){if(await isCancelled(dir,next.id))return;let path=join2(dir,"pending",`${next.id}.json`);await writeAtomic(path,serialize(next)),await isCancelled(dir,next.id)&&await rm2(path,{force:!0})}async function occurrenceNumbers(dir,state,id){let names;try{names=await readdir2(join2(dir,state))}catch(error){if(isFileSystemError(error,"ENOENT"))return[];throw error}let prefix=`${id}@`;return names.filter(name=>name.startsWith(prefix)).map(name=>Number.parseInt(name.slice(prefix.length),10)).filter(occurrence=>Number.isSafeInteger(occurrence))}async function restoreAbandonedSchedule(dir,job,occurrence,now){if(job.everyMs===null||await isCancelled(dir,job.id))return;let pending=join2(dir,"pending",`${job.id}.json`);if(await stat2(pending).then(()=>!0,()=>!1)||[...await occurrenceNumbers(dir,"firing",job.id),...await occurrenceNumbers(dir,"failed",job.id)].some(n=>n>occurrence))return;let next={...job,fireCount:occurrence,dueAt:nextRecurringDueAt(job.dueAt,job.everyMs,now),lastError:null};await ensureDir(join2(dir,"pending"));let temp=join2(dir,"pending",`.schedule-${randomUUID2()}.tmp`);try{await writeFile2(temp,serialize(next),{encoding:"utf8",mode:384}),await link(temp,pending)}catch(error){if(!isFileSystemError(error,"EEXIST"))throw error;return}finally{await rm2(temp,{force:!0})}if(await isCancelled(dir,job.id)){await rm2(pending,{force:!0});return}return next}async function settleOccurrence(dir,record,job,occurrence,outcome){if(!outcome.ok&&!await isCancelled(dir,job.id)){let failed=join2(dir,"failed",`${job.id}@${occurrence}.json`);await writeAtomic(failed,serialize({...job,lastError:outcome.error})),await isCancelled(dir,job.id)&&await rm2(failed,{force:!0});let older=(await occurrenceNumbers(dir,"failed",job.id)).sort((a,b)=>b-a);for(let stale of older.slice(10))await rm2(join2(dir,"failed",`${job.id}@${stale}.json`),{force:!0})}await rm2(join2(dir,record),{force:!0})}async function pruneTombstones(dir,listing,now){let names;try{names=await readdir2(join2(dir,"cancelled"))}catch(error){if(isFileSystemError(error,"ENOENT"))return;throw error}let live=new Set(listing.jobs.filter(record=>record.state!=="failed").map(record=>record.job.id));for(let id of names){if(!isScheduledJobId(id)||live.has(id))continue;let info=await stat2(tombstonePath(dir,id)).catch(()=>{});info!==void 0&&now-info.mtimeMs>TOMBSTONE_RETENTION_MS&&await rm2(tombstonePath(dir,id),{force:!0})}}import{mkdir as mkdir2,readdir as readdir3,stat as stat4}from"node:fs/promises";import{join as join3}from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import{link as link2,open,readFile as readFile3,rename as rename3,stat as stat3,unlink}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile2}from"node:fs/promises";var LINUX_CLOCK_TICKS_PER_SECOND=100;async function linuxProcessStartMs(pid){let[stat5,systemStat]=await Promise.all([readFile2(`/proc/${pid}/stat`,"utf8"),readFile2("/proc/stat","utf8")]),afterComm=stat5.slice(stat5.lastIndexOf(")")+2).split(" "),startTicks=Number(afterComm[19]),bootSeconds=Number(/^btime (\d+)/m.exec(systemStat)?.[1]);if(!(!Number.isFinite(startTicks)||!Number.isFinite(bootSeconds)))return Math.round((bootSeconds+startTicks/LINUX_CLOCK_TICKS_PER_SECOND)*1e3)}function execText(command,args,env){return new Promise((resolve,reject)=>{execFile(command,[...args],{encoding:"utf8",timeout:5e3,windowsHide:!0,...env===void 0?{}:{env}},(error,stdout)=>{error?reject(error):resolve(stdout)})})}async function darwinProcessStartMs(pid){let text=(await execText("ps",["-o","lstart=","-p",String(pid)],{...process.env,LC_ALL:"C",LANG:"C"})).trim();if(text.length!==0)return processStartTimeMs(text)}async function windowsProcessStartMs(pid){let script=`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,text=(await execText("powershell",["-NoProfile","-NonInteractive","-Command",script])).trim();return processStartTimeMs(text)}async function readProcessStartMs(pid){try{switch(process.platform){case"linux":return await linuxProcessStartMs(pid);case"darwin":return await darwinProcessStartMs(pid);case"win32":return await windowsProcessStartMs(pid);default:return}}catch{return}}function errorCode(error){if(typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string")return error.code}async function unlinkIfPresent(path){try{await unlink(path)}catch(error){if(errorCode(error)!=="ENOENT")throw error}}async function readLeaseText(path){try{return await readFile3(path,"utf8")}catch(error){if(errorCode(error)==="ENOENT")return;throw error}}async function writeTemp(path,content,mode){let temp=`${path}.${process.pid}.${randomUUID3().slice(0,8)}.tmp`,file=await open(temp,"wx",mode);try{await file.writeFile(content,"utf8")}finally{await file.close()}return temp}async function publishExclusive(path,content,options={}){let temp=await writeTemp(path,content,options.mode);try{await link2(temp,path)}catch(error){let code=errorCode(error);if(code!=="ENOTSUP"&&code!=="EOPNOTSUPP"&&code!=="EPERM")throw error;let file=await open(path,"wx",options.mode);try{await file.writeFile(content,"utf8")}finally{await file.close()}}finally{await unlinkIfPresent(temp)}}async function publishReplace(path,content,options={}){let temp=await writeTemp(path,content,options.mode);try{await rename3(temp,path)}catch(error){throw await unlinkIfPresent(temp),error}}function pidAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode(error)==="EPERM"}}var UNREADABLE_LOCK_STALE_MS=3e4;function readLockHolder(raw){try{let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null||!("pid"in parsed)||!("bootAtMs"in parsed)||!("processStartedAtMs"in parsed))return;let{pid,bootAtMs,processStartedAtMs}=parsed;return typeof pid!="number"||typeof bootAtMs!="number"||typeof processStartedAtMs!="number"?void 0:{pid,bootAtMs,processStartedAtMs}}catch{return}}async function reclaimLockState(lock,probes={}){let raw=await readLeaseText(lock);if(raw===void 0)return{state:"free"};let holder=readLockHolder(raw);if(holder===void 0)return await stat3(lock).then(info=>Date.now()-info.mtimeMs,()=>0)>UNREADABLE_LOCK_STALE_MS?{state:"stale",raw}:{state:"held"};if(!sameBoot(holder.bootAtMs,processBootAtMs()))return{state:"stale",raw};if(holder.pid===process.pid)return sameProcessStartMs(holder.processStartedAtMs,ownProcessStartedAtMs())?{state:"held",holder}:{state:"stale",raw};if(!(probes.isProcessAlive??pidAlive)(holder.pid))return{state:"stale",raw};let observed=await(probes.readProcessStartMs??readProcessStartMs)(holder.pid).catch(()=>{});return observed===void 0?{state:"held",holder,unproven:!0}:sameProcessStartMs(holder.processStartedAtMs,observed)?{state:"held",holder}:{state:"stale",raw}}async function breakStaleLock(lock,raw){let aside=`${lock}.${process.pid}.${randomUUID3().slice(0,8)}.broken`;try{await rename3(lock,aside)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}let moved=await readFile3(aside,"utf8");if(moved!==raw)try{await publishExclusive(lock,moved)}catch(error){if(errorCode(error)!=="EEXIST")throw error}await unlinkIfPresent(aside)}async function takeReclaimLock(lock,probes){let mine=JSON.stringify({pid:process.pid,bootAtMs:processBootAtMs(),processStartedAtMs:ownProcessStartedAtMs()});for(let attempt=0;attempt<3;attempt+=1){try{return await publishExclusive(lock,mine),mine}catch(error){if(errorCode(error)!=="EEXIST")throw error}let seen=await reclaimLockState(lock,probes);if(seen.state==="held")return{holder:seen.holder};seen.state==="stale"&&await breakStaleLock(lock,seen.raw)}return{}}async function reclaimInspected(path,inspected,probes={}){let lock=`${path}.lock`,taken=await takeReclaimLock(lock,probes);if(typeof taken!="string")return{outcome:"busy",...taken.holder?{holder:taken.holder}:{}};try{return await readLeaseText(path)!==inspected?{outcome:"changed"}:(await unlinkIfPresent(path),{outcome:"removed"})}finally{await readLeaseText(lock)===taken&&await unlinkIfPresent(lock)}}var RUNNER_HEARTBEAT_STALE_MS=12e4,RUNNER_HEARTBEAT_INTERVAL_MS=3e4,DEFAULT_MAX_DELIVERY_MS=9e5,PRIVATE={mode:384};function ownRunnerIdentity(){return{pid:process.pid,processStartedAtMs:ownProcessStartedAtMs()}}function leasePath(dir,pid){return join3(runnersDir(dir),`${pid}.json`)}async function writeRunnerLease(dir,lease,now){await mkdir2(runnersDir(dir),{recursive:!0,mode:448});let identity=ownRunnerIdentity();await publishReplace(leasePath(dir,identity.pid),JSON.stringify({...identity,bootAtMs:processBootAtMs(),beatAt:now,...lease}),PRIVATE)}async function removeRunnerLease(dir){await unlinkIfPresent(leasePath(dir,process.pid))}function parseLease(raw){try{let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null)return;let beatAt="beatAt"in parsed?parsed.beatAt:void 0;if(typeof beatAt!="number")return;let watch="watch"in parsed&&parsed.watch===!0,exec="exec"in parsed&&typeof parsed.exec=="string"?parsed.exec:null;return{beatAt,watch,exec}}catch{return}}async function liveRunners(dir){let names;try{names=await readdir3(runnersDir(dir))}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return[];throw error}let runners=[];for(let name of names){if(!/^\d+\.json$/.test(name))continue;let path=join3(runnersDir(dir),name),state=await reclaimLockState(path);if(state.state==="stale"&&await breakStaleLock(path,state.raw),state.state!=="held"||state.holder===void 0)continue;let raw=await readLeaseText(path),lease=raw===void 0?void 0:parseLease(raw);lease!==void 0&&runners.push({pid:state.holder.pid,processStartedAtMs:state.holder.processStartedAtMs,...lease})}return runners}async function isWatchRunnerAvailable(dir,now){return(await liveRunners(dir)).some(runner=>runner.watch&&now-runner.beatAt<=RUNNER_HEARTBEAT_STALE_MS)}function isOwnerAmong(owner,runners){return runners.some(runner=>runner.pid===owner.pid&&sameProcessStartMs(runner.processStartedAtMs,owner.processStartedAtMs))}function sessionLockPath(dir,sessionId){return join3(dir,"sessions",`${encodeURIComponent(sessionId)}.lock`)}function isDeliveryGroupAlive(pid){try{return process.kill(process.platform==="win32"?pid:-pid,0),!0}catch(error){return errorCode(error)==="EPERM"}}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch(error){return errorCode(error)==="EPERM"}}async function orphanedDelivery(raw,lockAgeMs,probes){let parsed;try{parsed=JSON.parse(raw)}catch{return}if(typeof parsed!="object"||parsed===null)return;let field=key=>key in parsed?Reflect.get(parsed,key):void 0,boot=field("bootAtMs");if(typeof boot!="number"||!sameBoot(boot,processBootAtMs()))return;let pid=field("deliveryPid"),startedAt=field("deliveryStartedAtMs");if(typeof pid!="number"||typeof startedAt!="number"){let maxDeliveryMs=field("maxDeliveryMs"),runner=field("pid");return field("gated")===!1&&typeof maxDeliveryMs=="number"&&lockAgeMs<=maxDeliveryMs&&typeof runner=="number"?runner:void 0}if(!isDeliveryGroupAlive(pid))return;if(!isPidAlive(pid))return pid;let leaderStart=await(probes.readProcessStartMs??readProcessStartMs)(pid).catch(()=>{});return leaderStart!==void 0&&sameProcessStartMs(startedAt,leaderStart)?pid:void 0}async function acquireSessionDeliveryLock(dir,sessionId,options={}){let probes=options,path=sessionLockPath(dir,sessionId),identity={pid:process.pid,bootAtMs:processBootAtMs(),processStartedAtMs:ownProcessStartedAtMs(),gated:options.gated??process.platform!=="win32",maxDeliveryMs:options.maxDeliveryMs??DEFAULT_MAX_DELIVERY_MS},mine=JSON.stringify(identity);for(let attempt=0;attempt<3;attempt+=1){try{await publishExclusive(path,mine,PRIVATE);let tail=Promise.resolve(),serialized=operation=>{let run=tail.then(operation);return tail=run.catch(()=>{}),run};return{acquired:!0,attachDelivery:pid=>serialized(async()=>{let startedAt=Math.floor(Date.now()/1e3)*1e3;if(await readLeaseText(path)!==mine)throw new Error("session delivery lock was lost");let next=JSON.stringify({...identity,deliveryPid:pid,deliveryStartedAtMs:startedAt});await publishReplace(path,next,PRIVATE),mine=next}),release:()=>serialized(async()=>{await readLeaseText(path)===mine&&await unlinkIfPresent(path)})}}catch(error){let code=errorCode(error);if(code==="ENOENT"){await mkdir2(join3(dir,"sessions"),{recursive:!0,mode:448});continue}if(code!=="EEXIST")throw error}let state=await reclaimLockState(path);if(state.state==="held")return{acquired:!1,heldByPid:state.holder?.pid};if(state.state==="stale"){let lockAgeMs=await stat4(path).then(info=>Date.now()-info.mtimeMs,()=>0),delivering=await orphanedDelivery(state.raw,lockAgeMs,probes);if(delivering!==void 0)return{acquired:!1,heldByPid:delivering};await breakStaleLock(path,state.raw)}}return{acquired:!1,heldByPid:void 0}}import{randomUUID as randomUUID5}from"node:crypto";import{existsSync,mkdirSync,readFileSync,renameSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{mkdir as mkdir4}from"node:fs/promises";import{dirname as dirname3,join as join6}from"node:path";var SessionHeldError=class extends Error{constructor(sessionFile,holders){let who=holders.map(h=>h.cwd?`pid ${h.pid} in ${h.cwd}`:`pid ${h.pid}`).join("; ");super(`This session is open in another ${APP_NAME} process (${who}). Quit it there, then try again.`),this.code="ESESSIONHELD",this.name="SessionHeldError",this.sessionFile=sessionFile,this.holders=holders}},SessionMovingError=class extends Error{constructor(sessionFile,moverPid){let who=moverPid===void 0?"another process":`another process (pid ${moverPid})`;super(`Session ${sessionFile} is being moved by ${who}. Try again in a moment.`),this.code="ESESSIONMOVING",this.name="SessionMovingError",this.moverPid=moverPid}},SessionMovedError=class extends Error{constructor(sessionFile){super(`Session ${sessionFile} no longer exists: another process moved it. Resume it from its new location.`),this.code="ESESSIONMOVED",this.name="SessionMovedError"}};import{readdir as readdir4}from"node:fs/promises";import{join as join4}from"node:path";var HOLDER_RECORD=/^\d+\.json$/;function parseCwd(raw){let parsed=JSON.parse(raw);if(!(typeof parsed!="object"||parsed===null||!("cwd"in parsed)))return typeof parsed.cwd=="string"?parsed.cwd:void 0}async function fenced(fenceSession){return fenceSession===void 0?!1:fenceSession().then(()=>!0,()=>!1)}function holderGeneration(parsed){return typeof parsed!="object"||parsed===null?{}:{..."host_instance"in parsed&&typeof parsed.host_instance=="string"?{host_instance:parsed.host_instance}:{},..."host_daemon_dir"in parsed&&typeof parsed.host_daemon_dir=="string"?{host_daemon_dir:parsed.host_daemon_dir}:{}}}async function liveHolders(dir,probes={},fenceSession){let holders=[];for(let name of await readdir4(dir)){if(!HOLDER_RECORD.test(name))continue;let path=join4(dir,name),before=await readLeaseText(path),state=await reclaimLockState(path,probes);if(state.state==="stale"&&await breakStaleLock(path,state.raw),state.state!=="held"||state.holder===void 0)continue;let raw=await readLeaseText(path),stable=raw!==void 0&&raw===before,parsed=stable?JSON.parse(raw):void 0;if(stable&&state.unproven===!0&&await probes.holderEnded?.(holderGeneration(parsed))===!0&&await fenced(fenceSession)){await breakStaleLock(path,raw);continue}let endpoint=typeof parsed=="object"&&parsed!==null&&"host_instance"in parsed&&typeof parsed.host_instance=="string"?{host_instance:parsed.host_instance,..."host_socket"in parsed&&typeof parsed.host_socket=="string"?{host_socket:parsed.host_socket}:{}}:{};holders.push({pid:state.holder.pid,cwd:stable?parseCwd(raw):void 0,...endpoint})}return holders}import{randomUUID as randomUUID4}from"node:crypto";import{mkdir as mkdir3,readFile as readFile4,rename as rename4,rm as rm3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname2,join as join5}from"node:path";var InvalidSidecarStoreError=class extends Error{constructor(message,options){super(message,options),this.name="InvalidSidecarStoreError"}},UnsupportedSidecarStoreVersionError=class extends Error{constructor(message){super(message),this.name="UnsupportedSidecarStoreVersionError"}},mutationTails=new Map,snapshots=new Map;function encodedSessionId(sessionId){return encodeURIComponent(sessionId)}function sidecarFilePath(ref){return join5(ref.baseDir,`${encodedSessionId(ref.sessionId)}.json`)}function createSidecarStore(options){let ref={baseDir:options.baseDir,sessionId:options.sessionId},filePath=sidecarFilePath(ref);async function read(){let raw;try{raw=await readFile4(filePath,"utf8")}catch(error){if(isFileSystemError2(error,"ENOENT"))return null;throw error}let state=parsePayload(raw,options,ref);return snapshots.set(filePath,state),state}async function write(state){await mkdir3(dirname2(filePath),{recursive:!0}),await writeAtomic2(filePath,`${JSON.stringify(state,null,2)}
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-MLVIYDHK.js";import{parseArgs,printHelp}from"./chunk-BZ75DRZB.js";import{CONFIG_DIR_NAME,DISPLAY_VERSION,getAgentDir}from"./chunk-7YO7VQZW.js";import{createHash}from"node:crypto";import{existsSync,mkdirSync,readFileSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join}from"node:path";var CACHE_FILE_VERSION=1,MAX_CACHED_SCOPES=8;function cachePath(agentDir){return join(agentDir,"cache","help-flags.json")}function scopeKey(scope){let material=[scope.cwd,scope.noExtensions?"no-extensions":"extensions",scope.projectTrusted?"trusted":"untrusted",...scope.cliExtensionPaths].join("\0");return createHash("sha256").update(material).digest("hex").slice(0,32)}function stamp(path){try{let stats=statSync(path);return stats.isDirectory()?`d:${stats.mtimeMs}`:`f:${stats.mtimeMs}:${stats.size}`}catch{return"absent"}}function discoveryInputs(scope,extensionPaths){let paths=new Set([join(scope.agentDir,"settings.json"),join(scope.agentDir,"extensions"),join(scope.agentDir,"trust.json"),join(scope.cwd,CONFIG_DIR_NAME,"settings.json"),join(scope.cwd,CONFIG_DIR_NAME,"extensions")]);for(let path of extensionPaths)isAbsolute(path)&&(paths.add(path),paths.add(dirname(path)));for(let path of scope.cliExtensionPaths)isAbsolute(path)&&paths.add(path);return[...paths].sort()}function readCacheFile(agentDir){try{let parsed=JSON.parse(readFileSync(cachePath(agentDir),"utf8"));return parsed.version!==CACHE_FILE_VERSION||typeof parsed.scopes!="object"||parsed.scopes===null?void 0:parsed}catch{return}}function readHelpFlagsCache(scope){let cached=readCacheFile(scope.agentDir)?.scopes[scopeKey(scope)];if(!(!cached||cached.appVersion!==DISPLAY_VERSION||!Array.isArray(cached.inputs))){for(let input of cached.inputs)if(stamp(input.path)!==input.state)return;return[...cached.flags]}}function writeHelpFlagsCache(options){let{scope,flags,extensionPaths}=options;try{let scopes={...readCacheFile(scope.agentDir)?.scopes??{}};scopes[scopeKey(scope)]={writtenAt:Date.now(),appVersion:DISPLAY_VERSION,inputs:discoveryInputs(scope,extensionPaths).map(path=>({path,state:stamp(path)})),flags:[...flags]};let keptEntries=Object.entries(scopes).sort(([,left],[,right])=>right.writtenAt-left.writtenAt).slice(0,MAX_CACHED_SCOPES),file={version:CACHE_FILE_VERSION,scopes:Object.fromEntries(keptEntries)},target=cachePath(scope.agentDir);mkdirSync(dirname(target),{recursive:!0});let temporary=`${target}.${process.pid}.tmp`;writeFileSync(temporary,JSON.stringify(file),{mode:384});try{renameSync(temporary,target)}catch(error){throw existsSync(temporary)&&rmSync(temporary,{force:!0}),error}}catch{return}}function isPlainHelpRequest(parsed){return parsed.help===!0&&parsed.print!==!0&&parsed.mode===void 0}function resolveHelpProjectTrust(parsed,cwd,agentDir){return parsed.projectTrustOverride!==void 0?parsed.projectTrustOverride:hasTrustRequiringProjectResources(cwd)?new ProjectTrustStore(agentDir).get(cwd)===!0:!0}function helpFlagsScope(parsed,cwd,agentDir,projectTrusted){return{cwd,agentDir,cliExtensionPaths:[...parsed.extensions??[]],noExtensions:parsed.noExtensions===!0,projectTrusted}}function tryPrintHelpWithoutEngine(argv){let parsed;try{parsed=parseArgs([...argv])}catch{return!1}if(!isPlainHelpRequest(parsed)||parsed.diagnostics.length>0)return!1;if(parsed.noExtensions===!0)return printHelp([]),!0;let flags;try{let cwd=process.cwd(),agentDir=getAgentDir();flags=readHelpFlagsCache(helpFlagsScope(parsed,cwd,agentDir,resolveHelpProjectTrust(parsed,cwd,agentDir)))}catch{return!1}return flags?(printHelp(flags),!0):!1}export{writeHelpFlagsCache,isPlainHelpRequest,resolveHelpProjectTrust,helpFlagsScope,tryPrintHelpWithoutEngine};
2
+ import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-MLVIYDHK.js";import{parseArgs,printHelp}from"./chunk-U67ML6CQ.js";import{CONFIG_DIR_NAME,DISPLAY_VERSION,getAgentDir}from"./chunk-7YO7VQZW.js";import{createHash}from"node:crypto";import{existsSync,mkdirSync,readFileSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join}from"node:path";var CACHE_FILE_VERSION=1,MAX_CACHED_SCOPES=8;function cachePath(agentDir){return join(agentDir,"cache","help-flags.json")}function scopeKey(scope){let material=[scope.cwd,scope.noExtensions?"no-extensions":"extensions",scope.projectTrusted?"trusted":"untrusted",...scope.cliExtensionPaths].join("\0");return createHash("sha256").update(material).digest("hex").slice(0,32)}function stamp(path){try{let stats=statSync(path);return stats.isDirectory()?`d:${stats.mtimeMs}`:`f:${stats.mtimeMs}:${stats.size}`}catch{return"absent"}}function discoveryInputs(scope,extensionPaths){let paths=new Set([join(scope.agentDir,"settings.json"),join(scope.agentDir,"extensions"),join(scope.agentDir,"trust.json"),join(scope.cwd,CONFIG_DIR_NAME,"settings.json"),join(scope.cwd,CONFIG_DIR_NAME,"extensions")]);for(let path of extensionPaths)isAbsolute(path)&&(paths.add(path),paths.add(dirname(path)));for(let path of scope.cliExtensionPaths)isAbsolute(path)&&paths.add(path);return[...paths].sort()}function readCacheFile(agentDir){try{let parsed=JSON.parse(readFileSync(cachePath(agentDir),"utf8"));return parsed.version!==CACHE_FILE_VERSION||typeof parsed.scopes!="object"||parsed.scopes===null?void 0:parsed}catch{return}}function readHelpFlagsCache(scope){let cached=readCacheFile(scope.agentDir)?.scopes[scopeKey(scope)];if(!(!cached||cached.appVersion!==DISPLAY_VERSION||!Array.isArray(cached.inputs))){for(let input of cached.inputs)if(stamp(input.path)!==input.state)return;return[...cached.flags]}}function writeHelpFlagsCache(options){let{scope,flags,extensionPaths}=options;try{let scopes={...readCacheFile(scope.agentDir)?.scopes??{}};scopes[scopeKey(scope)]={writtenAt:Date.now(),appVersion:DISPLAY_VERSION,inputs:discoveryInputs(scope,extensionPaths).map(path=>({path,state:stamp(path)})),flags:[...flags]};let keptEntries=Object.entries(scopes).sort(([,left],[,right])=>right.writtenAt-left.writtenAt).slice(0,MAX_CACHED_SCOPES),file={version:CACHE_FILE_VERSION,scopes:Object.fromEntries(keptEntries)},target=cachePath(scope.agentDir);mkdirSync(dirname(target),{recursive:!0});let temporary=`${target}.${process.pid}.tmp`;writeFileSync(temporary,JSON.stringify(file),{mode:384});try{renameSync(temporary,target)}catch(error){throw existsSync(temporary)&&rmSync(temporary,{force:!0}),error}}catch{return}}function isPlainHelpRequest(parsed){return parsed.help===!0&&parsed.print!==!0&&parsed.mode===void 0}function resolveHelpProjectTrust(parsed,cwd,agentDir){return parsed.projectTrustOverride!==void 0?parsed.projectTrustOverride:hasTrustRequiringProjectResources(cwd)?new ProjectTrustStore(agentDir).get(cwd)===!0:!0}function helpFlagsScope(parsed,cwd,agentDir,projectTrusted){return{cwd,agentDir,cliExtensionPaths:[...parsed.extensions??[]],noExtensions:parsed.noExtensions===!0,projectTrusted}}function tryPrintHelpWithoutEngine(argv){let parsed;try{parsed=parseArgs([...argv])}catch{return!1}if(!isPlainHelpRequest(parsed)||parsed.diagnostics.length>0)return!1;if(parsed.noExtensions===!0)return printHelp([]),!0;let flags;try{let cwd=process.cwd(),agentDir=getAgentDir();flags=readHelpFlagsCache(helpFlagsScope(parsed,cwd,agentDir,resolveHelpProjectTrust(parsed,cwd,agentDir)))}catch{return!1}return flags?(printHelp(flags),!0):!1}export{writeHelpFlagsCache,isPlainHelpRequest,resolveHelpProjectTrust,helpFlagsScope,tryPrintHelpWithoutEngine};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import"./chunk-MYAENL22.js";import{enableStartupCompileCache}from"./chunk-I5NIJZDY.js";import"./chunk-DYWHYQUD.js";import{installStaleExtensionContainment,main}from"./chunk-DITSGW4R.js";import"./chunk-CZYADQ2E.js";import"./chunk-CZR7C6CY.js";import{configureHttpDispatcher}from"./chunk-LR6Z6V54.js";import"./chunk-DXJJP6RP.js";import"./chunk-HCF5M6NA.js";import"./chunk-GOB5BLDV.js";import"./chunk-GY5MR5KR.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-7UUOGZKR.js";import"./chunk-SGATKHO4.js";import"./chunk-MLVIYDHK.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-VUKNGMDT.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-MRN6IKOQ.js";import"./chunk-4TRKE3ZC.js";import"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import"./chunk-II22E3CV.js";import"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-H6IG2ITJ.js";import"./chunk-YJA2B7FQ.js";import"./chunk-JAXZOEJE.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-AVLYZET7.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
3
+ import"./chunk-MYAENL22.js";import{enableStartupCompileCache}from"./chunk-UT6AJHPK.js";import"./chunk-PXKF2RHD.js";import{installStaleExtensionContainment,main}from"./chunk-GVJ76VQI.js";import"./chunk-SGDOZT6B.js";import"./chunk-VOBD6FQG.js";import{configureHttpDispatcher}from"./chunk-NQC7MI2G.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-42OY5SZZ.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-7UUOGZKR.js";import"./chunk-Y5OTHMXO.js";import"./chunk-MLVIYDHK.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-3LNSLJ7N.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-3VOG6WFU.js";import"./chunk-BMYNMUVZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-U67ML6CQ.js";import"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import"./chunk-II22E3CV.js";import"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-QH2HSCMX.js";import"./chunk-FDL4CF6F.js";import"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-IUHU5PEC.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
@@ -1,9 +1,10 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-HPCS4HM4.js";import{ConnectError,createMcpLogger,isMcpNeedsAuthError,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,loadMcpSdkTypes,reapProcessTree,safeOn,safeTimer}from"./chunk-CDRFFHLL.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";var MCP_CLIENT_ELICITATION_CAPABILITY={elicitation:{}},MCP_ELICITATION_TIMEOUT_MS=300*1e3,legacyUiProvider;async function configureMcpElicitation(client,owner=legacyUiProvider,timeoutMs=MCP_ELICITATION_TIMEOUT_MS){let{ElicitRequestSchema}=await loadMcpSdkTypes();client.setRequestHandler(ElicitRequestSchema,async request2=>{let params=request2.params;if(!("requestedSchema"in params))return{action:"decline"};let ui=typeof owner=="function"?owner():owner?.getMcpElicitationUi();return ui===void 0?{action:"decline"}:await runElicitationForm(ui,params.message,params.requestedSchema,timeoutMs)})}async function runElicitationForm(ui,message,requestedSchema,timeoutMs=MCP_ELICITATION_TIMEOUT_MS){let timer,timeout=new Promise(resolve=>{timer=safeTimer("mcp.elicitation.timeout",timeoutMs,()=>resolve({action:"cancel"}),{logger:createMcpLogger("elicitation")})});try{return await Promise.race([collectForm(ui,message,requestedSchema),timeout])}finally{timer!==void 0&&clearTimeout(timer)}}async function collectForm(ui,message,requestedSchema){let content={},required=new Set(requestedSchema.required??[]);for(let[name,property]of Object.entries(requestedSchema.properties??{})){let title=`${message} - ${property.title??name}`;if(property.type==="boolean"){content[name]=await ui.confirm(title,property.description??name);continue}if(Array.isArray(property.enum)&&property.enum.length>0){let picked=await ui.select(title,property.enum.map(String));if(picked===void 0)return{action:"decline"};content[name]=picked;continue}let answer=await ui.input(title,property.description);if(answer===void 0||answer.length===0){if(required.has(name))return{action:"decline"};continue}if(property.type==="number"||property.type==="integer"){let parsed=Number(answer);if(!Number.isFinite(parsed))return{action:"decline"};content[name]=parsed;continue}content[name]=answer}return{action:"accept",content}}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options){let client=await buildMcpClient(options.elicitationUiProvider);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}async function buildMcpClient(elicitationUiProvider){let{Client:McpClient}=await loadMcpSdkClient(),client=new McpClient({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:MCP_CLIENT_ELICITATION_CAPABILITY});return await configureMcpElicitation(client,elicitationUiProvider),client}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink){let pending="",stderr=transport.stderr;stderr!=null&&(safeOn(stderr,"data","transport.stderr.data",chunk=>{if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;pending+=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logger.stderr(line)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{pending.length>0&&logger.stderr(pending),pending=""},sink))}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}import{Buffer as Buffer2}from"node:buffer";var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params);return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=/^[\x20-\x7E]*$/.test(name)&&!name.startsWith("base64:")?name:`base64:${Buffer2.from(name,"utf8").toString("base64url")}`),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord(response)||response.jsonrpc!=="2.0"||!isRecord(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}function mutualVersion(error,options){if(!(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions))return error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1)}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
2
+ import{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-HPCS4HM4.js";import{ConnectError,createMcpLogger,isMcpNeedsAuthError,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,loadMcpSdkTypes,reapProcessTree,safeOn,safeTimer}from"./chunk-CDRFFHLL.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";var MCP_CLIENT_ELICITATION_CAPABILITY={elicitation:{}};function mcpClientCapabilities(elicitationEnabled=!0){return elicitationEnabled?MCP_CLIENT_ELICITATION_CAPABILITY:{}}var MCP_ELICITATION_TIMEOUT_MS=300*1e3,legacyUiProvider;async function rejectElicitation(){let{ErrorCode,McpError}=await loadMcpSdkTypes();throw new McpError(ErrorCode.InternalError,"Elicitation cannot be processed")}async function configureMcpElicitation(client,owner=legacyUiProvider,timeoutMs=MCP_ELICITATION_TIMEOUT_MS,elicitationEnabled=!0){if(!elicitationEnabled){let{ErrorCode,McpError}=await loadMcpSdkTypes();client.fallbackRequestHandler=async request2=>{if(request2.method==="elicitation/create")return rejectElicitation();throw new McpError(ErrorCode.MethodNotFound,"Method not found")};return}let{ElicitRequestSchema}=await loadMcpSdkTypes();client.setRequestHandler(ElicitRequestSchema,async request2=>{let params=request2.params;if(!("requestedSchema"in params))return rejectElicitation();let ui=typeof owner=="function"?owner():owner?.getMcpElicitationUi();return ui===void 0?rejectElicitation():await runElicitationForm(ui,params.message,params.requestedSchema,timeoutMs)})}async function runElicitationForm(ui,message,requestedSchema,timeoutMs=MCP_ELICITATION_TIMEOUT_MS){let timer,timeout=new Promise(resolve=>{timer=safeTimer("mcp.elicitation.timeout",timeoutMs,()=>resolve({action:"cancel"}),{logger:createMcpLogger("elicitation")})});try{return await Promise.race([collectForm(ui,message,requestedSchema),timeout])}finally{timer!==void 0&&clearTimeout(timer)}}async function collectForm(ui,message,requestedSchema){let content={},required=new Set(requestedSchema.required??[]);for(let[name,property]of Object.entries(requestedSchema.properties??{})){let title=`${message} - ${property.title??name}`;if(property.type==="boolean"){let picked=await ui.select(property.description?`${title}
3
+ ${property.description}`:title,["Yes","No"]);if(picked===void 0)return{action:"cancel"};switch(picked.trim().toLowerCase()){case"yes":case"y":case"true":content[name]=!0;break;case"no":case"n":case"false":content[name]=!1;break;default:return rejectElicitation()}continue}if(Array.isArray(property.enum)&&property.enum.length>0){let picked=await ui.select(title,property.enum.map(String));if(picked===void 0)return{action:"cancel"};content[name]=picked;continue}let answer=await ui.input(title,property.description);if(answer===void 0)return{action:"cancel"};if(answer.length===0){if(required.has(name))return rejectElicitation();continue}if(property.type==="number"||property.type==="integer"){let parsed=Number(answer);if(!Number.isFinite(parsed))return rejectElicitation();content[name]=parsed;continue}content[name]=answer}return Object.keys(content).length===0&&await ui.select(message,["Submit"])!=="Submit"?{action:"cancel"}:{action:"accept",content}}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options){let client=await buildMcpClient(options.elicitationUiProvider,options.elicitationEnabled);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}async function buildMcpClient(elicitationUiProvider,elicitationEnabled=!0){let{Client:McpClient}=await loadMcpSdkClient(),client=new McpClient({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:mcpClientCapabilities(elicitationEnabled)});return await configureMcpElicitation(client,elicitationUiProvider,void 0,elicitationEnabled),client}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink){let pending="",stderr=transport.stderr;stderr!=null&&(safeOn(stderr,"data","transport.stderr.data",chunk=>{if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;pending+=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logger.stderr(line)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{pending.length>0&&logger.stderr(pending),pending=""},sink))}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}import{Buffer as Buffer2}from"node:buffer";var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params);return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=/^[\x20-\x7E]*$/.test(name)&&!name.startsWith("base64:")?name:`base64:${Buffer2.from(name,"utf8").toString("base64url")}`),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord(response)||response.jsonrpc!=="2.0"||!isRecord(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}function mutualVersion(error,options){if(!(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions))return error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1)}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
3
4
  `).split(`
4
5
 
5
6
  `)){let data=event.split(`
6
7
  `).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).replace(/^ /,"")).join(`
7
8
  `),value=parseJson(data);if(complete(value)||modernError(value))return value}}async function probeHttpEra(url,fetch,options){let version=MODERN_PROTOCOL_VERSION;for(let attempt=0;attempt<2;attempt++){let response,value;try{let discoveryRequest=request(options,version);response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...deriveModernHeaders(discoveryRequest)},body:JSON.stringify(discoveryRequest)}),value=await body(response)}catch(cause){if(isMcpNeedsAuthError(cause))throw cause;return indeterminate("transport","Check the MCP endpoint connection and retry discovery.",{cause})}let error=modernError(value);if(response.status===400){if(!error)return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(error.code!==-32022)return{kind:attempt?"modern-version-retry":"modern-OK",version,error};if(attempt===1)return indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});let mutual=mutualVersion(error,options);if(!mutual)return indeterminate("no-mutual-version","Update client or server to share a supported protocol version.",{era:"modern"});version=mutual;continue}if(!error&&errorReply(value))return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(!response.ok)return indeterminate("http-status","Check endpoint, authentication, or server health before retrying.",{status:response.status});let discovery=complete(value);return discovery?{kind:attempt?"modern-version-retry":"modern-OK",version,discovery}:error?{kind:attempt?"modern-version-retry":"modern-OK",version,error}:indeterminate("invalid-discovery","Check that the server returns a complete server/discover envelope.")}return indeterminate("version-retry-rejected","Update client or server protocol versions.",{era:"modern"})}async function probeStdioEra(send,options){let version=MODERN_PROTOCOL_VERSION,retryRejected=()=>indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});for(let attempt=0;attempt<2;attempt++){let id=attempt===0?STDIO_PROBE_ID:`${STDIO_PROBE_ID}-${attempt}`,value;try{value=await send(request(options,version,id))}catch(error2){return attempt>0?retryRejected():error2 instanceof StdioProbeSilence?{kind:"legacy-fallback",silent:!0}:{kind:"legacy-fallback",restart:!0}}let kind=attempt===0?"modern-OK":"modern-version-retry",discovery=complete(value,id);if(discovery)return{kind,version,discovery};if(!errorReply(value,id))return attempt>0?retryRejected():{kind:"legacy-fallback",restart:!0};let error=modernError(value);if(!error)return attempt>0?retryRejected():{kind:"legacy-fallback"};let mutual=attempt===0?mutualVersion(error,options):void 0;if(!mutual)return{kind,version,error};version=mutual}return retryRejected()}function modernHttpFetch(spec,signal){let fetch=fetchWithinOrigin();return async(url,init)=>{let requestSignal=init?.signal?AbortSignal.any([signal,init.signal]):signal,send=()=>{let headers=new Headers,tokens=spec.authProvider?.tokens();tokens&&headers.set("Authorization",`Bearer ${tokens.access_token}`),new Headers(spec.requestInit?.headers).forEach((value,key)=>{headers.set(key,value)});for(let key of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(key);return new Headers(init?.headers).forEach((value,key)=>{headers.set(key,value)}),headers.delete("Mcp-Session-Id"),fetch(url,{...spec.requestInit,...init,headers,signal:requestSignal})},response=await send();if(spec.authProvider&&(response.status===401||response.status===403)){let{auth,extractWWWAuthenticateParams,UnauthorizedError}=await loadMcpSdkAuth(),{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(response.status===401||error==="insufficient_scope"){if(await response.body?.cancel(),await auth(spec.authProvider,{serverUrl:spec.url,resourceMetadataUrl,scope,fetchFn:(target,request2)=>fetch(target,{...request2,signal:request2?.signal?AbortSignal.any([requestSignal,request2.signal]):requestSignal})})!=="AUTHORIZED")throw new UnauthorizedError;if(response=await send(),response.status===401)throw await response.body?.cancel(),new UnauthorizedError("Server returned 401 after successful authentication")}}return response}}var ModernTransportError=class extends Error{constructor(message){super(message),this.name="ModernTransportError"}},ModernHttpTransport=class{#options;#abort=new AbortController;#started=!1;#closed=!1;constructor(options){this.#options=options}async start(){if(this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport cannot be started twice");this.#started=!0}async close(){this.#closed||(this.#closed=!0,this.#abort.abort(),this.onclose?.())}async send(message){if(!this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport is not open");try{let version=this.#options.protocolVersion??MODERN_PROTOCOL_VERSION,headers=new Headers(this.#options.headers);for(let name of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(name);headers.set("Content-Type","application/json"),headers.set("Accept","application/json, text/event-stream");let body2=message;if("method"in message){let request2=modernizeRequest("id"in message?message.id:0,message.method,this.#options.clientInfo,this.#options.clientCapabilities,version,message.params);for(let[name,value]of Object.entries(deriveModernHeaders(request2)))headers.set(name,value);if("id"in message)body2=request2;else{let{id:_id,...notification}=request2;body2=notification}}else headers.set("MCP-Protocol-Version",version);let response=await this.#options.fetch(this.#options.url,{method:"POST",headers,body:JSON.stringify(body2),signal:this.#abort.signal});if(this.#abort.signal.throwIfAborted(),response.status===202||response.status===204)return;let mediaType=response.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase();if(mediaType==="application/json"){let incoming=JSONRPCMessageSchema.parse(await response.json());if(!response.ok&&!("error"in incoming))throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status}`);this.#abort.signal.throwIfAborted(),this.onmessage?.(incoming)}else if(response.ok&&mediaType==="text/event-stream"&&response.body)await this.#consumeSse(response.body,"method"in message&&"id"in message?message.id:void 0);else throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status} (${mediaType??"no content type"})`)}catch(error){let failure=error instanceof Error?error:new ModernTransportError(String(error));throw this.onerror?.(failure),failure}}async#consumeSse(stream,requestId){let reader=stream.getReader(),decoder=new TextDecoder,aborted=Promise.withResolvers(),onabort=()=>aborted.reject(this.#abort.signal.reason);this.#abort.signal.addEventListener("abort",onabort,{once:!0});let buffer="",data=[],event="";try{for(;;){let{value,done}=await Promise.race([reader.read(),aborted.promise]);for(this.#abort.signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});;){let match=/[\r\n]/.exec(buffer);if(match===null)break;let end=match.index;if(!done&&buffer[end]==="\r"&&end+1===buffer.length)break;let line=buffer.slice(0,end);if(buffer=buffer.slice(end+(buffer.slice(end,end+2)===`\r
8
9
  `?2:1)),line===""){if(data.length>0&&(event===""||event==="message")){let incoming=JSONRPCMessageSchema.parse(JSON.parse(data.join(`
9
- `)));if(this.onmessage?.(incoming),"id"in incoming&&!("method"in incoming)&&incoming.id===requestId)return}data=[],event=""}else if(!line.startsWith(":")){let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),text=colon===-1?"":line.slice(colon+1).replace(/^ /,"");field==="data"&&data.push(text),field==="event"&&(event=text)}}if(done){if(requestId!==void 0)throw new ModernTransportError("Modern MCP SSE ended before the request response");return}}}finally{this.#abort.signal.removeEventListener("abort",onabort),await reader.cancel(),reader.releaseLock()}}};function modernInitializeResult(discovery,wireVersion){if(!discovery.supportedVersions.includes(wireVersion))throw new ModernTransportError(`Discovery does not support negotiated MCP version ${wireVersion}`);return InitializeResultSchema.parse({protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:discovery.capabilities,serverInfo:discovery._meta["io.modelcontextprotocol/serverInfo"],...discovery.instructions===void 0?{}:{instructions:discovery.instructions}})}function normalizeModernResult(message){return"result"in message&&message.result.nextCursor===null&&delete message.result.nextCursor,message}var ModernSdkBridge=class{#transport;#initializeResult;#initialized=!1;constructor(transport,discovery,wireVersion){this.#initializeResult=modernInitializeResult(discovery,wireVersion),this.#transport=transport}async start(){this.#transport.onmessage=(message,extra)=>{this.onmessage?.(normalizeModernResult(message),extra)},this.#transport.onclose=()=>this.onclose?.(),this.#transport.onerror=error=>this.onerror?.(error),await this.#transport.start()}async send(message,options){if("method"in message&&message.method==="initialize"){if(!("id"in message)||this.#initialized)throw new ModernTransportError("Modern MCP bridge has already initialized");this.#initialized=!0,this.onmessage?.({jsonrpc:"2.0",id:message.id,result:this.#initializeResult});return}"method"in message&&message.method==="notifications/initialized"&&!("id"in message)||await this.#transport.send(message,options)}close(){return this.#transport.close()}};var STDIO_PROBE_MS=2e3;function probeStdioTransport(transport,options,logger,timeoutMs,serverName,onModern,probeMs=STDIO_PROBE_MS){let start=transport.start.bind(transport),close=transport.close.bind(transport),send=transport.send.bind(transport),abort=new AbortController;transport.close=async()=>{abort.abort(),await close()},transport.start=async()=>{await start();let outcome=await probeStdioEra(exchange,options);if(abort.signal.throwIfAborted(),outcome.kind==="legacy-fallback"){outcome.restart?await restart():outcome.silent&&awaitLateDiscovery();return}if(outcome.kind==="indeterminate"||!outcome.discovery){let reason=outcome.kind==="indeterminate"?outcome.reason:outcome.error?.message,message=`MCP server ${serverName} modern discovery failed: ${reason}`;throw logger.error(message),new ConnectError(message,{phase:"modern-stdio",serverName})}speakModern(outcome.discovery,outcome.version),onModern?.(outcome.version)};async function exchange(request2){let reply=Promise.withResolvers(),signal=AbortSignal.any([abort.signal,AbortSignal.timeout(Math.min(probeMs,Math.floor(timeoutMs/4)))]),onabort=()=>reply.reject(abort.signal.aborted?abort.signal.reason:new StdioProbeSilence),{onmessage,onclose,onerror}=transport;signal.addEventListener("abort",onabort,{once:!0}),transport.onmessage=(message,extra)=>{"id"in message&&!("method"in message)&&message.id===request2.id?reply.resolve(message):onmessage?.(message,extra)},transport.onclose=()=>reply.reject(new ModernTransportError("MCP stdio closed during discovery")),transport.onerror=error=>reply.reject(error);try{return signal.throwIfAborted(),send(request2).catch(reply.reject),await reply.promise}finally{signal.removeEventListener("abort",onabort),transport.onmessage=onmessage,transport.onclose=onclose,transport.onerror=onerror}}async function restart(){logger.info(`MCP server ${serverName}: no clean discovery answer; restarting it for the legacy handshake`);let pid=transport.pid,stale=pid==null?0:1,onclose=transport.onclose;transport.onclose=()=>{stale>0?stale--:onclose?.()},pid!=null&&await reapProcessTree(pid,{termWaitMs:200,killWaitMs:200}),await close(),stale=0,abort.signal.throwIfAborted(),await start(),abort.signal.aborted&&(await close(),abort.signal.throwIfAborted())}function awaitLateDiscovery(){let{onmessage:deliver,onclose,onerror}=transport,late,initialize,initializeId,restarting,settle=()=>{transport.onmessage=deliver,transport.onclose=onclose,transport.onerror=onerror,transport.send=send},unclean=report=>{if(restarting)return report();let replay=initialize;restarting=(async()=>{try{await restart(),replay&&await send(replay)}catch(error){abort.signal.aborted||onerror?.(error instanceof Error?error:new Error(String(error))),onclose?.()}})()};transport.onclose=()=>unclean(()=>onclose?.()),transport.onerror=error=>unclean(()=>onerror?.(error)),transport.onmessage=(message,extra)=>{if("id"in message&&!("method"in message)&&typeof message.id=="string"&&message.id.startsWith(STDIO_PROBE_ID)){late??=discoveryReply(message,message.id);return}let isInitializeReply=initializeId!==void 0&&"id"in message&&message.id===initializeId;if(isInitializeReply&&late&&"error"in message&&late.supportedVersions.includes(MODERN_PROTOCOL_VERSION)){let discovery=late;logger.info(`MCP server ${serverName}: late discovery reply; switching to modern`),settle(),speakModern(discovery,MODERN_PROTOCOL_VERSION),onModern?.(MODERN_PROTOCOL_VERSION),deliver?.({jsonrpc:"2.0",id:initializeId,result:modernInitializeResult(discovery,MODERN_PROTOCOL_VERSION)},extra);return}isInitializeReply&&settle(),deliver?.(message,extra)},transport.send=async(message,sendOptions)=>("method"in message&&message.method==="initialize"&&"id"in message&&(initialize=message,initializeId=message.id),restarting&&await restarting,send(message,sendOptions))}function speakModern(discovery,version){let initializeResult=modernInitializeResult(discovery,version),deliver=transport.onmessage,initialized=!1;transport.onmessage=(message,extra)=>deliver?.(normalizeModernResult(message),extra),transport.send=async(message,sendOptions)=>{if(!("method"in message))return send(message,sendOptions);if(message.method==="initialize"){if(!("id"in message)||initialized)throw new ModernTransportError("Modern MCP stdio has already initialized");initialized=!0,transport.onmessage?.({jsonrpc:"2.0",id:message.id,result:initializeResult});return}if(message.method==="notifications/initialized"&&!("id"in message))return;let request2=modernizeRequest("id"in message?message.id:0,message.method,options.clientInfo,options.clientCapabilities,version,message.params);if("id"in message)return send(request2,sendOptions);let{id:_id,...notification}=request2;return send(notification,sendOptions)}}}var clientInfo={name:"senpi-mcp-client",version:"0.0.0"},probeOptions={clientInfo,clientCapabilities:MCP_CLIENT_ELICITATION_CAPABILITY,supportedVersions:[MODERN_PROTOCOL_VERSION]};async function materializeNegotiatedTransport(options,serverName,timeoutMs,signal){signal.throwIfAborted();let{spec,logger}=options,outcome={kind:"legacy-fallback"};if(spec.kind==="http"){let fetch=modernHttpFetch(spec,signal),timeout=AbortSignal.timeout(timeoutMs);if(outcome=await probeHttpEra(spec.url,(url,init)=>fetch(url,{...init,signal:timeout}),probeOptions),signal.throwIfAborted(),timeout.throwIfAborted(),outcome.kind==="modern-OK"||outcome.kind==="modern-version-retry"){if(!outcome.discovery)throw new ConnectError(`MCP server ${serverName} modern discovery failed: ${outcome.error?.message}`,{phase:"connect",serverName});let{Client}=await loadMcpSdkClient(),client=new Client(clientInfo,{capabilities:MCP_CLIENT_ELICITATION_CAPABILITY});await configureMcpElicitation(client,options.elicitationUiProvider);let transport=new ModernSdkBridge(new ModernHttpTransport({url:spec.url,fetch,clientInfo,clientCapabilities:MCP_CLIENT_ELICITATION_CAPABILITY,protocolVersion:outcome.version}),outcome.discovery,outcome.version),version=outcome.version;return logVersion(transport,()=>version),{client,transport,readPid:()=>null,close:async()=>{await transport.close(),await client.close()}}}if(outcome.kind==="indeterminate"&&(outcome.era==="modern"||outcome.reason==="invalid-discovery"))throw new ConnectError(`MCP server ${serverName}: ${outcome.reason}. ${outcome.action}`,{phase:"connect",serverName,cause:outcome.cause})}let legacy=await materializeMcpTransport(options),stdioModernVersion;return spec.kind==="stdio"&&probeStdioTransport(legacy.transport,probeOptions,logger,timeoutMs,serverName,version=>{stdioModernVersion=version}),logVersion(legacy.transport,()=>stdioModernVersion),legacy;function logVersion(transport,readModernVersion){let setVersion=transport.setProtocolVersion?.bind(transport);transport.setProtocolVersion=sdkVersion=>{setVersion?.(sdkVersion);let modernVersion=readModernVersion();logger.info(`MCP server ${serverName} negotiated: era=${modernVersion?"modern":"legacy"} version=${modernVersion??sdkVersion}`)}}}export{materializeNegotiatedTransport};
10
+ `)));if(this.onmessage?.(incoming),"id"in incoming&&!("method"in incoming)&&incoming.id===requestId)return}data=[],event=""}else if(!line.startsWith(":")){let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),text=colon===-1?"":line.slice(colon+1).replace(/^ /,"");field==="data"&&data.push(text),field==="event"&&(event=text)}}if(done){if(requestId!==void 0)throw new ModernTransportError("Modern MCP SSE ended before the request response");return}}}finally{this.#abort.signal.removeEventListener("abort",onabort),await reader.cancel(),reader.releaseLock()}}};function modernInitializeResult(discovery,wireVersion){if(!discovery.supportedVersions.includes(wireVersion))throw new ModernTransportError(`Discovery does not support negotiated MCP version ${wireVersion}`);return InitializeResultSchema.parse({protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:discovery.capabilities,serverInfo:discovery._meta["io.modelcontextprotocol/serverInfo"],...discovery.instructions===void 0?{}:{instructions:discovery.instructions}})}function normalizeModernResult(message){return"result"in message&&message.result.nextCursor===null&&delete message.result.nextCursor,message}var ModernSdkBridge=class{#transport;#initializeResult;#initialized=!1;constructor(transport,discovery,wireVersion){this.#initializeResult=modernInitializeResult(discovery,wireVersion),this.#transport=transport}async start(){this.#transport.onmessage=(message,extra)=>{this.onmessage?.(normalizeModernResult(message),extra)},this.#transport.onclose=()=>this.onclose?.(),this.#transport.onerror=error=>this.onerror?.(error),await this.#transport.start()}async send(message,options){if("method"in message&&message.method==="initialize"){if(!("id"in message)||this.#initialized)throw new ModernTransportError("Modern MCP bridge has already initialized");this.#initialized=!0,this.onmessage?.({jsonrpc:"2.0",id:message.id,result:this.#initializeResult});return}"method"in message&&message.method==="notifications/initialized"&&!("id"in message)||await this.#transport.send(message,options)}close(){return this.#transport.close()}};var STDIO_PROBE_MS=2e3;function probeStdioTransport(transport,options,logger,timeoutMs,serverName,onModern,probeMs=STDIO_PROBE_MS){let start=transport.start.bind(transport),close=transport.close.bind(transport),send=transport.send.bind(transport),abort=new AbortController;transport.close=async()=>{abort.abort(),await close()},transport.start=async()=>{await start();let outcome=await probeStdioEra(exchange,options);if(abort.signal.throwIfAborted(),outcome.kind==="legacy-fallback"){outcome.restart?await restart():outcome.silent&&awaitLateDiscovery();return}if(outcome.kind==="indeterminate"||!outcome.discovery){let reason=outcome.kind==="indeterminate"?outcome.reason:outcome.error?.message,message=`MCP server ${serverName} modern discovery failed: ${reason}`;throw logger.error(message),new ConnectError(message,{phase:"modern-stdio",serverName})}speakModern(outcome.discovery,outcome.version),onModern?.(outcome.version)};async function exchange(request2){let reply=Promise.withResolvers(),signal=AbortSignal.any([abort.signal,AbortSignal.timeout(Math.min(probeMs,Math.floor(timeoutMs/4)))]),onabort=()=>reply.reject(abort.signal.aborted?abort.signal.reason:new StdioProbeSilence),{onmessage,onclose,onerror}=transport;signal.addEventListener("abort",onabort,{once:!0}),transport.onmessage=(message,extra)=>{"id"in message&&!("method"in message)&&message.id===request2.id?reply.resolve(message):onmessage?.(message,extra)},transport.onclose=()=>reply.reject(new ModernTransportError("MCP stdio closed during discovery")),transport.onerror=error=>reply.reject(error);try{return signal.throwIfAborted(),send(request2).catch(reply.reject),await reply.promise}finally{signal.removeEventListener("abort",onabort),transport.onmessage=onmessage,transport.onclose=onclose,transport.onerror=onerror}}async function restart(){logger.info(`MCP server ${serverName}: no clean discovery answer; restarting it for the legacy handshake`);let pid=transport.pid,stale=pid==null?0:1,onclose=transport.onclose;transport.onclose=()=>{stale>0?stale--:onclose?.()},pid!=null&&await reapProcessTree(pid,{termWaitMs:200,killWaitMs:200}),await close(),stale=0,abort.signal.throwIfAborted(),await start(),abort.signal.aborted&&(await close(),abort.signal.throwIfAborted())}function awaitLateDiscovery(){let{onmessage:deliver,onclose,onerror}=transport,late,initialize,initializeId,restarting,settle=()=>{transport.onmessage=deliver,transport.onclose=onclose,transport.onerror=onerror,transport.send=send},unclean=report=>{if(restarting)return report();let replay=initialize;restarting=(async()=>{try{await restart(),replay&&await send(replay)}catch(error){abort.signal.aborted||onerror?.(error instanceof Error?error:new Error(String(error))),onclose?.()}})()};transport.onclose=()=>unclean(()=>onclose?.()),transport.onerror=error=>unclean(()=>onerror?.(error)),transport.onmessage=(message,extra)=>{if("id"in message&&!("method"in message)&&typeof message.id=="string"&&message.id.startsWith(STDIO_PROBE_ID)){late??=discoveryReply(message,message.id);return}let isInitializeReply=initializeId!==void 0&&"id"in message&&message.id===initializeId;if(isInitializeReply&&late&&"error"in message&&late.supportedVersions.includes(MODERN_PROTOCOL_VERSION)){let discovery=late;logger.info(`MCP server ${serverName}: late discovery reply; switching to modern`),settle(),speakModern(discovery,MODERN_PROTOCOL_VERSION),onModern?.(MODERN_PROTOCOL_VERSION),deliver?.({jsonrpc:"2.0",id:initializeId,result:modernInitializeResult(discovery,MODERN_PROTOCOL_VERSION)},extra);return}isInitializeReply&&settle(),deliver?.(message,extra)},transport.send=async(message,sendOptions)=>("method"in message&&message.method==="initialize"&&"id"in message&&(initialize=message,initializeId=message.id),restarting&&await restarting,send(message,sendOptions))}function speakModern(discovery,version){let initializeResult=modernInitializeResult(discovery,version),deliver=transport.onmessage,initialized=!1;transport.onmessage=(message,extra)=>deliver?.(normalizeModernResult(message),extra),transport.send=async(message,sendOptions)=>{if(!("method"in message))return send(message,sendOptions);if(message.method==="initialize"){if(!("id"in message)||initialized)throw new ModernTransportError("Modern MCP stdio has already initialized");initialized=!0,transport.onmessage?.({jsonrpc:"2.0",id:message.id,result:initializeResult});return}if(message.method==="notifications/initialized"&&!("id"in message))return;let request2=modernizeRequest("id"in message?message.id:0,message.method,options.clientInfo,options.clientCapabilities,version,message.params);if("id"in message)return send(request2,sendOptions);let{id:_id,...notification}=request2;return send(notification,sendOptions)}}}var clientInfo={name:"senpi-mcp-client",version:"0.0.0"};async function materializeNegotiatedTransport(options,serverName,timeoutMs,signal){signal.throwIfAborted();let clientCapabilities=mcpClientCapabilities(options.elicitationEnabled),probeOptions={clientInfo,clientCapabilities,supportedVersions:[MODERN_PROTOCOL_VERSION]},{spec,logger}=options,outcome={kind:"legacy-fallback"};if(spec.kind==="http"){let fetch=modernHttpFetch(spec,signal),timeout=AbortSignal.timeout(timeoutMs);if(outcome=await probeHttpEra(spec.url,(url,init)=>fetch(url,{...init,signal:timeout}),probeOptions),signal.throwIfAborted(),timeout.throwIfAborted(),outcome.kind==="modern-OK"||outcome.kind==="modern-version-retry"){if(!outcome.discovery)throw new ConnectError(`MCP server ${serverName} modern discovery failed: ${outcome.error?.message}`,{phase:"connect",serverName});let{Client}=await loadMcpSdkClient(),client=new Client(clientInfo,{capabilities:clientCapabilities});await configureMcpElicitation(client,options.elicitationUiProvider,void 0,options.elicitationEnabled);let transport=new ModernSdkBridge(new ModernHttpTransport({url:spec.url,fetch,clientInfo,clientCapabilities,protocolVersion:outcome.version}),outcome.discovery,outcome.version),version=outcome.version;return logVersion(transport,()=>version),{client,transport,readPid:()=>null,close:async()=>{await transport.close(),await client.close()}}}if(outcome.kind==="indeterminate"&&(outcome.era==="modern"||outcome.reason==="invalid-discovery"))throw new ConnectError(`MCP server ${serverName}: ${outcome.reason}. ${outcome.action}`,{phase:"connect",serverName,cause:outcome.cause})}let legacy=await materializeMcpTransport(options),stdioModernVersion;return spec.kind==="stdio"&&probeStdioTransport(legacy.transport,probeOptions,logger,timeoutMs,serverName,version=>{stdioModernVersion=version}),logVersion(legacy.transport,()=>stdioModernVersion),legacy;function logVersion(transport,readModernVersion){let setVersion=transport.setProtocolVersion?.bind(transport);transport.setProtocolVersion=sdkVersion=>{setVersion?.(sdkVersion);let modernVersion=readModernVersion();logger.info(`MCP server ${serverName} negotiated: era=${modernVersion?"modern":"legacy"} version=${modernVersion??sdkVersion}`)}}}export{materializeNegotiatedTransport};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-SGATKHO4.js";import"./chunk-MLVIYDHK.js";import"./chunk-GZVCRV7I.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
2
+ import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-Y5OTHMXO.js";import"./chunk-MLVIYDHK.js";import"./chunk-GZVCRV7I.js";import"./chunk-U67ML6CQ.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-MRN6IKOQ.js";import"./chunk-4TRKE3ZC.js";import"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import"./chunk-II22E3CV.js";import"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
2
+ import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-3VOG6WFU.js";import"./chunk-BMYNMUVZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-U67ML6CQ.js";import"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import"./chunk-II22E3CV.js";import"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};