@code-yeongyu/senpi 2026.11.2-3 → 2026.11.3-1

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 (169) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/bundle/chunks/{anthropic-messages-WUPLDYD6.js → anthropic-messages-AFWQB3KN.js} +1 -1
  3. package/dist/bundle/chunks/{args-AOI4NEA6.js → args-O3WS4WCO.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-O4GRBX4R.js → chunk-3WJ2DE2G.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-LMIETUPG.js → chunk-4BF4FLT6.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-T5ZJ2Q4O.js → chunk-4SENPCEA.js} +1 -1
  7. package/dist/bundle/chunks/chunk-5DZD623T.js +448 -0
  8. package/dist/bundle/chunks/{chunk-TXOR5BQL.js → chunk-6BSMXZKQ.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-VRWJJMHO.js → chunk-7565XQAU.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-IWM5QRAE.js → chunk-7KLEFHSU.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-FO56LSUK.js → chunk-BNIZP4OS.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-L3V65XW7.js → chunk-CJWSQ6CK.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-QLTQ3UUI.js → chunk-DAPBNRN5.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-GIY7PGOH.js → chunk-DPBPO5OU.js} +1 -1
  15. package/dist/bundle/chunks/chunk-ESQBKTNG.js +2 -0
  16. package/dist/bundle/chunks/{chunk-N4TSAHRL.js → chunk-EVTTLPIY.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-NYXXKS6D.js → chunk-F4OHTL2K.js} +3 -2
  18. package/dist/bundle/chunks/{chunk-TVMW2SUP.js → chunk-FJ2UCBOA.js} +2 -2
  19. package/dist/bundle/chunks/{chunk-KVPRQ5KN.js → chunk-FLM6GZPT.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-P4AT7SBE.js → chunk-HBCNDC53.js} +1 -1
  21. package/dist/bundle/chunks/chunk-MOH5HOHX.js +2 -0
  22. package/dist/bundle/chunks/{chunk-7FUO655J.js → chunk-MOOFLKLI.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-IHOQR7TU.js → chunk-PX7FF5LE.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-QAM6AXA2.js → chunk-QTQ3ES2S.js} +12 -9
  25. package/dist/bundle/chunks/{chunk-FJSJUVQQ.js → chunk-TOOB6OLG.js} +3 -3
  26. package/dist/bundle/chunks/{chunk-662SCMTH.js → chunk-VPDQ6MOL.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-BW4YXS7X.js → chunk-WCRNJYHO.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-ZSVWKOAJ.js → chunk-ZNLCKKF6.js} +170 -226
  29. package/dist/bundle/chunks/{cli-main-534A3WSC.js → cli-main-XM5FWY3Z.js} +1 -1
  30. package/dist/bundle/chunks/{credential-accounts-OAK2E5O2.js → credential-accounts-YZYSKA7X.js} +1 -1
  31. package/dist/bundle/chunks/{health-write-EB4CPHXN.js → health-write-45CX64T2.js} +1 -1
  32. package/dist/bundle/chunks/{help-fast-path-U2PSNNWO.js → help-fast-path-3EDGRKQM.js} +1 -1
  33. package/dist/bundle/chunks/{host-command-WJIMRBGN.js → host-command-PZ4VYQIW.js} +1 -1
  34. package/dist/bundle/chunks/{host-session-command-PWVPQ2OV.js → host-session-command-OJFARE5Q.js} +1 -1
  35. package/dist/bundle/chunks/{interactive-mode-NPHFDPGH.js → interactive-mode-7JSJVVIS.js} +1 -1
  36. package/dist/bundle/chunks/{login-health-7G2DZVOV.js → login-health-YOPTYRTU.js} +1 -1
  37. package/dist/bundle/chunks/{main-I6FJAFUP.js → main-3YGJ2O4I.js} +1 -1
  38. package/dist/bundle/chunks/{multi-session-host-7E26R5JF.js → multi-session-host-N2RQ7JSZ.js} +4 -4
  39. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  40. package/dist/bundle/chunks/{openai-codex-responses-VNBMMIL3.js → openai-codex-responses-YTWLG4OL.js} +1 -1
  41. package/dist/bundle/chunks/{openai-completions-JLR32APM.js → openai-completions-TIFDYHZL.js} +1 -1
  42. package/dist/bundle/chunks/{openai-images-LEBNERSM.js → openai-images-OAEMY4RG.js} +1 -1
  43. package/dist/bundle/chunks/{openai-responses-JCDUNMHA.js → openai-responses-L35NIG5Y.js} +1 -1
  44. package/dist/bundle/chunks/{package-manager-cli-CBSDV36M.js → package-manager-cli-JPNA27E5.js} +1 -1
  45. package/dist/bundle/chunks/{role-LP6LVNCY.js → role-45Y7PQFC.js} +1 -1
  46. package/dist/bundle/chunks/{rotation-stream-ZDCNHIBE.js → rotation-stream-WXWJKJZN.js} +1 -1
  47. package/dist/bundle/chunks/{rpc-mode-GBBTN2WP.js → rpc-mode-Z7MN2ZWA.js} +1 -1
  48. package/dist/bundle/chunks/{run-attached-tui-PVLUHHJX.js → run-attached-tui-TI6MELEI.js} +1 -1
  49. package/dist/bundle/chunks/{schedule-command-W45NYTTK.js → schedule-command-OZ5ESMIT.js} +1 -1
  50. package/dist/bundle/chunks/{session-control-endpoint-LFLUNALC.js → session-control-endpoint-5YKBYJOO.js} +1 -1
  51. package/dist/bundle/chunks/{session-picker-OZUINLD7.js → session-picker-CMRV72VA.js} +1 -1
  52. package/dist/bundle/chunks/session-worker.js +324 -376
  53. package/dist/bundle/chunks/{state-store-SZARKD36.js → state-store-Q47AYMRI.js} +1 -1
  54. package/dist/bundle/cli.js +2 -2
  55. package/dist/bundle/index.js +1 -1
  56. package/dist/bundle/rpc-entry.js +1 -1
  57. package/dist/bundle/runtime-manifest.json +1 -1
  58. package/dist/core/agent-session.d.ts +8 -0
  59. package/dist/core/agent-session.js +68 -60
  60. package/dist/core/credential-pool/classify.d.ts +3 -2
  61. package/dist/core/credential-pool/classify.js +10 -3
  62. package/dist/core/dynamic-prompt/build.d.ts +2 -1
  63. package/dist/core/dynamic-prompt/build.js +1 -2
  64. package/dist/core/dynamic-prompt/handoff.d.ts +1 -1
  65. package/dist/core/dynamic-prompt/handoff.js +9 -9
  66. package/dist/core/dynamic-prompt/identity.js +1 -1
  67. package/dist/core/dynamic-prompt/intent-gate.d.ts +1 -1
  68. package/dist/core/dynamic-prompt/intent-gate.js +8 -8
  69. package/dist/core/dynamic-prompt/policies.d.ts +1 -1
  70. package/dist/core/dynamic-prompt/policies.js +5 -7
  71. package/dist/core/dynamic-prompt/style.js +5 -5
  72. package/dist/core/dynamic-prompt/tool-section.d.ts +5 -0
  73. package/dist/core/dynamic-prompt/tool-section.js +8 -6
  74. package/dist/core/dynamic-prompt/verification.d.ts +6 -6
  75. package/dist/core/dynamic-prompt/verification.js +12 -12
  76. package/dist/core/dynamic-prompt/working-task.d.ts +1 -1
  77. package/dist/core/dynamic-prompt/working-task.js +3 -3
  78. package/dist/core/dynamic-prompt/workstation.js +1 -1
  79. package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.d.ts +13 -0
  80. package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js +64 -2
  81. package/dist/core/extensions/builtin/anthropic-subscription/session-stream.js +5 -1
  82. package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.d.ts +7 -0
  83. package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.js +28 -1
  84. package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts +2 -0
  85. package/dist/core/extensions/builtin/bash-timeout/index.d.ts +1 -1
  86. package/dist/core/extensions/builtin/bash-timeout/index.js +3 -28
  87. package/dist/core/extensions/builtin/bash-timeout/timeout.d.ts +0 -11
  88. package/dist/core/extensions/builtin/bash-timeout/timeout.js +0 -11
  89. package/dist/core/extensions/builtin/imagegen/index.d.ts +0 -1
  90. package/dist/core/extensions/builtin/imagegen/index.js +0 -11
  91. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +5 -5
  92. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +5 -5
  93. package/dist/core/extensions/builtin/prompt-preset/glm-5.d.ts +1 -1
  94. package/dist/core/extensions/builtin/prompt-preset/glm-5.js +1 -1
  95. package/dist/core/extensions/builtin/terminal/extension.js +8 -1
  96. package/dist/core/extensions/builtin/terminal/notify.js +9 -3
  97. package/dist/core/extensions/builtin/terminal/prompt.d.ts +7 -1
  98. package/dist/core/extensions/builtin/terminal/prompt.js +27 -60
  99. package/dist/core/extensions/builtin/terminal/tools/bash.js +10 -2
  100. package/dist/core/extensions/builtin/todotools/normalize.d.ts +20 -3
  101. package/dist/core/extensions/builtin/todotools/normalize.js +251 -5
  102. package/dist/core/extensions/builtin/todotools/prompt.d.ts +2 -2
  103. package/dist/core/extensions/builtin/todotools/prompt.js +5 -5
  104. package/dist/core/extensions/builtin/todotools/tools/todo.js +9 -8
  105. package/dist/core/extensions/builtin/webfetch/webfetch/tool.js +0 -5
  106. package/dist/core/extensions/builtin/websearch/index.js +9 -4
  107. package/dist/core/extensions/builtin/websearch/websearch/tool.d.ts +2 -0
  108. package/dist/core/extensions/builtin/websearch/websearch/tool.js +3 -1
  109. package/dist/core/model-runtime.js +1 -1
  110. package/dist/core/provider-failure.d.ts +6 -0
  111. package/dist/core/provider-failure.js +6 -2
  112. package/dist/core/retry-fallback/exhaustion.d.ts +18 -0
  113. package/dist/core/retry-fallback/exhaustion.js +20 -0
  114. package/dist/core/system-prompt.js +1 -1
  115. package/dist/core/tools/bash.d.ts +3 -1
  116. package/dist/core/tools/bash.js +14 -4
  117. package/dist/core/tools/edit.d.ts +1 -1
  118. package/dist/core/tools/edit.js +1 -6
  119. package/dist/core/tools/grep/index.js +2 -3
  120. package/dist/core/tools/powershell.d.ts +1 -1
  121. package/dist/core/tools/powershell.js +1 -1
  122. package/dist/core/tools/read.d.ts +1 -1
  123. package/dist/core/tools/read.js +1 -1
  124. package/dist/core/tools/write.d.ts +1 -1
  125. package/dist/core/tools/write.js +1 -1
  126. package/dist/engine-trust/shell-trust.d.ts +36 -0
  127. package/dist/engine-trust/shell-trust.js +44 -0
  128. package/dist/engine-trust/transport-failure.d.ts +12 -0
  129. package/dist/engine-trust/transport-failure.js +48 -0
  130. package/dist/modes/interactive/interactive-mode.js +9 -3
  131. package/dist/modes/print-mode.js +2 -1
  132. package/dist/modes/rpc/compact-catalog-families.d.ts +5 -2
  133. package/dist/modes/rpc/compact-catalog-families.js +5 -2
  134. package/dist/modes/rpc/compact-catalog-registry.d.ts +9 -1
  135. package/dist/modes/rpc/compact-catalog-registry.js +9 -2
  136. package/dist/modes/rpc/compact-recovery-manifest-kinds.d.ts +17 -0
  137. package/dist/modes/rpc/compact-recovery-manifest-kinds.js +21 -0
  138. package/dist/modes/rpc/compact-recovery-manifest-shape.d.ts +7 -0
  139. package/dist/modes/rpc/compact-recovery-manifest.js +11 -3
  140. package/dist/modes/rpc/compact-socket-commands.js +6 -0
  141. package/dist/modes/rpc/connection-handler.js +21 -5
  142. package/dist/modes/rpc/connection-question-bridge.d.ts +3 -1
  143. package/dist/modes/rpc/connection-question-bridge.js +4 -1
  144. package/dist/modes/rpc/connection-roles.d.ts +8 -0
  145. package/dist/modes/rpc/connection-roles.js +18 -0
  146. package/dist/modes/rpc/method-classes-schema-session.d.ts +4 -0
  147. package/dist/modes/rpc/method-classes-schema-session.js +1 -0
  148. package/dist/modes/rpc/method-classes-schema.d.ts +4 -0
  149. package/dist/modes/rpc/protocol-identity.js +2 -0
  150. package/dist/modes/rpc/remote-origin.d.ts +31 -0
  151. package/dist/modes/rpc/remote-origin.js +58 -0
  152. package/dist/modes/rpc/rpc-protocol-info-types.d.ts +8 -0
  153. package/dist/modes/rpc/rpc-question-types.d.ts +7 -0
  154. package/dist/modes/rpc/rpc-question-types.js +0 -3
  155. package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
  156. package/dist/modes/rpc/session-registry.js +12 -3
  157. package/dist/modes/rpc/session-worker-client.js +2 -0
  158. package/dist/modes/rpc/session-worker-protocol.d.ts +3 -0
  159. package/dist/modes/rpc/session-worker.js +2 -0
  160. package/docs/engine-socket/fixtures/admission-routes/c-baseline.json +3 -3
  161. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  162. package/docs/engine-socket/fixtures/admission-routes/i-reset-stream.json +3 -3
  163. package/docs/engine-socket/fixtures/recovery-manifest/index.json +32 -0
  164. package/docs/engine-socket/fixtures/recovery-manifest/one-partial-family.json +118 -0
  165. package/docs/rpc.md +93 -3
  166. package/package.json +6 -6
  167. package/dist/bundle/chunks/chunk-7UC4W2T2.js +0 -2
  168. package/dist/bundle/chunks/chunk-R23WXN4L.js +0 -448
  169. package/dist/bundle/chunks/chunk-W5NLCRB3.js +0 -2
@@ -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-L5OFGHDA.js";import{advanceSessionFence}from"./chunk-SOMFLLPD.js";import{killWindowsProcessTree}from"./chunk-T5ZJ2Q4O.js";import{APP_NAME}from"./chunk-ISZ4EWIS.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{processStartTimeMs,sameProcessStartMs}from"./chunk-O5RYI3IW.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-L5OFGHDA.js";import{advanceSessionFence}from"./chunk-SOMFLLPD.js";import{killWindowsProcessTree}from"./chunk-4SENPCEA.js";import{APP_NAME}from"./chunk-ISZ4EWIS.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{processStartTimeMs,sameProcessStartMs}from"./chunk-O5RYI3IW.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 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 join4}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 join4(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{buildProviderDiagnostic,categoryForTransportCode,classifyProviderFailure}from"./chunk-7UC4W2T2.js";import{attachProviderDiagnostic}from"./chunk-3SASTB6Y.js";var SSE_ERROR_ENVELOPE_MAX_BYTES=8192;function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function optionalString(value){if(value!=null)return typeof value=="string"?value:null}function anthropicProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),direct=optionalString(Reflect.get(error,"type")),body=Reflect.get(error,"error"),nested=isRecord(body)&&isRecord(body.error)?optionalString(body.error.type):void 0;if(direct===null||nested===null||direct!==void 0&&nested!==void 0&&direct!==nested)return;let code=direct??nested;if(code===void 0&&status==null)return;let diagnostic=classifyProviderFailure({status,code});if(diagnostic?.category!=="quota"&&diagnostic?.category!=="rate_limit")return diagnostic;let headers=Reflect.get(error,"headers");if(!(headers instanceof Headers))return diagnostic;let resets=["5h","7d"].flatMap(window=>{let utilization=Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`)),reset=Number(headers.get(`anthropic-ratelimit-unified-${window}-reset`))*1e3;return utilization>=1&&Number.isFinite(reset)&&reset>Date.now()?[reset]:[]});return resets.length===0?diagnostic:{...diagnostic,resetsAt:Math.max(...resets)}}catch{return}}function anthropicProviderDiagnosticFromSseData(data){try{if(new TextEncoder().encode(data).length>SSE_ERROR_ENVELOPE_MAX_BYTES)return;let parsed=JSON.parse(data);if(!isRecord(parsed)||parsed.type!=="error"||!isRecord(parsed.error))return;let code=parsed.error.type;return typeof code!="string"?void 0:classifyProviderFailure({status:void 0,code})}catch{return}}var OPENAI_COMPATIBLE_PRECISE_TYPES=new Set(["exceeded_current_quota_error","insufficient_quota"]);function openAICompatibleProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),code=optionalString(Reflect.get(error,"code"));if(code===null)return;let type=code===void 0?optionalString(Reflect.get(error,"type")):void 0,token=code??(typeof type=="string"&&OPENAI_COMPATIBLE_PRECISE_TYPES.has(type)?type:void 0);return token===void 0&&status==null?void 0:classifyProviderFailure({status,code:token})}catch{return}}function siwcProviderDiagnosticFromError(error){let diagnostic=openAICompatibleProviderDiagnosticFromError(error);return diagnostic===void 0?void 0:{...diagnostic,route:"siwc"}}var TRANSPORT_CAUSE_DEPTH=4;function transportProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let current=error,sdkConnectionError;for(let depth=0;depth<TRANSPORT_CAUSE_DEPTH&&(isRecord(current)||current instanceof Error);depth++){let code=Reflect.get(current,"code");if(typeof code=="string"&&categoryForTransportCode(code)!==void 0)return buildProviderDiagnostic({category:"network",code,evidence:"structured_transport"});for(let name of current instanceof Error?[current.name,current.constructor.name]:[])sdkConnectionError===void 0&&categoryForTransportCode(name)!==void 0&&(sdkConnectionError=name);current=Reflect.get(current,"cause")}return sdkConnectionError===void 0?void 0:buildProviderDiagnostic({category:"network",code:sdkConnectionError,evidence:"structured_transport"})}catch{return}}function classifyWithTransport(classify,error){return classify(error)??transportProviderDiagnosticFromError(error)}async function awaitProviderTransport(request,classify){try{return await request()}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classifyWithTransport(classify,error)),error}}async function*iterateProviderTransport(source,classify){try{yield*source}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classifyWithTransport(classify,error)),error}}export{anthropicProviderDiagnosticFromError,anthropicProviderDiagnosticFromSseData,openAICompatibleProviderDiagnosticFromError,siwcProviderDiagnosticFromError,transportProviderDiagnosticFromError,awaitProviderTransport,iterateProviderTransport};
2
+ import{buildProviderDiagnostic,categoryForTransportCode,classifyProviderFailure}from"./chunk-MOH5HOHX.js";import{attachProviderDiagnostic}from"./chunk-3SASTB6Y.js";var SSE_ERROR_ENVELOPE_MAX_BYTES=8192;function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function optionalString(value){if(value!=null)return typeof value=="string"?value:null}function anthropicProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),direct=optionalString(Reflect.get(error,"type")),body=Reflect.get(error,"error"),nested=isRecord(body)&&isRecord(body.error)?optionalString(body.error.type):void 0;if(direct===null||nested===null||direct!==void 0&&nested!==void 0&&direct!==nested)return;let code=direct??nested;if(code===void 0&&status==null)return;let diagnostic=classifyProviderFailure({status,code});if(diagnostic?.category!=="quota"&&diagnostic?.category!=="rate_limit")return diagnostic;let headers=Reflect.get(error,"headers");if(!(headers instanceof Headers))return diagnostic;let resets=["5h","7d"].flatMap(window=>{let utilization=Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`)),reset=Number(headers.get(`anthropic-ratelimit-unified-${window}-reset`))*1e3;return utilization>=1&&Number.isFinite(reset)&&reset>Date.now()?[reset]:[]});return resets.length===0?diagnostic:{...diagnostic,resetsAt:Math.max(...resets)}}catch{return}}function anthropicProviderDiagnosticFromSseData(data){try{if(new TextEncoder().encode(data).length>SSE_ERROR_ENVELOPE_MAX_BYTES)return;let parsed=JSON.parse(data);if(!isRecord(parsed)||parsed.type!=="error"||!isRecord(parsed.error))return;let code=parsed.error.type;return typeof code!="string"?void 0:classifyProviderFailure({status:void 0,code})}catch{return}}var OPENAI_COMPATIBLE_PRECISE_TYPES=new Set(["exceeded_current_quota_error","insufficient_quota"]);function openAICompatibleProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),code=optionalString(Reflect.get(error,"code"));if(code===null)return;let type=code===void 0?optionalString(Reflect.get(error,"type")):void 0,token=code??(typeof type=="string"&&OPENAI_COMPATIBLE_PRECISE_TYPES.has(type)?type:void 0);return token===void 0&&status==null?void 0:classifyProviderFailure({status,code:token})}catch{return}}function siwcProviderDiagnosticFromError(error){let diagnostic=openAICompatibleProviderDiagnosticFromError(error);return diagnostic===void 0?void 0:{...diagnostic,route:"siwc"}}var TRANSPORT_CAUSE_DEPTH=4;function transportProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let current=error,sdkConnectionError;for(let depth=0;depth<TRANSPORT_CAUSE_DEPTH&&(isRecord(current)||current instanceof Error);depth++){let code=Reflect.get(current,"code");if(typeof code=="string"&&categoryForTransportCode(code)!==void 0)return buildProviderDiagnostic({category:"network",code,evidence:"structured_transport"});for(let name of current instanceof Error?[current.name,current.constructor.name]:[])sdkConnectionError===void 0&&categoryForTransportCode(name)!==void 0&&(sdkConnectionError=name);current=Reflect.get(current,"cause")}return sdkConnectionError===void 0?void 0:buildProviderDiagnostic({category:"network",code:sdkConnectionError,evidence:"structured_transport"})}catch{return}}function classifyWithTransport(classify,error){return classify(error)??transportProviderDiagnosticFromError(error)}async function awaitProviderTransport(request,classify){try{return await request()}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classifyWithTransport(classify,error)),error}}async function*iterateProviderTransport(source,classify){try{yield*source}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classifyWithTransport(classify,error)),error}}export{anthropicProviderDiagnosticFromError,anthropicProviderDiagnosticFromSseData,openAICompatibleProviderDiagnosticFromError,siwcProviderDiagnosticFromError,transportProviderDiagnosticFromError,awaitProviderTransport,iterateProviderTransport};
@@ -1,3 +1,3 @@
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{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";import{envValue}from"./chunk-ISZ4EWIS.js";import{format}from"node:util";var OUTPUT_DELIVERY_LIMIT_MS=3e4,nativeLog=console.log,nativeStdoutWrite=process.stdout.write;async function captureStdout(print){if(console.log!==nativeLog||process.stdout.write!==nativeStdoutWrite)return{result:await print(),output:""};let chunks=[];console.log=(...args)=>{chunks.push(`${format(...args)}
3
- `)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-CBSDV36M.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-CBSDV36M.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-PWVPQ2OV.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-WJIMRBGN.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-W45NYTTK.js");return await runScheduleCommand(args.slice(1))}export{captureStdout,exitAfterOutput,printThenExit,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
3
+ `)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-JPNA27E5.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-JPNA27E5.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-OJFARE5Q.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-PZ4VYQIW.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-OZ5ESMIT.js");return await runScheduleCommand(args.slice(1))}export{captureStdout,exitAfterOutput,printThenExit,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
@@ -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{appendDebugLogEntry}from"./chunk-YWD54RHU.js";import{isRecoverableInspectorVmImportError}from"./chunk-IWM5QRAE.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
2
+ import{appendDebugLogEntry}from"./chunk-YWD54RHU.js";import{isRecoverableInspectorVmImportError}from"./chunk-7KLEFHSU.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
@@ -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-UKSFF47T.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-LP6LVNCY.js");await runToolChildRole()}
4
+ `),process.exit(70));let{runToolChildRole}=await import("./role-45Y7PQFC.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{DynamicBorder,keyDisplayText,keyHint,observeVisibleStderrWrites,rawKeyHint,restoreStderr,takeOverStderr}from"./chunk-7FUO655J.js";import{isWSL}from"./chunk-LGO25HPL.js";import{getEditorTheme,sharedMarkdownTheme,theme,usageLimitScope}from"./chunk-BW4YXS7X.js";import{userWordBlocks}from"./chunk-57MRFI6E.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-YWD54RHU.js";import{Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-D2ROBVZ4.js";import{redactSensitiveOutput}from"./chunk-LNAZ7XEU.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC}from"./chunk-TG4E7Z7W.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,describeProviderFailureForUser,stripTurnRetrySuppressionPrefix}from"./chunk-TBARMJ75.js";import{getDebugLogPath,stripBom}from"./chunk-ISZ4EWIS.js";import{typebox_exports}from"./chunk-MIENF2YK.js";var CODEX_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"User-facing label (1-5 words)."}),description:typebox_exports.String({description:"One short sentence explaining impact/tradeoff if selected."})},{additionalProperties:!1}),CODEX_QUESTION=typebox_exports.Object({id:typebox_exports.String({pattern:"^[a-z][a-z0-9]*(_[a-z0-9]+)*$",description:"Stable identifier for mapping answers (snake_case)."}),header:typebox_exports.String({minLength:1,maxLength:12,description:"Short header label shown in the UI (12 or fewer chars)."}),question:typebox_exports.String({minLength:1,description:"Single-sentence prompt shown to the user."}),options:typebox_exports.Array(CODEX_OPTION,{minItems:2,maxItems:3,description:'Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option in this list; the client will add a free-form "Other" option automatically.'}),multiSelect:typebox_exports.Optional(typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one."}))},{additionalProperties:!1}),CODEX_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CODEX_QUESTION,{minItems:1,maxItems:3,description:"Questions to show the user. Prefer 1 and do not exceed 3"}),wait_for_answer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))},{additionalProperties:!1}),CLAUDE_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:typebox_exports.Optional(typebox_exports.String({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}))}),CLAUDE_QUESTION=typebox_exports.Object({question:typebox_exports.String({minLength:1,description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:typebox_exports.String({minLength:1,maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:typebox_exports.Optional(typebox_exports.Array(CLAUDE_OPTION,{minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no Other option, that will be provided automatically."})),multiSelect:typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}),CLAUDE_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CLAUDE_QUESTION,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"}),waitForAnswer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))});var WAIT_FLAG_STEER_TEXT="This call omitted wait_for_answer (or waitForAnswer). Set true to pause here until the user answers, false to keep working and receive the answer later as a user message.",DEFAULT_ASK_USER_TIMEOUT_MS=1800*1e3,HEADER_MAX=12,SNAKE_CASE=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,LIMITS={codex:{maxQuestions:3,minOptions:2,maxOptions:3,optionsRequired:!0},claude:{maxQuestions:4,minOptions:2,maxOptions:4,optionsRequired:!1}},AskUserSchemaError=class extends Error{constructor(message){super(message),this.name="AskUserSchemaError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readWaitFlag(variant,args){let value=args[variant==="codex"?"wait_for_answer":"waitForAnswer"];if(typeof value!="boolean")throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);return value}function parseOptions(raw,min,max,required,requireDescription){if(raw===void 0){if(required)throw new AskUserSchemaError(`options must contain ${min} to ${max} items`);return[]}if(!Array.isArray(raw))throw new AskUserSchemaError("options must be an array");if(raw.length<min||raw.length>max)throw new AskUserSchemaError(required?`options must contain ${min} to ${max} items`:`options must contain ${min} to ${max} items when present`);let options=[];for(let item of raw){if(!isRecord(item))throw new AskUserSchemaError("each option must be an object");let label=typeof item.label=="string"?item.label.trim():"";if(label.length===0)throw new AskUserSchemaError("option label must be non-empty");let description=typeof item.description=="string"?item.description.trim():void 0;if(requireDescription&&(description===void 0||description.length===0))throw new AskUserSchemaError("option description is required");options.push(description===void 0||description.length===0?{label}:{label,description})}return options}function parseQuestion(variant,raw,index){if(!isRecord(raw))throw new AskUserSchemaError("each question must be an object");let limits=LIMITS[variant],header=typeof raw.header=="string"?raw.header.trim():"";if(header.length===0)throw new AskUserSchemaError("header must be non-empty");if(header.length>HEADER_MAX)throw new AskUserSchemaError("header must be 12 or fewer characters");let question=typeof raw.question=="string"?raw.question.trim():"";if(question.length===0)throw new AskUserSchemaError("question must be non-empty");let options=parseOptions(raw.options,limits.minOptions,limits.maxOptions,limits.optionsRequired,variant==="codex"),id;if(variant==="claude")id=`q${index+1}`;else if(id=typeof raw.id=="string"?raw.id.trim():"",!SNAKE_CASE.test(id))throw new AskUserSchemaError("id must be snake_case");let multiSelect;if(variant==="claude"){if(typeof raw.multiSelect!="boolean")throw new AskUserSchemaError("multiSelect is required");multiSelect=raw.multiSelect}else multiSelect=raw.multiSelect===!0;return{id,header,question,options,multiSelect}}function toCanonical(variant,args,options){if(!isRecord(args))throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);let waitForAnswer=readWaitFlag(variant,args);if(args.required!==void 0&&typeof args.required!="boolean")throw new AskUserSchemaError("required must be a boolean when present");let limits=LIMITS[variant];if(!Array.isArray(args.questions)||args.questions.length<1||args.questions.length>limits.maxQuestions)throw new AskUserSchemaError(`questions must contain 1 to ${limits.maxQuestions} items`);return{requestId:options?.requestId??crypto.randomUUID(),questions:args.questions.map((question,index)=>parseQuestion(variant,question,index)),waitForAnswer,timeoutMs:options?.timeoutMs??DEFAULT_ASK_USER_TIMEOUT_MS,...args.required===!0?{required:!0}:{}}}var INLINE_WORDS={comment:text=>text,typed:(_header,text)=>text},reference=label=>`(see [${label}] below)`;function separatedWords(requestId){let words=[],place=(base,text)=>{let taken=words.filter(word=>word.label===base||word.label.startsWith(`${base} (`)).length,label=taken===0?base:`${base} (${taken+1})`;return words.push({label,text}),reference(label)};return{words,comment:text=>place(`The user's comment for question ${requestId}`,text),typed:(header,text)=>place(`The user's answer to ${header} for question ${requestId}`,text)}}function resolveUserWordReferences(text,words){return words.reduce((resolved,word)=>resolved.split(reference(word.label)).join(word.text),text)}function readUserWordBlocks(content){let texts=content.flatMap(block=>block.type==="text"?[block.text]:[]);if(texts.length%2!==0)return;let words=[];for(let index=0;index<texts.length;index+=2){let label=/^\[(.+)\]$/s.exec(texts[index]??"")?.[1],text=texts[index+1];if(label===void 0||text===void 0)return;words.push({label,text})}return words}function headerFor(id,questions){return questions.find(question=>question.id===id)?.header??id}function questionTextFor(id,questions){return questions.find(question=>question.id===id)?.question??id}function typedText(answer){if(answer.selected.length>0)return;let text=answer.text?.trim();return text===void 0||text.length===0?void 0:text}function answerBody(answer,header,words=INLINE_WORDS,offered=[]){if(!answer)return;if(answer.selected.length>0)return answer.selected.join(", ");let text=typedText(answer);if(text!==void 0)return offered.some(option=>option.label===text)?text:words.typed(header,text)}function answeredLines(response,questions,words){let lines=[],seen=new Set;for(let question of questions){let body=answerBody(response.answers[question.id],question.header,words,question.options);body!==void 0&&(lines.push(`${question.header}: ${body}`),seen.add(question.id))}for(let[id,answer]of Object.entries(response.answers)){if(seen.has(id))continue;let header=headerFor(id,questions),body=answerBody(answer,header,words);body!==void 0&&lines.push(`${header}: ${body}`)}return lines}function unansweredLine(response,questions){let unanswered=response.unanswered.map(id=>headerFor(id,questions));return unanswered.length>0?[`Unanswered: ${unanswered.join(", ")}`]:[]}var CANCELLED_BY_USER="The user cancelled the question after answering part of it.",CANCELLED_AFTER_ANSWERS="The question was cancelled after part of it was answered.";function isCancelledWithAnswersLine(line){return line===CANCELLED_BY_USER||line===CANCELLED_AFTER_ANSWERS}function showsPartialAnswers(response){return response.status!=="cancelled"||response.cancelOrigin!=="user"&&response.cancelOrigin!=="ui_failure"?!1:Object.values(response.answers).some(answer=>answerBody(answer,"")!==void 0)}function selectedBlock(prefix,selected){return selected.length===1?[`${prefix} ${selected[0]}`]:[prefix,...selected]}var GATED_NO_ANSWER="No answer: do not take the action it gates. Keep that action pending and end the turn.";function formatGatedNoAnswer(response,questions,words,cancellationReason){let lines=[cancellationReason??(response.status==="timed_out"?`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`:response.status==="cancelled"?"The user dismissed the question.":response.status==="orphaned-after-restart"?"The pending question could not be resumed after a restart.":"This session has no user attached (subagent or headless).")],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected (not an answer):",selected)),lines.push(GATED_NO_ANSWER),lines.join(`
2
+ import{DynamicBorder,keyDisplayText,keyHint,observeVisibleStderrWrites,rawKeyHint,restoreStderr,takeOverStderr}from"./chunk-MOOFLKLI.js";import{isWSL}from"./chunk-LGO25HPL.js";import{getEditorTheme,sharedMarkdownTheme,theme,usageLimitScope}from"./chunk-WCRNJYHO.js";import{userWordBlocks}from"./chunk-57MRFI6E.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-YWD54RHU.js";import{Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-D2ROBVZ4.js";import{redactSensitiveOutput}from"./chunk-LNAZ7XEU.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC}from"./chunk-TG4E7Z7W.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,describeProviderFailureForUser,stripTurnRetrySuppressionPrefix}from"./chunk-TBARMJ75.js";import{getDebugLogPath,stripBom}from"./chunk-ISZ4EWIS.js";import{typebox_exports}from"./chunk-MIENF2YK.js";var CODEX_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"User-facing label (1-5 words)."}),description:typebox_exports.String({description:"One short sentence explaining impact/tradeoff if selected."})},{additionalProperties:!1}),CODEX_QUESTION=typebox_exports.Object({id:typebox_exports.String({pattern:"^[a-z][a-z0-9]*(_[a-z0-9]+)*$",description:"Stable identifier for mapping answers (snake_case)."}),header:typebox_exports.String({minLength:1,maxLength:12,description:"Short header label shown in the UI (12 or fewer chars)."}),question:typebox_exports.String({minLength:1,description:"Single-sentence prompt shown to the user."}),options:typebox_exports.Array(CODEX_OPTION,{minItems:2,maxItems:3,description:'Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option in this list; the client will add a free-form "Other" option automatically.'}),multiSelect:typebox_exports.Optional(typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one."}))},{additionalProperties:!1}),CODEX_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CODEX_QUESTION,{minItems:1,maxItems:3,description:"Questions to show the user. Prefer 1 and do not exceed 3"}),wait_for_answer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))},{additionalProperties:!1}),CLAUDE_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:typebox_exports.Optional(typebox_exports.String({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}))}),CLAUDE_QUESTION=typebox_exports.Object({question:typebox_exports.String({minLength:1,description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:typebox_exports.String({minLength:1,maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:typebox_exports.Optional(typebox_exports.Array(CLAUDE_OPTION,{minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no Other option, that will be provided automatically."})),multiSelect:typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}),CLAUDE_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CLAUDE_QUESTION,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"}),waitForAnswer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))});var WAIT_FLAG_STEER_TEXT="This call omitted wait_for_answer (or waitForAnswer). Set true to pause here until the user answers, false to keep working and receive the answer later as a user message.",DEFAULT_ASK_USER_TIMEOUT_MS=1800*1e3,HEADER_MAX=12,SNAKE_CASE=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,LIMITS={codex:{maxQuestions:3,minOptions:2,maxOptions:3,optionsRequired:!0},claude:{maxQuestions:4,minOptions:2,maxOptions:4,optionsRequired:!1}},AskUserSchemaError=class extends Error{constructor(message){super(message),this.name="AskUserSchemaError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readWaitFlag(variant,args){let value=args[variant==="codex"?"wait_for_answer":"waitForAnswer"];if(typeof value!="boolean")throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);return value}function parseOptions(raw,min,max,required,requireDescription){if(raw===void 0){if(required)throw new AskUserSchemaError(`options must contain ${min} to ${max} items`);return[]}if(!Array.isArray(raw))throw new AskUserSchemaError("options must be an array");if(raw.length<min||raw.length>max)throw new AskUserSchemaError(required?`options must contain ${min} to ${max} items`:`options must contain ${min} to ${max} items when present`);let options=[];for(let item of raw){if(!isRecord(item))throw new AskUserSchemaError("each option must be an object");let label=typeof item.label=="string"?item.label.trim():"";if(label.length===0)throw new AskUserSchemaError("option label must be non-empty");let description=typeof item.description=="string"?item.description.trim():void 0;if(requireDescription&&(description===void 0||description.length===0))throw new AskUserSchemaError("option description is required");options.push(description===void 0||description.length===0?{label}:{label,description})}return options}function parseQuestion(variant,raw,index){if(!isRecord(raw))throw new AskUserSchemaError("each question must be an object");let limits=LIMITS[variant],header=typeof raw.header=="string"?raw.header.trim():"";if(header.length===0)throw new AskUserSchemaError("header must be non-empty");if(header.length>HEADER_MAX)throw new AskUserSchemaError("header must be 12 or fewer characters");let question=typeof raw.question=="string"?raw.question.trim():"";if(question.length===0)throw new AskUserSchemaError("question must be non-empty");let options=parseOptions(raw.options,limits.minOptions,limits.maxOptions,limits.optionsRequired,variant==="codex"),id;if(variant==="claude")id=`q${index+1}`;else if(id=typeof raw.id=="string"?raw.id.trim():"",!SNAKE_CASE.test(id))throw new AskUserSchemaError("id must be snake_case");let multiSelect;if(variant==="claude"){if(typeof raw.multiSelect!="boolean")throw new AskUserSchemaError("multiSelect is required");multiSelect=raw.multiSelect}else multiSelect=raw.multiSelect===!0;return{id,header,question,options,multiSelect}}function toCanonical(variant,args,options){if(!isRecord(args))throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);let waitForAnswer=readWaitFlag(variant,args);if(args.required!==void 0&&typeof args.required!="boolean")throw new AskUserSchemaError("required must be a boolean when present");let limits=LIMITS[variant];if(!Array.isArray(args.questions)||args.questions.length<1||args.questions.length>limits.maxQuestions)throw new AskUserSchemaError(`questions must contain 1 to ${limits.maxQuestions} items`);return{requestId:options?.requestId??crypto.randomUUID(),questions:args.questions.map((question,index)=>parseQuestion(variant,question,index)),waitForAnswer,timeoutMs:options?.timeoutMs??DEFAULT_ASK_USER_TIMEOUT_MS,...args.required===!0?{required:!0}:{}}}var INLINE_WORDS={comment:text=>text,typed:(_header,text)=>text},reference=label=>`(see [${label}] below)`;function separatedWords(requestId){let words=[],place=(base,text)=>{let taken=words.filter(word=>word.label===base||word.label.startsWith(`${base} (`)).length,label=taken===0?base:`${base} (${taken+1})`;return words.push({label,text}),reference(label)};return{words,comment:text=>place(`The user's comment for question ${requestId}`,text),typed:(header,text)=>place(`The user's answer to ${header} for question ${requestId}`,text)}}function resolveUserWordReferences(text,words){return words.reduce((resolved,word)=>resolved.split(reference(word.label)).join(word.text),text)}function readUserWordBlocks(content){let texts=content.flatMap(block=>block.type==="text"?[block.text]:[]);if(texts.length%2!==0)return;let words=[];for(let index=0;index<texts.length;index+=2){let label=/^\[(.+)\]$/s.exec(texts[index]??"")?.[1],text=texts[index+1];if(label===void 0||text===void 0)return;words.push({label,text})}return words}function headerFor(id,questions){return questions.find(question=>question.id===id)?.header??id}function questionTextFor(id,questions){return questions.find(question=>question.id===id)?.question??id}function typedText(answer){if(answer.selected.length>0)return;let text=answer.text?.trim();return text===void 0||text.length===0?void 0:text}function answerBody(answer,header,words=INLINE_WORDS,offered=[]){if(!answer)return;if(answer.selected.length>0)return answer.selected.join(", ");let text=typedText(answer);if(text!==void 0)return offered.some(option=>option.label===text)?text:words.typed(header,text)}function answeredLines(response,questions,words){let lines=[],seen=new Set;for(let question of questions){let body=answerBody(response.answers[question.id],question.header,words,question.options);body!==void 0&&(lines.push(`${question.header}: ${body}`),seen.add(question.id))}for(let[id,answer]of Object.entries(response.answers)){if(seen.has(id))continue;let header=headerFor(id,questions),body=answerBody(answer,header,words);body!==void 0&&lines.push(`${header}: ${body}`)}return lines}function unansweredLine(response,questions){let unanswered=response.unanswered.map(id=>headerFor(id,questions));return unanswered.length>0?[`Unanswered: ${unanswered.join(", ")}`]:[]}var CANCELLED_BY_USER="The user cancelled the question after answering part of it.",CANCELLED_AFTER_ANSWERS="The question was cancelled after part of it was answered.";function isCancelledWithAnswersLine(line){return line===CANCELLED_BY_USER||line===CANCELLED_AFTER_ANSWERS}function showsPartialAnswers(response){return response.status!=="cancelled"||response.cancelOrigin!=="user"&&response.cancelOrigin!=="ui_failure"?!1:Object.values(response.answers).some(answer=>answerBody(answer,"")!==void 0)}function selectedBlock(prefix,selected){return selected.length===1?[`${prefix} ${selected[0]}`]:[prefix,...selected]}var GATED_NO_ANSWER="No answer: do not take the action it gates. Keep that action pending and end the turn.";function formatGatedNoAnswer(response,questions,words,cancellationReason){let lines=[cancellationReason??(response.status==="timed_out"?`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`:response.status==="cancelled"?"The user dismissed the question.":response.status==="orphaned-after-restart"?"The pending question could not be resumed after a restart.":"This session has no user attached (subagent or headless).")],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected (not an answer):",selected)),lines.push(GATED_NO_ANSWER),lines.join(`
3
3
  `)}function formatGatedCancellation(reason,response,requestId,questions){return formatGatedNoAnswer(response,questions,separatedWords(requestId),reason)}function formatBody(response,questions,words,required=!1){if(required&&response.status!=="answered"&&response.status!=="comment-submitted")return formatGatedNoAnswer(response,questions,words);switch(response.status){case"answered":return[...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
4
4
  `);case"comment-submitted":{let comment=response.comment?.trim()??"";return[`The user responded: ${comment.length>0?words.comment(comment):""}`,...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
5
5
  `)}case"timed_out":{let lines=[`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected:",selected),...unansweredLine(response,questions)),lines.push("Continue the work to completion on your best judgment; do not ask this question again this turn."),lines.join(`