@code-yeongyu/senpi 2026.10.24-2 → 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 (178) hide show
  1. package/CHANGELOG.md +37 -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-3VOG6WFU.js +27 -0
  5. package/dist/bundle/chunks/{chunk-HHYSXDYP.js → chunk-42OY5SZZ.js} +2 -2
  6. package/dist/bundle/chunks/chunk-7IRLFYNM.js +23 -0
  7. package/dist/bundle/chunks/{chunk-FIBIVBQK.js → chunk-7UUOGZKR.js} +1 -1
  8. package/dist/bundle/chunks/chunk-BMYNMUVZ.js +7 -0
  9. package/dist/bundle/chunks/{chunk-JAXZOEJE.js → chunk-BWA4FVFW.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-AGQSRWNN.js → chunk-EHQXLHRB.js} +1 -1
  11. package/dist/bundle/chunks/chunk-EWOEVVQT.js +4 -0
  12. package/dist/bundle/chunks/{chunk-YJA2B7FQ.js → chunk-FDL4CF6F.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-RQHK4QZ5.js → chunk-FWXMMMCV.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-OA5INWHI.js → chunk-GVJ76VQI.js} +102 -42
  15. package/dist/bundle/chunks/{chunk-HCF5M6NA.js → chunk-GXY5JEI5.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-VZAYN5SB.js → chunk-HKUXKTFW.js} +1 -1
  17. package/dist/bundle/chunks/chunk-II22E3CV.js +3 -0
  18. package/dist/bundle/chunks/{chunk-ONLNXGO3.js → chunk-IUHU5PEC.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-LR6Z6V54.js → chunk-NQC7MI2G.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-IELM5U6I.js → chunk-PXKF2RHD.js} +2 -2
  21. package/dist/bundle/chunks/{chunk-BRXN5R2F.js → chunk-QH2HSCMX.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-QQSCUEYJ.js → chunk-RHHBXIRN.js} +2 -5
  23. package/dist/bundle/chunks/chunk-RVYSJBZ7.js +7 -0
  24. package/dist/bundle/chunks/chunk-SGDOZT6B.js +8 -0
  25. package/dist/bundle/chunks/{chunk-BZ75DRZB.js → chunk-U67ML6CQ.js} +4 -2
  26. package/dist/bundle/chunks/{chunk-3N2PQEQV.js → chunk-UT6AJHPK.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-RAIZG6HA.js → chunk-V3CK2AVC.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-CZR7C6CY.js → chunk-VOBD6FQG.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-HRPMLI7O.js → chunk-VRDU425E.js} +2 -2
  30. package/dist/bundle/chunks/{chunk-OUPD5LWY.js → chunk-XUFUKDKJ.js} +3 -3
  31. package/dist/bundle/chunks/{chunk-SGATKHO4.js → chunk-Y5OTHMXO.js} +1 -1
  32. package/dist/bundle/chunks/{chunk-QEQG42HL.js → chunk-ZGAB7WQA.js} +1 -1
  33. package/dist/bundle/chunks/cli-main-UH3MAREK.js +3 -0
  34. package/dist/bundle/chunks/{dispatch-KQEGIXQW.js → dispatch-DEP4PEDZ.js} +3 -2
  35. package/dist/bundle/chunks/{help-fast-path-6PVN7WI5.js → help-fast-path-ZHZGXAUG.js} +1 -1
  36. package/dist/bundle/chunks/host-command-OQR4RDTM.js +2 -0
  37. package/dist/bundle/chunks/host-lifecycle-U36U7JTE.js +3 -0
  38. package/dist/bundle/chunks/host-lifecycle.js +26 -21
  39. package/dist/bundle/chunks/host-session-command-IGB27ZPJ.js +20 -0
  40. package/dist/bundle/chunks/{host-socket-request-KKGH3JHV.js → host-socket-request-ZDJGSSZO.js} +1 -1
  41. package/dist/bundle/chunks/interactive-mode-R5RCSJ2F.js +2 -0
  42. package/dist/bundle/chunks/{list-tips-BO5RP34W.js → list-tips-CREX4IXZ.js} +1 -1
  43. package/dist/bundle/chunks/{multi-session-host-O5GZQSRL.js → multi-session-host-YZEMYUFY.js} +12 -12
  44. package/dist/bundle/chunks/{package-manager-cli-LC5GAGTW.js → package-manager-cli-5FOXDKUA.js} +1 -1
  45. package/dist/bundle/chunks/{role-4G43UDOC.js → role-M2MTVACJ.js} +1 -1
  46. package/dist/bundle/chunks/{rotation-stream-RXMCJJUL.js → rotation-stream-U7YQMC7H.js} +1 -1
  47. package/dist/bundle/chunks/rpc-mode-6K62CZBW.js +2 -0
  48. package/dist/bundle/chunks/rpc-monitor-source-OL5KU6NO.js +3 -0
  49. package/dist/bundle/chunks/{schedule-command-QNCVE4HM.js → schedule-command-XBW4EOG5.js} +1 -1
  50. package/dist/bundle/chunks/session-control-endpoint-54TMCS7Q.js +3 -0
  51. package/dist/bundle/chunks/{session-picker-HIC5ZTE6.js → session-picker-P2VUU2MQ.js} +1 -1
  52. package/dist/bundle/chunks/session-worker.js +437 -368
  53. package/dist/bundle/cli.js +2 -2
  54. package/dist/bundle/host-supervisor.js +26 -21
  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/cli/args.d.ts +2 -0
  59. package/dist/cli/args.js +27 -0
  60. package/dist/cli/host-command-args.d.ts +33 -0
  61. package/dist/cli/host-command-args.js +145 -0
  62. package/dist/cli/host-command.d.ts +1 -30
  63. package/dist/cli/host-command.js +5 -137
  64. package/dist/cli/host-session-command.d.ts +1 -0
  65. package/dist/cli/host-session-command.js +5 -3
  66. package/dist/core/agent-session.js +1 -1
  67. package/dist/core/extensions/builtin/anthropic-subscription/index.js +4 -2
  68. package/dist/core/extensions/builtin/anthropic-subscription/options.js +2 -1
  69. package/dist/core/extensions/builtin/anthropic-subscription/sdk-boundary.js +9 -2
  70. package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.d.ts +3 -0
  71. package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.js +9 -0
  72. package/dist/core/extensions/builtin/anthropic-subscription/settings.d.ts +1 -1
  73. package/dist/core/extensions/builtin/anthropic-subscription/settings.js +3 -1
  74. package/dist/core/extensions/builtin/anthropic-subscription/stream.js +4 -1
  75. package/dist/core/extensions/builtin/btw/index.js +4 -1
  76. package/dist/core/extensions/builtin/compaction/lane-policy.js +3 -1
  77. package/dist/core/extensions/builtin/look-at/runner.js +1 -0
  78. package/dist/core/extensions/builtin/mcp/connection-types.d.ts +2 -0
  79. package/dist/core/extensions/builtin/mcp/connection.js +3 -0
  80. package/dist/core/extensions/builtin/mcp/elicitation.d.ts +5 -2
  81. package/dist/core/extensions/builtin/mcp/elicitation.js +57 -11
  82. package/dist/core/extensions/builtin/mcp/index.js +1 -1
  83. package/dist/core/extensions/builtin/mcp/modern/dispatch.js +6 -9
  84. package/dist/core/extensions/builtin/mcp/service-connection.d.ts +1 -0
  85. package/dist/core/extensions/builtin/mcp/service-connection.js +1 -0
  86. package/dist/core/extensions/builtin/mcp/service.js +1 -0
  87. package/dist/core/extensions/builtin/mcp/transport-sdk.d.ts +1 -0
  88. package/dist/core/extensions/builtin/mcp/transport-sdk.js +5 -5
  89. package/dist/core/extensions/builtin/mcp/transport.d.ts +1 -0
  90. package/dist/core/extensions/builtin/mcp/transport.js +1 -0
  91. package/dist/core/extensions/builtin/prompt-preset/contract.js +6 -1
  92. package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.d.ts +3 -0
  93. package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.js +93 -0
  94. package/dist/core/extensions/builtin/prompt-preset/matchers.d.ts +2 -0
  95. package/dist/core/extensions/builtin/prompt-preset/matchers.js +9 -0
  96. package/dist/core/extensions/builtin/prompt-preset/presets.js +3 -0
  97. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
  98. package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
  99. package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.d.ts +2 -1
  100. package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.js +12 -4
  101. package/dist/core/external-admission.d.ts +4 -1
  102. package/dist/core/external-admission.js +18 -2
  103. package/dist/core/lifecycle-session-binding.js +20 -0
  104. package/dist/core/sdk.js +1 -0
  105. package/dist/core/session-spawned-by.d.ts +4 -0
  106. package/dist/core/session-spawned-by.js +16 -0
  107. package/dist/main.js +7 -2
  108. package/dist/modes/rpc/host-admission-proxy.d.ts +2 -1
  109. package/dist/modes/rpc/host-admission-proxy.js +10 -9
  110. package/dist/modes/rpc/host-cli-entry.d.ts +2 -0
  111. package/dist/modes/rpc/host-cli-entry.js +13 -1
  112. package/dist/modes/rpc/host-ensure-client.d.ts +5 -1
  113. package/dist/modes/rpc/host-ensure-client.js +8 -0
  114. package/dist/modes/rpc/host-ensure-types.d.ts +1 -0
  115. package/dist/modes/rpc/host-ensure.js +6 -11
  116. package/dist/modes/rpc/host-gc-pass.js +3 -0
  117. package/dist/modes/rpc/host-gc.js +3 -0
  118. package/dist/modes/rpc/host-internal-transport.d.ts +16 -5
  119. package/dist/modes/rpc/host-internal-transport.js +40 -9
  120. package/dist/modes/rpc/host-lifecycle-proxy.d.ts +4 -8
  121. package/dist/modes/rpc/host-lifecycle-proxy.js +9 -21
  122. package/dist/modes/rpc/host-lifecycle-shutdown.d.ts +2 -0
  123. package/dist/modes/rpc/host-lifecycle-shutdown.js +3 -0
  124. package/dist/modes/rpc/host-lifecycle.js +9 -16
  125. package/dist/modes/rpc/host-observe-request.js +1 -1
  126. package/dist/modes/rpc/host-probe.d.ts +8 -6
  127. package/dist/modes/rpc/host-probe.js +13 -13
  128. package/dist/modes/rpc/host-request-key-root.d.ts +8 -0
  129. package/dist/modes/rpc/host-request-key-root.js +14 -0
  130. package/dist/modes/rpc/host-runner.d.ts +3 -1
  131. package/dist/modes/rpc/host-runner.js +6 -1
  132. package/dist/modes/rpc/host-socket-bind.d.ts +6 -0
  133. package/dist/modes/rpc/host-socket-bind.js +42 -0
  134. package/dist/modes/rpc/host-socket-request.d.ts +3 -2
  135. package/dist/modes/rpc/host-socket-request.js +55 -10
  136. package/dist/modes/rpc/host-status.d.ts +3 -2
  137. package/dist/modes/rpc/host-status.js +5 -0
  138. package/dist/modes/rpc/host-supervisor-log.d.ts +1 -0
  139. package/dist/modes/rpc/host-supervisor-log.js +3 -0
  140. package/dist/modes/rpc/host-watchdog.d.ts +8 -1
  141. package/dist/modes/rpc/host-watchdog.js +37 -12
  142. package/dist/modes/rpc/internal-channel.js +14 -14
  143. package/dist/modes/rpc/multi-session-host.js +18 -46
  144. package/dist/modes/rpc/rpc-auth-client.d.ts +13 -0
  145. package/dist/modes/rpc/rpc-auth-client.js +142 -0
  146. package/dist/modes/rpc/rpc-auth-proof.d.ts +12 -0
  147. package/dist/modes/rpc/rpc-auth-proof.js +27 -0
  148. package/dist/modes/rpc/rpc-client-socket.d.ts +5 -0
  149. package/dist/modes/rpc/rpc-client-socket.js +30 -0
  150. package/dist/modes/rpc/rpc-client.d.ts +2 -0
  151. package/dist/modes/rpc/rpc-client.js +2 -24
  152. package/dist/modes/rpc/rpc-host-command-types.d.ts +4 -0
  153. package/dist/modes/rpc/rpc-protocol-info-types.d.ts +6 -0
  154. package/dist/modes/rpc/rpc-public-auth.d.ts +41 -0
  155. package/dist/modes/rpc/rpc-public-auth.js +237 -0
  156. package/dist/modes/rpc/rpc-public-key.d.ts +28 -0
  157. package/dist/modes/rpc/rpc-public-key.js +193 -0
  158. package/dist/modes/rpc/session-router-open-profile.js +2 -10
  159. package/dist/modes/rpc/socket-ownership.d.ts +7 -0
  160. package/dist/modes/rpc/socket-ownership.js +17 -0
  161. package/docs/rpc.md +108 -2
  162. package/docs/settings.md +1 -1
  163. package/docs/usage.md +14 -0
  164. package/package.json +6 -6
  165. package/dist/bundle/chunks/chunk-3474DPZK.js +0 -2
  166. package/dist/bundle/chunks/chunk-64CFJHKT.js +0 -7
  167. package/dist/bundle/chunks/chunk-B6NJHBLH.js +0 -21
  168. package/dist/bundle/chunks/chunk-HZTQHE5O.js +0 -26
  169. package/dist/bundle/chunks/chunk-IBDADH5Z.js +0 -4
  170. package/dist/bundle/chunks/chunk-OJZD7CO7.js +0 -8
  171. package/dist/bundle/chunks/cli-main-4JNPG6LB.js +0 -3
  172. package/dist/bundle/chunks/host-command-I3ZMWQQ3.js +0 -2
  173. package/dist/bundle/chunks/host-lifecycle-QEO422VW.js +0 -3
  174. package/dist/bundle/chunks/host-session-command-INULKX6E.js +0 -20
  175. package/dist/bundle/chunks/interactive-mode-SYWJVPKK.js +0 -2
  176. package/dist/bundle/chunks/rpc-mode-JMCYSP4P.js +0 -2
  177. package/dist/bundle/chunks/rpc-monitor-source-34AQDTZ6.js +0 -3
  178. package/dist/bundle/chunks/session-control-endpoint-IW5X56WN.js +0 -3
@@ -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{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-OA5INWHI.js";import"./chunk-OJZD7CO7.js";import"./chunk-CZR7C6CY.js";import{DefaultPackageManager,DynamicBorder,SettingsManager,keyHint,rawKeyHint}from"./chunk-LR6Z6V54.js";import"./chunk-DXJJP6RP.js";import"./chunk-HCF5M6NA.js";import"./chunk-HHYSXDYP.js";import"./chunk-GY5MR5KR.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-FIBIVBQK.js";import"./chunk-SGATKHO4.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./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{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-HZTQHE5O.js";import"./chunk-64CFJHKT.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-RQHK4QZ5.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-BZ75DRZB.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import{runtimeExecArgv}from"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.js";import"./chunk-HB35RBP4.js";import{appendHiddenTuiStdout}from"./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-BRXN5R2F.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-YJA2B7FQ.js";import{killProcessTree}from"./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{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-ONLNXGO3.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}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{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
2
+ import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-GVJ76VQI.js";import"./chunk-SGDOZT6B.js";import"./chunk-VOBD6FQG.js";import{DefaultPackageManager,DynamicBorder,SettingsManager,keyHint,rawKeyHint}from"./chunk-NQC7MI2G.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-42OY5SZZ.js";import"./chunk-GY5MR5KR.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-CDRFFHLL.js";import"./chunk-7UUOGZKR.js";import"./chunk-Y5OTHMXO.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./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{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-3VOG6WFU.js";import"./chunk-BMYNMUVZ.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-U67ML6CQ.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import"./chunk-II22E3CV.js";import{runtimeExecArgv}from"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.js";import"./chunk-HB35RBP4.js";import{appendHiddenTuiStdout}from"./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{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-FDL4CF6F.js";import{killProcessTree}from"./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{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}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_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}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{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
3
3
  `)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...runtimeExecArgv(),cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
4
4
  `,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
5
5
  `)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
@@ -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{MODULE_JOB_KIND,NOTICE_TAIL_MAX_CHARS,TERMINAL_CHILD_JOB_KINDS,TerminalManager,ToolChildJobError,childTerminalIdScope,controlFd,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createModuleJobHandler,createPtyBashTool,goShimScript,runToolChild,sanitizeTerminalOutput,withControlPipe}from"./chunk-BRXN5R2F.js";import"./chunk-YJA2B7FQ.js";import{getShellConfig}from"./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-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";var PTY_GO_SHIM='stty -echo 2>/dev/null; IFS= read -r _go || exit 127; stty echo 2>/dev/null; exec "$0" "$@"';function parseArgs(value){let field=name=>typeof value=="object"&&value!==null?Reflect.get(value,name):void 0,cwd=field("cwd"),toolCallId=field("toolCallId"),env=field("env");if(typeof cwd!="string"||typeof toolCallId!="string"||typeof env!="object"||env===null)throw new ToolChildJobError("terminal_job_bad_args","a terminal job needs cwd, toolCallId and env");let shellPath=field("shellPath"),timeoutAction=field("timeoutAction");return{params:field("params"),toolCallId,cwd,env:Object.fromEntries(Object.entries(env).filter(entry=>typeof entry[1]=="string")),...typeof shellPath=="string"?{shellPath}:{},defaultCols:Number(field("defaultCols"))||0,defaultRows:Number(field("defaultRows"))||0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{}}}function barrierFor(job){return{wrap:(command,args)=>({command:"/bin/sh",args:["-c",PTY_GO_SHIM,command,...args]}),async release(session){if(session.pid===void 0)throw new ToolChildJobError("terminal_spawn_failed","the PTY reported no pid");let gated=job.gate.request({jobId:job.jobId,origin:"terminal",api:"pty.spawn",containment:"own-group",lifetime:"owned",pid:session.pid,pgid:session.pid});session.onExit(exitCode=>job.gate.done(gated.launchId,exitCode===null?{}:{exitCode})),job.gate.skipsAckWait||await gated.acked,job.gate.invokeNow(gated.launchId),session.write(`go
2
+ import{MODULE_JOB_KIND,NOTICE_TAIL_MAX_CHARS,TERMINAL_CHILD_JOB_KINDS,TerminalManager,ToolChildJobError,childTerminalIdScope,controlFd,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createModuleJobHandler,createPtyBashTool,goShimScript,runToolChild,sanitizeTerminalOutput,withControlPipe}from"./chunk-QH2HSCMX.js";import"./chunk-FDL4CF6F.js";import{getShellConfig}from"./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-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";var PTY_GO_SHIM='stty -echo 2>/dev/null; IFS= read -r _go || exit 127; stty echo 2>/dev/null; exec "$0" "$@"';function parseArgs(value){let field=name=>typeof value=="object"&&value!==null?Reflect.get(value,name):void 0,cwd=field("cwd"),toolCallId=field("toolCallId"),env=field("env");if(typeof cwd!="string"||typeof toolCallId!="string"||typeof env!="object"||env===null)throw new ToolChildJobError("terminal_job_bad_args","a terminal job needs cwd, toolCallId and env");let shellPath=field("shellPath"),timeoutAction=field("timeoutAction");return{params:field("params"),toolCallId,cwd,env:Object.fromEntries(Object.entries(env).filter(entry=>typeof entry[1]=="string")),...typeof shellPath=="string"?{shellPath}:{},defaultCols:Number(field("defaultCols"))||0,defaultRows:Number(field("defaultRows"))||0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{}}}function barrierFor(job){return{wrap:(command,args)=>({command:"/bin/sh",args:["-c",PTY_GO_SHIM,command,...args]}),async release(session){if(session.pid===void 0)throw new ToolChildJobError("terminal_spawn_failed","the PTY reported no pid");let gated=job.gate.request({jobId:job.jobId,origin:"terminal",api:"pty.spawn",containment:"own-group",lifetime:"owned",pid:session.pid,pgid:session.pid});session.onExit(exitCode=>job.gate.done(gated.launchId,exitCode===null?{}:{exitCode})),job.gate.skipsAckWait||await gated.acked,job.gate.invokeNow(gated.launchId),session.write(`go
3
3
  `)}}}function exitSummary(id,runtime){let output=sanitizeTerminalOutput(runtime.fullOutput()).trimEnd(),exit=runtime.exitResult;return{event:"background_exit",id,exit:exit===null?null:{exitCode:exit.exitCode,signal:exit.signal,cancelled:exit.cancelled,timedOut:exit.timedOut},output:output.length>NOTICE_TAIL_MAX_CHARS?output.slice(output.length-NOTICE_TAIL_MAX_CHARS-1):output}}function createTerminalJobHandlers(injected){let manager=injected,managerFor=generation=>(manager??=new TerminalManager({idScope:childTerminalIdScope(generation)}),manager),tell=(job,wake)=>{job.wake(TERMINAL_CHILD_JOB_KINDS.bash,wake).catch(error=>{process.stderr.write(`tool-child: terminal ${wake.event} for ${wake.id} not delivered: ${error instanceof Error?error.message:String(error)}
4
4
  `)})},contextFor=(args,job)=>({manager:managerFor(job.generation),...args.timeoutAction===void 0?{}:{timeoutAction:args.timeoutAction},onBackgroundStart:(id,description,startedAtMs)=>tell(job,{event:"background_start",id,description,startedAtMs}),onBackgroundExit:(id,runtime)=>tell(job,exitSummary(id,runtime)),cwd:args.cwd,...args.shellPath===void 0?{}:{shellPath:args.shellPath},defaultCols:args.defaultCols,defaultRows:args.defaultRows,getEnv:()=>({...args.env}),launchBarrier:barrierFor(job)}),run=create=>async(value,job)=>{let args=parseArgs(value),tool=create(contextFor(args,job));if(!value_exports.Check(tool.parameters,args.params))throw new ToolChildJobError("terminal_job_bad_args","the tool's parameters do not match its schema");let onUpdate=update=>{job.update(update).catch(error=>{process.stderr.write(`tool-child: ${args.toolCallId} update not sent: ${error instanceof Error?error.message:String(error)}
5
5
  `)})};return tool.execute(args.toolCallId,args.params,job.signal,onUpdate,{cwd:args.cwd})};return{[TERMINAL_CHILD_JOB_KINDS.bash]:run(createPtyBashTool),[TERMINAL_CHILD_JOB_KINDS.output]:run(createBashOutputTool),[TERMINAL_CHILD_JOB_KINDS.input]:run(createBashInputTool),[TERMINAL_CHILD_JOB_KINDS.resize]:run(createBashResizeTool),[TERMINAL_CHILD_JOB_KINDS.kill]:run(createKillBashTool)}}import{access}from"node:fs/promises";import{constants as osConstants}from"node:os";import{spawn}from"node:child_process";import{once}from"node:events";import{Socket}from"node:net";async function launchOwnGroup(launch){if(process.platform==="win32")throw new Error("launchOwnGroup is POSIX-only; Windows launches are contained by the job");let callerStdio=[...launch.options?.stdio??["ignore","pipe","pipe"]],fd=controlFd(callerStdio),shim=spawn("/bin/sh",["-c",goShimScript(fd),launch.program,...launch.args],{...launch.options,detached:!0,stdio:withControlPipe(callerStdio,fd,"ignore","pipe")}),pid=shim.pid,exited=once(shim,"exit").then(([exitCode,signal])=>({exitCode,signal}));if(pid===void 0)throw new Error(`could not start ${launch.program}`);let gated=launch.gate.request({jobId:launch.jobId,origin:launch.origin,api:launch.api,containment:"own-group",lifetime:launch.lifetime??"owned",pid,pgid:pid});if(exited.then(({exitCode,signal})=>launch.gate.done(gated.launchId,{...exitCode===null?{}:{exitCode},...signal===null?{}:{signal}})),launch.gate.skipsAckWait||await Promise.race([gated.acked,exited]),shim.exitCode===null&&shim.signalCode===null){launch.gate.invokeNow(gated.launchId);let control=shim.stdio[fd];control instanceof Socket&&(control.on("error",()=>{}),exited.then(()=>control.destroy()),control.unref(),control.write(`go
@@ -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{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-OX5QL4YF.js";import{applyAccountOrder,classifyCredentialFailure,getConfigValueEnvVarNames,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover,slotsOfOwnKind}from"./chunk-VUKNGMDT.js";import{activeModelBlockUntil,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import{acquireHalfOpenLease}from"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import{discoverEnvSlots}from"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.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{ConfigReferenceError}from"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await writeHealthUnlessStoreBusy(`lease release on ${slotName}`,()=>repository.mutateSlotState(providerId,lane,slotName,current=>{if(current?.lease?.id!==leaseId)return current;let{lease:_released,...rest}=current;return rest}))}function probeLease(repository,providerId,lane,slotName,now){return writeHealthUnlessStoreBusy(`probe lease on ${slotName}`,()=>acquireHalfOpenLease(repository,providerId,lane,slotName,{now}))}function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}function overlayModelBlock(slot,until){return until===void 0||slot.blockedUntil!==void 0&&slot.blockedUntil>=until?slot:{...slot,blockedUntil:until,blockReason:slot.blockReason??"rate_limit"}}var warnedSlotReferences=new Set;async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,modelId=options.modelId,now=sources.now??Date.now,{providerId,credential,env,repository}=sources,policySlots=[],referenceError;for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key;try{key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,typeof ref.value=="string"?{}:Object.fromEntries(getConfigValueEnvVarNames(ref.value).flatMap(variable=>{let value=env(variable);return value===void 0?[]:[[variable,value]]}))):void 0}catch(error){if(!(error instanceof ConfigReferenceError))throw error;let notice=`${error.field}: configuration reference ${error.reason}; skipping credential slot`;warnedSlotReferences.has(notice)||(warnedSlotReferences.add(notice),console.warn(notice)),referenceError??=error;continue}key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of slotsOfOwnKind(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),lease;if(!(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()&&(lease=await probeLease(repository,providerId,"stored",slot.name,now()),lease===void 0))){if(lease!==void 0&&lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=leasedState?.credentialRevision===storedRevision?leasedState:void 0,leasedModelUntil=activeModelBlockUntil(leasedApplicable?.modelBlocks,modelId,now());await releaseLeaseIfModelBlocked(repository,providerId,"stored",slot.name,lease.leaseId,leasedModelUntil),slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable),modelUntil))}}if(policySlots.length===0){if(slots.length===0&&referenceError!==void 0)throw referenceError;return slots}let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases,modelId);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];if(envSlots.length===0&&referenceError!==void 0)throw referenceError;return listEnvRotationSlots(sources,envSlots,acquireLeases,modelId)}async function listEnvRotationSlots(sources,envSlots,acquireLeases,modelId){if(envSlots.length===0)return[];let{providerId,repository}=sources,now=sources.now??Date.now,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await probeLease(repository,providerId,"env",slot.name,now());if(lease===void 0)continue;if(lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"env"))[slot.name];applicable=leasedState?.credentialRevision===revision?leasedState:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),await releaseLeaseIfModelBlocked(repository,providerId,"env",slot.name,lease.leaseId,modelUntil)}}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision){let sameMaterial=current!==void 0&&current.credentialRevision===credentialRevision,{stateVersion:_stateVersion,...kept}=sameMaterial?current:{stateVersion:0};return{...kept,lease:void 0,...credentialRevision===void 0?{}:{credentialRevision},modelBlocks:withModelBlock(sameMaterial?current.modelBlocks:void 0,modelBlockKey(family,modelId),blockedUntil,now)}}function blockPatch(block,current,now,credentialRevision,policy,modelId){if(block.reason==="rate_limit"&&block.modelFamily!==void 0&&modelId!==void 0){let blockedUntil=now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs);return modelBlockPatch(block.modelFamily,modelId,blockedUntil,current,now,credentialRevision)}let failureCount=(current?.failureCount??0)+1,liveModelBlocks=current?.credentialRevision===credentialRevision?pruneModelBlocks(current?.modelBlocks,now):void 0,base={failureCount,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt},...liveModelBlocks===void 0?{}:{modelBlocks:liveModelBlocks}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:block.reason==="auth_error"?{...base,blockedUntil:now+9e5,blockReason:"auth_error"}:{...base,blockReason:block.reason}}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,pooled=sources.credential,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ranked=useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates,winner=applyAccountOrder(pooled?.order,ranked)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await writeHealthUnlessStoreBusy(`success on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,failureCount:void 0,modelBlocks:pruneModelBlocks(current.modelBlocks,now(),options.modelId)}:void 0))},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await writeHealthUnlessStoreBusy(`${block.reason} block on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy,options.modelId)))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
2
+ import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-OX5QL4YF.js";import{applyAccountOrder,classifyCredentialFailure,getConfigValueEnvVarNames,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover,slotsOfOwnKind}from"./chunk-3LNSLJ7N.js";import{activeModelBlockUntil,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import{acquireHalfOpenLease}from"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import{discoverEnvSlots}from"./chunk-4AOMNOGY.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.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{ConfigReferenceError}from"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await writeHealthUnlessStoreBusy(`lease release on ${slotName}`,()=>repository.mutateSlotState(providerId,lane,slotName,current=>{if(current?.lease?.id!==leaseId)return current;let{lease:_released,...rest}=current;return rest}))}function probeLease(repository,providerId,lane,slotName,now){return writeHealthUnlessStoreBusy(`probe lease on ${slotName}`,()=>acquireHalfOpenLease(repository,providerId,lane,slotName,{now}))}function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}function overlayModelBlock(slot,until){return until===void 0||slot.blockedUntil!==void 0&&slot.blockedUntil>=until?slot:{...slot,blockedUntil:until,blockReason:slot.blockReason??"rate_limit"}}var warnedSlotReferences=new Set;async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,modelId=options.modelId,now=sources.now??Date.now,{providerId,credential,env,repository}=sources,policySlots=[],referenceError;for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key;try{key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,typeof ref.value=="string"?{}:Object.fromEntries(getConfigValueEnvVarNames(ref.value).flatMap(variable=>{let value=env(variable);return value===void 0?[]:[[variable,value]]}))):void 0}catch(error){if(!(error instanceof ConfigReferenceError))throw error;let notice=`${error.field}: configuration reference ${error.reason}; skipping credential slot`;warnedSlotReferences.has(notice)||(warnedSlotReferences.add(notice),console.warn(notice)),referenceError??=error;continue}key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of slotsOfOwnKind(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),lease;if(!(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()&&(lease=await probeLease(repository,providerId,"stored",slot.name,now()),lease===void 0))){if(lease!==void 0&&lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=leasedState?.credentialRevision===storedRevision?leasedState:void 0,leasedModelUntil=activeModelBlockUntil(leasedApplicable?.modelBlocks,modelId,now());await releaseLeaseIfModelBlocked(repository,providerId,"stored",slot.name,lease.leaseId,leasedModelUntil),slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable),modelUntil))}}if(policySlots.length===0){if(slots.length===0&&referenceError!==void 0)throw referenceError;return slots}let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases,modelId);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];if(envSlots.length===0&&referenceError!==void 0)throw referenceError;return listEnvRotationSlots(sources,envSlots,acquireLeases,modelId)}async function listEnvRotationSlots(sources,envSlots,acquireLeases,modelId){if(envSlots.length===0)return[];let{providerId,repository}=sources,now=sources.now??Date.now,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await probeLease(repository,providerId,"env",slot.name,now());if(lease===void 0)continue;if(lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"env"))[slot.name];applicable=leasedState?.credentialRevision===revision?leasedState:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),await releaseLeaseIfModelBlocked(repository,providerId,"env",slot.name,lease.leaseId,modelUntil)}}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision){let sameMaterial=current!==void 0&&current.credentialRevision===credentialRevision,{stateVersion:_stateVersion,...kept}=sameMaterial?current:{stateVersion:0};return{...kept,lease:void 0,...credentialRevision===void 0?{}:{credentialRevision},modelBlocks:withModelBlock(sameMaterial?current.modelBlocks:void 0,modelBlockKey(family,modelId),blockedUntil,now)}}function blockPatch(block,current,now,credentialRevision,policy,modelId){if(block.reason==="rate_limit"&&block.modelFamily!==void 0&&modelId!==void 0){let blockedUntil=now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs);return modelBlockPatch(block.modelFamily,modelId,blockedUntil,current,now,credentialRevision)}let failureCount=(current?.failureCount??0)+1,liveModelBlocks=current?.credentialRevision===credentialRevision?pruneModelBlocks(current?.modelBlocks,now):void 0,base={failureCount,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt},...liveModelBlocks===void 0?{}:{modelBlocks:liveModelBlocks}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:block.reason==="auth_error"?{...base,blockedUntil:now+9e5,blockReason:"auth_error"}:{...base,blockReason:block.reason}}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,pooled=sources.credential,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ranked=useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates,winner=applyAccountOrder(pooled?.order,ranked)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await writeHealthUnlessStoreBusy(`success on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,failureCount:void 0,modelBlocks:pruneModelBlocks(current.modelBlocks,now(),options.modelId)}:void 0))},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await writeHealthUnlessStoreBusy(`${block.reason} block on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy,options.modelId)))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
@@ -0,0 +1,2 @@
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{runRpcMode}from"./chunk-GVJ76VQI.js";import"./chunk-SGDOZT6B.js";import"./chunk-VOBD6FQG.js";import"./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"./chunk-IUHU5PEC.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./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";export{runRpcMode};
@@ -0,0 +1,3 @@
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{allocateMonitorId,endpointSockets,matchesTask,subscriptionFor,wantsRecord}from"./chunk-7UUOGZKR.js";import"./chunk-FWXMMMCV.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-II22E3CV.js";import"./chunk-RHHBXIRN.js";import{MAX_RPC_LINE_CHARACTERS,OBSERVE_REQUEST_FIELD,attachJsonlLineReader}from"./chunk-RVYSJBZ7.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";var DELTA_KINDS=new Set(["message_update","tool_execution_update","bash_execution_update"]),SURFACE_KINDS=new Set(["loaded_surfaces_changed","commands_changed"]),LAST_TEXT_LIMIT=60,RpcMonitorCoalescer=class{#windows=new Map;#flush;constructor(flush){this.#flush=flush}accept(sessionKey2,label,record){let type=String(record.type),delta=DELTA_KINDS.has(type);if(!delta&&!SURFACE_KINDS.has(type))return!1;let key=delta?`${sessionKey2}#deltas`:`${sessionKey2}#${type}`,open=this.#windows.get(key),last=delta?lastText(record):"";if(open!==void 0)return open.count+=1,last!==""&&(open.last=last),!0;let window={count:1,last,timer:setTimeout(()=>{this.#windows.delete(key),this.#flush(delta?`rpc ${label()} streaming +${window.count} deltas${window.last===""?"":` (last: "${window.last}")`}`:`rpc ${label()} ${type} x${window.count}`)},delta?2e3:5e3)};return this.#windows.set(key,window),!0}dispose(){for(let window of this.#windows.values())clearTimeout(window.timer);this.#windows.clear()}};function lastText(record){let event=record.assistantMessageEvent,flat=(event?.type==="text_delta"&&typeof event.delta=="string"?event.delta:typeof record.output=="string"?record.output:"").replace(/\s+/g," ").trim();return flat.length>LAST_TEXT_LIMIT?flat.slice(-LAST_TEXT_LIMIT):flat}import{createConnection}from"node:net";var SUBSCRIBE_ID="monitor-subscribe";async function openRpcObserver(socketPath,subscription,handlers,options={}){let secret=socketNeedsHandshake(socketPath)?await readSocketSecret(socketSecretPath(socketPath)):void 0,authenticated=socketNeedsHandshake(socketPath)?void 0:await connectAuthenticatedRpcSocket(socketPath,void 0,options),socket=authenticated?.socket??createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),answer=Promise.withResolvers(),ended=!1,end=reason=>{ended||(ended=!0,answer.reject(new Error(`rpc monitor: ${socketPath}: ${reason}`)),handlers.closed(reason))},subscribe=()=>{secret!==void 0&&sendSocketHandshake(socket,secret);let frame={...subscription,[OBSERVE_REQUEST_FIELD]:!0,id:SUBSCRIBE_ID,type:"subscribe_sessions"};socket.write(`${JSON.stringify(frame)}
3
+ `)},detach=attachJsonlLineReader(socket,line=>{let record;try{record=JSON.parse(line)}catch{return}if(record.type==="response"&&record.id===SUBSCRIBE_ID){record.success===!0?answer.resolve(record):(answer.reject(new Error(`rpc monitor: ${socketPath} refused the subscription: ${String(record.error)}`)),socket.destroy());return}handlers.record(record)},{maxLineLength:MAX_RPC_LINE_CHARACTERS});return socket.on("error",error=>end(error.message)),socket.once("close",()=>{detach(),end("connection closed")}),authenticated?subscribe():socket.once("connect",subscribe),{subscribed:answer.promise,close:()=>socket.destroy()}}var RpcMonitorRenderer=class{#sessions=new Map;#namedThisBatch=new Set;seed(socket,snapshot){return snapshot.map(row=>{let view=this.#view(socket,row);view.status=String(row.status);let model=modelId(row.model),attachments=typeof row.attachments=="number"?row.attachments:0;return`${view.label} ${view.status} (${attachments} attached${model===void 0?"":`, model ${model}`})`})}forgetSocket(socket){let count2=0;for(let key of[...this.#sessions.keys()])key.startsWith(`${socket}#`)&&(this.#sessions.delete(key),count2++);return count2}statuses(){return new Map([...this.#sessions].map(([key,view])=>[key,view.status]))}label(socket,record){let view=this.#view(socket,record),key=sessionKey(socket,record);return this.#namedThisBatch.has(key)?view.label:(this.#namedThisBatch.size===0&&queueMicrotask(()=>this.#namedThisBatch.clear()),this.#namedThisBatch.add(key),`${view.label} (${String(record.sessionId)})`)}render(socket,record){switch(record.type){case"session_status":return this.#status(socket,record);case"effect_status":{let detail=record.disposition??reasonOf(record.outcome);return`rpc ${this.label(socket,record)} effect ${String(record.kind)} ${tail(String(record.effectId))} ${String(record.state)}${detail===void 0?"":` (${String(detail)})`}`}case"agent_end":return`rpc ${this.label(socket,record)} agent_end${record.aborted===!0?` aborted(${String(record.abortSource??"user")})`:""}`;case"model_changed":return`rpc ${this.label(socket,record)} model_changed -> ${modelId(record.model)??"?"}${record.source===void 0?"":` (${String(record.source)})`}`;case"queue_update":return`rpc ${this.label(socket,record)} queue_update steering=${count(record.steering)} followUp=${count(record.followUp)}`;case"session_replaced":return`rpc ${this.label(socket,record)} session_replaced -> ${String(record.durableSessionId??record.newSessionId??"?")}`;case"session_closed":return`rpc ${this.label(socket,record)} session_closed ${String(record.reason??"")}`.trimEnd();case"extension_event":return`rpc ${this.label(socket,record)} extension_event ${String(record.name??record.event??"")}`.trimEnd();case"entry_appended":return`rpc ${this.label(socket,record)} entry_appended ${entryType(record)}`;case"tool_execution_start":case"tool_execution_end":return`rpc ${this.label(socket,record)} tool ${String(record.toolName??"?")} ${record.type==="tool_execution_start"?"started":"ended"}`;case"turn_end":case"turn_start":case"agent_start":case"agent_idle":case"agent_settled":return`rpc ${this.label(socket,record)} ${record.type}`;default:{let{type:_type,sessionId:_sessionId,...rest}=record,json=JSON.stringify(rest),body=json.length>160?`${json.slice(0,160)}...`:json;return`rpc ${this.label(socket,record)} ${String(record.type)} ${body}`}}}#status(socket,record){let view=this.#view(socket,record),to=String(record.status),from=view.status;if(view.status=to,from===to)return;let change=record.lastChange,why=change===void 0?"":` (${String(change.cause)}, by ${String(change.by)})`;return`rpc ${this.label(socket,record)} status ${from} -> ${to}${why} seq=${String(record.seq)}`}#view(socket,record){let key=sessionKey(socket,record),view=this.#sessions.get(key);return view===void 0?(view={label:labelOf(record),status:"unknown"},this.#sessions.set(key,view)):(typeof record.name=="string"||contextTask(record)!==void 0)&&(view.label=labelOf(record)),view}};function sessionKey(socket,record){return`${socket}#${String(record.sessionId)}`}function labelOf(record){let task=contextTask(record);return task!==void 0?task:typeof record.name=="string"&&record.name!==""?record.name:(typeof record.durableSessionId=="string"?record.durableSessionId:String(record.sessionId)).slice(0,8)}function contextTask(record){let context=record.context;return typeof context?.task_id=="string"?context.task_id:void 0}function modelId(model){return typeof model=="object"&&model!==null&&"id"in model?String(model.id):void 0}function reasonOf(outcome){return typeof outcome=="object"&&outcome!==null&&"reason"in outcome?String(outcome.reason):void 0}function count(value){return Array.isArray(value)?value.length:typeof value=="number"?value:0}function tail(id){return id.length>8?id.slice(-8):id}function entryType(record){let entry=record.entry;return String(entry?.type??record.entryType??"?")}var RPC_RESCAN_MS=3e4,RpcMonitorWatch=class{#options;#observers=new Map;#hosts=new Map;#renderer=new RpcMonitorRenderer;#coalescer;#taskSessions=new Set;#rescan;#stopped=!1;constructor(options){this.#options=options,this.#coalescer=new RpcMonitorCoalescer(options.line)}async start(){let rows=await this.#join();return this.#rescan=setInterval(()=>{this.#join()},RPC_RESCAN_MS),this.#rescan.unref?.(),rows}checkpoint(){return{hosts:Object.fromEntries(this.#hosts),statuses:Object.fromEntries(this.#renderer.statuses())}}diffSince(saved){let lines=[];for(let[socket,host]of this.#hosts){let before=saved.hosts[socket];before!==void 0&&before.generation!==host.generation&&lines.push(`rpc host ${socket} restarted (generation ${before.generation} -> ${host.generation})`)}let now=this.#renderer.statuses();for(let[key,status]of Object.entries(saved.statuses)){let label=key.slice(key.lastIndexOf("#")+1).slice(0,8),current=now.get(key),socket=key.slice(0,key.lastIndexOf("#"));current===void 0?lines.push(this.#hosts.has(socket)&&this.#options.target.kind!=="children"?`rpc ${label} closed (gone while detached)`:this.#hosts.has(socket)?`rpc ${label} no longer listed (closed or no longer a child while detached)`:`rpc ${label} unreachable (its host did not answer)`):current!==status&&lines.push(`rpc ${label} status ${status} -> ${current} (changed while detached)`)}return lines}stop(){this.#stopped=!0,this.#rescan!==void 0&&clearInterval(this.#rescan),this.#coalescer.dispose();for(let observer of this.#observers.values())observer.close();this.#observers.clear()}async#join(){let fresh=(await(this.#options.endpoints??(()=>endpointSockets(this.#options.agentDir)))().catch(()=>[])).filter(socket=>!this.#observers.has(socket));return(await Promise.all(fresh.map(socket=>this.#observe(socket)))).flat()}async#observe(socket){if(this.#stopped)return[];let{target,events}=this.#options,observer;try{observer=await openRpcObserver(socket,subscriptionFor(target,events),{record:record=>{this.#stopped||this.#record(socket,record)},closed:()=>this.#lost(socket,observer)})}catch{return[]}if(this.#stopped)return observer.close(),[];this.#observers.set(socket,observer);let answer=await observer.subscribed.catch(()=>{});if(this.#stopped)return observer.close(),[];let data=answer?.data;if(data===void 0)return[];this.#hosts.set(socket,{instanceId:String(data.hostInstanceId),generation:String(data.hostGeneration)});let matched=(Array.isArray(data.snapshot)?data.snapshot:[]).filter(row=>matchesTask(target,row));for(let row of matched)this.#taskSessions.add(sessionKey(socket,row));if(target.kind!=="all"&&target.kind!=="children"&&matched.length===0)return observer.close(),this.#observers.delete(socket),[];let rows=this.#renderer.seed(socket,matched);return this.#options.checkpoint?.(this.checkpoint()),rows}#lost(socket,observer){if(this.#observers.get(socket)!==observer||(this.#observers.delete(socket),this.#stopped))return;let forgotten=this.#renderer.forgetSocket(socket);for(let key of[...this.#taskSessions])key.startsWith(`${socket}#`)&&this.#taskSessions.delete(key);(this.#hosts.delete(socket)||forgotten>0)&&(this.#options.line(`rpc host ${socket} gone (${forgotten} session${forgotten===1?"":"s"} no longer watched)`),this.#options.checkpoint?.(this.checkpoint()))}#record(socket,record){let{target,events,exclude}=this.#options,type=String(record.type);if(!wantsRecord(events,exclude,type))return;let key=sessionKey(socket,record);if(target.kind==="task"&&(matchesTask(target,record)&&this.#taskSessions.add(key),!this.#taskSessions.has(key))||this.#coalescer.accept(key,()=>this.#renderer.label(socket,record),record))return;let line=this.#renderer.render(socket,record);line!==void 0&&(this.#options.line(line),type==="session_status"&&this.#options.checkpoint?.(this.checkpoint()))}};var RPC_WATCHER_TIMED_OUT_SUMMARY="watcher timed_out",RpcMonitorSource=class{#records=new Map;#host;#nextId=1;constructor(host){this.#host=host}get(id){return this.#records.get(id)}values(){return this.#records.values()}keys(){return this.#records.keys()}async register(options){let id=`rpc_${this.#nextId++}`,monitorId=options.monitorId??allocateMonitorId(),watch=new RpcMonitorWatch({agentDir:options.agentDir,target:options.target,events:options.events,exclude:options.exclude,...options.endpoints===void 0?{}:{endpoints:options.endpoints},line:line=>this.#line(id,line),...options.onCheckpoint===void 0?{}:{checkpoint:checkpoint=>options.onCheckpoint?.(monitorId,checkpoint)}}),record={id,monitorId,description:options.description,startedAtMs:Date.now(),command:null,filter:options.filter,persistent:options.persistent,deadlineMs:options.persistent||options.timeoutMs===void 0?null:Date.now()+options.timeoutMs,fireCount:0,lastFiredAtMs:null,expiresAt:options.expiresAt,paused:!1,settled:!1,rpcWatch:watch,targetText:options.targetText,mutedDropped:0,lastLine:void 0,deadline:options.persistent||options.timeoutMs===void 0?void 0:setTimeout(()=>this.settle(id,RPC_WATCHER_TIMED_OUT_SUMMARY),options.timeoutMs)};this.#records.set(id,record),this.#host.changed();let rows=await watch.start();if(options.restoredFrom!==void 0)for(let line of watch.diffSince(options.restoredFrom))this.#line(id,line);return{id,monitorId,rows}}settle(id,summary){let record=this.#records.get(id);return record===void 0||record.settled?!1:(record.settled=!0,record.rpcWatch.stop(),clearTimeout(record.deadline),this.#records.delete(id),this.#host.changed(),summary!=="watcher disposed"&&this.#host.emit(record,{type:"summary",id,description:record.description,summary}),this.#host.ended(record,summary===RPC_WATCHER_TIMED_OUT_SUMMARY?"timeout":summary==="watcher disposed"?"disposed":"killed",null),!0)}settleAll(summary){let ids=[...this.#records.keys()];for(let id of ids)this.settle(id,summary);return ids.length}#line(id,line){let record=this.#records.get(id);if(!(record===void 0||record.settled)&&!(record.filter instanceof RegExp&&!record.filter.test(line))&&line!==record.lastLine){if(record.lastLine=line,record.paused){record.mutedDropped+=1;return}this.#host.emit(record,{type:"line",id,description:record.description,line})}}};export{RpcMonitorSource};
@@ -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{RUNNER_HEARTBEAT_INTERVAL_MS,RUNNER_HEARTBEAT_STALE_MS,cancelScheduledJob,deferWhileSessionOpen,execHookDelivery,listScheduledJobs,liveRunners,ownRunnerIdentity,removeRunnerLease,runDueJobs,scheduleDir,sessionResumeDelivery,writeRunnerLease}from"./chunk-CZR7C6CY.js";import"./chunk-CNPDUC4D.js";import"./chunk-SOMFLLPD.js";import{resolveCliMainPath,runtimeExecArgv}from"./chunk-B6NJHBLH.js";import"./chunk-OUPD5LWY.js";import"./chunk-QQSCUEYJ.js";import"./chunk-U3VOXCGP.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-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-QN2BHP3M.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";import{mkdirSync,watch}from"node:fs";import{join}from"node:path";function writeLine(value){process.stdout.write(`${JSON.stringify(value)}
2
+ import{RUNNER_HEARTBEAT_INTERVAL_MS,RUNNER_HEARTBEAT_STALE_MS,cancelScheduledJob,deferWhileSessionOpen,execHookDelivery,listScheduledJobs,liveRunners,ownRunnerIdentity,removeRunnerLease,runDueJobs,scheduleDir,sessionResumeDelivery,writeRunnerLease}from"./chunk-VOBD6FQG.js";import"./chunk-CNPDUC4D.js";import"./chunk-SOMFLLPD.js";import{resolveCliMainPath,runtimeExecArgv}from"./chunk-7IRLFYNM.js";import"./chunk-XUFUKDKJ.js";import"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import"./chunk-RVYSJBZ7.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-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-QN2BHP3M.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";import{mkdirSync,watch}from"node:fs";import{join}from"node:path";function writeLine(value){process.stdout.write(`${JSON.stringify(value)}
3
3
  `)}function resolveDelivery(options){let timeoutMs=options.timeoutSeconds*1e3;return options.exec!==void 0?{deliver:execHookDelivery(options.exec,timeoutMs),shouldDefer:void 0}:{deliver:sessionResumeDelivery({command:process.execPath,args:isBunBinary?[]:[...runtimeExecArgv(),resolveCliMainPath()]},timeoutMs),shouldDefer:deferWhileSessionOpen}}function reporter(){let deferred=new Map,invalid=new Map;return result=>{let ok=!0,stillInvalid=new Set;for(let event of result.events){if(event.event==="deferred"){if(deferred.get(event.id)===event.reason)continue;deferred.set(event.id,event.reason)}else if(event.event==="invalid"){if(stillInvalid.add(event.file),invalid.get(event.file)===event.error)continue;invalid.set(event.file,event.error)}else event.event==="fired"?(deferred.delete(event.id),event.outcome==="failed"&&(ok=!1)):event.event==="error"&&(ok=!1);writeLine(event)}for(let file of invalid.keys())stillInvalid.has(file)||invalid.delete(file);return ok}}async function guardedPass(pass){try{return await pass()}catch(error){return{events:[{event:"error",error:error instanceof Error?error.message:String(error)}],nextDueAt:void 0}}}async function runPasses(dir,options){let plan=resolveDelivery(options),owner=ownRunnerIdentity(),startedAt=Date.now(),lease=()=>writeRunnerLease(dir,{startedAt,watch:options.watch,exec:options.exec??null},Date.now()),report=reporter(),pass=()=>runDueJobs({dir,now:Date.now,deliver:plan.deliver,owner,concurrency:options.concurrency,deliveryTimeoutMs:options.timeoutSeconds*1e3,shouldDefer:plan.shouldDefer});await lease();let leaseFailing=!1,heartbeat=setInterval(()=>{lease().then(()=>{leaseFailing=!1},error=>{leaseFailing||writeLine({event:"lease_error",error:error instanceof Error?error.message:String(error)}),leaseFailing=!0})},RUNNER_HEARTBEAT_INTERVAL_MS),watcher,stopping=!1,wake,stop=()=>{stopping=!0,wake?.()};try{if(!options.watch)return report(await guardedPass(pass))?0:1;process.on("SIGTERM",stop),process.on("SIGINT",stop);let pendingDir=join(dir,"pending");for(mkdirSync(pendingDir,{recursive:!0,mode:448}),watcher=watch(pendingDir,()=>wake?.()),writeLine({event:"watching",pid:process.pid,dir,pollSeconds:options.pollSeconds});!stopping;){let rescan=!1,woken=new Promise(resolve=>{wake=()=>{rescan=!0,resolve()}}),result=await guardedPass(pass);if(report(result),stopping)break;if(rescan)continue;let untilDue=result.nextDueAt===void 0?Number.POSITIVE_INFINITY:result.nextDueAt-Date.now(),waitMs=Math.max(0,Math.min(options.pollSeconds*1e3,untilDue)),timer;await Promise.race([woken,new Promise(resolve=>timer=setTimeout(resolve,waitMs))]),clearTimeout(timer)}return writeLine({event:"stopped",pid:process.pid}),0}finally{clearInterval(heartbeat),watcher?.close(),process.off("SIGTERM",stop),process.off("SIGINT",stop),await removeRunnerLease(dir)}}var EXIT_OK=0,EXIT_FAILED=1,EXIT_USAGE=2,DEFAULT_POLL_SECONDS=60,DEFAULT_TIMEOUT_SECONDS=900,DEFAULT_CONCURRENCY=4,USAGE=`usage: ${APP_NAME} schedule <list|cancel|run> [options]
4
4
 
5
5
  list [--json] every scheduled prompt, all sessions
@@ -0,0 +1,3 @@
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{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,refusal,sessionRuntimeView,socketSink}from"./chunk-HKUXKTFW.js";import{WakeScheduler,answeredUiRequestId,availableModelsData,buildRpcSessionState,interruptRunningTurn,onProcessContinue,rpcCommandShapeError,runGetEffectStatus,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-42OY5SZZ.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import{SESSION_STATUS_CAPABILITY,acquireHostEnsureLock,engineBuildIdentity,gcHostEndpoints}from"./chunk-BMYNMUVZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-FWXMMMCV.js";import"./chunk-KUPQO7MC.js";import"./chunk-U67ML6CQ.js";import"./chunk-26UBFF6N.js";import"./chunk-EWOEVVQT.js";import{tuiSocketName}from"./chunk-II22E3CV.js";import{thisProcessStartTime,writeHostRegistration}from"./chunk-XUFUKDKJ.js";import{createDaemonDirectories,createHostDaemonPaths}from"./chunk-RHHBXIRN.js";import"./chunk-U3VOXCGP.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-RVYSJBZ7.js";import"./chunk-HB35RBP4.js";import"./chunk-RUGYFYH7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-FDL4CF6F.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-YU2P3CAR.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-VRDU425E.js";import{authenticateSocket,createSocketSecret,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm2}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions){this.writer=new SessionEventWriter(()=>{}),this.attached=new Set,this.session=session,this.writer.status.setSource({sessionIds:()=>[this.handle],entryView:id=>id===this.handle?this.entryView():void 0,view:id=>id===this.handle?{entry:this.entryView(),runtime:sessionRuntimeView(session,pendingQuestions())}:void 0}),this.writer.registerConnection(NULL_CONNECTION,{writeRaw:()=>{},waitForBackpressure:async()=>{}}),this.stopRecords=subscribeSessionRecords(session,record=>this.writer.enqueue(this.handle,record))}get handle(){return this.session.sessionId}opened(connection){this.writer.registerConnection(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.writer.unregisterConnection(key)}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.writer.attachConnectionToSession(key,this.handle),this.writer.status.publish(this.handle,"attach","client"),!0)}isAttached(connection){return this.attached.has(keyOf(connection))}run(connection,task){return this.writer.withConnection(keyOf(connection),task)}respond(connection,answer2){this.writer.enqueueControl(answer2,keyOf(connection)).catch(()=>connection.transport.close?.())}dispose(){this.stopRecords()}entryView(){let manager=this.session.sessionManager,path=this.session.sessionFile,name=manager.getSessionName();return{state:"open",kind:"interactive",cwd:manager.getCwd(),attachments:1+this.attached.size,durableSessionId:this.session.sessionId,...path!==void 0?{sessionPath:path}:{},...name!==void 0?{name}:{},context:{}}}},NULL_CONNECTION="tui-null";function keyOf(connection){return`tui-${connection.id}`}import{randomUUID}from"node:crypto";import{realpathSync}from"node:fs";import{resolve}from"node:path";var TUI_RPC_COMMANDS=["open_session","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","get_effect_status"];async function runTuiRpcCommand(context,connection,command){switch(command.type){case"open_session":return openSession(context,connection,command);case"subscribe_sessions":return subscribe(context,connection,command);case"unsubscribe_sessions":return answerUnsubscribeSessions(command,keyOf(connection),context.attachments.writer.status);case"steer":case"follow_up":return admitInput(context,command,command.type==="steer"?"steer":"followUp",command.whenIdle);case"prompt":return admitPrompt(context,command);case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}function idOf(command){return typeof command.id=="string"?command.id:void 0}function openSession(context,connection,command){let{session,attachments}=context,ownPath=typeof command.sessionPath=="string"&&samePath(command.sessionPath,session.sessionFile),ownId=command.sessionId!==void 0&&command.sessionId===session.sessionId;return!ownPath&&!ownId?refusal(idOf(command),"open_session","terminal_single_session",{reason:"this terminal hosts one session and the request names another",action:"open it by this terminal's sessionPath, or open the other session on a host"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:attachments.handle,state:buildRpcSessionState(session),attached:!0}})}),null)}function subscribe(context,connection,command){let{writer}=context.attachments,key=keyOf(connection),{answer:answer2,activate}=answerSubscribeSessions(command,key,writer.status);return activate===void 0?answer2:(writer.enqueueControl(answer2,key).then(()=>{writer.hasConnection(key)?writer.status.activate(activate):writer.status.unsubscribe(key,activate)}).catch(()=>writer.status.unsubscribe(key,activate)),null)}function admitPrompt(context,command){let behavior=command.streamingBehavior;return behavior===void 0&&context.session.isStreaming?refusal(idOf(command),"prompt","session_busy",{reason:"a turn is running and the prompt names no streamingBehavior",action:'send it with streamingBehavior "steer" or "followUp", or as a steer/follow_up'}):admitInput(context,command,behavior==="followUp"?"followUp":"steer","start")}var UNSERVED_INPUT_FIELDS=["images","thinkingLevel","expandPromptTemplates","unknownCommandAsText","sessionTitlePrompt","enqueueOrder"];function samePath(requested,own){if(own===void 0)return!1;let canonical=path=>{try{return realpathSync(resolve(path))}catch{return resolve(path)}};return canonical(requested)===canonical(own)}function admitInput(context,command,deliverAs,whenIdle){let id=idOf(command),unserved=UNSERVED_INPUT_FIELDS.filter(field=>command[field]!==void 0);if(unserved.length>0)return refusal(id,command.type,"unsupported_field",{reason:`a terminal delivers input through its admission, which carries text only, not ${unserved.join(", ")}`,action:"send the message without those fields, or send it to a host session"});let message=command.message;if(typeof message!="string"||message.trim()==="")return refusal(id,command.type,"invalid_message",{reason:"message is empty",action:"send a non-empty message"});if(whenIdle!==void 0&&whenIdle!=="queue"&&whenIdle!=="start")return refusal(id,command.type,"invalid_when_idle",{reason:`whenIdle must be "queue" or "start", not ${JSON.stringify(whenIdle)}`,action:'send whenIdle: "queue" (the default) or "start"'});let admission=context.session.externalAdmission,clientMessageId=typeof command.clientMessageId=="string"?command.clientMessageId:void 0,expected=typeof command.expected_turn_id=="number"?command.expected_turn_id:admission.turnEpoch,result=admission.admit({delivery_id:clientMessageId??`tui-rpc-${randomUUID()}`,text:message,sender:{kind:"external",platform:"rpc"},deliverAs,expected_turn_id:expected,whenIdle:whenIdle==="start"?"start":"queue"}),identity=clientMessageId===void 0?{}:{clientMessageId};switch(result.kind){case"started":return answered(id,command.type,{disposition:"started",...identity});case"steered":case"queued":return answered(id,command.type,{disposition:"queued",...identity});case"already_admitted":return answered(id,command.type,{disposition:"queued",duplicate:!0,...identity});case"held_draft":return refusal(id,command.type,"held_draft",{reason:"the user is composing in this terminal, so nothing was delivered",action:"retry after the draft is sent or cleared"});case"turn_conflict":return refusal(id,command.type,"turn_conflict",{reason:`the turn moved on (now ${result.turn_epoch}); this steer named an earlier one`,action:"read get_state's turn_epoch and send it again"})}}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}import{chmod}from"node:fs/promises";import{createServer}from"node:net";async function listenControlSocket(socketPath,secret,handlers){let clients=new Set,nextConnection=0,server=createServer(socket=>{clients.add(socket),socket.once("close",()=>clients.delete(socket)),socket.on("error",()=>socket.destroy()),authenticateSocket(socket,secret,()=>acceptConnection(socket,++nextConnection,handlers))});return await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(socketPath,()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),await chmod(socketPath,384),{close:()=>closeServer(server,clients)}}function acceptConnection(socket,id,handlers){let connection={id,send:record=>{handlers.respond!==void 0?handlers.respond(connection,record):socket.destroyed||socket.write(serializeJsonLine(record))},transport:socketSink(socket)};handlers.opened?.(connection);let detach=attachJsonlLineReader(socket,line=>{answer(connection,line,handlers)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>connection.send(failure(void 0,"parse","RPC line exceeds the size limit."))});socket.once("close",()=>{detach(),handlers.closed(connection)})}async function answer(connection,line,handlers){let parsed;try{parsed=JSON.parse(line)}catch{connection.send(failure(void 0,"parse","Invalid JSON."));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError!==void 0||!isCommand(parsed)){connection.send(failure(void 0,"parse",shapeError??"RPC command needs a string `type`."));return}let answer2=await handlers.command(connection,parsed);answer2!==null&&connection.send(answer2)}function isCommand(value){return typeof value=="object"&&value!==null&&"type"in value&&typeof value.type=="string"}function failure(id,command,error){return{...id===void 0?{}:{id},type:"response",command,success:!1,error}}function success(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,...data===void 0?{}:{data}}}function closeServer(server,clients){for(let client of clients)client.destroy();return new Promise(resolve2=>server.close(()=>resolve2()))}var SESSION_CONTROL_COMMANDS=["get_available_models","get_available_thinking_levels","set_model","set_thinking_level","interrupt"];async function runSessionControlCommand(session,controls,command){let{id,type}=command;switch(type){case"get_available_models":return success(id,type,await availableModelsData(session));case"get_available_thinking_levels":return success(id,type,{levels:session.getAvailableThinkingLevels()});case"set_model":return await setModel(session,controls,command);case"set_thinking_level":{let level=session.getAvailableThinkingLevels().find(candidate=>candidate===command.level);return level===void 0?failure(id,type,unsupportedThinkingLevel(command.level)):(controls.selectThinkingLevel(level,command.scope!=="turn"),success(id,type))}case"interrupt":return success(id,type,await interruptRunningTurn(session,command.turnId,()=>controls.interruptTurn()));default:return}}async function setModel(session,controls,command){let{id,type}=command,model=(await session.modelRegistry.getAvailable()).find(candidate=>candidate.provider===command.provider&&candidate.id===command.modelId);if(model===void 0)return failure(id,type,`Model not found: ${String(command.provider)}/${String(command.modelId)}`);try{let change=await controls.selectModel(model);return success(id,type,{...model,systemPromptName:change?.systemPromptName})}catch(error){return failure(id,type,error instanceof Error?error.message:String(error))}}var TUI_CONTROL_CAPABILITY="tui_control",TUI_CONTROL_COMMANDS=["get_protocol_info","list_sessions","get_state","get_messages","set_session_name","subscribe","wake","extension_ui_response",...SESSION_CONTROL_COMMANDS,...TUI_RPC_COMMANDS];async function runControlCommand(context,connection,command){let{id,type}=command,{session}=context;switch(type){case"get_protocol_info":{let build=engineBuildIdentity();return success(id,type,{protocolVersion:1,serverVersion:VERSION,capabilities:[TUI_CONTROL_CAPABILITY,SESSION_STATUS_CAPABILITY],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS})}case"list_sessions":return success(id,type,{sessions:[sessionRow(session)]});case"get_state":return success(id,type,{...buildRpcSessionState(session),turn_epoch:session.externalAdmission.turnEpoch,blocking_question:context.surface.blockingQuestion(),compacting:session.isCompacting,editor_has_draft:context.surface.draftHold()!==void 0,state_version:context.feed.stateVersion});case"get_messages":return success(id,type,{messages:session.messages});case"set_session_name":{let name=typeof command.name=="string"?command.name.trim():"";return name===""?failure(id,type,"Session name cannot be empty"):(session.setSessionName(name),success(id,type))}case"subscribe":{let cursor=typeof command.cursor=="number"?command.cursor:void 0;return success(id,type,{cursor:context.feed.subscribe(connection.id,cursor,connection.send)})}case"wake":{let ids=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry=>typeof entry=="string"):void 0,result=await context.wake(ids);return success(id,type,{admitted:result.admitted??[]})}case"extension_ui_response":return answerQuestion(context.surface,command);default:{let rpc=await runTuiRpcCommand(context,connection,command);return rpc!==void 0?rpc:await runSessionControlCommand(session,context.surface,command)??failure(id,type,"unsupported")}}}function sessionRow(session){let manager=session.sessionManager,created=manager.getHeader()?.timestamp??null,last=manager.getEntries().at(-1);return{sessionId:session.sessionId,sessionPath:session.sessionFile??null,session_file:session.sessionFile??null,kind:"interactive",surface:"tui",cwd:manager.getCwd(),name:session.sessionName??null,created_at:created,updated_at:last?.timestamp??created,attachments:1}}function answerQuestion(surface,command){let frameId=command.id,requestId=answeredUiRequestId(command),request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return failure(frameId,"extension_ui_response","unknown_request");let response=questionResponse(command,request.questions);return response==="question_incomplete"?failure(frameId,"extension_ui_response",response):response===void 0||!surface.answerQuestion(requestId,response)?failure(frameId,"extension_ui_response","invalid_response"):success(frameId,"extension_ui_response")}function questionResponse(command,questions){if(command.cancelled===!0)return{status:"cancelled",cancelOrigin:"user",answers:{},unanswered:[]};let answers=command.answers;if(typeof answers!="object"||answers===null||Array.isArray(answers))return;let parsed={};for(let[question,value]of Object.entries(answers)){if(typeof value!="object"||value===null||!("selected"in value)||!Array.isArray(value.selected))return;let selected=value.selected.filter(entry=>typeof entry=="string"),text="text"in value&&typeof value.text=="string"?value.text:void 0;parsed[question]=text===void 0?{selected}:{selected,text}}let comment=typeof command.comment=="string"?command.comment:void 0,status=settledQuestionStatus(parsed,comment);if(status===void 0)return"question_incomplete";let unanswered=unansweredQuestionIds(questions,parsed);return{status,resolvedBy:"control_endpoint",answers:parsed,unanswered,...comment===void 0?{}:{comment}}}var ControlFeed=class{constructor(){this.seq=0,this.stateVersionValue=0,this.ring=[],this.subscribers=new Map}get stateVersion(){return this.stateVersionValue}publish(kind,data={}){kind==="state"&&(this.stateVersionValue+=1);let event={type:"session_control_event",seq:++this.seq,kind,data:kind==="state"?{...data,state_version:this.stateVersionValue}:data};this.ring.push(event),this.ring.length>256&&this.ring.shift();for(let send of this.subscribers.values())send(event)}subscribe(connection,cursor,send){if(this.subscribers.set(connection,send),cursor!==void 0)for(let event of this.ring)event.seq>cursor&&send(event);return this.seq}unsubscribe(connection){this.subscribers.delete(connection)}clear(){this.subscribers.clear()}};import{createHash}from"node:crypto";import{rmSync}from"node:fs";import{chmod as chmod2,lstat,mkdir,realpath,rm}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join}from"node:path";var PRIVATE_DIRECTORY_MODE=448,REGISTRY_LOCK_WAIT_MS=5e3;async function resolveTuiSocket(agentDir,instanceId){let name=tuiSocketName(instanceId),primary=join(agentDir,"rpc","tui",name);if(Buffer.byteLength(primary)<=MAX_SOCKET_PATH_BYTES)return await makePrivateDirectory(dirname(primary)),primary;let fallbackName=`senpi-rpc-${createHash("sha256").update(agentDir).digest("hex").slice(0,8)}`,scopedRoot=join(tmpdir(),fallbackName),root=Buffer.byteLength(join(scopedRoot,"tui",name))<=MAX_SOCKET_PATH_BYTES?scopedRoot:join("/tmp",fallbackName),tuiRoot=join(root,"tui");await makePrivateDirectory(tuiRoot);for(let directory of[root,tuiRoot])await assertPrivateDirectory(directory);let fallback=join(tuiRoot,name);if(Buffer.byteLength(fallback)>MAX_SOCKET_PATH_BYTES)throw new Error(`socket path ${fallback} exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);return fallback}async function makePrivateDirectory(directory){await mkdir(directory,{recursive:!0,mode:PRIVATE_DIRECTORY_MODE}),await chmod2(directory,PRIVATE_DIRECTORY_MODE)}async function assertPrivateDirectory(directory){let stat=await lstat(await realpath(directory)),ownedByUs=process.getuid===void 0||stat.uid===process.getuid();if(!stat.isDirectory()||!ownedByUs||(stat.mode&63)!==0)throw new Error(`alt_root_unsafe: ${directory} is not a private directory of this user`)}async function registerTuiEndpoint(options){let paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir}),release=await acquireHostEnsureLock(options.socket,REGISTRY_LOCK_WAIT_MS);try{await writeHostRegistration(paths,{record:{pid:process.pid,processStartTime:await thisProcessStartTime()},socket:options.socket,instanceId:options.instanceId,generation:0,launchProfileId:"tui",build:engineBuildIdentity()},{fresh:!0}),await createDaemonDirectories(paths,{kind:"tui"})}finally{await release()}return{paths,socket:options.socket}}async function unregisterTuiEndpoint(entry){let release=await acquireHostEnsureLock(entry.socket,REGISTRY_LOCK_WAIT_MS).catch(()=>{});try{await rm(entry.socket,{force:!0}),await rm(socketSecretPath(entry.socket),{force:!0}),await rm(entry.paths.dir,{recursive:!0,force:!0})}finally{await release?.()}}function unregisterTuiEndpointSync(entry){rmSync(entry.socket,{force:!0}),rmSync(socketSecretPath(entry.socket),{force:!0}),rmSync(entry.paths.dir,{recursive:!0,force:!0})}var REPORT_TEXT_LIMIT=4e3;function activateControlEndpoint(parts){let{context,feed,wake}=parts,{session,surface}=context;session.externalAdmission.setEditorSource(()=>editorHold(context));let unsubscribeSession=session.subscribe(event=>{event.type==="agent_start"?feed.publish("state"):event.type==="agent_idle"?(feed.publish("completion",{turn_epoch:session.externalAdmission.turnEpoch}),feed.publish("state"),wake("idle")):event.type==="agent_end"||event.type==="queue_update"||event.type==="compaction_start"||event.type==="compaction_end"?feed.publish("state"):event.type==="message_end"&&event.message.role==="assistant"&&feed.publish("report",{text:assistantText(event.message).slice(0,REPORT_TEXT_LIMIT)})}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>{wake("emitted")}),unsubscribeInputs=session.externalAdmission.onInputsSettled(()=>queueMicrotask(()=>{wake("submission")})),stopContinue=onProcessContinue(()=>{wake("continue")}),exitCleanup=()=>unregisterTuiEndpointSync(parts.entry);process.once("exit",exitCleanup);let disposing,dispose=()=>(disposing??=(async()=>{process.removeListener("exit",exitCleanup),unsubscribeSession(),unsubscribeEmitted(),unsubscribeInputs(),stopContinue(),parts.stopInbox(),parts.scheduler.dispose(),feed.clear(),session.externalAdmission.setEditorSource(void 0),await parts.server.close(),await sessionReferenced(parts.options,surface)||await session.sessionManager.discardHeaderOnlyFile(),await unregisterTuiEndpoint(parts.entry)})(),disposing);return{socket:parts.entry.socket,wake:reason=>{wake(reason)},noteState:()=>feed.publish("state"),noteQuestions:()=>feed.publish("question",{pending:[...surface.pendingQuestionIds()]}),dispose}}function editorHold(context){let hold=context.surface.draftHold(),revision=context.editorRevision();return hold===void 0?{revision}:{hold_reason:hold,revision}}async function sessionReferenced(options,surface){if(options.isSessionReferenced===void 0)return!1;try{return await options.isSessionReferenced()}catch(error){return surface.notice(`control endpoint kept the session file: ${error instanceof Error?error.message:String(error)}`),!0}}function assistantText(message){return message.role!=="assistant"?"":message.content.flatMap(part=>part.type==="text"?[part.text]:[]).join(`
3
+ `)}async function registerSessionControlEndpoint(context,options){let cleanups=[];try{let endpoint=await openEndpoint(context,options,cleanups);return{registration:{status:"registered",socket:endpoint.socket,dispose:endpoint.dispose},endpoint}}catch(error){for(let cleanup of cleanups.reverse())await Promise.resolve(cleanup()).catch(()=>{});let reason=errorText(error);return context.surface.notice(`control endpoint unavailable: ${reason}`),{registration:{status:"failed",reason}}}}async function openEndpoint(context,options,cleanups){let{session,agentDir,surface}=context;thisProcessStartTime();let headerDurable=session.sessionManager.persistHeaderNow();headerDurable.catch(()=>{});let instanceId=randomUUID2(),socket=await resolveTuiSocket(agentDir,instanceId);cleanups.push(()=>rm2(socket,{force:!0}),()=>rm2(socketSecretPath(socket),{force:!0}));let secret=await createSocketSecret(socketSecretPath(socket)),feed=new ControlFeed,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result=await options.drain(event)??{admitted:[]};return failing=void 0,result},error=>{let reason=errorText(error);reason!==failing&&(failing=reason,surface.notice(`control endpoint drain failed: ${reason}`))});cleanups.push(()=>scheduler.dispose());let wake=(reason,ids)=>scheduler.request(reason,ids),attachments=new ControlAttachments(session,()=>surface.pendingQuestionIds().length);cleanups.push(()=>attachments.dispose());let commandContext={instanceId,session,surface,feed,wake:ids=>wake("command",ids),attachments},server=await listenControlSocket(socket,secret,{command:(connection,command)=>runControlCommand(commandContext,connection,command),opened:connection=>attachments.opened(connection),respond:(connection,answer2)=>attachments.respond(connection,answer2),closed:connection=>{feed.unsubscribe(connection.id),attachments.closed(connection)},listenerError:error=>surface.notice(`control endpoint listener failed: ${error.message}`)});cleanups.push(()=>server.close()),await headerDurable;let entry=await registerTuiEndpoint({agentDir,socket,instanceId});cleanups.push(()=>unregisterTuiEndpoint(entry));let inbox=await watchInbox(options.inboxDir,()=>{wake("inbox")},error=>surface.notice(`control endpoint inbox watch failed: ${errorText(error)}`));cleanups.push(()=>inbox.stop());let endpoint=activateControlEndpoint({context,options,entry,server,scheduler,feed,stopInbox:inbox.stop,wake});return endpoint.wake("inbox"),inbox.armed.then(()=>endpoint.wake("inbox")),setImmediate(()=>{gcHostEndpoints(agentDir,{kinds:["tui"]}).catch(error=>surface.notice(`control endpoint gc of dead terminals failed: ${errorText(error)}`))}),endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};
@@ -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{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-LR6Z6V54.js";import{KeybindingsManager}from"./chunk-HCF5M6NA.js";import"./chunk-AGQSRWNN.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-QMRJYMNH.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-PELNNWGO.js";import{setKeybindings}from"./chunk-YJA2B7FQ.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-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-YU2P3CAR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};
2
+ import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-NQC7MI2G.js";import{KeybindingsManager}from"./chunk-GXY5JEI5.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-QMRJYMNH.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-PELNNWGO.js";import{setKeybindings}from"./chunk-FDL4CF6F.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-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-YU2P3CAR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};