@code-yeongyu/senpi 2026.11.13 → 2026.11.15

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 (95) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundle/chunks/{args-H56W53X6.js → args-JWBI5LNO.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-MNN2TINI.js → azure-openai-responses-PEMLRPJ5.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-HZQHA4PA.js → chunk-3RILB2OD.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-Y4PFEXFN.js → chunk-5IXYN6DK.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-BKDXY6EM.js → chunk-5NECOJNK.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-NI2AOYP6.js → chunk-6MRUNB3Z.js} +1 -1
  8. package/dist/bundle/chunks/chunk-6QQL3SKM.js +2 -0
  9. package/dist/bundle/chunks/{chunk-I4N2OIY4.js → chunk-6QXAYNO7.js} +17 -17
  10. package/dist/bundle/chunks/{chunk-7T2LAWZ4.js → chunk-73HGQTJN.js} +1 -1
  11. package/dist/bundle/chunks/chunk-75O3CWR5.js +2 -0
  12. package/dist/bundle/chunks/{chunk-AZ27TE3H.js → chunk-7BX3JQ7F.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-NDI6N4NJ.js → chunk-7CXLNKEH.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-E6ZBTSC6.js → chunk-A3LGSX7Z.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-7GD2EO6T.js → chunk-FYVQEZYN.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-U4FAWC6C.js → chunk-GXPH7RN6.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-SFACYIB6.js → chunk-IK3S2NDB.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-V4VDIV3U.js → chunk-PWA75RQU.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-IREUIMFE.js → chunk-PWTXZXHH.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-KKB3K5CV.js → chunk-Q4RJ4WLE.js} +1 -1
  21. package/dist/bundle/chunks/chunk-QVG5SUSV.js +2 -0
  22. package/dist/bundle/chunks/chunk-RLIY3AUC.js +2 -0
  23. package/dist/bundle/chunks/{chunk-EQT4WNCW.js → chunk-TACOXP5H.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-NXGSYUMV.js → chunk-TB6LIKVR.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-JLCZIEBC.js → chunk-THYIV26N.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-6FE42M54.js → chunk-VGHGM5PR.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CU6HUYL7.js → chunk-WAGFTIT4.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-UYPH6RHY.js → chunk-Z4PN2MDA.js} +2 -2
  29. package/dist/bundle/chunks/{chunk-JJYN347Z.js → chunk-ZJUL5ODW.js} +1 -1
  30. package/dist/bundle/chunks/{cli-main-MY53RXU3.js → cli-main-MM2XCVYE.js} +1 -1
  31. package/dist/bundle/chunks/credential-accounts-RXZIUKFM.js +2 -0
  32. package/dist/bundle/chunks/github-copilot.js +1 -1
  33. package/dist/bundle/chunks/{hand-entry-AXTVMVJK.js → hand-entry-MBOPYO6I.js} +1 -1
  34. package/dist/bundle/chunks/{headless-host-SU5O2KZ2.js → headless-host-OEK6W65T.js} +1 -1
  35. package/dist/bundle/chunks/{health-write-TN7EXGLI.js → health-write-44JERGEJ.js} +1 -1
  36. package/dist/bundle/chunks/{help-fast-path-TFQ4HJNO.js → help-fast-path-JWHUCE4E.js} +1 -1
  37. package/dist/bundle/chunks/{host-command-FG56Y53E.js → host-command-O2K2WIPO.js} +1 -1
  38. package/dist/bundle/chunks/{host-session-command-UFEOW7EP.js → host-session-command-EWA6N4JJ.js} +1 -1
  39. package/dist/bundle/chunks/interactive-mode-VSZYRVYY.js +2 -0
  40. package/dist/bundle/chunks/{login-health-XBTIORM4.js → login-health-V4B6LSCP.js} +1 -1
  41. package/dist/bundle/chunks/main-VEWKRBTD.js +2 -0
  42. package/dist/bundle/chunks/{multi-session-host-Q6SHI22A.js → multi-session-host-HC6NR5N2.js} +1 -1
  43. package/dist/bundle/chunks/{openai-codex-responses-VRGOAFEG.js → openai-codex-responses-IFPWK7NG.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-2BTL5MA2.js +5 -0
  45. package/dist/bundle/chunks/{package-manager-cli-LILAWI3Q.js → package-manager-cli-OZ6DK6GI.js} +3 -3
  46. package/dist/bundle/chunks/{role-KODRTWH5.js → role-BTH5PVME.js} +1 -1
  47. package/dist/bundle/chunks/{rotation-stream-2KNROTYB.js → rotation-stream-ZGPXLY62.js} +1 -1
  48. package/dist/bundle/chunks/rpc-mode-WPF3NVBL.js +2 -0
  49. package/dist/bundle/chunks/{run-attached-tui-OEFHV5CZ.js → run-attached-tui-RVVYEINN.js} +1 -1
  50. package/dist/bundle/chunks/{schedule-command-VO4RP2KX.js → schedule-command-6TAAG2KU.js} +1 -1
  51. package/dist/bundle/chunks/{session-control-endpoint-CCVRJHSC.js → session-control-endpoint-3FNVOKKT.js} +1 -1
  52. package/dist/bundle/chunks/{session-picker-VN5I2ZDI.js → session-picker-YDXDCBRL.js} +1 -1
  53. package/dist/bundle/chunks/session-slot-N4E4OSCX.js +2 -0
  54. package/dist/bundle/chunks/session-worker.js +22 -21
  55. package/dist/bundle/chunks/{state-store-7RVODZJU.js → state-store-I6MUHET3.js} +1 -1
  56. package/dist/bundle/cli.js +2 -2
  57. package/dist/bundle/index.js +1 -1
  58. package/dist/bundle/rpc-entry.js +1 -1
  59. package/dist/bundle/runtime-manifest.json +1 -1
  60. package/dist/core/agent-session.d.ts +5 -3
  61. package/dist/core/agent-session.js +16 -6
  62. package/dist/core/credential-accounts.d.ts +5 -3
  63. package/dist/core/credential-accounts.js +8 -6
  64. package/dist/core/credential-pool/classify.js +5 -1
  65. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.d.ts +6 -0
  66. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.js +14 -0
  67. package/dist/core/extensions/builtin/anthropic-subscription/prompt-bridge.js +3 -1
  68. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +4 -1
  69. package/dist/core/extensions/builtin/permission-system/index.js +5 -1
  70. package/dist/core/reasoning-baseline.d.ts +8 -1
  71. package/dist/core/reasoning-baseline.js +24 -0
  72. package/dist/modes/rpc/connection-handler.js +4 -0
  73. package/dist/modes/rpc/method-classes-schema-session.d.ts +3 -0
  74. package/dist/modes/rpc/method-classes-schema-session.js +6 -2
  75. package/dist/modes/rpc/method-classes-schema.d.ts +3 -0
  76. package/dist/modes/rpc/project-expected-cwd.d.ts +29 -0
  77. package/dist/modes/rpc/project-expected-cwd.js +45 -0
  78. package/dist/modes/rpc/rpc-error-types.d.ts +7 -1
  79. package/dist/modes/rpc/rpc-error-types.js +6 -0
  80. package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
  81. package/dist/package-manager-cli.d.ts +14 -0
  82. package/dist/package-manager-cli.js +20 -4
  83. package/dist/utils/version-check.d.ts +10 -7
  84. package/dist/utils/version-check.js +24 -5
  85. package/docs/rpc.md +20 -7
  86. package/package.json +7 -7
  87. package/dist/bundle/chunks/chunk-GLTOBXZY.js +0 -2
  88. package/dist/bundle/chunks/chunk-PBUV2Z3R.js +0 -2
  89. package/dist/bundle/chunks/chunk-WRBOKYPS.js +0 -2
  90. package/dist/bundle/chunks/credential-accounts-ZB5IXHIG.js +0 -2
  91. package/dist/bundle/chunks/interactive-mode-PHES47E3.js +0 -2
  92. package/dist/bundle/chunks/main-PR4FI6HQ.js +0 -2
  93. package/dist/bundle/chunks/openai-responses-I7PXRWCM.js +0 -4
  94. package/dist/bundle/chunks/rpc-mode-CGVK4SSA.js +0 -2
  95. package/dist/bundle/chunks/session-slot-GHJVOSG7.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-I4N2OIY4.js";import"./chunk-Y4PFEXFN.js";import"./chunk-KKB3K5CV.js";import"./chunk-NI2AOYP6.js";import"./chunk-WRBOKYPS.js";import"./chunk-CU6HUYL7.js";import"./chunk-NLYT7BND.js";import{DefaultPackageManager,SettingsManager}from"./chunk-EQT4WNCW.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-7GD2EO6T.js";import"./chunk-WMDJMN5W.js";import"./chunk-GTJJ73DE.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-V4VDIV3U.js";import"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import{DynamicBorder,initTheme,keyHint,rawKeyHint,stopThemeWatcher,theme}from"./chunk-BKDXY6EM.js";import"./chunk-HKCFMDJN.js";import"./chunk-E6ZBTSC6.js";import"./chunk-3QPE75AR.js";import"./chunk-ULWRGKP2.js";import"./chunk-4B5JSLLR.js";import"./chunk-FWIO636S.js";import"./chunk-MOVB6H22.js";import"./chunk-DLPV4B3R.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-UYPH6RHY.js";import"./chunk-AZ27TE3H.js";import"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import"./chunk-C4AHHZ6P.js";import"./chunk-CEFKVI3E.js";import{lockWithLossHandling}from"./chunk-HGCQAMC6.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import{appendHiddenTuiStdout}from"./chunk-EUCZC2RF.js";import"./chunk-WHQ2QPP5.js";import"./chunk-PBUV2Z3R.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-2IKL4F24.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-HZQHA4PA.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{killProcessTree}from"./chunk-JJYN347Z.js";import"./chunk-NDI6N4NJ.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-GLTOBXZY.js";import"./chunk-U4FAWC6C.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-2SOVDETB.js";import{runtimeExecArgv}from"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.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-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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-6QXAYNO7.js";import"./chunk-5IXYN6DK.js";import"./chunk-Q4RJ4WLE.js";import"./chunk-6MRUNB3Z.js";import"./chunk-75O3CWR5.js";import"./chunk-WAGFTIT4.js";import"./chunk-NLYT7BND.js";import{DefaultPackageManager,SettingsManager}from"./chunk-TACOXP5H.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-FYVQEZYN.js";import"./chunk-WMDJMN5W.js";import"./chunk-GTJJ73DE.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-PWA75RQU.js";import"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import{DynamicBorder,initTheme,keyHint,rawKeyHint,stopThemeWatcher,theme}from"./chunk-5NECOJNK.js";import"./chunk-HKCFMDJN.js";import"./chunk-A3LGSX7Z.js";import"./chunk-3QPE75AR.js";import"./chunk-ULWRGKP2.js";import"./chunk-4B5JSLLR.js";import"./chunk-FWIO636S.js";import"./chunk-MOVB6H22.js";import"./chunk-DLPV4B3R.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-Z4PN2MDA.js";import"./chunk-7BX3JQ7F.js";import"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import"./chunk-C4AHHZ6P.js";import"./chunk-CEFKVI3E.js";import{lockWithLossHandling}from"./chunk-HGCQAMC6.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import{appendHiddenTuiStdout}from"./chunk-EUCZC2RF.js";import"./chunk-WHQ2QPP5.js";import"./chunk-RLIY3AUC.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-2IKL4F24.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-3RILB2OD.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{killProcessTree}from"./chunk-ZJUL5ODW.js";import"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-QVG5SUSV.js";import"./chunk-GXPH7RN6.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-2SOVDETB.js";import{runtimeExecArgv}from"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.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-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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],windowsHide:!0});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(`
@@ -89,5 +89,5 @@ Options:
89
89
  -a, --approve Trust project-local files for this command
90
90
  -na, --no-approve Ignore project-local files for this command
91
91
  `);return}}function parsePackageCommand(args){let[rawCommand,...rest]=args,command;if(rawCommand==="uninstall"?command="remove":(rawCommand==="install"||rawCommand==="remove"||rawCommand==="update"||rawCommand==="list")&&(command=rawCommand),!command)return;let local=!1,force=!1,omoLocalUpdateWorker=!1,projectTrustOverride,help=!1,invalidOption,invalidArgument,missingOptionValue,conflictingOptions,source,selfFlag=!1,extensionsFlag=!1,modelsFlag=!1,allFlag=!1,extensionFlagSource;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help"){help=!0;continue}if(arg==="-l"||arg==="--local"){command==="install"||command==="remove"?local=!0:invalidOption=invalidOption??arg;continue}if(arg==="--self"){command==="update"?selfFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--extensions"){command==="update"?extensionsFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--models"){command==="update"?modelsFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--all"){command==="update"?allFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--approve"||arg==="-a"){projectTrustOverride=!0;continue}if(arg==="--no-approve"||arg==="-na"){projectTrustOverride=!1;continue}if(arg==="--force"){command==="update"?force=!0:invalidOption=invalidOption??arg;continue}if(arg==="--omo-local-update-worker"){command==="update"?omoLocalUpdateWorker=!0:invalidOption=invalidOption??arg;continue}if(arg==="--extension"){if(command!=="update"){invalidOption=invalidOption??arg;continue}let value=rest[index+1];!value||value.startsWith("-")?missingOptionValue=missingOptionValue??arg:extensionFlagSource?(conflictingOptions=conflictingOptions??"--extension can only be provided once",index++):(extensionFlagSource=value,index++);continue}if(arg.startsWith("-")){invalidOption=invalidOption??arg;continue}source?invalidArgument=invalidArgument??arg:source=arg}let updateTarget,showExtensionsSkippedNote=!1;return command==="update"&&(allFlag&&(selfFlag||extensionsFlag||modelsFlag||extensionFlagSource)&&(conflictingOptions=conflictingOptions??"--all cannot be combined with --self, --extensions, --models, or --extension"),allFlag&&source&&(conflictingOptions=conflictingOptions??"--all cannot be combined with a positional source"),modelsFlag?((selfFlag||extensionsFlag||allFlag||extensionFlagSource)&&(conflictingOptions=conflictingOptions??"--models cannot be combined with --self, --extensions, --all, or --extension"),source&&(conflictingOptions=conflictingOptions??"--models cannot be combined with a positional source"),updateTarget={type:"models"}):extensionFlagSource?((selfFlag||extensionsFlag||allFlag)&&(conflictingOptions=conflictingOptions??"--extension cannot be combined with --self, --extensions, or --all"),source&&(conflictingOptions=conflictingOptions??"--extension cannot be combined with a positional source"),updateTarget={type:"extensions",source:extensionFlagSource}):source?source==="self"||source==="pi"||source===APP_NAME?updateTarget=extensionsFlag?{type:"all"}:{type:"self"}:((extensionsFlag||selfFlag||allFlag)&&(conflictingOptions=conflictingOptions??"positional update targets cannot be combined with --self, --extensions, or --all"),updateTarget={type:"extensions",source}):allFlag?updateTarget={type:"all"}:selfFlag&&extensionsFlag?updateTarget={type:"all"}:selfFlag?updateTarget={type:"self"}:extensionsFlag?updateTarget={type:"extensions"}:(updateTarget={type:"self"},showExtensionsSkippedNote=!0)),{command,source,updateTarget,showExtensionsSkippedNote,omoLocalUpdateWorker,local,force,projectTrustOverride,help,invalidOption,invalidArgument,missingOptionValue,conflictingOptions}}function updateTargetIncludesSelf(target){return target.type==="all"||target.type==="self"}function updateTargetIncludesExtensions(target){return target.type==="all"||target.type==="extensions"}async function refreshModelCatalogs(agentDir){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);try{let result=await(await ModelRuntime.create({authPath:join5(agentDir,"auth.json"),modelsPath:join5(agentDir,"models.json"),allowModelNetwork:!1,signal:controller.signal})).refresh({allowNetwork:!0,force:!0,signal:controller.signal});if(result.aborted)throw new Error("Model catalog refresh timed out.");if(result.errors.size>0){let details=Array.from(result.errors,([provider,error])=>`${provider}: ${error.message}`).join("; ");throw new Error(`Could not refresh model catalogs: ${details}`)}}finally{clearTimeout(timeout)}console.log(source_default.green("Model catalogs refreshed"))}function printSelfUpdateUnavailable(npmCommand,updatePackageTarget=PACKAGE_NAME){console.error(`error: ${APP_NAME} cannot self-update this installation.`),console.error(getSelfUpdateUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageTarget));let entrypoint=process.argv[1];entrypoint&&(console.error(""),console.error(`Location of ${APP_NAME} executable: ${entrypoint}`))}function printSelfUpdateFallback(command){console.error(source_default.dim(`If this keeps failing, run this command yourself: ${command.display}`))}function printPnpmSelfUpdateMetadataHint(){console.error(source_default.yellow("If pnpm reports missing package versions, its cached registry metadata may be stale.")),console.error(source_default.yellow(`Run \`pnpm store prune\` and retry \`${APP_NAME} update --self\`.`))}function printSelfUpdateNote(note){let trimmedNote=note.trim();if(trimmedNote){console.log(),console.log(source_default.bold(source_default.yellow("Update note")));try{let width=Math.max(20,process.stdout.columns??80),renderedLines=new Markdown(trimmedNote,0,0,SELF_UPDATE_NOTE_MARKDOWN_THEME).render(width).map(line=>line.trimEnd());console.log(renderedLines.join(`
92
- `))}catch{console.log(trimmedNote)}console.log()}}async function getSelfUpdatePlan(force){let brandUpdate=brandProfile()?.update;if(brandUpdate)return console.log(source_default.yellow(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with:`)),console.log(source_default.cyan(` ${brandUpdate.command}`)),{packageName:brandUpdate.packageName,installSpec:brandUpdate.command,version:DISPLAY_VERSION,shouldRun:!1};let latestRelease;try{latestRelease=await getLatestPiRelease(VERSION,{retry:!0})}catch(error){throw new Error(`Could not determine latest ${APP_NAME} version: ${formatVersionCheckError(error)}`,{cause:error})}if(!latestRelease)throw new Error(`Could not determine latest ${APP_NAME} version.`);let packageName=latestRelease.packageName??PACKAGE_NAME,installSpec=`${packageName}@${latestRelease.version}`;return force||packageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)?{packageName,installSpec,version:latestRelease.version,...latestRelease.note?{note:latestRelease.note}:{},shouldRun:!0}:(console.log(source_default.green(`${APP_NAME} is already up to date (v${VERSION})`)),{packageName,installSpec,version:latestRelease.version,shouldRun:!1})}async function runSelfUpdate(command){console.log(source_default.dim(`Updating ${APP_NAME} with ${command.display}...`));for(let step of command.steps??[command])await new Promise((resolve4,reject)=>{let child=spawnProcess(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve4():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}function prepareWindowsNpmSelfUpdate(){if(process.platform!=="win32")return;let packageDir=getInstallPackageDir();cleanupWindowsSelfUpdateQuarantine(packageDir),quarantineWindowsNativeDependencies(packageDir)}function getCommandAppMode(){return process.stdin.isTTY&&process.stdout.isTTY?"interactive":"print"}function reportProjectTrustWarnings(warnings){for(let warning of warnings)console.error(source_default.yellow(`Warning: ${warning}`))}async function createCommandSettingsManager(options){let settingsManager=SettingsManager.create(options.cwd,options.agentDir,{projectTrusted:!1}),projectTrustWarnings=[],trustStore=new ProjectTrustStore(options.agentDir);if(options.useSavedProjectTrustOnly){let savedProjectTrusted=trustStore.get(options.cwd)===!0;return settingsManager.setProjectTrusted(options.projectTrustOverride??savedProjectTrusted),{settingsManager,projectTrustWarnings}}let appMode=getCommandAppMode(),extensionsResult=options.projectTrustOverride===void 0&&hasTrustRequiringProjectResources(options.cwd)?await new DefaultResourceLoader({cwd:options.cwd,agentDir:options.agentDir,settingsManager,extensionFactories:options.extensionFactories}).loadProjectTrustExtensions():void 0;for(let error of extensionsResult?.errors??[])projectTrustWarnings.push(`Failed to load extension "${error.path}": ${error.error}`);let projectTrusted=await resolveProjectTrusted({cwd:options.cwd,trustStore,trustOverride:options.projectTrustOverride,defaultProjectTrust:settingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd:options.cwd,mode:appMode,settingsManager,hasUI:appMode==="interactive"}),onExtensionError:message=>projectTrustWarnings.push(message)});return settingsManager.setProjectTrusted(projectTrusted),{settingsManager,projectTrustWarnings}}async function handleConfigCommand(args,runtimeOptions={}){let[command,...rest]=args;if(command!=="config")return!1;if(rest.includes("-h")||rest.includes("--help"))return printConfigCommandHelp(),!0;if(rest[0]===CONFIG_IMPORT_PI_ARGV)return runConfigImportPi(rest.slice(1)),!0;let local=!1,projectTrustOverride;for(let arg of rest)if(arg==="-l"||arg==="--local")local=!0;else if(arg==="-a"||arg==="--approve")projectTrustOverride=!0;else if(arg==="-na"||arg==="--no-approve")projectTrustOverride=!1;else return arg.startsWith("-")?(console.error(source_default.red(`Unknown option ${arg} for "config".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${CONFIG_COMMAND_USAGE}".`)),process.exitCode=1,!0):(console.error(source_default.red(`Unexpected argument ${arg}.`)),console.error(source_default.dim(`Usage: ${CONFIG_COMMAND_USAGE}`)),process.exitCode=1,!0);let cwd=process.cwd(),agentDir=getAgentDir(),{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride,extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),local&&!settingsManager.isProjectTrusted())return console.error(source_default.red("Project is not trusted. Use --approve to modify local resource config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"config command");let builtinExtensions=(runtimeOptions.extensionFactories??[]).filter(isBuiltinExtension).map(input=>input.name),globalSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1}),globalResolvedPaths=await new DefaultPackageManager({cwd,agentDir,settingsManager:globalSettingsManager,builtinExtensions}).resolve(),projectResolvedPaths=settingsManager.isProjectTrusted()?await new DefaultPackageManager({cwd,agentDir,settingsManager,builtinExtensions}).resolve():globalResolvedPaths;await selectConfig({resolvedPaths:{global:globalResolvedPaths,project:projectResolvedPaths},settingsManager,cwd,agentDir,writeScope:local?"project":"global",projectModeAvailable:settingsManager.isProjectTrusted()}),process.exit(0)}async function handlePackageCommand(args,runtimeOptions={}){let options=parsePackageCommand(args);if(!options)return!1;if(options.help)return printPackageCommandHelp(options.command),!0;if(options.invalidOption)return console.error(source_default.red(`Unknown option ${options.invalidOption} for "${options.command}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getPackageCommandUsage(options.command)}".`)),process.exitCode=1,!0;if(options.missingOptionValue)return console.error(source_default.red(`Missing value for ${options.missingOptionValue}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.invalidArgument)return console.error(source_default.red(`Unexpected argument ${options.invalidArgument}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.conflictingOptions)return console.error(source_default.red(options.conflictingOptions)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;let source=options.source;if((options.command==="install"||options.command==="remove")&&!source)return console.error(source_default.red(`Missing ${options.command} source.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.command==="update"&&options.updateTarget?.type==="models"){try{await refreshModelCatalogs(getAgentDir())}catch(error){let message=error instanceof Error?error.message:"Unknown model catalog refresh error";console.error(source_default.red(`Error: ${message}`)),process.exitCode=1}return!0}let cwd=process.cwd(),agentDir=getAgentDir(),writesProjectPackageConfig=(options.command==="install"||options.command==="remove")&&options.local,{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride:options.projectTrustOverride,useSavedProjectTrustOnly:options.command==="update",extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),!settingsManager.isProjectTrusted()&&writesProjectPackageConfig)return console.error(source_default.red("Project is not trusted. Use --approve to modify local package config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"package command");let selfUpdateNpmCommand=settingsManager.getGlobalSettings().npmCommand,packageManager=new DefaultPackageManager({cwd,agentDir,settingsManager});packageManager.setProgressCallback(event=>{event.type==="start"&&process.stdout.write(source_default.dim(`${event.message}
93
- `))});try{switch(options.command){case"install":return await packageManager.installAndPersist(source,{local:options.local}),console.log(source_default.green(`Installed ${source}`)),!0;case"remove":return await packageManager.removeAndPersist(source,{local:options.local})?(console.log(source_default.green(`Removed ${source}`)),!0):(console.error(source_default.red(`No matching package found for ${source}`)),process.exitCode=1,!0);case"list":{let configuredPackages=packageManager.listConfiguredPackages(),userPackages=configuredPackages.filter(pkg=>pkg.scope==="user"),projectPackages=configuredPackages.filter(pkg=>pkg.scope==="project");if(configuredPackages.length===0)return console.log(source_default.dim("No packages installed.")),!0;let formatPackage=pkg=>{let display=pkg.filtered?`${pkg.source} (filtered)`:pkg.source;console.log(` ${display}`),pkg.installedPath&&console.log(source_default.dim(` ${pkg.installedPath}`))};if(userPackages.length>0){console.log(source_default.bold("User packages:"));for(let pkg of userPackages)formatPackage(pkg)}if(projectPackages.length>0){userPackages.length>0&&console.log(),console.log(source_default.bold("Project packages:"));for(let pkg of projectPackages)formatPackage(pkg)}return!0}case"update":{let target=options.updateTarget??{type:"self"};if(options.omoLocalUpdateWorker)return await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"build"}),!0;if(options.showExtensionsSkippedNote&&await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"dispatch"}),options.showExtensionsSkippedNote&&console.log(source_default.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`)),updateTargetIncludesExtensions(target)){let updateSource=target.type==="extensions"?target.source:void 0;await packageManager.update(updateSource),console.log(updateSource?source_default.green(`Updated ${updateSource}`):source_default.green("Updated packages"))}if(updateTargetIncludesSelf(target)){let managedInstallRoot=getActiveManagedInstallRoot();if(managedInstallRoot&&options.force)return console.error(source_default.red(`Managed ${APP_NAME} installations do not support --force; rerun the installer to repair this installation.`)),process.exitCode=1,!0;let selfUpdatePlan=await getSelfUpdatePlan(options.force);if(!selfUpdatePlan.shouldRun)return!0;if(managedInstallRoot){selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{console.log(source_default.dim(`Updating managed ${APP_NAME} installation...`)),await runManagedSelfUpdate(managedInstallRoot,selfUpdatePlan.version)}catch(error){let message=error instanceof Error?error.message:"Unknown managed update error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}return console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)),!0}let installMethod=detectInstallMethod();if(process.platform==="win32"&&installMethod!=="npm"&&installMethod!=="pnpm")return console.error(source_default.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`)),console.error(source_default.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`)),process.exitCode=1,!0;let selfUpdateTarget={packageName:selfUpdatePlan.packageName,installSpec:selfUpdatePlan.installSpec},selfUpdateCommand=getSelfUpdateCommand(PACKAGE_NAME,selfUpdateNpmCommand,selfUpdateTarget);if(!selfUpdateCommand)return printSelfUpdateUnavailable(selfUpdateNpmCommand,selfUpdateTarget),process.exitCode=1,!0;selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{installMethod==="npm"&&prepareWindowsNpmSelfUpdate(),await runSelfUpdate(selfUpdateCommand)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),installMethod==="pnpm"&&printPnpmSelfUpdateMetadataHint(),printSelfUpdateFallback(selfUpdateCommand),process.exitCode=1,!0}console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`))}return!0}}}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}}export{cleanupManagedInstall,handleConfigCommand,handlePackageCommand};
92
+ `))}catch{console.log(trimmedNote)}console.log()}}function selfUpdatePlanAfterLookupFailure(installMethod,reason){if(installMethod!=="bun-binary")throw new Error(`Could not determine latest ${APP_NAME} version${reason?`: ${reason}`:"."}`);return console.log(source_default.yellow(`Could not check the latest ${APP_NAME} release${reason?` (${reason})`:""}.`)),console.log(source_default.cyan("Download from: https://github.com/code-yeongyu/senpi/releases/latest")),{packageName:PACKAGE_NAME,installSpec:PACKAGE_NAME,version:VERSION,shouldRun:!1}}async function getSelfUpdatePlan(force){let brandUpdate=brandProfile()?.update;if(brandUpdate)return console.log(source_default.yellow(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with:`)),console.log(source_default.cyan(` ${brandUpdate.command}`)),{packageName:brandUpdate.packageName,installSpec:brandUpdate.command,version:DISPLAY_VERSION,shouldRun:!1};let latestRelease;try{latestRelease=await getLatestPiRelease(VERSION,{retry:!0})}catch(error){try{return selfUpdatePlanAfterLookupFailure(detectInstallMethod(),formatVersionCheckError(error))}catch(planError){throw planError instanceof Error?Object.assign(planError,{cause:error}):planError}}if(!latestRelease)return selfUpdatePlanAfterLookupFailure(detectInstallMethod(),"");let packageName=latestRelease.packageName??PACKAGE_NAME,installSpec=`${packageName}@${latestRelease.version}`;return force||packageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)?{packageName,installSpec,version:latestRelease.version,...latestRelease.note?{note:latestRelease.note}:{},shouldRun:!0}:(console.log(source_default.green(`${APP_NAME} is already up to date (v${VERSION})`)),{packageName,installSpec,version:latestRelease.version,shouldRun:!1})}async function runSelfUpdate(command){console.log(source_default.dim(`Updating ${APP_NAME} with ${command.display}...`));for(let step of command.steps??[command])await new Promise((resolve4,reject)=>{let child=spawnProcess(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve4():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}function prepareWindowsNpmSelfUpdate(){if(process.platform!=="win32")return;let packageDir=getInstallPackageDir();cleanupWindowsSelfUpdateQuarantine(packageDir),quarantineWindowsNativeDependencies(packageDir)}function getCommandAppMode(){return process.stdin.isTTY&&process.stdout.isTTY?"interactive":"print"}function reportProjectTrustWarnings(warnings){for(let warning of warnings)console.error(source_default.yellow(`Warning: ${warning}`))}async function createCommandSettingsManager(options){let settingsManager=SettingsManager.create(options.cwd,options.agentDir,{projectTrusted:!1}),projectTrustWarnings=[],trustStore=new ProjectTrustStore(options.agentDir);if(options.useSavedProjectTrustOnly){let savedProjectTrusted=trustStore.get(options.cwd)===!0;return settingsManager.setProjectTrusted(options.projectTrustOverride??savedProjectTrusted),{settingsManager,projectTrustWarnings}}let appMode=getCommandAppMode(),extensionsResult=options.projectTrustOverride===void 0&&hasTrustRequiringProjectResources(options.cwd)?await new DefaultResourceLoader({cwd:options.cwd,agentDir:options.agentDir,settingsManager,extensionFactories:options.extensionFactories}).loadProjectTrustExtensions():void 0;for(let error of extensionsResult?.errors??[])projectTrustWarnings.push(`Failed to load extension "${error.path}": ${error.error}`);let projectTrusted=await resolveProjectTrusted({cwd:options.cwd,trustStore,trustOverride:options.projectTrustOverride,defaultProjectTrust:settingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd:options.cwd,mode:appMode,settingsManager,hasUI:appMode==="interactive"}),onExtensionError:message=>projectTrustWarnings.push(message)});return settingsManager.setProjectTrusted(projectTrusted),{settingsManager,projectTrustWarnings}}async function handleConfigCommand(args,runtimeOptions={}){let[command,...rest]=args;if(command!=="config")return!1;if(rest.includes("-h")||rest.includes("--help"))return printConfigCommandHelp(),!0;if(rest[0]===CONFIG_IMPORT_PI_ARGV)return runConfigImportPi(rest.slice(1)),!0;let local=!1,projectTrustOverride;for(let arg of rest)if(arg==="-l"||arg==="--local")local=!0;else if(arg==="-a"||arg==="--approve")projectTrustOverride=!0;else if(arg==="-na"||arg==="--no-approve")projectTrustOverride=!1;else return arg.startsWith("-")?(console.error(source_default.red(`Unknown option ${arg} for "config".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${CONFIG_COMMAND_USAGE}".`)),process.exitCode=1,!0):(console.error(source_default.red(`Unexpected argument ${arg}.`)),console.error(source_default.dim(`Usage: ${CONFIG_COMMAND_USAGE}`)),process.exitCode=1,!0);let cwd=process.cwd(),agentDir=getAgentDir(),{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride,extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),local&&!settingsManager.isProjectTrusted())return console.error(source_default.red("Project is not trusted. Use --approve to modify local resource config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"config command");let builtinExtensions=(runtimeOptions.extensionFactories??[]).filter(isBuiltinExtension).map(input=>input.name),globalSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1}),globalResolvedPaths=await new DefaultPackageManager({cwd,agentDir,settingsManager:globalSettingsManager,builtinExtensions}).resolve(),projectResolvedPaths=settingsManager.isProjectTrusted()?await new DefaultPackageManager({cwd,agentDir,settingsManager,builtinExtensions}).resolve():globalResolvedPaths;await selectConfig({resolvedPaths:{global:globalResolvedPaths,project:projectResolvedPaths},settingsManager,cwd,agentDir,writeScope:local?"project":"global",projectModeAvailable:settingsManager.isProjectTrusted()}),process.exit(0)}async function handlePackageCommand(args,runtimeOptions={}){let options=parsePackageCommand(args);if(!options)return!1;if(options.help)return printPackageCommandHelp(options.command),!0;if(options.invalidOption)return console.error(source_default.red(`Unknown option ${options.invalidOption} for "${options.command}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getPackageCommandUsage(options.command)}".`)),process.exitCode=1,!0;if(options.missingOptionValue)return console.error(source_default.red(`Missing value for ${options.missingOptionValue}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.invalidArgument)return console.error(source_default.red(`Unexpected argument ${options.invalidArgument}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.conflictingOptions)return console.error(source_default.red(options.conflictingOptions)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;let source=options.source;if((options.command==="install"||options.command==="remove")&&!source)return console.error(source_default.red(`Missing ${options.command} source.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.command==="update"&&options.updateTarget?.type==="models"){try{await refreshModelCatalogs(getAgentDir())}catch(error){let message=error instanceof Error?error.message:"Unknown model catalog refresh error";console.error(source_default.red(`Error: ${message}`)),process.exitCode=1}return!0}let cwd=process.cwd(),agentDir=getAgentDir(),writesProjectPackageConfig=(options.command==="install"||options.command==="remove")&&options.local,{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride:options.projectTrustOverride,useSavedProjectTrustOnly:options.command==="update",extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),!settingsManager.isProjectTrusted()&&writesProjectPackageConfig)return console.error(source_default.red("Project is not trusted. Use --approve to modify local package config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"package command");let selfUpdateNpmCommand=settingsManager.getGlobalSettings().npmCommand,packageManager=new DefaultPackageManager({cwd,agentDir,settingsManager});packageManager.setProgressCallback(event=>{event.type==="start"&&process.stdout.write(source_default.dim(`${event.message}
93
+ `))});try{switch(options.command){case"install":return await packageManager.installAndPersist(source,{local:options.local}),console.log(source_default.green(`Installed ${source}`)),!0;case"remove":return await packageManager.removeAndPersist(source,{local:options.local})?(console.log(source_default.green(`Removed ${source}`)),!0):(console.error(source_default.red(`No matching package found for ${source}`)),process.exitCode=1,!0);case"list":{let configuredPackages=packageManager.listConfiguredPackages(),userPackages=configuredPackages.filter(pkg=>pkg.scope==="user"),projectPackages=configuredPackages.filter(pkg=>pkg.scope==="project");if(configuredPackages.length===0)return console.log(source_default.dim("No packages installed.")),!0;let formatPackage=pkg=>{let display=pkg.filtered?`${pkg.source} (filtered)`:pkg.source;console.log(` ${display}`),pkg.installedPath&&console.log(source_default.dim(` ${pkg.installedPath}`))};if(userPackages.length>0){console.log(source_default.bold("User packages:"));for(let pkg of userPackages)formatPackage(pkg)}if(projectPackages.length>0){userPackages.length>0&&console.log(),console.log(source_default.bold("Project packages:"));for(let pkg of projectPackages)formatPackage(pkg)}return!0}case"update":{let target=options.updateTarget??{type:"self"};if(options.omoLocalUpdateWorker)return await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"build"}),!0;if(options.showExtensionsSkippedNote&&await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"dispatch"}),options.showExtensionsSkippedNote&&console.log(source_default.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`)),updateTargetIncludesExtensions(target)){let updateSource=target.type==="extensions"?target.source:void 0;await packageManager.update(updateSource),console.log(updateSource?source_default.green(`Updated ${updateSource}`):source_default.green("Updated packages"))}if(updateTargetIncludesSelf(target)){let managedInstallRoot=getActiveManagedInstallRoot();if(managedInstallRoot&&options.force)return console.error(source_default.red(`Managed ${APP_NAME} installations do not support --force; rerun the installer to repair this installation.`)),process.exitCode=1,!0;let selfUpdatePlan=await getSelfUpdatePlan(options.force);if(!selfUpdatePlan.shouldRun)return!0;if(managedInstallRoot){selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{console.log(source_default.dim(`Updating managed ${APP_NAME} installation...`)),await runManagedSelfUpdate(managedInstallRoot,selfUpdatePlan.version)}catch(error){let message=error instanceof Error?error.message:"Unknown managed update error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}return console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)),!0}let installMethod=detectInstallMethod();if(process.platform==="win32"&&installMethod!=="npm"&&installMethod!=="pnpm")return console.error(source_default.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`)),console.error(source_default.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`)),process.exitCode=1,!0;let selfUpdateTarget={packageName:selfUpdatePlan.packageName,installSpec:selfUpdatePlan.installSpec},selfUpdateCommand=getSelfUpdateCommand(PACKAGE_NAME,selfUpdateNpmCommand,selfUpdateTarget);if(!selfUpdateCommand)return printSelfUpdateUnavailable(selfUpdateNpmCommand,selfUpdateTarget),process.exitCode=1,!0;selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{installMethod==="npm"&&prepareWindowsNpmSelfUpdate(),await runSelfUpdate(selfUpdateCommand)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),installMethod==="pnpm"&&printPnpmSelfUpdateMetadataHint(),printSelfUpdateFallback(selfUpdateCommand),process.exitCode=1,!0}console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`))}return!0}}}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}}export{cleanupManagedInstall,handleConfigCommand,handlePackageCommand,selfUpdatePlanAfterLookupFailure};
@@ -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-HZQHA4PA.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{getShellConfig}from"./chunk-JJYN347Z.js";import"./chunk-NDI6N4NJ.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{SecretOutputRedactor}from"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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"),autoReap=field("backgroundAutoReapMinutes");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,redactSecretsInOutput:field("redactSecretsInOutput")===!0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{},...typeof autoReap=="number"&&Number.isFinite(autoReap)?{backgroundAutoReapMinutes:autoReap}:{}}}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-3RILB2OD.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{getShellConfig}from"./chunk-ZJUL5ODW.js";import"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{SecretOutputRedactor}from"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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"),autoReap=field("backgroundAutoReapMinutes");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,redactSecretsInOutput:field("redactSecretsInOutput")===!0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{},...typeof autoReap=="number"&&Number.isFinite(autoReap)?{backgroundAutoReapMinutes:autoReap}:{}}}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,...runtime.autoReapedAfterMinutes===void 0?{}:{autoReapedAfterMinutes:runtime.autoReapedAfterMinutes}}}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},...args.backgroundAutoReapMinutes===void 0?{}:{backgroundAutoReapMinutes:args.backgroundAutoReapMinutes},onBackgroundStart:(id,description,startedAtMs,command,autoReapMinutes)=>tell(job,{event:"background_start",id,description,startedAtMs,...command===void 0?{}:{command},...autoReapMinutes===void 0?{}:{autoReapMinutes}}),onBackgroundExit:(id,runtime)=>tell(job,exitSummary(id,runtime)),onBackgroundReapFailed:(id,autoReapMinutes,reason)=>tell(job,{event:"background_reap_failed",id,autoReapMinutes,reason}),cwd:args.cwd,...args.shellPath===void 0?{}:{shellPath:args.shellPath},defaultCols:args.defaultCols,defaultRows:args.defaultRows,redactSecretsInOutput:args.redactSecretsInOutput,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,3 +1,3 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-HLY7CND7.js";import{orderRotationSlots,pickRotationSlot,rememberHeadroomAccount,rememberedHeadroomAccount}from"./chunk-7T2LAWZ4.js";import{getConfigValueEnvVarNames,isCommittedRotationOutput,isRotationStreamStart,resolveConfigValue,rotationErrorFromEvent}from"./chunk-AZ27TE3H.js";import{emitProviderAccountFailover,emitProviderAccountsChanged,slotsOfOwnKind,subscriptionLimits}from"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import{discoverEnvSlots}from"./chunk-C4AHHZ6P.js";import{KNOWN_SLOT_STATE_FIELDS,acquireHalfOpenLease,applicableStoredState}from"./chunk-CEFKVI3E.js";import"./chunk-HGCQAMC6.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import{roundRobinState}from"./chunk-WHQ2QPP5.js";import{classifyCredentialFailure,credentialFailureText,runCredentialFailover}from"./chunk-PBUV2Z3R.js";import"./chunk-WB4BUHOH.js";import{activeModelBlockUntil,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-NJ43NBSP.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-JJYN347Z.js";import"./chunk-NDI6N4NJ.js";import"./chunk-R7J5TEYK.js";import{redactSecrets}from"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import{ConfigReferenceError}from"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import{credentialPoolBlockedDiagnostic,sanitizeProviderDiagnostic}from"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";import{appendFile,chmod,rename,stat}from"node:fs/promises";var BLOCK_LOG_MAX_BYTES=256*1024,EXCERPT_MAX_CHARS=240,EMAIL=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,UUID=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,PREFIXED_ID=/\b(?:user|org|acct|account|ws|workspace)[-_][A-Za-z0-9]{6,}\b/gi;function redactBlockExcerpt(text){let masked=redactSecrets(text).replace(EMAIL,"[EMAIL]").replace(UUID,"[ID]").replace(PREFIXED_ID,"[ID]").replace(/\s+/g," ").trim();return masked.length>EXCERPT_MAX_CHARS?`${masked.slice(0,EXCERPT_MAX_CHARS)}\u2026`:masked}var pendingWrites=new Map;function appendCredentialBlockLog(path,entry){let next=(pendingWrites.get(path)??Promise.resolve()).then(()=>writeEntry(path,entry));pendingWrites.set(path,next),next.finally(()=>{pendingWrites.get(path)===next&&pendingWrites.delete(path)})}async function writeEntry(path,entry){try{let size=await fileSize(path);size!==void 0&&size>=BLOCK_LOG_MAX_BYTES&&await rename(path,`${path}.1`),await appendFile(path,`${JSON.stringify(entry)}
2
+ import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-HLY7CND7.js";import{orderRotationSlots,pickRotationSlot,rememberHeadroomAccount,rememberedHeadroomAccount}from"./chunk-73HGQTJN.js";import{getConfigValueEnvVarNames,isCommittedRotationOutput,isRotationStreamStart,resolveConfigValue,rotationErrorFromEvent}from"./chunk-7BX3JQ7F.js";import{emitProviderAccountFailover,emitProviderAccountsChanged,slotsOfOwnKind,subscriptionLimits}from"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import{discoverEnvSlots}from"./chunk-C4AHHZ6P.js";import{KNOWN_SLOT_STATE_FIELDS,acquireHalfOpenLease,applicableStoredState}from"./chunk-CEFKVI3E.js";import"./chunk-HGCQAMC6.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import{roundRobinState}from"./chunk-WHQ2QPP5.js";import{classifyCredentialFailure,credentialFailureText,runCredentialFailover}from"./chunk-RLIY3AUC.js";import"./chunk-WB4BUHOH.js";import{activeModelBlockUntil,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-NJ43NBSP.js";import"./chunk-6QQL3SKM.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-ZJUL5ODW.js";import"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import{redactSecrets}from"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import{ConfigReferenceError}from"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import{credentialPoolBlockedDiagnostic,sanitizeProviderDiagnostic}from"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";import{appendFile,chmod,rename,stat}from"node:fs/promises";var BLOCK_LOG_MAX_BYTES=256*1024,EXCERPT_MAX_CHARS=240,EMAIL=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,UUID=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,PREFIXED_ID=/\b(?:user|org|acct|account|ws|workspace)[-_][A-Za-z0-9]{6,}\b/gi;function redactBlockExcerpt(text){let masked=redactSecrets(text).replace(EMAIL,"[EMAIL]").replace(UUID,"[ID]").replace(PREFIXED_ID,"[ID]").replace(/\s+/g," ").trim();return masked.length>EXCERPT_MAX_CHARS?`${masked.slice(0,EXCERPT_MAX_CHARS)}\u2026`:masked}var pendingWrites=new Map;function appendCredentialBlockLog(path,entry){let next=(pendingWrites.get(path)??Promise.resolve()).then(()=>writeEntry(path,entry));pendingWrites.set(path,next),next.finally(()=>{pendingWrites.get(path)===next&&pendingWrites.delete(path)})}async function writeEntry(path,entry){try{let size=await fileSize(path);size!==void 0&&size>=BLOCK_LOG_MAX_BYTES&&await rename(path,`${path}.1`),await appendFile(path,`${JSON.stringify(entry)}
3
3
  `,{mode:384}),await chmod(path,384)}catch{}}async function fileSize(path){try{return(await stat(path)).size}catch{return}}async function releaseProbeLease(repository,providerId,lane,slotName,leaseId){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}))}async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await releaseProbeLease(repository,providerId,lane,slotName,leaseId)}async function probeInFlight(repository,providerId,lane,slot,isApplicable,now){let state=(await repository.listSlots(providerId,lane))[slot.name],lease=isApplicable(state)?state?.lease:void 0;if(!(lease===void 0||lease.expiresAt<=now))return{...slot,blockedUntil:lease.expiresAt,blockReason:PROBE_IN_FLIGHT}}var PROBE_IN_FLIGHT="probe_in_flight";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)){if(slot.signedOut===!0)continue;let persisted=state[slot.name],revisions=await repository.storedSlotRevisions(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),storedRevision=revisions.account,materialRevision=revisions.material,applicable=applicableStoredState(persisted,revisions),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)){let inFlight=await probeInFlight(repository,providerId,"stored",{name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision,materialRevision},state2=>applicableStoredState(state2,revisions)!==void 0,now());inFlight!==void 0&&slots.push(inFlight);continue}if(lease!==void 0&&lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=applicableStoredState(leasedState,revisions),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,materialRevision,...leasedModelUntil===void 0?{heldLeaseId:lease.leaseId}:{}},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision,materialRevision},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()),heldLeaseId;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){let inFlight=await probeInFlight(repository,providerId,"env",{name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},state2=>state2?.credentialRevision===revision,now());inFlight!==void 0&&slots.push(inFlight);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),modelUntil===void 0&&(heldLeaseId=lease.leaseId)}}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName,...heldLeaseId===void 0?{}:{heldLeaseId}},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function sameLineage(current,credentialRevision,lineage){return current===void 0?!1:current.credentialRevision===credentialRevision?!0:current.credentialRevision!==void 0&&lineage.includes(current.credentialRevision)}function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision,lineage){let sameMaterial=sameLineage(current,credentialRevision,lineage),{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,lineage=[]){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,lineage)}let kept=sameLineage(current,credentialRevision,lineage)?current:void 0,unknownFields=Object.fromEntries(Object.entries(kept??{}).filter(([field])=>!KNOWN_SLOT_STATE_FIELDS.has(field))),failureCount=(kept?.failureCount??0)+1,liveModelBlocks=kept===void 0?void 0:pruneModelBlocks(kept.modelBlocks,now),base={...unknownFields,failureCount,...credentialRevision===void 0?{}:{credentialRevision},...kept?.lastSuccessAt===void 0?{}:{lastSuccessAt:kept.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.usageLimit?{usageLimit:!0}:{}}:block.reason==="auth_error"?{...base,blockedUntil:now+9e5,blockReason:"auth_error"}:{...base,blockReason:block.reason}}function withPoolRetryAt(event,retryAt){if(event.type!=="error")return event;let own=sanitizeProviderDiagnostic(event.error.providerDiagnostic),limit=own?.category==="rate_limit"||own?.category==="quota",unclassifiedLimit=own===void 0||own.category==="unknown"&&own.httpStatus===429;if(!limit&&!unclassifiedLimit)return event;let providerDiagnostic=own!==void 0&&limit?sanitizeProviderDiagnostic({...own,resetsAt:own.resetsAt??retryAt})??own:credentialPoolBlockedDiagnostic(retryAt);return providerDiagnostic===void 0?event:{...event,error:{...event.error,providerDiagnostic}}}function failoverReason(block){return block.reason==="account_disabled"?"billing":block.reason}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.accountStrategy!==void 0||sources.policy?.affinity!==!1,pooled=sources.credential,now=sources.now??Date.now,rememberAffinity=useAffinity&&options.affinityKey!==void 0,roundRobin=sources.policy?.accountStrategy==="round-robin"?roundRobinState.session(sources.providerId,options.affinityKey):void 0,leaving;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let remembered=roundRobin?.account??(rememberAffinity?rememberedHeadroomAccount(sources.repository,sources.providerId,affinityKey):void 0),policy={affinityKey,useAffinity,hasher,...pooled?.order===void 0?{}:{order:pooled.order},...sources.policy?.accountStrategy===void 0?{}:{strategy:sources.policy.accountStrategy},...roundRobin===void 0?{}:{roundRobinOffset:roundRobin.offset},headroom:{providerId:sources.providerId,limits:subscriptionLimits.snapshot(),now:now(),...remembered===void 0?{}:{remembered}}},winner=pickRotationSlot(candidates,policy);if(!winner)throw new Error("credential rotation selected from an empty candidate set");return roundRobin!==void 0?winner.pinned!==!0&&(roundRobin.account=winner.name):rememberAffinity&&winner.pinned!==!0&&(remembered!==void 0||winner!==orderRotationSlots(candidates,policy)[0])&&rememberHeadroomAccount(sources.repository,sources.providerId,affinityKey,winner.name),winner},runAttempt:slot=>(leaving!==void 0&&leaving.name!==slot.name&&emitProviderAccountFailover(sources.providerId,leaving.name,slot.name,failoverReason(leaving.block)),leaving=void 0,runAttempt(slot)),onRotate:({slot,block,committedOutput})=>{leaving=committedOutput?void 0:{name:slot.name,block}},isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,withPoolRetryAt,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{let released=!1;await writeHealthUnlessStoreBusy(`success on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>{if(!current)return;let modelBlocks=pruneModelBlocks(current.modelBlocks,now(),options.modelId);return released=current.blockedUntil!==void 0||current.blockReason!==void 0||Object.keys(modelBlocks??{}).length!==Object.keys(current.modelBlocks??{}).length,{...current,...slot.storedRevision===void 0?{}:{credentialRevision:slot.storedRevision},lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,usageLimit:void 0,failureCount:void 0,modelBlocks}}))!==STORE_BUSY&&released&&emitProviderAccountsChanged(sources.providerId)},releaseSlot:async slot=>{slot.heldLeaseId!==void 0&&await releaseProbeLease(sources.repository,sources.providerId,slot.lane,slot.name,slot.heldLeaseId)},persistBlock:async(slot,block,error)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):block.reason==="auth_error"?slot.materialRevision:slot.storedRevision,written=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,[...slot.storedRevision===void 0?[]:[slot.storedRevision],...slot.materialRevision===void 0?[]:[slot.materialRevision]])));written!==STORE_BUSY&&emitProviderAccountsChanged(sources.providerId);let blockedUntil=written===STORE_BUSY?void 0:written?.blockedUntil,blockLogPath=sources.repository.blockLogPath?.();blockLogPath!==void 0&&appendCredentialBlockLog(blockLogPath,{at:new Date(now()).toISOString(),provider:sources.providerId,slot:slot.name,reason:block.reason,...blockedUntil===void 0?{}:{blockedUntil:new Date(blockedUntil).toISOString()},...block.reason==="rate_limit"&&block.resetSource!==void 0?{resetSource:block.resetSource}:{},...block.reason==="rate_limit"&&block.modelFamily!==void 0?{model:block.modelFamily}:{},...error===void 0?{}:{excerpt:redactBlockExcerpt(credentialFailureText(error))}})},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-6QXAYNO7.js";import"./chunk-5IXYN6DK.js";import"./chunk-Q4RJ4WLE.js";import"./chunk-6MRUNB3Z.js";import"./chunk-75O3CWR5.js";import"./chunk-WAGFTIT4.js";import"./chunk-NLYT7BND.js";import"./chunk-TACOXP5H.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-FYVQEZYN.js";import"./chunk-WMDJMN5W.js";import"./chunk-GTJJ73DE.js";import"./chunk-VD7AKTGP.js";import"./chunk-PWA75RQU.js";import"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import"./chunk-5NECOJNK.js";import"./chunk-HKCFMDJN.js";import"./chunk-A3LGSX7Z.js";import"./chunk-3QPE75AR.js";import"./chunk-ULWRGKP2.js";import"./chunk-4B5JSLLR.js";import"./chunk-FWIO636S.js";import"./chunk-MOVB6H22.js";import"./chunk-DLPV4B3R.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-WMHESZCU.js";import"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import"./chunk-E5O4SP5I.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-Z4PN2MDA.js";import"./chunk-7BX3JQ7F.js";import"./chunk-GILDYS3O.js";import"./chunk-KLAX467B.js";import"./chunk-C4AHHZ6P.js";import"./chunk-CEFKVI3E.js";import"./chunk-HGCQAMC6.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EUCZC2RF.js";import"./chunk-WHQ2QPP5.js";import"./chunk-RLIY3AUC.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-2IKL4F24.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-3RILB2OD.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import"./chunk-ZJUL5ODW.js";import"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-QVG5SUSV.js";import"./chunk-GXPH7RN6.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-2SOVDETB.js";import"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{AskUserQuestionComponent,AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,UserMessageComponent,createChatViewport,createInteractiveTui}from"./chunk-V4VDIV3U.js";import{connectRpcClientSocket,requestDeadlineMs}from"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import{ExtensionInputComponent,ExtensionSelectorComponent,getEditorTheme,initTheme,sharedMarkdownTheme,stopThemeWatcher,theme}from"./chunk-BKDXY6EM.js";import"./chunk-HKCFMDJN.js";import"./chunk-E6ZBTSC6.js";import{KeybindingsManager}from"./chunk-ULWRGKP2.js";import"./chunk-26UBFF6N.js";import"./chunk-E5O4SP5I.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-KLAX467B.js";import"./chunk-EUCZC2RF.js";import"./chunk-NJ43NBSP.js";import"./chunk-YU2P3CAR.js";import{Container,Markdown,Text,TuiAltScreen,setKeybindings}from"./chunk-4PMRUR4L.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import{markModeCrashHandler}from"./chunk-ZFIC2DZV.js";import"./chunk-RUGTHELO.js";import"./chunk-HW6AAS3R.js";import{getAgentDir}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{randomUUID}from"node:crypto";var AttachRefusedError=class extends Error{constructor(code,message){super(message),this.name="AttachRefusedError",this.code=code}},AnswerRefusedError=class extends Error{constructor(code){super(`Answer refused: ${code}`),this.name="AnswerRefusedError",this.code=code}},ANSWER_DEADLINE_MS=3e4,AttachClient=class{constructor(onRecord,onDisconnect,options={}){this.pending=new Map,this.closed=!1,this.onRecord=onRecord,this.onDisconnect=onDisconnect,this.answerDeadlineMs=options.answerDeadlineMs??ANSWER_DEADLINE_MS}async connect(path){let socket=await connectRpcClientSocket(path,{});if(this.closed)throw socket.destroy(),new Error("Disconnected");this.socket=socket,this.stopReading=attachJsonlLineReader(socket,line=>this.receive(socket,line),{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>this.fail(socket,"the endpoint sent a record over the line limit")}),socket.once("error",()=>socket.destroy()),socket.once("close",()=>{this.socket=void 0,this.rejectPending(),this.closed||this.onDisconnect(this.failure)})}request(command){let id=randomUUID();return this.track(id,requestDeadlineMs(command),`No acknowledgement for ${command.type}; its outcome is unknown`,{...command,id})}async answer(sessionId,response){await this.track(response.id,this.answerDeadlineMs,"No acknowledgement for the answer",{...response,sessionId,answerId:randomUUID()})}close(){this.closed=!0,this.stopReading?.(),this.socket?.destroy(),this.socket=void 0,this.rejectPending()}track(id,deadlineMs,unanswered,record){return new Promise((resolve,reject)=>{let timer=setTimeout(()=>{this.pending.delete(id),reject(new Error(unanswered))},deadlineMs);if(this.pending.set(id,{resolve:answer=>{clearTimeout(timer),resolve(answer)},reject:error=>{clearTimeout(timer),reject(error)}}),this.socket?.writable&&!this.socket.destroyed){this.socket.write(serializeJsonLine(record));return}clearTimeout(timer),this.pending.delete(id),reject(new Error("Disconnected"))})}receive(socket,line){let record;try{record=JSON.parse(line)}catch{this.fail(socket,"the endpoint sent an unreadable record");return}if(record.type==="response"){let pending=record.id?this.pending.get(record.id):void 0;if(!pending)return;record.id&&this.pending.delete(record.id),record.success?pending.resolve(record):record.command==="extension_ui_response"?pending.reject(new AnswerRefusedError(record.error)):pending.reject(new Error(record.error));return}try{this.onRecord(record)}catch(error){this.fail(socket,`a ${record.type} record could not be shown (${error instanceof Error?error.message:String(error)})`)}}fail(socket,reason){this.failure??=reason,socket.destroy()}rejectPending(){for(let request of this.pending.values())request.reject(new Error("Disconnected; pending command outcome is unknown"));this.pending.clear()}};function remoteOriginLabel(request){let origin="remoteOrigin"in request?request.remoteOrigin:void 0;if(typeof origin!="object"||origin===null||!("deviceId"in origin))return;let name="deviceName"in origin&&typeof origin.deviceName=="string"?clean(origin.deviceName):"",id=typeof origin.deviceId=="string"?clean(origin.deviceId):"",device=name||id;return device?`Requested from ${device}`:void 0}var clean=value=>value.replace(/[\u0000-\u001f\u007f-\u009f]/g,"").trim(),AttachDialogs=class extends Container{constructor(ui,keys,answer,report,focusEditor){super(),this.queue=[],this.seen=new Set,this.settled=new Set,this.closed=!1,this.ui=ui,this.keys=keys,this.answer=answer,this.report=report,this.focusEditor=focusEditor}get active(){return this.current!==void 0}accept(request){this.seen.has(request.id)||["select","confirm","input","editor","question"].includes(request.method)&&(this.seen.add(request.id),this.queue.push(request),this.showNext())}resolve(id){this.settled.add(id);let index=this.queue.findIndex(request=>request.id===id);index>=0&&this.queue.splice(index,1),this.current?.request.id===id&&this.dismiss()}handleInput(data){this.current?.component.handleInput?.(data)}dispose(){this.closed=!0,this.queue.length=0,this.current?.component.dispose?.(),this.current=void 0,this.clear()}dismiss(){this.current?.component.dispose?.(),this.current=void 0,this.clear(),this.focusEditor(),this.showNext(),this.ui.requestRender()}submit(request,response){this.dismiss(),this.answer(response).catch(error=>{let code=error instanceof AnswerRefusedError?error.code:void 0;if(code==="question_already_resolved"||code==="unknown_extension_ui_request"){this.report(`Not accepted: ${code} (already settled)`);return}this.closed||this.settled.has(request.id)||(this.report(request.method==="input"&&request.secret?"Secret answer was not acknowledged. The outcome is unknown; enter a new answer only after checking.":`${error instanceof Error?error.message:String(error)}. Answer again.`),!(request.method==="input"&&request.secret&&(!(error instanceof AnswerRefusedError)||Date.now()>=(request.deadlineAtMs??0)))&&(this.queue.unshift(request),this.showNext(),this.ui.requestRender()))})}showNext(){if(this.current)return;let request=this.queue.shift();if(!request)return;let finish=response=>{this.current?.request.id===request.id&&this.submit(request,request.method==="input"&&request.secret?{...response,secret:!0,uiRequestId:request.id,id:crypto.randomUUID(),answerId:crypto.randomUUID()}:response)},cancel=()=>finish({type:"extension_ui_response",id:request.id,cancelled:!0}),component;switch(request.method){case"select":component=new ExtensionSelectorComponent(request.title,request.options,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel,{tui:this.ui,timeout:request.timeout});break;case"confirm":component=new ExtensionSelectorComponent(request.title,["Yes","No"],value=>finish({type:"extension_ui_response",id:request.id,confirmed:value==="Yes"}),cancel,{tui:this.ui,timeout:request.timeout,description:request.message});break;case"input":if(request.secret&&(request.deadlineAtMs===void 0||request.deadlineAtMs<=Date.now())){this.settled.add(request.id),this.showNext();return}component=new ExtensionInputComponent(request.title,request.placeholder,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel,{tui:this.ui,timeout:request.timeout,secret:request.secret,deadlineAtMs:request.deadlineAtMs});break;case"editor":component=new ExtensionEditorComponent(this.ui,this.keys,request.title,request.prefill,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel);break;case"question":component=new AskUserQuestionComponent({requestId:request.requestId,questions:request.questions,waitForAnswer:request.waitForAnswer,timeoutMs:request.remainingMs},response=>response.status==="answered"||response.status==="comment-submitted"?finish({type:"extension_ui_response",id:request.id,answers:response.answers,comment:response.comment}):cancel(),{tui:this.ui,getDeadlineAtMs:()=>request.deadlineAtMs});break;default:return}this.current={request,component};let origin=remoteOriginLabel(request);origin&&this.addChild(new Text(theme.fg("warning",origin),1,0)),this.addChild(component),this.ui.setFocus(component),this.ui.requestRender()}};var RecordRenderer=class extends Container{constructor(){super(...arguments),this.rows=[],this.finalized=new Set,this.historyKeys=new Map}prepend(entries){let added=[];for(let entry of entries){if(entry.type!=="message")continue;let key=entry.id;this.historyKeys.set(this.messageKey(entry.message),key),this.finalized.add(key),!this.rows.some(row=>row.key===key)&&added.push({key,message:entry.message,component:this.component(entry.message)})}this.rows=[...added,...this.rows],this.rebuild()}accept(record){switch(record.type){case"message_start":if(this.finalized.has(this.key(record.message,record.entryId)))return;this.put(record.message,record.entryId);break;case"message_update":{if(record.message){this.put(record.message,record.entryId);break}let active=this.active;if(!active)return;let event=record.assistantMessageEvent,content=active.message.content;switch(event.type){case"text_start":content[event.contentIndex]={type:"text",text:""};break;case"thinking_start":content[event.contentIndex]={type:"thinking",thinking:""};break;case"text_delta":{let part=content[event.contentIndex];part?.type==="text"?part.text+=event.delta:content[event.contentIndex]={type:"text",text:event.delta};break}case"thinking_delta":{let part=content[event.contentIndex];part?.type==="thinking"?part.thinking+=event.delta:content[event.contentIndex]={type:"thinking",thinking:event.delta};break}case"toolcall_start":content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}};break;case"toolcall_end":content[event.contentIndex]=event.toolCall;break;default:break}active.message.usage=record.usage,active.component.updateContent(active.message);break}case"message_end":this.put(record.message,record.entryId),this.finalized.add(this.key(record.message,record.entryId)),this.active=void 0;break;default:break}}messageKey(message){return message.role==="toolResult"?`tool:${message.toolCallId}`:`${message.role}:${message.timestamp}`}key(message,entryId){return entryId??this.historyKeys.get(this.messageKey(message))??this.messageKey(message)}put(message,entryId){let key=this.key(message,entryId),existing=this.rows.find(row=>row.key===key)??this.rows.find(row=>!this.finalized.has(row.key)&&this.messageKey(row.message)===this.messageKey(message));if(message.role==="assistant"){let component=existing?.component instanceof AssistantMessageComponent?existing.component:new AssistantMessageComponent,snapshot=structuredClone(message);component.updateContent(snapshot),this.active={key,message:snapshot,component},existing?(existing.key=key,existing.component=component,existing.message=snapshot):this.rows.push({key,message:snapshot,component})}else existing?(existing.key=key,existing.message=message,existing.component=this.component(message)):this.rows.push({key,message,component:this.component(message)});this.rebuild()}component(message){switch(message.role){case"assistant":return new AssistantMessageComponent(message);case"user":{let text=typeof message.content=="string"?message.content:message.content.map(part=>part.type==="text"?part.text:"[image]").join(`
2
+ import{AskUserQuestionComponent,AssistantMessageComponent,CustomEditor,ExtensionEditorComponent,UserMessageComponent,createChatViewport,createInteractiveTui}from"./chunk-PWA75RQU.js";import{connectRpcClientSocket,requestDeadlineMs}from"./chunk-M2VJVJMK.js";import"./chunk-TQHNFP77.js";import{ExtensionInputComponent,ExtensionSelectorComponent,getEditorTheme,initTheme,sharedMarkdownTheme,stopThemeWatcher,theme}from"./chunk-5NECOJNK.js";import"./chunk-HKCFMDJN.js";import"./chunk-A3LGSX7Z.js";import{KeybindingsManager}from"./chunk-ULWRGKP2.js";import"./chunk-26UBFF6N.js";import"./chunk-E5O4SP5I.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-KLAX467B.js";import"./chunk-EUCZC2RF.js";import"./chunk-NJ43NBSP.js";import"./chunk-YU2P3CAR.js";import{Container,Markdown,Text,TuiAltScreen,setKeybindings}from"./chunk-4PMRUR4L.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import{markModeCrashHandler}from"./chunk-ZFIC2DZV.js";import"./chunk-RUGTHELO.js";import"./chunk-HW6AAS3R.js";import{getAgentDir}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{randomUUID}from"node:crypto";var AttachRefusedError=class extends Error{constructor(code,message){super(message),this.name="AttachRefusedError",this.code=code}},AnswerRefusedError=class extends Error{constructor(code){super(`Answer refused: ${code}`),this.name="AnswerRefusedError",this.code=code}},ANSWER_DEADLINE_MS=3e4,AttachClient=class{constructor(onRecord,onDisconnect,options={}){this.pending=new Map,this.closed=!1,this.onRecord=onRecord,this.onDisconnect=onDisconnect,this.answerDeadlineMs=options.answerDeadlineMs??ANSWER_DEADLINE_MS}async connect(path){let socket=await connectRpcClientSocket(path,{});if(this.closed)throw socket.destroy(),new Error("Disconnected");this.socket=socket,this.stopReading=attachJsonlLineReader(socket,line=>this.receive(socket,line),{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>this.fail(socket,"the endpoint sent a record over the line limit")}),socket.once("error",()=>socket.destroy()),socket.once("close",()=>{this.socket=void 0,this.rejectPending(),this.closed||this.onDisconnect(this.failure)})}request(command){let id=randomUUID();return this.track(id,requestDeadlineMs(command),`No acknowledgement for ${command.type}; its outcome is unknown`,{...command,id})}async answer(sessionId,response){await this.track(response.id,this.answerDeadlineMs,"No acknowledgement for the answer",{...response,sessionId,answerId:randomUUID()})}close(){this.closed=!0,this.stopReading?.(),this.socket?.destroy(),this.socket=void 0,this.rejectPending()}track(id,deadlineMs,unanswered,record){return new Promise((resolve,reject)=>{let timer=setTimeout(()=>{this.pending.delete(id),reject(new Error(unanswered))},deadlineMs);if(this.pending.set(id,{resolve:answer=>{clearTimeout(timer),resolve(answer)},reject:error=>{clearTimeout(timer),reject(error)}}),this.socket?.writable&&!this.socket.destroyed){this.socket.write(serializeJsonLine(record));return}clearTimeout(timer),this.pending.delete(id),reject(new Error("Disconnected"))})}receive(socket,line){let record;try{record=JSON.parse(line)}catch{this.fail(socket,"the endpoint sent an unreadable record");return}if(record.type==="response"){let pending=record.id?this.pending.get(record.id):void 0;if(!pending)return;record.id&&this.pending.delete(record.id),record.success?pending.resolve(record):record.command==="extension_ui_response"?pending.reject(new AnswerRefusedError(record.error)):pending.reject(new Error(record.error));return}try{this.onRecord(record)}catch(error){this.fail(socket,`a ${record.type} record could not be shown (${error instanceof Error?error.message:String(error)})`)}}fail(socket,reason){this.failure??=reason,socket.destroy()}rejectPending(){for(let request of this.pending.values())request.reject(new Error("Disconnected; pending command outcome is unknown"));this.pending.clear()}};function remoteOriginLabel(request){let origin="remoteOrigin"in request?request.remoteOrigin:void 0;if(typeof origin!="object"||origin===null||!("deviceId"in origin))return;let name="deviceName"in origin&&typeof origin.deviceName=="string"?clean(origin.deviceName):"",id=typeof origin.deviceId=="string"?clean(origin.deviceId):"",device=name||id;return device?`Requested from ${device}`:void 0}var clean=value=>value.replace(/[\u0000-\u001f\u007f-\u009f]/g,"").trim(),AttachDialogs=class extends Container{constructor(ui,keys,answer,report,focusEditor){super(),this.queue=[],this.seen=new Set,this.settled=new Set,this.closed=!1,this.ui=ui,this.keys=keys,this.answer=answer,this.report=report,this.focusEditor=focusEditor}get active(){return this.current!==void 0}accept(request){this.seen.has(request.id)||["select","confirm","input","editor","question"].includes(request.method)&&(this.seen.add(request.id),this.queue.push(request),this.showNext())}resolve(id){this.settled.add(id);let index=this.queue.findIndex(request=>request.id===id);index>=0&&this.queue.splice(index,1),this.current?.request.id===id&&this.dismiss()}handleInput(data){this.current?.component.handleInput?.(data)}dispose(){this.closed=!0,this.queue.length=0,this.current?.component.dispose?.(),this.current=void 0,this.clear()}dismiss(){this.current?.component.dispose?.(),this.current=void 0,this.clear(),this.focusEditor(),this.showNext(),this.ui.requestRender()}submit(request,response){this.dismiss(),this.answer(response).catch(error=>{let code=error instanceof AnswerRefusedError?error.code:void 0;if(code==="question_already_resolved"||code==="unknown_extension_ui_request"){this.report(`Not accepted: ${code} (already settled)`);return}this.closed||this.settled.has(request.id)||(this.report(request.method==="input"&&request.secret?"Secret answer was not acknowledged. The outcome is unknown; enter a new answer only after checking.":`${error instanceof Error?error.message:String(error)}. Answer again.`),!(request.method==="input"&&request.secret&&(!(error instanceof AnswerRefusedError)||Date.now()>=(request.deadlineAtMs??0)))&&(this.queue.unshift(request),this.showNext(),this.ui.requestRender()))})}showNext(){if(this.current)return;let request=this.queue.shift();if(!request)return;let finish=response=>{this.current?.request.id===request.id&&this.submit(request,request.method==="input"&&request.secret?{...response,secret:!0,uiRequestId:request.id,id:crypto.randomUUID(),answerId:crypto.randomUUID()}:response)},cancel=()=>finish({type:"extension_ui_response",id:request.id,cancelled:!0}),component;switch(request.method){case"select":component=new ExtensionSelectorComponent(request.title,request.options,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel,{tui:this.ui,timeout:request.timeout});break;case"confirm":component=new ExtensionSelectorComponent(request.title,["Yes","No"],value=>finish({type:"extension_ui_response",id:request.id,confirmed:value==="Yes"}),cancel,{tui:this.ui,timeout:request.timeout,description:request.message});break;case"input":if(request.secret&&(request.deadlineAtMs===void 0||request.deadlineAtMs<=Date.now())){this.settled.add(request.id),this.showNext();return}component=new ExtensionInputComponent(request.title,request.placeholder,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel,{tui:this.ui,timeout:request.timeout,secret:request.secret,deadlineAtMs:request.deadlineAtMs});break;case"editor":component=new ExtensionEditorComponent(this.ui,this.keys,request.title,request.prefill,value=>finish({type:"extension_ui_response",id:request.id,value}),cancel);break;case"question":component=new AskUserQuestionComponent({requestId:request.requestId,questions:request.questions,waitForAnswer:request.waitForAnswer,timeoutMs:request.remainingMs},response=>response.status==="answered"||response.status==="comment-submitted"?finish({type:"extension_ui_response",id:request.id,answers:response.answers,comment:response.comment}):cancel(),{tui:this.ui,getDeadlineAtMs:()=>request.deadlineAtMs});break;default:return}this.current={request,component};let origin=remoteOriginLabel(request);origin&&this.addChild(new Text(theme.fg("warning",origin),1,0)),this.addChild(component),this.ui.setFocus(component),this.ui.requestRender()}};var RecordRenderer=class extends Container{constructor(){super(...arguments),this.rows=[],this.finalized=new Set,this.historyKeys=new Map}prepend(entries){let added=[];for(let entry of entries){if(entry.type!=="message")continue;let key=entry.id;this.historyKeys.set(this.messageKey(entry.message),key),this.finalized.add(key),!this.rows.some(row=>row.key===key)&&added.push({key,message:entry.message,component:this.component(entry.message)})}this.rows=[...added,...this.rows],this.rebuild()}accept(record){switch(record.type){case"message_start":if(this.finalized.has(this.key(record.message,record.entryId)))return;this.put(record.message,record.entryId);break;case"message_update":{if(record.message){this.put(record.message,record.entryId);break}let active=this.active;if(!active)return;let event=record.assistantMessageEvent,content=active.message.content;switch(event.type){case"text_start":content[event.contentIndex]={type:"text",text:""};break;case"thinking_start":content[event.contentIndex]={type:"thinking",thinking:""};break;case"text_delta":{let part=content[event.contentIndex];part?.type==="text"?part.text+=event.delta:content[event.contentIndex]={type:"text",text:event.delta};break}case"thinking_delta":{let part=content[event.contentIndex];part?.type==="thinking"?part.thinking+=event.delta:content[event.contentIndex]={type:"thinking",thinking:event.delta};break}case"toolcall_start":content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}};break;case"toolcall_end":content[event.contentIndex]=event.toolCall;break;default:break}active.message.usage=record.usage,active.component.updateContent(active.message);break}case"message_end":this.put(record.message,record.entryId),this.finalized.add(this.key(record.message,record.entryId)),this.active=void 0;break;default:break}}messageKey(message){return message.role==="toolResult"?`tool:${message.toolCallId}`:`${message.role}:${message.timestamp}`}key(message,entryId){return entryId??this.historyKeys.get(this.messageKey(message))??this.messageKey(message)}put(message,entryId){let key=this.key(message,entryId),existing=this.rows.find(row=>row.key===key)??this.rows.find(row=>!this.finalized.has(row.key)&&this.messageKey(row.message)===this.messageKey(message));if(message.role==="assistant"){let component=existing?.component instanceof AssistantMessageComponent?existing.component:new AssistantMessageComponent,snapshot=structuredClone(message);component.updateContent(snapshot),this.active={key,message:snapshot,component},existing?(existing.key=key,existing.component=component,existing.message=snapshot):this.rows.push({key,message:snapshot,component})}else existing?(existing.key=key,existing.message=message,existing.component=this.component(message)):this.rows.push({key,message,component:this.component(message)});this.rebuild()}component(message){switch(message.role){case"assistant":return new AssistantMessageComponent(message);case"user":{let text=typeof message.content=="string"?message.content:message.content.map(part=>part.type==="text"?part.text:"[image]").join(`
3
3
  `);return new UserMessageComponent(text)}case"toolResult":{let text=message.content.map(part=>part.type==="text"?part.text:"[image]").join(`
4
4
  `),result=new Container;return result.addChild(new Text(theme.fg("muted",message.toolName),1,0)),result.addChild(new Markdown(text,1,0,sharedMarkdownTheme())),result}default:return new Text("content"in message?String(message.content):message.role,1,0)}}rebuild(){this.clear();for(let row of this.rows)this.addChild(row.component)}};var ATTACH_CLIENT_CAPABILITIES=["interactive_user","question","grant_select","secret_input_v1"],WidthReporter=class{constructor(inner,onWidth){this.inner=inner,this.onWidth=onWidth}render(width){return this.onWidth(width),this.inner.render(width)}invalidate(){this.inner.invalidate()}};function validateAttachTerminal(inputIsTTY,outputIsTTY){if(!inputIsTTY||!outputIsTTY)throw new Error("--attach requires an interactive terminal on stdin and stdout")}var AttachedTui=class extends Container{constructor(ui,finish,options={}){super(),this.transcript=new RecordRenderer,this.statusText=new Text("Connecting",1,0),this.status=new WidthReporter(this.statusText,width=>this.reportWidth(width)),this.connected=!1,this.attached=!1,this.closing=!1,this.streaming=!1,this.buffering=[],this.ui=ui;let keys=KeybindingsManager.create();setKeybindings(keys),this.editor=new CustomEditor(ui,getEditorTheme(),keys),this.dialogs=new AttachDialogs(ui,keys,response=>this.sessionId?this.client.answer(this.sessionId,response):Promise.reject(new Error("Disconnected")),message=>this.showStatus(message),()=>ui.setFocus(this)),this.client=new AttachClient(record=>{record.sessionId&&record.sessionId!==this.sessionId||(this.buffering?this.buffering.push(record):this.record(record))},reason=>{this.connected=!1,this.dialogs.dispose(),ui.setFocus(this),this.showStatus(reason?`Disconnected: ${reason}`:"Disconnected")},{answerDeadlineMs:options.answerDeadlineMs}),this.editor.onSubmit=text=>{if(text.trim()==="/quit"){finish();return}this.perform(()=>this.submit(text),()=>{this.editor.getText()===""&&this.editor.setText(text)})},this.editor.onCtrlD=finish,this.editor.onAction("app.clear",finish),this.editor.onEscape=()=>this.perform(()=>this.abort()),this.addChild(this.transcript),this.addChild(this.status),this.addChild(this.dialogs),this.addChild(this.editor);let input=new Container;input.addChild(this.dialogs),input.addChild(this.editor),this.layoutRoot=createChatViewport({document:this.transcript,pendingMessages:new Container,status:this.status,editor:input,footer:new Text("/history /steer <text> /abort /quit",1,0),scrollbarTrackStyle:text=>theme.fg("scrollbarTrack",text),scrollbarThumbStyle:text=>theme.fg("scrollbarThumb",text)}).root}get focused(){return this.editor.focused}set focused(value){this.editor.focused=value}async connect(address,ref){let path=address.startsWith("unix://")?address.slice(7):address;if(!path||path.includes("://")||/^\\\\\.\\pipe\\/i.test(path))throw new Error("--attach needs a local socket path or a named pipe's logical filesystem path");try{await this.client.connect(path),this.connected=!0,this.width=this.ui.terminal.columns,await this.client.request({type:"set_client_info",width:this.width,capabilities:[...ATTACH_CLIENT_CAPABILITIES]});let listing=await this.client.request({type:"list_sessions",observe:!0});if(listing.command!=="list_sessions")throw new Error("Expected a session listing");let exact=listing.data.sessions.filter(row2=>row2.sessionId===ref||row2.durableSessionId===ref||row2.sessionPath===ref),matches=exact.length?exact:listing.data.sessions.filter(row2=>row2.durableSessionId?.startsWith(ref)),row=matches.length===1?matches[0]:void 0;if(!row?.durableSessionId)throw new Error(matches.length>1?"Ambiguous session reference":"No live session matches the reference");if(row.retain_on_disconnect!==!0)throw new AttachRefusedError("session_not_retained",`Session ${ref} is not retained on disconnect: the endpoint ends it when its last client leaves, so leaving this view could end it. Attach to a session opened with retain_on_disconnect.`);this.sessionId=row.sessionId,await this.client.request({type:"attach_session",sessionId:row.sessionId,durableSessionId:row.durableSessionId}),this.attached=!0;let subscribed=await this.client.request({type:"subscribe_sessions",sessions:{ids:[row.sessionId]},mirror:"all"}),state=await this.client.request({type:"get_state",sessionId:row.sessionId,observe:!0});if(state.command!=="get_state")throw new Error("Expected session state");this.state=state.data,this.streaming=state.data.isStreaming,await this.loadHistory();for(let dialog of[...state.data.pendingDialogs??[],...state.data.pendingQuestions??[]])this.dialogs.accept(dialog);if(this.showStatus(this.streaming?"Running":"Attached"),subscribed.command==="subscribe_sessions")for(let status of subscribed.data.snapshot)this.record(status);let buffered=this.buffering??[];this.buffering=void 0;for(let record of buffered)this.record(record)}catch(error){try{await this.close()}catch(releaseError){throw new AggregateError([error,releaseError],error instanceof Error?error.message:String(error))}throw error}}loadHistory(){return this.loadingHistory?this.loadingHistory:(this.loadingHistory=this.readHistory().finally(()=>{this.loadingHistory=void 0}),this.loadingHistory)}async readHistory(){if(!this.sessionId||!this.connected)return;let response=await this.client.request({type:"get_entries",sessionId:this.sessionId,tail:100,before:this.before,observe:!0});if(response.command!=="get_entries")throw new Error("Expected history entries");this.before=response.data.next_before,this.transcript.prepend(response.data.entries),this.ui.requestRender()}async submit(text){if(!this.connected||!this.sessionId)throw new Error("Disconnected; attach again to send input");if(text.trim()==="/history"){this.before&&await this.loadHistory();return}if(text.trim()==="/abort"){await this.abort();return}let steer=text.startsWith("/steer ")||this.streaming,message=text.startsWith("/steer ")?text.slice(7):text;message.trim()&&await this.client.request({type:steer?"steer":"prompt",sessionId:this.sessionId,message,clientMessageId:randomUUID2()})}async abort(){!this.sessionId||!this.connected||await this.client.request({type:"abort",sessionId:this.sessionId,intent:"stop",effectId:randomUUID2()})}async close(){if(!this.closing){this.closing=!0,this.dialogs.dispose();try{this.connected&&this.attached&&this.sessionId&&await this.client.request({type:"release_attachment",sessionId:this.sessionId})}finally{this.connected=!1,this.client.close()}}}handleInput(data){this.dialogs.active?this.dialogs.handleInput(data):this.editor.handleInput(data),this.ui.requestRender()}record(record){switch(this.transcript.accept(record),record.type){case"extension_ui_request":record.method==="notify"?this.showStatus(record.message):this.dialogs.accept(record);break;case"question_resolved":case"secret_input_settled":this.dialogs.resolve(record.id);break;case"session_status":this.streaming=record.status==="running",this.showStatus(record.status);break;case"agent_start":this.streaming=!0,this.showStatus("Running");break;case"agent_end":case"agent_settled":this.streaming=!1,this.showStatus("Attached");break;default:break}this.ui.requestRender()}reportWidth(width){!this.attached||!this.connected||width===this.width||(this.width=width,this.perform(async()=>{await this.client.request({type:"set_client_info",width})}))}showStatus(value){this.statusText.setText(theme.fg("muted",`${value}${this.state?.sessionName?` - ${this.state.sessionName}`:""}`)),this.ui.requestRender()}perform(action,onError){action().catch(error=>{onError?.(),this.showStatus(error instanceof Error?error.message:String(error))})}};async function runAttachedTui(options){validateAttachTerminal(process.stdin.isTTY,process.stdout.isTTY),initTheme(options.theme);let ui=createInteractiveTui({tuiMode:options.tuiMode??"regular",showHardwareCursor:!1,logDirectory:getAgentDir()}),restored=!1,restore=()=>{if(!restored){restored=!0;try{ui.stop()}finally{stopThemeWatcher()}}},crash=error=>{try{restore()}finally{console.error(error),process.exit(1)}};markModeCrashHandler(crash),process.prependListener("uncaughtException",crash),process.prependListener("unhandledRejection",crash);let finish=()=>{},done=new Promise(resolve=>{finish=resolve}),interrupt=()=>{},interrupted=new Promise(resolve=>{interrupt=()=>resolve("interrupted")}),view=new AttachedTui(ui,finish),leaving=!1,stop=exitCode=>{leaving&&(restore(),process.exit(exitCode)),leaving=!0,finish(),interrupt()},onSigterm=()=>stop(143),onSigint=()=>stop(130);process.on("SIGTERM",onSigterm),process.on("SIGINT",onSigint),ui.addChild(view),ui instanceof TuiAltScreen&&ui.setLayoutRoot(view.layoutRoot),ui.setFocus(view),ui.start();try{await Promise.race([view.connect(options.address,options.session).then(()=>"connected"),interrupted])==="connected"&&await done}finally{leaving=!0;try{restore()}finally{try{await view.close()}finally{process.off("SIGTERM",onSigterm),process.off("SIGINT",onSigint),process.off("uncaughtException",crash),process.off("unhandledRejection",crash)}}}}export{runAttachedTui};
@@ -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-CU6HUYL7.js";import"./chunk-GTJJ73DE.js";import"./chunk-SOMFLLPD.js";import"./chunk-26UBFF6N.js";import{resolveCliMainPath}from"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-U3VOXCGP.js";import"./chunk-JJYN347Z.js";import"./chunk-NDI6N4NJ.js";import"./chunk-R7J5TEYK.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{runtimeExecArgv}from"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-44BJPS5I.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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-WAGFTIT4.js";import"./chunk-GTJJ73DE.js";import"./chunk-SOMFLLPD.js";import"./chunk-26UBFF6N.js";import{resolveCliMainPath}from"./chunk-5HMYIYQB.js";import"./chunk-OSNR3IRD.js";import"./chunk-UCXBDE6R.js";import"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import"./chunk-SF4MQDKZ.js";import"./chunk-U3VOXCGP.js";import"./chunk-ZJUL5ODW.js";import"./chunk-7CXLNKEH.js";import"./chunk-R7J5TEYK.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{runtimeExecArgv}from"./chunk-LJFQYCFH.js";import"./chunk-K3GAGIPX.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,getAgentDir,isBunBinary}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-44BJPS5I.js";import"./chunk-O5RYI3IW.js";import"./chunk-RFFMEA4B.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
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,presenterContextReply,refusal,sessionRuntimeView,socketSink,startMcpPresenterControl}from"./chunk-6FE42M54.js";import{CONNECTION_ROLE_FIXED,ConnectionRoles,MAX_RPC_MESSAGE_CHARACTERS,TerminalSealedSecrets,WakeScheduler,admitExternalMessage,admitExternalMessageFieldError,answerGetEntries,answeredUiRequestId,availableModelsData,buildRpcSessionState,getSnapshot,interruptRunningTurn,onProcessContinue,remoteOriginDeclaration,rpcCommandShapeError,runAbort,runGetEffectStatus,sessionUiAnswerLedger,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-KKB3K5CV.js";import"./chunk-WRBOKYPS.js";import"./chunk-XI6THO4F.js";import"./chunk-WMDJMN5W.js";import"./chunk-VD7AKTGP.js";import"./chunk-TQHNFP77.js";import"./chunk-HKCFMDJN.js";import"./chunk-MOVB6H22.js";import{ENTRIES_TAIL_CAPABILITY,INTERACTIVE_USER_CAPABILITY,OBSERVE_READS_CAPABILITY,SESSION_STATUS_CAPABILITY,TUI_OBSERVER_CAPABILITY,describeRpcMethodClasses,engineBuildIdentity,gcHostEndpoints}from"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import{tuiSocketName}from"./chunk-E5O4SP5I.js";import"./chunk-7WYJAYHH.js";import{acquireHostEnsureLock,thisProcessStartTime,writeHostRegistration}from"./chunk-UCXBDE6R.js";import{createDaemonDirectories,createHostDaemonPaths}from"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-NJ43NBSP.js";import"./chunk-NDI6N4NJ.js";import"./chunk-SFACYIB6.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-IREUIMFE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-5XHOHZIR.js";import{authenticateSocket,createSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{VERSION}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm3}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions,presenters){this.writer=new SessionEventWriter(()=>{}),this.roles=new ConnectionRoles,this.receipts=new Map,this.attached=new Set,this.session=session,this.presenters=presenters,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),this.presenters?.opened(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.roles.release(key),this.presenters?.closed(key),this.writer.unregisterConnection(key)}detach(connection){let key=keyOf(connection);return this.attached.delete(key)?(this.presenters?.detach(key),this.writer.detachConnectionFromSession(key,this.handle),this.writer.status.publish(this.handle,"detach","client"),!0):!1}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.presenters?.attach(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{realpathSync}from"node:fs";import{resolve}from"node:path";import{randomUUID}from"node:crypto";function idOf(command){return typeof command.id=="string"?command.id:void 0}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}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","chainCount"];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,fingerprint=JSON.stringify([command.type,message,deliverAs,whenIdle??null]),prior=clientMessageId===void 0?void 0:context.attachments.receipts.get(clientMessageId);if(prior!==void 0)return prior.fingerprint!==fingerprint?refusal(id,command.type,"client_message_id_conflict",{reason:`clientMessageId ${clientMessageId} was already used for different input`,action:"send new input with a new clientMessageId"}):answered(id,command.type,{disposition:prior.disposition,clientMessageId,replayed:!0,duplicate:!0,admission:prior.admission});let 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},admitted=disposition=>{if(clientMessageId===void 0)return answered(id,command.type,{disposition});let receipt={fingerprint,disposition,admission:{clientMessageId,durableSessionId:context.session.sessionId,disposition}};return context.attachments.receipts.set(clientMessageId,receipt),answered(id,command.type,{disposition,clientMessageId,admission:receipt.admission})};switch(result.kind){case"started":return admitted("started");case"steered":case"queued":return admitted("queued");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"})}}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(resolveSocketTransportAddress(socketPath,process.platform,secret),()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),process.platform!=="win32"&&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()))}function setClientInfo(attachments,connection,command){let key=keyOf(connection),origin=remoteOriginDeclaration(command.remoteOrigin,declared=>attachments.roles.acceptsOrigin(key,declared));if("refusal"in origin)return failure(command.id,"set_client_info",origin.refusal);let capabilities=command.capabilities;if(capabilities!==void 0){if(!Array.isArray(capabilities)||!capabilities.every(entry=>typeof entry=="string"))return failure(command.id,"set_client_info","capabilities must be an array of strings");if(attachments.roles.declare(key,capabilities)!=="declared")return failure(command.id,"set_client_info",CONNECTION_ROLE_FIXED);attachments.presenters?.declare(key,capabilities)}return origin.origin!==void 0&&attachments.roles.declareOrigin(key,origin.origin),success(command.id,"set_client_info")}function admitTerminalDelivery(session,attachments,connection,command){let key=keyOf(connection),answer2=admitExternalMessage(session,command,{origin:attachments.roles.originOf(key),connectionOrigin:attachments.roles.isDelegated(key)?"delegated":"local"}),{id}=command;if(answer2.ok)return success(id,command.type,answer2.data);let{refusal:refusal2}=answer2;return{...failure(id,command.type,refusal2.message),errorCode:refusal2.errorCode,..."errorData"in refusal2&&refusal2.errorData!==void 0?{errorData:refusal2.errorData}:{}}}import{rm}from"node:fs/promises";var TERMINAL_PRESENTER_COMMANDS=["mcp_presenter_context","mcp_form_presented","mcp_form_response","mcp_form_sync","mcp_presenter_secret_answer"];async function startTerminalPresenters(presenter){let surface=new TerminalPresenterSurface(presenter.local),started=await startMcpPresenterControl(surface,{enforcement:!0,account:presenter.account});return{surface,dispose:async()=>{started?.control.dispose(),started?.dir&&await rm(started.dir,{recursive:!0,force:!0})}}}function presents(capabilities){return capabilities.includes("interactive_user")&&capabilities.includes("mcp_form_presenter_v1")}function writePrivate(transport,record){try{return transport.writeRaw(serializeJsonLine(record)),!0}catch{return!1}}var TerminalPresenterSurface=class{constructor(local){this.sharedAuthority=!0,this.peers=new Map,this.local=local,this.authority=local.authority,this.binding=local.binding,this.sessionId=local.sessionId}attachSealedSecrets(source){let sealed=new TerminalSealedSecrets(source,this.sessionId,this.local.admit);return this.local.sealed=sealed,()=>{this.local.sealed===sealed&&(this.local.sealed=void 0),sealed.dispose()}}getMcpFormBinding(sessionId){return sessionId===this.sessionId?this.binding:void 0}findMcpPresenterConnection(nonce){for(let peer of this.peers.values())if(peer.sender?.nonce===nonce)return peer.sender}getConnectionCapabilities(id){return this.peers.get(id)?.capabilities}advertiseMcpPresenterControl(path){this.controlEndpoint=path}withdrawMcpPresenterControl(path){this.controlEndpoint===path&&(this.controlEndpoint=void 0)}opened(id,transport){this.peers.set(id,{transport,capabilities:[],attached:!1})}declare(id,capabilities){let peer=this.peers.get(id);if(peer){if(peer.capabilities=[...capabilities],!presents(capabilities)){peer.sender&&this.authority.withdraw(peer.sender);return}if(!peer.sender){let sender=this.authority.connect(id,frame=>this.peers.get(id)!==peer||!writePrivate(peer.transport,frame)?(this.authority.detach(sender),!1):(peer.transport.waitForBackpressure().catch(()=>this.authority.detach(sender)),!0));peer.sender=sender}peer.attached&&this.authority.attach(peer.sender,this.binding)}}attach(id){let peer=this.peers.get(id);peer&&(peer.attached=!0,peer.sender&&this.authority.attach(peer.sender,this.binding))}detach(id){let peer=this.peers.get(id);peer&&(peer.attached=!1,peer.sender&&this.authority.detach(peer.sender,this.binding))}closed(id){let sender=this.peers.get(id)?.sender;this.peers.delete(id),sender&&this.authority.detach(sender)}receive(id,frame){let peer=this.peers.get(id);if(!peer)return;if(frame.type==="mcp_presenter_secret_answer"){let lineId=typeof frame.id=="string"?{id:frame.id}:{};(this.local.sealed?.receive(id,frame)??Promise.resolve({error:"secret_answer_refused"})).catch(()=>({error:"secret_answer_refused"})).then(reply2=>{!writePrivate(peer.transport,{type:"mcp_presenter_secret_reply",...lineId,...reply2})&&peer.sender&&this.authority.detach(peer.sender)});return}let sender=peer.sender,reply=frame.type==="mcp_presenter_context"?presenterContextReply(this.authority,sender,frame,this.controlEndpoint):sender?this.authority.receive(sender,frame):{error:"presenter_not_authorized"},answer2={type:"mcp_form_reply",...typeof frame.id=="string"?{id:frame.id}:{},...reply};!writePrivate(peer.transport,answer2)&&sender&&this.authority.detach(sender)}};var TUI_RPC_COMMANDS=["open_session","park_session","claim_session","get_snapshot","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","admit_external_message","get_effect_status","set_client_info","attach_session","release_attachment","abort",...TERMINAL_PRESENTER_COMMANDS],STOP_REQUIRES_INTERACTIVE_CLIENT="stop_requires_interactive_client: declare interactive_user with set_client_info first";async function runTuiRpcCommand(context,connection,command){switch(command.type){case"get_snapshot":{let{attachments,session}=context;if(command.sessionId!==void 0&&command.sessionId!==attachments.handle)return{id:command.id,type:"response",command:command.type,success:!1,error:"unknown_session"};let snapshot=getSnapshot(session,{tail:command.tail,maxBytes:command.maxBytes},{enqueue:markerId=>attachments.run(connection,()=>attachments.writer.enqueue(attachments.handle,{type:"snapshot_marker",markerId}))});return"error"in snapshot?{id:command.id,type:"response",command:command.type,success:!1,error:snapshot.error}:answered(idOf(command),command.type,snapshot.data)}case"open_session":return openSession(context,connection,command);case"park_session":case"claim_session":return failure(idOf(command),command.type,"multi_session_disabled");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"admit_external_message":{let fieldError=admitExternalMessageFieldError(command,MAX_RPC_MESSAGE_CHARACTERS);return fieldError!==void 0?failure(idOf(command),command.type,fieldError):admitTerminalDelivery(context.session,context.attachments,connection,command)}case"set_client_info":return setClientInfo(context.attachments,connection,command);case"attach_session":return attachSession(context,connection,command);case"release_attachment":return releaseAttachment(context,connection,command);case"abort":return abort(context,connection,command);case"mcp_presenter_context":case"mcp_form_presented":case"mcp_form_response":case"mcp_form_sync":case"mcp_presenter_secret_answer":return context.attachments.presenters?(context.attachments.presenters.receive(keyOf(connection),command),null):void 0;case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}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 attachSession(context,connection,command){let{session,attachments}=context,id=idOf(command);if(command.sessionId!==attachments.handle)return refusal(id,"attach_session","unknown_session",{reason:"this terminal hosts one session and the request names another",action:"attach with this terminal's sessionId from list_sessions"});let instanceMatches=command.expectedHostInstance===void 0||command.expectedHostInstance===context.instanceId;return command.durableSessionId!==session.sessionId||!instanceMatches?refusal(id,"attach_session","session_identity_mismatch",{reason:"durableSessionId or expectedHostInstance does not name this terminal's session",action:"read list_sessions and get_protocol_info again, then attach with their ids"}):command.takeover===!0?refusal(id,"attach_session","takeover_unsupported",{reason:"only a headless engine with a takeover ledger takes sessions over",action:"attach without takeover"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"attach_session",success:!0,data:{sessionId:attachments.handle,attached:!0}})}),null)}function releaseAttachment(context,connection,command){return command.sessionId!==context.attachments.handle||!context.attachments.detach(connection)?refusal(idOf(command),"release_attachment","session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session or open_session"}):success(command.id,"release_attachment",{deferred:!1})}async function abort(context,connection,command){let key=keyOf(connection);if(command.intent==="stop"&&!context.attachments.roles.has(key,INTERACTIVE_USER_CAPABILITY))return failure(command.id,"abort",STOP_REQUIRES_INTERACTIVE_CLIENT);let{session}=context;return runAbort({session,by:{connectionId:key},sessionId:context.attachments.handle},command,()=>(command.intent==="stop"?session.stop():session.abort()).catch(cause=>{connection.send({type:"rpc_error",error:String(cause)})}))}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 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)}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","get_entries","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,TUI_OBSERVER_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,"snapshot_cursor","ui_answer_ledger"],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS,method_classes:describeRpcMethodClasses()})}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"get_entries":return answerGetEntries(session,command);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,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,retain_on_disconnect:!0}}function answerQuestion(context,command){if(command.secret===!0)return failure(command.id,"extension_ui_response","invalid_secret_response");let{surface,session}=context,ledger=sessionUiAnswerLedger(session),answerId=command.answerId;if(answerId!==void 0&&(typeof answerId!="string"||answerId.length<1||answerId.length>256))return failure(command.id,"extension_ui_response","invalid_answer_id");let frameId=command.id,requestId=answeredUiRequestId(command),receipt=requestId===void 0||answerId===void 0?void 0:ledger.lookup(requestId,answerId);if(receipt==="replay")return{...success(frameId,"extension_ui_response"),disposition:receipt};if(receipt==="already_answered")return{...failure(frameId,"extension_ui_response","already_answered"),disposition:receipt};let request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return{...failure(frameId,"extension_ui_response",answerId===void 0?"unknown_request":"unknown_extension_ui_request"),disposition:"unknown"};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"):(ledger.record(requestId,answerId),{...success(frameId,"extension_ui_response"),disposition:"applied"})}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 as rm2}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(process.platform==="win32"||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 rm2(entry.socket,{force:!0}),await rm2(socketSecretPath(entry.socket),{force:!0}),await rm2(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(`
2
+ import{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,presenterContextReply,refusal,sessionRuntimeView,socketSink,startMcpPresenterControl}from"./chunk-VGHGM5PR.js";import{CONNECTION_ROLE_FIXED,ConnectionRoles,MAX_RPC_MESSAGE_CHARACTERS,TerminalSealedSecrets,WakeScheduler,admitExternalMessage,admitExternalMessageFieldError,answerGetEntries,answeredUiRequestId,availableModelsData,buildRpcSessionState,getSnapshot,interruptRunningTurn,onProcessContinue,remoteOriginDeclaration,rpcCommandShapeError,runAbort,runGetEffectStatus,sessionUiAnswerLedger,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-Q4RJ4WLE.js";import"./chunk-75O3CWR5.js";import"./chunk-XI6THO4F.js";import"./chunk-WMDJMN5W.js";import"./chunk-VD7AKTGP.js";import"./chunk-TQHNFP77.js";import"./chunk-HKCFMDJN.js";import"./chunk-MOVB6H22.js";import{ENTRIES_TAIL_CAPABILITY,INTERACTIVE_USER_CAPABILITY,OBSERVE_READS_CAPABILITY,SESSION_STATUS_CAPABILITY,TUI_OBSERVER_CAPABILITY,describeRpcMethodClasses,engineBuildIdentity,gcHostEndpoints}from"./chunk-IJXKHJYR.js";import"./chunk-QMRJYMNH.js";import"./chunk-DZQA5LVN.js";import"./chunk-IEY2SL46.js";import"./chunk-26UBFF6N.js";import"./chunk-4JMGWVRH.js";import{tuiSocketName}from"./chunk-E5O4SP5I.js";import"./chunk-7WYJAYHH.js";import{acquireHostEnsureLock,thisProcessStartTime,writeHostRegistration}from"./chunk-UCXBDE6R.js";import{createDaemonDirectories,createHostDaemonPaths}from"./chunk-YI6KRJDC.js";import"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-NJ43NBSP.js";import"./chunk-7CXLNKEH.js";import"./chunk-IK3S2NDB.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-PWTXZXHH.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-UAOOH2V7.js";import"./chunk-WDTJ6JKE.js";import"./chunk-OH5TKHW7.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-5XHOHZIR.js";import{authenticateSocket,createSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{VERSION}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm3}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions,presenters){this.writer=new SessionEventWriter(()=>{}),this.roles=new ConnectionRoles,this.receipts=new Map,this.attached=new Set,this.session=session,this.presenters=presenters,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),this.presenters?.opened(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.roles.release(key),this.presenters?.closed(key),this.writer.unregisterConnection(key)}detach(connection){let key=keyOf(connection);return this.attached.delete(key)?(this.presenters?.detach(key),this.writer.detachConnectionFromSession(key,this.handle),this.writer.status.publish(this.handle,"detach","client"),!0):!1}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.presenters?.attach(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{realpathSync}from"node:fs";import{resolve}from"node:path";import{randomUUID}from"node:crypto";function idOf(command){return typeof command.id=="string"?command.id:void 0}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}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","chainCount"];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,fingerprint=JSON.stringify([command.type,message,deliverAs,whenIdle??null]),prior=clientMessageId===void 0?void 0:context.attachments.receipts.get(clientMessageId);if(prior!==void 0)return prior.fingerprint!==fingerprint?refusal(id,command.type,"client_message_id_conflict",{reason:`clientMessageId ${clientMessageId} was already used for different input`,action:"send new input with a new clientMessageId"}):answered(id,command.type,{disposition:prior.disposition,clientMessageId,replayed:!0,duplicate:!0,admission:prior.admission});let 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},admitted=disposition=>{if(clientMessageId===void 0)return answered(id,command.type,{disposition});let receipt={fingerprint,disposition,admission:{clientMessageId,durableSessionId:context.session.sessionId,disposition}};return context.attachments.receipts.set(clientMessageId,receipt),answered(id,command.type,{disposition,clientMessageId,admission:receipt.admission})};switch(result.kind){case"started":return admitted("started");case"steered":case"queued":return admitted("queued");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"})}}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(resolveSocketTransportAddress(socketPath,process.platform,secret),()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),process.platform!=="win32"&&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()))}function setClientInfo(attachments,connection,command){let key=keyOf(connection),origin=remoteOriginDeclaration(command.remoteOrigin,declared=>attachments.roles.acceptsOrigin(key,declared));if("refusal"in origin)return failure(command.id,"set_client_info",origin.refusal);let capabilities=command.capabilities;if(capabilities!==void 0){if(!Array.isArray(capabilities)||!capabilities.every(entry=>typeof entry=="string"))return failure(command.id,"set_client_info","capabilities must be an array of strings");if(attachments.roles.declare(key,capabilities)!=="declared")return failure(command.id,"set_client_info",CONNECTION_ROLE_FIXED);attachments.presenters?.declare(key,capabilities)}return origin.origin!==void 0&&attachments.roles.declareOrigin(key,origin.origin),success(command.id,"set_client_info")}function admitTerminalDelivery(session,attachments,connection,command){let key=keyOf(connection),answer2=admitExternalMessage(session,command,{origin:attachments.roles.originOf(key),connectionOrigin:attachments.roles.isDelegated(key)?"delegated":"local"}),{id}=command;if(answer2.ok)return success(id,command.type,answer2.data);let{refusal:refusal2}=answer2;return{...failure(id,command.type,refusal2.message),errorCode:refusal2.errorCode,..."errorData"in refusal2&&refusal2.errorData!==void 0?{errorData:refusal2.errorData}:{}}}import{rm}from"node:fs/promises";var TERMINAL_PRESENTER_COMMANDS=["mcp_presenter_context","mcp_form_presented","mcp_form_response","mcp_form_sync","mcp_presenter_secret_answer"];async function startTerminalPresenters(presenter){let surface=new TerminalPresenterSurface(presenter.local),started=await startMcpPresenterControl(surface,{enforcement:!0,account:presenter.account});return{surface,dispose:async()=>{started?.control.dispose(),started?.dir&&await rm(started.dir,{recursive:!0,force:!0})}}}function presents(capabilities){return capabilities.includes("interactive_user")&&capabilities.includes("mcp_form_presenter_v1")}function writePrivate(transport,record){try{return transport.writeRaw(serializeJsonLine(record)),!0}catch{return!1}}var TerminalPresenterSurface=class{constructor(local){this.sharedAuthority=!0,this.peers=new Map,this.local=local,this.authority=local.authority,this.binding=local.binding,this.sessionId=local.sessionId}attachSealedSecrets(source){let sealed=new TerminalSealedSecrets(source,this.sessionId,this.local.admit);return this.local.sealed=sealed,()=>{this.local.sealed===sealed&&(this.local.sealed=void 0),sealed.dispose()}}getMcpFormBinding(sessionId){return sessionId===this.sessionId?this.binding:void 0}findMcpPresenterConnection(nonce){for(let peer of this.peers.values())if(peer.sender?.nonce===nonce)return peer.sender}getConnectionCapabilities(id){return this.peers.get(id)?.capabilities}advertiseMcpPresenterControl(path){this.controlEndpoint=path}withdrawMcpPresenterControl(path){this.controlEndpoint===path&&(this.controlEndpoint=void 0)}opened(id,transport){this.peers.set(id,{transport,capabilities:[],attached:!1})}declare(id,capabilities){let peer=this.peers.get(id);if(peer){if(peer.capabilities=[...capabilities],!presents(capabilities)){peer.sender&&this.authority.withdraw(peer.sender);return}if(!peer.sender){let sender=this.authority.connect(id,frame=>this.peers.get(id)!==peer||!writePrivate(peer.transport,frame)?(this.authority.detach(sender),!1):(peer.transport.waitForBackpressure().catch(()=>this.authority.detach(sender)),!0));peer.sender=sender}peer.attached&&this.authority.attach(peer.sender,this.binding)}}attach(id){let peer=this.peers.get(id);peer&&(peer.attached=!0,peer.sender&&this.authority.attach(peer.sender,this.binding))}detach(id){let peer=this.peers.get(id);peer&&(peer.attached=!1,peer.sender&&this.authority.detach(peer.sender,this.binding))}closed(id){let sender=this.peers.get(id)?.sender;this.peers.delete(id),sender&&this.authority.detach(sender)}receive(id,frame){let peer=this.peers.get(id);if(!peer)return;if(frame.type==="mcp_presenter_secret_answer"){let lineId=typeof frame.id=="string"?{id:frame.id}:{};(this.local.sealed?.receive(id,frame)??Promise.resolve({error:"secret_answer_refused"})).catch(()=>({error:"secret_answer_refused"})).then(reply2=>{!writePrivate(peer.transport,{type:"mcp_presenter_secret_reply",...lineId,...reply2})&&peer.sender&&this.authority.detach(peer.sender)});return}let sender=peer.sender,reply=frame.type==="mcp_presenter_context"?presenterContextReply(this.authority,sender,frame,this.controlEndpoint):sender?this.authority.receive(sender,frame):{error:"presenter_not_authorized"},answer2={type:"mcp_form_reply",...typeof frame.id=="string"?{id:frame.id}:{},...reply};!writePrivate(peer.transport,answer2)&&sender&&this.authority.detach(sender)}};var TUI_RPC_COMMANDS=["open_session","park_session","claim_session","get_snapshot","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","admit_external_message","get_effect_status","set_client_info","attach_session","release_attachment","abort",...TERMINAL_PRESENTER_COMMANDS],STOP_REQUIRES_INTERACTIVE_CLIENT="stop_requires_interactive_client: declare interactive_user with set_client_info first";async function runTuiRpcCommand(context,connection,command){switch(command.type){case"get_snapshot":{let{attachments,session}=context;if(command.sessionId!==void 0&&command.sessionId!==attachments.handle)return{id:command.id,type:"response",command:command.type,success:!1,error:"unknown_session"};let snapshot=getSnapshot(session,{tail:command.tail,maxBytes:command.maxBytes},{enqueue:markerId=>attachments.run(connection,()=>attachments.writer.enqueue(attachments.handle,{type:"snapshot_marker",markerId}))});return"error"in snapshot?{id:command.id,type:"response",command:command.type,success:!1,error:snapshot.error}:answered(idOf(command),command.type,snapshot.data)}case"open_session":return openSession(context,connection,command);case"park_session":case"claim_session":return failure(idOf(command),command.type,"multi_session_disabled");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"admit_external_message":{let fieldError=admitExternalMessageFieldError(command,MAX_RPC_MESSAGE_CHARACTERS);return fieldError!==void 0?failure(idOf(command),command.type,fieldError):admitTerminalDelivery(context.session,context.attachments,connection,command)}case"set_client_info":return setClientInfo(context.attachments,connection,command);case"attach_session":return attachSession(context,connection,command);case"release_attachment":return releaseAttachment(context,connection,command);case"abort":return abort(context,connection,command);case"mcp_presenter_context":case"mcp_form_presented":case"mcp_form_response":case"mcp_form_sync":case"mcp_presenter_secret_answer":return context.attachments.presenters?(context.attachments.presenters.receive(keyOf(connection),command),null):void 0;case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}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 attachSession(context,connection,command){let{session,attachments}=context,id=idOf(command);if(command.sessionId!==attachments.handle)return refusal(id,"attach_session","unknown_session",{reason:"this terminal hosts one session and the request names another",action:"attach with this terminal's sessionId from list_sessions"});let instanceMatches=command.expectedHostInstance===void 0||command.expectedHostInstance===context.instanceId;return command.durableSessionId!==session.sessionId||!instanceMatches?refusal(id,"attach_session","session_identity_mismatch",{reason:"durableSessionId or expectedHostInstance does not name this terminal's session",action:"read list_sessions and get_protocol_info again, then attach with their ids"}):command.takeover===!0?refusal(id,"attach_session","takeover_unsupported",{reason:"only a headless engine with a takeover ledger takes sessions over",action:"attach without takeover"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"attach_session",success:!0,data:{sessionId:attachments.handle,attached:!0}})}),null)}function releaseAttachment(context,connection,command){return command.sessionId!==context.attachments.handle||!context.attachments.detach(connection)?refusal(idOf(command),"release_attachment","session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session or open_session"}):success(command.id,"release_attachment",{deferred:!1})}async function abort(context,connection,command){let key=keyOf(connection);if(command.intent==="stop"&&!context.attachments.roles.has(key,INTERACTIVE_USER_CAPABILITY))return failure(command.id,"abort",STOP_REQUIRES_INTERACTIVE_CLIENT);let{session}=context;return runAbort({session,by:{connectionId:key},sessionId:context.attachments.handle},command,()=>(command.intent==="stop"?session.stop():session.abort()).catch(cause=>{connection.send({type:"rpc_error",error:String(cause)})}))}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 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)}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","get_entries","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,TUI_OBSERVER_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,"snapshot_cursor","ui_answer_ledger"],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS,method_classes:describeRpcMethodClasses()})}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"get_entries":return answerGetEntries(session,command);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,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,retain_on_disconnect:!0}}function answerQuestion(context,command){if(command.secret===!0)return failure(command.id,"extension_ui_response","invalid_secret_response");let{surface,session}=context,ledger=sessionUiAnswerLedger(session),answerId=command.answerId;if(answerId!==void 0&&(typeof answerId!="string"||answerId.length<1||answerId.length>256))return failure(command.id,"extension_ui_response","invalid_answer_id");let frameId=command.id,requestId=answeredUiRequestId(command),receipt=requestId===void 0||answerId===void 0?void 0:ledger.lookup(requestId,answerId);if(receipt==="replay")return{...success(frameId,"extension_ui_response"),disposition:receipt};if(receipt==="already_answered")return{...failure(frameId,"extension_ui_response","already_answered"),disposition:receipt};let request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return{...failure(frameId,"extension_ui_response",answerId===void 0?"unknown_request":"unknown_extension_ui_request"),disposition:"unknown"};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"):(ledger.record(requestId,answerId),{...success(frameId,"extension_ui_response"),disposition:"applied"})}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 as rm2}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(process.platform==="win32"||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 rm2(entry.socket,{force:!0}),await rm2(socketSecretPath(entry.socket),{force:!0}),await rm2(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
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(()=>rm3(socket,{force:!0}),()=>rm3(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),presenters=context.mcpPresenter?await startTerminalPresenters(context.mcpPresenter):void 0;presenters&&cleanups.push(presenters.dispose);let attachments=new ControlAttachments(session,()=>surface.pendingQuestionIds().length,presenters?.surface);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)}`))}),presenters?{...endpoint,dispose:()=>endpoint.dispose().finally(presenters.dispose)}:endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};