@code-yeongyu/senpi 2026.9.29-5 → 2026.9.30

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 (140) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/bundle/chunks/{anthropic-messages-HEVKB3PL.js → anthropic-messages-ADSIWAJ5.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-32AFWZEH.js → app-server-command-B3ZYM2WN.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-2WAKOPNA.js → chunk-4P4DUW66.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-7RVWDN5Z.js → chunk-6GV3L3GZ.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-OUG6SDT7.js → chunk-6JZQLUAJ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-MJQWYN2W.js → chunk-7MKMDWHC.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-XBGO2JZD.js → chunk-A7AQSA6R.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-BJICJY47.js → chunk-DVVROXLZ.js} +1 -1
  10. package/dist/bundle/chunks/chunk-EIG6K5U3.js +6 -0
  11. package/dist/bundle/chunks/chunk-FAWC2EIR.js +2 -0
  12. package/dist/bundle/chunks/{chunk-WCAKUCN3.js → chunk-FNCILR4E.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-XHEMQA2T.js → chunk-HPESFBMB.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-BBNWT72C.js → chunk-HVBFDRP4.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-63QHOG5A.js → chunk-I77ENHCQ.js} +81 -74
  16. package/dist/bundle/chunks/{chunk-UMLU3I2G.js → chunk-ITXF6FAM.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-77AUUH3Z.js → chunk-IXONH7ML.js} +2 -2
  18. package/dist/bundle/chunks/{chunk-K2SHQNAA.js → chunk-JX2CSKLG.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-4VWWEMCJ.js → chunk-JXZ5LDJP.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-VLTMFAWQ.js → chunk-KWI3KUF2.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-7CQX3QFV.js → chunk-L4QGZJKQ.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-AGVPQLIU.js → chunk-MDXUQDGF.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-2N3BZ5DV.js → chunk-OOA6OL42.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-2POUJCWM.js → chunk-OVGH7VP3.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-ZDNR3YVJ.js → chunk-RMVQ5YRX.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-SH6VUPE4.js → chunk-T5MOQDGL.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CNYWF72S.js → chunk-VKECIIYV.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-U7BNOE23.js → chunk-VNYUGCC7.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-ZPMJIPQC.js → chunk-YSNNL5HU.js} +1 -1
  30. package/dist/bundle/chunks/cli-main-F6WNYPUT.js +3 -0
  31. package/dist/bundle/chunks/{help-fast-path-ZUNFOE53.js → help-fast-path-34Z6I2PH.js} +1 -1
  32. package/dist/bundle/chunks/{host-command-V2LDNNXB.js → host-command-PUOIPEBI.js} +1 -1
  33. package/dist/bundle/chunks/{host-lifecycle-PFLJRXEN.js → host-lifecycle-4VJUHV5U.js} +1 -1
  34. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  35. package/dist/bundle/chunks/{interactive-mode-J6KGDRR7.js → interactive-mode-KM454JPC.js} +1 -1
  36. package/dist/bundle/chunks/{list-tips-ASETMEFS.js → list-tips-GWRRD5UC.js} +1 -1
  37. package/dist/bundle/chunks/{multi-session-host-IBVJ3WN7.js → multi-session-host-ZFT6RM2S.js} +2 -2
  38. package/dist/bundle/chunks/{native-loader-WM7NDPEO.js → native-loader-HW7GQYPY.js} +1 -1
  39. package/dist/bundle/chunks/{openai-completions-SA2UJW7Q.js → openai-completions-32RTG3Q4.js} +1 -1
  40. package/dist/bundle/chunks/{package-manager-cli-JJ5R7UWV.js → package-manager-cli-LNQOWI3A.js} +1 -1
  41. package/dist/bundle/chunks/{rg-engine-G2YTYL2T.js → rg-engine-LWZA7TRH.js} +1 -1
  42. package/dist/bundle/chunks/{rotation-stream-EX7PWQ4S.js → rotation-stream-DIKK7U57.js} +1 -1
  43. package/dist/bundle/chunks/{rpc-mode-ITND2BVC.js → rpc-mode-H7QGQI4P.js} +1 -1
  44. package/dist/bundle/chunks/{schedule-command-D6JNRP3D.js → schedule-command-BUFJOM5L.js} +1 -1
  45. package/dist/bundle/chunks/session-control-endpoint-QIIA6MFR.js +3 -0
  46. package/dist/bundle/chunks/{session-picker-K5FIKV6C.js → session-picker-P53MTWTS.js} +1 -1
  47. package/dist/bundle/chunks/session-worker.js +110 -103
  48. package/dist/bundle/chunks/{state-store-IIQL55GC.js → state-store-QGLITAI4.js} +1 -1
  49. package/dist/bundle/cli.js +2 -2
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/bundle/runtime-manifest.json +1 -1
  53. package/dist/cli.js +1 -1
  54. package/dist/core/dynamic-prompt/build.d.ts +4 -3
  55. package/dist/core/dynamic-prompt/build.js +4 -2
  56. package/dist/core/dynamic-prompt/handoff.d.ts +9 -1
  57. package/dist/core/dynamic-prompt/handoff.js +11 -1
  58. package/dist/core/dynamic-prompt/intent-gate.js +1 -1
  59. package/dist/core/dynamic-prompt/style.js +4 -2
  60. package/dist/core/dynamic-prompt/types.d.ts +7 -1
  61. package/dist/core/dynamic-prompt/types.js +3 -1
  62. package/dist/core/dynamic-prompt/verification.d.ts +1 -1
  63. package/dist/core/dynamic-prompt/verification.js +2 -1
  64. package/dist/core/extensions/builtin/anthropic-subscription/stream-protocol.d.ts +1 -1
  65. package/dist/core/extensions/builtin/anthropic-subscription/tools.d.ts +9 -2
  66. package/dist/core/extensions/builtin/anthropic-subscription/tools.js +9 -4
  67. package/dist/core/extensions/builtin/ask-user/resume.js +20 -9
  68. package/dist/core/extensions/builtin/ask-user/tool.d.ts +9 -0
  69. package/dist/core/extensions/builtin/ask-user/tool.js +1 -1
  70. package/dist/core/extensions/builtin/cache-keepalive/index.js +17 -4
  71. package/dist/core/extensions/builtin/chat-reply-scrub/index.d.ts +16 -0
  72. package/dist/core/extensions/builtin/chat-reply-scrub/index.js +39 -0
  73. package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.d.ts +7 -0
  74. package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.js +125 -0
  75. package/dist/core/extensions/builtin/index.js +3 -0
  76. package/dist/core/extensions/builtin/permission-system/cli.js +1 -0
  77. package/dist/core/extensions/builtin/permission-system/config.d.ts +1 -0
  78. package/dist/core/extensions/builtin/permission-system/config.js +10 -0
  79. package/dist/core/extensions/builtin/permission-system/index.js +2 -2
  80. package/dist/core/extensions/builtin/permission-system/settings.js +1 -1
  81. package/dist/core/extensions/builtin/permission-system/types.d.ts +1 -1
  82. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +5 -5
  83. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +6 -6
  84. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +4 -4
  85. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +4 -4
  86. package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +4 -4
  87. package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +9 -6
  88. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +10 -7
  89. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +15 -6
  90. package/dist/core/extensions/builtin/prompt-preset/gpt-surface.d.ts +2 -2
  91. package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +4 -4
  92. package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +4 -4
  93. package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +3 -3
  94. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.js +1 -1
  95. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js +1 -1
  96. package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +6 -6
  97. package/dist/core/extensions/builtin/recommended-models/index.d.ts +1 -1
  98. package/dist/core/extensions/builtin/recommended-models/index.js +1 -1
  99. package/dist/core/extensions/builtin/todotools/first-turn.d.ts +6 -4
  100. package/dist/core/extensions/builtin/todotools/first-turn.js +17 -5
  101. package/dist/core/extensions/builtin/todotools/todo-ask.d.ts +1 -0
  102. package/dist/core/extensions/builtin/todotools/todo-ask.js +1 -1
  103. package/dist/core/extensions/builtin/todotools/tools/todo.js +4 -1
  104. package/dist/core/resource-loader.js +7 -3
  105. package/dist/modes/interactive/components/ask-user-async-widget.d.ts +2 -0
  106. package/dist/modes/interactive/components/ask-user-async-widget.js +10 -0
  107. package/dist/modes/interactive/components/ask-user-question-state.js +3 -1
  108. package/dist/modes/interactive/interactive-mode.js +7 -1
  109. package/dist/modes/interactive/session-control-commands.d.ts +2 -1
  110. package/dist/modes/interactive/session-control-commands.js +15 -6
  111. package/dist/modes/rpc/connection-question-bridge.js +5 -5
  112. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  113. package/dist/modes/rpc/custom-capability.js +6 -0
  114. package/dist/modes/rpc/extension-ui-response.d.ts +11 -0
  115. package/dist/modes/rpc/extension-ui-response.js +18 -0
  116. package/dist/modes/rpc/host-lifecycle.d.ts +5 -2
  117. package/dist/modes/rpc/host-lifecycle.js +14 -8
  118. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  119. package/dist/modes/rpc/rpc-input-validation.d.ts +1 -1
  120. package/dist/modes/rpc/rpc-input-validation.js +3 -3
  121. package/dist/modes/rpc/rpc-mode.d.ts +3 -2
  122. package/dist/modes/rpc/rpc-mode.js +3 -2
  123. package/dist/modes/rpc/rpc-types.d.ts +4 -3
  124. package/dist/modes/rpc/session-command-router.js +4 -1
  125. package/dist/runtime-snapshot/enter.d.ts +1 -1
  126. package/dist/runtime-snapshot/enter.js +17 -7
  127. package/dist/runtime-snapshot/file-copier.d.ts +24 -0
  128. package/dist/runtime-snapshot/file-copier.js +76 -0
  129. package/dist/runtime-snapshot/layout.d.ts +8 -4
  130. package/dist/runtime-snapshot/layout.js +137 -70
  131. package/dist/runtime-snapshot/registry.d.ts +7 -0
  132. package/dist/runtime-snapshot/registry.js +63 -1
  133. package/dist/senpi +1 -1
  134. package/docs/providers.md +1 -1
  135. package/docs/rpc.md +34 -11
  136. package/package.json +6 -6
  137. package/dist/bundle/chunks/chunk-AWEAVBCR.js +0 -2
  138. package/dist/bundle/chunks/chunk-YLQTKWEC.js +0 -6
  139. package/dist/bundle/chunks/cli-main-ZPMYM3A3.js +0 -3
  140. package/dist/bundle/chunks/session-control-endpoint-UJJGG4WI.js +0 -3
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{acquireHostEnsureLock,acquireOwnershipSafeLock,anyGenerationLive,endpointKindOfSocket,gcHostEndpoints,hostEnsureLockOptions,hostEnsureLockTarget,listHostEndpoints,socketNeedsHandshake}from"./chunk-CNYWF72S.js";import{CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,hostLaunchProfile}from"./chunk-AWEAVBCR.js";import{DEFAULT_HOST_IDLE_EXIT_MS,INTERNAL_SUPERVISOR_FLAG,OBSERVE_REQUEST_FIELD,readHostCrashRecords,resolveCliMainPath}from"./chunk-MJQWYN2W.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,MAX_SOCKET_PATH_BYTES,ProcessIdentityUnreadableError,claimOwnerIsLive,clearHostRegistration,createDaemonDirectories,createHostDaemonPaths,createSocketSecret,ensureEndpointIdentity,generationBindPath,generationPaths,hostDaemonDirectoryPaths,legacyHostIsLive,parseJson,parseShardSocket,processIsLive,processMatchesPidFile,provenOwner,pruneDeadGenerations,readFileOrUndefined,readGenerationRows,readHostProcessMetrics,readHostRegistration,readHostSettings,readProcessStartTime,readSessionPathClaims,readSocketSecret,releaseGeneration,resolveSocketTransportAddress,sameEndpoint,sendSocketHandshake,shardKey,shardSocketPathForKey,socketSecretPath,statSocketIdentity,waitForStartTime,writeGenerationRecord,writeHostRegistration,writeHostSettings,writeStateFile,writtenByThisProcess}from"./chunk-UMLU3I2G.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-CIRZTP7W.js";import{compareEngineOrdinal,engineBuildIdentity}from"./chunk-AGVPQLIU.js";import{isSessionRuntimeKind}from"./chunk-7CQX3QFV.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-WCAKUCN3.js";import{writeSync}from"node:fs";import{join as join3,resolve as resolve3}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path=>["--extension",path])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR"]);function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}function parseHostProtocolInfo(data){if(!isRecord2(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile},...typeof data.memory_pressure=="boolean"&&{memory_pressure:data.memory_pressure}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord2(value)||typeof value.profile_id!="string"||!isRecord2(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host){super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"its pidfile was written by another process, so this one may not signal it; stop that host explicitly instead";case"legacy_host":return"a host from before the per-socket daemon directory is still running on this endpoint; it is never signalled, and no second host is started beside it";case"host_busy":return"its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id!==host.launch_profile.profile_id)return covers(client.launchProfile,host.launch_profile)?"profile_mismatch_attached":"profile_narrower_attached"}function covers(candidate,running){return candidate===void 0||running===void 0?!1:running.core.extensions.every(extension=>candidate.core.extensions.includes(extension))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,open as open2,readdir,readFile as readFile2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname as dirname3,join as join2}from"node:path";import{createConnection}from"node:net";function holdAttachment(socket){return socket.removeAllListeners("data"),socket.resume(),socket.on("error",()=>socket.destroy()),socket.unref(),{release:()=>socket.destroy()}}var DEFAULT_PROBE_TIMEOUT_MS=1e4,PROBE_REQUEST_ID="ensure-host-probe";function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS)}async function probeProtocolInfo(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function observeProtocolInfo(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},timeoutMs);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function holdProtocolInfo(socketPath,timeoutMs){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!0),info=outcome.answer===void 0?void 0:parseHostProtocolInfo(outcome.answer);if(outcome.kept===void 0)return;let hold=holdAttachment(outcome.kept);if(info!==void 0)return{info,hold};hold.release()}async function probeSocketReachable(socketPath,timeoutMs){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs)).connected}async function probeSessionCount(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs);if(!(!isRecord3(reply)||!Array.isArray(reply.sessions)))return reply.sessions.length}async function requestOnSocket(socketPath,command,timeoutMs){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs)).answer}async function connectAndAsk(socketPath,request,timeoutMs,keep=!1){let secret;if(socketNeedsHandshake(socketPath))try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return{connected:!1,answer:void 0}}return new Promise(resolveProbe=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,connected=!1,finish=value=>{if(!settled){if(settled=!0,clearTimeout(timeout),keep&&value!==void 0&&!socket.destroyed){resolveProbe({connected,answer:value,kept:socket});return}socket.destroy(),resolveProbe({connected,answer:value})}},timeout=setTimeout(()=>finish(),timeoutMs);socket.once("connect",()=>{connected=!0,socket.write(`${JSON.stringify(request)}
2
+ import{acquireHostEnsureLock,acquireOwnershipSafeLock,anyGenerationLive,endpointKindOfSocket,gcHostEndpoints,hostEnsureLockOptions,hostEnsureLockTarget,listHostEndpoints,socketNeedsHandshake}from"./chunk-VKECIIYV.js";import{CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,hostLaunchProfile}from"./chunk-FAWC2EIR.js";import{DEFAULT_HOST_IDLE_EXIT_MS,INTERNAL_SUPERVISOR_FLAG,OBSERVE_REQUEST_FIELD,readHostCrashRecords,resolveCliMainPath}from"./chunk-7MKMDWHC.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,MAX_SOCKET_PATH_BYTES,ProcessIdentityUnreadableError,claimOwnerIsLive,clearHostRegistration,createDaemonDirectories,createHostDaemonPaths,createSocketSecret,ensureEndpointIdentity,generationBindPath,generationPaths,hostDaemonDirectoryPaths,legacyHostIsLive,parseJson,parseShardSocket,processIsLive,processMatchesPidFile,provenOwner,pruneDeadGenerations,readFileOrUndefined,readGenerationRows,readHostProcessMetrics,readHostRegistration,readHostSettings,readProcessStartTime,readSessionPathClaims,readSocketSecret,releaseGeneration,resolveSocketTransportAddress,sameEndpoint,sendSocketHandshake,shardKey,shardSocketPathForKey,socketSecretPath,statSocketIdentity,waitForStartTime,writeGenerationRecord,writeHostRegistration,writeHostSettings,writeStateFile,writtenByThisProcess}from"./chunk-ITXF6FAM.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-CIRZTP7W.js";import{compareEngineOrdinal,engineBuildIdentity}from"./chunk-MDXUQDGF.js";import{isSessionRuntimeKind}from"./chunk-L4QGZJKQ.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-FNCILR4E.js";import{writeSync}from"node:fs";import{join as join3,resolve as resolve3}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path=>["--extension",path])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR"]);function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}function parseHostProtocolInfo(data){if(!isRecord2(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile},...typeof data.memory_pressure=="boolean"&&{memory_pressure:data.memory_pressure}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord2(value)||typeof value.profile_id!="string"||!isRecord2(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host){super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"its pidfile was written by another process, so this one may not signal it; stop that host explicitly instead";case"legacy_host":return"a host from before the per-socket daemon directory is still running on this endpoint; it is never signalled, and no second host is started beside it";case"host_busy":return"its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id!==host.launch_profile.profile_id)return covers(client.launchProfile,host.launch_profile)?"profile_mismatch_attached":"profile_narrower_attached"}function covers(candidate,running){return candidate===void 0||running===void 0?!1:running.core.extensions.every(extension=>candidate.core.extensions.includes(extension))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,open as open2,readdir,readFile as readFile2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname as dirname3,join as join2}from"node:path";import{createConnection}from"node:net";function holdAttachment(socket){return socket.removeAllListeners("data"),socket.resume(),socket.on("error",()=>socket.destroy()),socket.unref(),{release:()=>socket.destroy()}}var DEFAULT_PROBE_TIMEOUT_MS=1e4,PROBE_REQUEST_ID="ensure-host-probe";function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS)}async function probeProtocolInfo(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function observeProtocolInfo(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},timeoutMs);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function holdProtocolInfo(socketPath,timeoutMs){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!0),info=outcome.answer===void 0?void 0:parseHostProtocolInfo(outcome.answer);if(outcome.kept===void 0)return;let hold=holdAttachment(outcome.kept);if(info!==void 0)return{info,hold};hold.release()}async function probeSocketReachable(socketPath,timeoutMs){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs)).connected}async function probeSessionCount(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs);if(!(!isRecord3(reply)||!Array.isArray(reply.sessions)))return reply.sessions.length}async function requestOnSocket(socketPath,command,timeoutMs){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs)).answer}async function connectAndAsk(socketPath,request,timeoutMs,keep=!1){let secret;if(socketNeedsHandshake(socketPath))try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return{connected:!1,answer:void 0}}return new Promise(resolveProbe=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,connected=!1,finish=value=>{if(!settled){if(settled=!0,clearTimeout(timeout),keep&&value!==void 0&&!socket.destroyed){resolveProbe({connected,answer:value,kept:socket});return}socket.destroy(),resolveProbe({connected,answer:value})}},timeout=setTimeout(()=>finish(),timeoutMs);socket.once("connect",()=>{connected=!0,socket.write(`${JSON.stringify(request)}
3
3
  `)}),socket.on("data",chunk=>{for(buffer+=chunk.toString("utf8");;){let newline=buffer.indexOf(`
4
4
  `);if(newline===-1)return;let line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);let answer=readAnswer(line);if(answer!==void 0)return finish(answer)}}),socket.once("error",()=>finish()),socket.once("close",()=>finish()),secret&&sendSocketHandshake(socket,secret)})}function readAnswer(text){let parsed;try{parsed=JSON.parse(text)}catch{return}if(!(!isRecord3(parsed)||parsed.id!==PROBE_REQUEST_ID||parsed.success!==!0))return parsed.data??{}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{open,rm,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import{basename,dirname as dirname2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...process.execArgv,sibling,...supervisorArgs]}:{command:process.execPath,args:[...process.execArgv,resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}function initialHostEnvironment(options){return daemonEnvironment(process.env,options.env,{[ENV_AGENT_DIR]:options.agentDir??getAgentDir(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir})}function successorHostEnvironment(options){return daemonEnvironment(process.env,options.env,{[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),...options.agentDir?{[ENV_AGENT_DIR]:options.agentDir}:{},[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir})}async function stopHost(options){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}}),registered=await readHostRegistration(paths),owner=await provenOwner(registered,options.socket);if(!owner)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4);if(options.drain===!0)return!host?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY)||process.platform==="win32"?{action:"refuse",reason:"drain_unsupported"}:(signalGeneration(owner.pid,"SIGUSR1"),{action:"drained",pid:owner.pid});let sessions=await probeSessionCount(options.socket,options.timeoutMs??1e4);return options.force!==!0&&host!==void 0&&sessions!==void 0&&sessions>0?{action:"refuse",reason:"sessions_live"}:(signalGeneration(owner.pid,"SIGTERM"),await releaseGeneration(paths,{instanceId:owner.instanceId,pid:owner.pid}),{action:"stopped",pid:owner.pid})}function signalGeneration(pid,signal){try{return process.kill(pid,signal),!0}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return!1;throw error}}var DEFAULT_HANDOFF_READINESS_MS=3e4,SUCCESSOR_EXIT_WAIT_MS=5e3,SUCCESSOR_START_BUDGET_MS=1e4+DEFAULT_HANDOFF_READINESS_MS+2e3+SUCCESSOR_EXIT_WAIT_MS;async function startSuccessor(context){let{options,paths,host,owner}=context,generation=(host.generation??0)+1,instanceId=randomUUID(),bindSocket=generationBindPath(options.socket,generation);if(Buffer.byteLength(bindSocket)>MAX_SOCKET_PATH_BYTES)return{action:"refuse",reason:"socket_path_too_long",upgradeable:!0,detail:bindSocket};let replaced=await statSocketIdentity(options.socket);if(!replaced)return{action:"refuse",reason:"socket_replaced",upgradeable:!0};let running=await readHostSettings(paths),bootSettings=await readFileOrUndefined(paths.settingsFile);await writeHostSettings(paths,{socket:options.socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??running?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??running?.idleExitMs??9e5,generation,instanceId});let child,exited;try{await options._test?.beforeSpawn?.();let argv=["--socket",options.socket,"--bind",bindSocket,"--replace",`${replaced.dev}:${replaced.ino}`,...options.hostArgs??[]],launch=options._test?.launch?.(argv)??defaultHostLaunch(argv),stderr=await open(paths.stderrLog,"a",384),spawned=spawn(launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:successorHostEnvironment({agentDir:options.agentDir,env:options.env,paths,generation,instanceId}),stdio:["ignore","ignore",stderr.fd]});if(await stderr.close(),child=spawned,exited=new Promise(resolve4=>spawned.once("exit",()=>resolve4())),child.pid===void 0)throw new Error("failed to spawn the successor generation");let processStartTime=await waitForStartTime(child.pid,1e4).catch(()=>{})??null,registration={record:{pid:child.pid,processStartTime},socket:options.socket,instanceId,generation,launchProfileId:hostLaunchProfile(["--mode","rpc","--multi-session",...options.hostArgs??[]],process.cwd()).profile_id};await writeGenerationRecord(paths,registration),await options._test?.afterSpawn?.(child.pid);let answer=await awaitSuccessor(options,host,exited);if(!answer){let reason=await abortReason(options.socket,replaced),cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings});return{action:"refuse",reason,upgradeable:!0,...cleanupFailure&&{detail:cleanupFailure}}}return await writeHostRegistration(paths,registration),child.unref(),signalGeneration(owner.pid,"SIGUSR1"),{action:"handoff",pid:child.pid,socket:options.socket,generation:answer.generation??generation,instanceId:answer.instanceId??""}}catch(cause){let cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings}),detail=cause instanceof Error?cause.message:String(cause);return{action:"refuse",reason:"successor_unavailable",upgradeable:!0,detail:cleanupFailure?`${detail}; ${cleanupFailure}`:detail}}}async function abandonSuccessor(context){let{child,exited,paths,instanceId,bootSettings}=context;child!==void 0&&child.exitCode===null&&child.signalCode===null&&child.kill("SIGKILL");try{bootSettings===void 0?await rm(paths.settingsFile,{force:!0}):await writeFile(paths.settingsFile,bootSettings,{mode:HOST_STATE_FILE_MODE}),child?.pid===void 0?await rm(generationPaths(paths,instanceId).dir,{recursive:!0,force:!0}):exited!==void 0&&await exitedWithin(exited,SUCCESSOR_EXIT_WAIT_MS)&&await releaseGeneration(paths,{instanceId,pid:child.pid});return}catch(cause){return`successor cleanup failed: ${cause instanceof Error?cause.message:String(cause)}`}}async function exitedWithin(exited,ms){let timer,timedOut=new Promise(resolve4=>{timer=setTimeout(()=>resolve4(!1),ms)});try{return await Promise.race([exited.then(()=>!0),timedOut])}finally{clearTimeout(timer)}}async function awaitSuccessor(options,previous,exited){let deadline=Date.now()+(options._test?.readinessTimeoutMs??DEFAULT_HANDOFF_READINESS_MS),childGone=!1;for(exited.then(()=>{childGone=!0});Date.now()<=deadline;){let answer=await probeProtocolInfo(options.socket,2e3);if(answer&&answer.instanceId!==void 0&&answer.instanceId!==previous.instanceId)return answer;if(childGone)return;await delay(50)}}async function abortReason(socket,replaced){let current=await statSocketIdentity(socket).catch(()=>{});return current===void 0||current.dev!==replaced.dev||current.ino!==replaced.ino?"socket_replaced":"successor_unavailable"}function delay(ms){return new Promise(resolve4=>setTimeout(resolve4,ms))}var HANDOFF_PROBE_TIMEOUT_MS=1e4,HANDOFF_LOCK_HOLD_MS=HANDOFF_PROBE_TIMEOUT_MS+SUCCESSOR_START_BUDGET_MS,HANDOFF_LOCK_WAIT_MS=HANDOFF_PROBE_TIMEOUT_MS+HANDOFF_LOCK_HOLD_MS+1e4;async function handoffHost(options){if(handoffUnsupported(options))return{action:"refuse",reason:"upgrade_unsupported",upgradeable:!1};let release=await acquireHostEnsureLock(options.socket,HANDOFF_LOCK_WAIT_MS);try{return await handoffHostLocked(options)}finally{await release()}}async function handoffHostLocked(options){if(handoffUnsupported(options))return{action:"refuse",reason:"upgrade_unsupported",upgradeable:!1};let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}});await createDaemonDirectories(paths);let host=await probeProtocolInfo(options.socket,HANDOFF_PROBE_TIMEOUT_MS);if(!host)return{action:"refuse",reason:"no_host",upgradeable:!1};if(!host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY))return{action:"refuse",reason:"handoff_unsupported",upgradeable:!1};let registered=await readHostRegistration(paths),owner=await provenOwner(registered,options.socket);return owner?startSuccessor({options,paths,host,owner}):{action:"refuse",reason:"unknown_owner",upgradeable:!0}}function handoffUnsupported(options){return(options._test?.platform??process.platform)==="win32"}var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4;async function pollProtocolInfo(socket,timeoutMs,isCompatible2,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=holdProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let held=await probe;if(!held)return{ready:!1,protocol:lastProtocol,exited:raced};if(lastProtocol=held.info,isCompatible2(held.info))return{ready:!0,protocol:held.info,hold:held.hold};held.hold.release()}else if(raced){if(lastProtocol=raced.info,isCompatible2(raced.info))return{ready:!0,protocol:raced.info,hold:raced.hold};raced.hold.release()}await delay2(50)}return{ready:!1,protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}var EXISTING_HOST_PROBE_TIMEOUT_MS=1e4,DEFAULT_READINESS_TIMEOUT_MS=1e4,DEFAULT_STOP_TIMEOUT_MS=1e4,SIGKILL_GRACE_MS=2e3,ENSURE_LOCK_WAIT_MS=EXISTING_HOST_PROBE_TIMEOUT_MS+Math.max(DEFAULT_STOP_TIMEOUT_MS+SIGKILL_GRACE_MS+DEFAULT_READINESS_TIMEOUT_MS,HANDOFF_LOCK_HOLD_MS)+1e4,lockOptions=hostEnsureLockOptions(ENSURE_LOCK_WAIT_MS);async function ensureHost(options){let socket=normalizeSocketPath(options.socket),paths=createHostDaemonPaths({socket,...options.agentDir?{agentDir:options.agentDir}:{}});await createDaemonDirectories(paths);let lockTarget=hostEnsureLockTarget(socket);await mkdir(dirname3(lockTarget),{recursive:!0}),await writeFile2(lockTarget,"",{flag:"a",mode:384}),await reapOrphanedInternalHostDirs();let release=await acquireOwnershipSafeLock(`${lockTarget}.lock`,lockOptions);try{return await options._test?.afterLockAcquired?.(),await ensureHostLocked(paths,socket,options)}finally{await release()}}async function ensureHostLocked(paths,socket,options){await ensureEndpointIdentity(paths,socket,{repair:!0});let testOptions=options._test,registered=await readHostRegistration(paths),registeredHere=registersSocket(registered,socket),held=await holdProtocolInfo(socket,EXISTING_HOST_PROBE_TIMEOUT_MS),protocol=held?.info,startedByUs=registeredHere&&await writtenByThisProcess(registered?.writer,testOptions?.readProcessStartTime),attachedPid=registeredHere?registered?.record.pid??0:0,decision=decide(options,startedByUs,protocol);if(decision.action==="reuse"&&held)return{pid:attachedPid,socket,reused:!0,release:held.hold.release};switch(held?.hold.release(),decision.action){case"reuse":throw new Error(`host at ${socket} was reused without answering its probe`);case"refuse":throw new HostEnsureRefusedError(socket,decision.reason,protocol);case"handoff":return upgradeGeneration(paths,socket,options,attachedPid);case"start":break;default:return assertNever2(decision)}let probe=testOptions?.readProcessStartTime??readProcessStartTime,pidMatches=registeredHere&&registered?await matchesPidFileOrUnknown(registered.record,probe):!1,stranded;if(registered&&pidMatches)if(startedByUs){if(await probeSocketReachable(socket,EXISTING_HOST_PROBE_TIMEOUT_MS))throw new HostEnsureRefusedError(socket,"host_busy",protocol);await stopManagedHost(registered.record,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,probe)}else{if(await publicEndpointAccepts(socket))throw new HostEnsureRefusedError(socket,"foreign_writer",protocol);stranded=registered}if(await legacyHostIsLive(paths,probe))throw new HostEnsureRefusedError(socket,"legacy_host",protocol);return stranded!==void 0?startHost(paths,socket,options,stranded.generation+1):(registeredHere&&await clearHostRegistration(paths),startHost(paths,socket,options))}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}function decide(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}async function upgradeGeneration(paths,socket,options,attachedPid){let result=await handoffHostLocked({socket,agentDir:options.agentDir??getAgentDir(),hostArgs:options.hostArgs??[],...options.env?{env:options.env}:{},...options.policy?{policy:options.policy}:{},_test:{...options._test?.launch?{launch:options._test.launch}:{},...options._test?.readinessTimeoutMs?{readinessTimeoutMs:options._test.readinessTimeoutMs}:{}}});return result.action==="handoff"?{pid:result.pid,socket,reused:!1,release:await holdEnsured(socket)}:(await appendStderr(paths,`generation handoff refused: ${result.reason}${result.detail?` (${result.detail})`:""}`),{pid:attachedPid,socket,reused:!0,release:await holdEnsured(socket)})}async function holdEnsured(socket){let held=await holdProtocolInfo(socket,EXISTING_HOST_PROBE_TIMEOUT_MS);if(!held)throw new Error(`RPC socket host at ${socket} stopped answering before this ensure could hold it`);return held.hold.release}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:REQUIRED_HOST_CAPABILITIES,identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function registersSocket(registered,socket){return registered===void 0?!1:registered.socket===void 0||sameEndpoint(registered.socket,socket)}async function startHost(paths,socket,options,generation=0){let testOptions=options._test,instanceId=randomUUID2();process.platform==="win32"&&await createSocketSecret(socketSecretPath(socket)),await writeHostSettings(paths,{socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??9e5,generation,instanceId});let stderr=await open2(paths.stderrLog,generation===0?"w":"a",384),pidFile,child,exitedEarly,childExit;try{let supervisorArgs=["--socket",socket,...options.hostArgs??[]],launch=testOptions?.spawn??testOptions?.launch?.(supervisorArgs)??defaultHostLaunch(supervisorArgs);if(child=spawn2(launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:initialHostEnvironment({agentDir:options.agentDir,env:options.env,paths,instanceId,generation}),stdio:["ignore","ignore",stderr.fd]}),childExit=new Promise(resolveExit=>{child.once("exit",(code,signal)=>{exitedEarly={code,signal},resolveExit(exitedEarly)})}),child.pid===void 0)throw new Error("failed to spawn RPC socket host");let probe=testOptions?.readProcessStartTime??readProcessStartTime,observedStartTime=await Promise.race([waitForStartTime(child.pid,1e4,probe),childExit.then(()=>{throw new Error("RPC socket host exited before its start time could be read")})]),unhurriedProbe=testOptions?.readProcessStartTime?testOptions.readProcessStartTime:pid=>readProcessStartTime(pid,process.platform,15e3),processStartTime=observedStartTime??await unhurriedProbe(child.pid).catch(()=>{});pidFile={pid:child.pid,processStartTime:processStartTime??null},await testOptions?.beforePidFileWrite?.(),await writeHostRegistration(paths,{record:pidFile,socket,instanceId,generation,launchProfileId:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd()).profile_id}),child.unref()}catch(error){let exitedBeforeCleanup=exitedEarly;if(!exitedBeforeCleanup&&child&&child.exitCode===null&&child.signalCode===null){try{child.kill("SIGTERM")}catch{}if(childExit&&await Promise.race([childExit,delay3(2e3)]),child.exitCode===null&&child.signalCode===null)try{child.kill("SIGKILL")}catch{}}if(!exitedBeforeCleanup)throw await clearHostRegistration(paths),error;let diagnostic2=await appendStderr(paths,`RPC socket host exited with code ${exitedBeforeCleanup.code??"null"}${exitedBeforeCleanup.signal?` (${exitedBeforeCleanup.signal})`:""} before answering get_protocol_info`);throw await clearHostRegistration(paths),new Error(diagnostic2)}finally{await stderr.close()}let readinessTimeoutMs=testOptions?.readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS,result=await pollProtocolInfo(socket,readinessTimeoutMs,isCompatible,childExit);if(result.ready)return{pid:pidFile.pid,socket,reused:!1,release:result.hold.release};let stopFailure=await stopSpawnedChild(child,childExit,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS).then(()=>{},error=>error instanceof Error?error.message:String(error)),message=result.protocol?`RPC socket host answered get_protocol_info with protocolVersion ${result.protocol.protocolVersion}, serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`:result.exited?`RPC socket host exited with code ${result.exited.code??"null"}${result.exited.signal?` (${result.exited.signal})`:""} before answering get_protocol_info`:`spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`,diagnostic=await appendStderr(paths,stopFailure===void 0?message:`${message} (teardown also reported: ${stopFailure})`);throw await clearHostRegistration(paths),new Error(diagnostic)}async function matchesPidFileOrUnknown(pidFile,probe){try{return await processMatchesPidFile(pidFile,probe)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!1;throw error}}async function stopSpawnedChild(child,childExit,termTimeoutMs){let exited=()=>child.exitCode!==null||child.signalCode!==null;if(exited())return;let signal=name=>{try{child.kill(name)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}},waitFor=ms=>Promise.race([childExit.then(()=>!0),delay3(ms).then(()=>exited())]);if(signal("SIGTERM"),!await waitFor(termTimeoutMs)&&(signal("SIGKILL"),!await waitFor(SIGKILL_GRACE_MS)))throw new Error(`RPC socket host pid ${child.pid??"?"} remained alive after SIGKILL`)}async function stopManagedHost(pidFile,termTimeoutMs,readStartTime=readProcessStartTime){if(await signalValidated(pidFile,"SIGTERM",readStartTime),!await waitForGone(pidFile,termTimeoutMs,readStartTime)&&(await signalValidated(pidFile,"SIGKILL",readStartTime),!await waitForGone(pidFile,SIGKILL_GRACE_MS,readStartTime)))throw new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`)}async function resolvePidFileOwnership(pidFile,readStartTime){try{return await processMatchesPidFile(pidFile,readStartTime,processIsLive,{attempts:1})?"owns":"gone"}catch(error){if(error instanceof ProcessIdentityUnreadableError)return"unknown";throw error}}async function signalValidated(pidFile,signal,readStartTime=readProcessStartTime){if(await resolvePidFileOwnership(pidFile,readStartTime)==="owns")try{process.kill(pidFile.pid,signal)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}}async function waitForGone(pidFile,timeoutMs,readStartTime=readProcessStartTime){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await resolvePidFileOwnership(pidFile,readStartTime)==="gone")return!0;await delay3(50)}return await resolvePidFileOwnership(pidFile,readStartTime)==="gone"}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}async function reapOrphanedInternalHostDirs(){try{let entries=await readdir(tmpdir(),{withFileTypes:!0});await Promise.all(entries.filter(entry=>entry.isDirectory()&&entry.name.startsWith("senpi-rpc-host-internal-")).map(async entry=>{try{let owner=JSON.parse(await readFile2(join2(tmpdir(),entry.name,".owner"),"utf8"));typeof owner.pid=="number"&&typeof owner.processStartTime=="string"&&typeof owner.createdAt=="number"&&owner.processStartTime.length>0&&owner.createdAt<Date.now()-6e4&&(await readdir(join2(tmpdir(),entry.name))).length===1&&!await processMatchesPidFile({pid:owner.pid,processStartTime:owner.processStartTime}).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error})&&await rm2(join2(tmpdir(),entry.name),{recursive:!0,force:!0})}catch{}}))}catch{}}async function appendStderr(paths,message){try{let stderr=(await readFile2(paths.stderrLog,"utf8")).trim();return stderr?`${message}
5
5
  ${stderr}`:message}catch(error){if(isNodeErrorCode(error,"ENOENT"))return message;throw error}}function normalizeSocketPath(value){return value.startsWith("unix://")?value.slice(7):value}function delay3(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}function assertNever2(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}function parseSessionRows(reply){return!isRecord4(reply)||!Array.isArray(reply.sessions)?[]:reply.sessions.flatMap(entry=>isRecord4(entry)?[{id:typeof entry.sessionId=="string"?entry.sessionId:"",kind:typeof entry.kind=="string"?entry.kind:"interactive",session_path:typeof entry.sessionPath=="string"?entry.sessionPath:null,cwd:typeof entry.cwd=="string"?entry.cwd:null,name:typeof entry.name=="string"?entry.name:null,attachments:typeof entry.attachments=="number"?entry.attachments:0,context:stringRecord(entry.context)}]:[])}async function readClaimRows(paths,generations){let rows=[];for(let claim of await readSessionPathClaims(paths.reservationsDir)){let owner=claim.owner;rows.push({session_path:owner.sessionPath,owner_pid:owner.pid,instance_id:owner.instanceId,generation:generations.find(row=>row.instanceId===owner.instanceId)?.generation??null,attached:owner.attached??null,live:await claimOwnerIsLive(owner)})}return rows.sort((left,right)=>left.session_path.localeCompare(right.session_path))}function stringRecord(value){return isRecord4(value)?Object.fromEntries(Object.entries(value).filter(entry=>typeof entry[1]=="string")):null}function isRecord4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var STATUS_PROBE_TIMEOUT_MS=1e4;async function readHostStatus(options,read={}){return(await probeHostStatus(options,read)).report}async function probeHostStatus(options,read={}){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}}),prune=read.prune!==!1,includeWorkers=options.includeWorkers===!0,timeoutMs=read.timeoutMs??STATUS_PROBE_TIMEOUT_MS,host=await observeProtocolInfo(options.socket,timeoutMs);prune&&await pruneDeadGenerations(paths);let generations=await readGenerationRows(paths,{includeDead:!prune}),current=generations.find(row=>row.current&&row.alive),metrics=current?await readHostProcessMetrics(current.pid):UNOBSERVED_METRICS,listing=host===void 0?[]:await readSessionListing(options.socket,includeWorkers,timeoutMs),claims=await readClaimRows(paths,generations);return{report:{reachable:host!==void 0,socket:options.socket,pid:current?.pid??null,instanceId:host?.instanceId??current?.instanceId??null,generation:host?.generation??current?.generation??null,engineVersion:host?.engineVersion??current?.engineVersion??null,capabilities:host?.capabilities??[],launchProfile:host?.launch_profile??null,sessions:countSessions(listing),zombies:metrics.zombies,rss_mb:metrics.rss_mb,host_rss_mb:metrics.host_rss_mb,open_fds:metrics.open_fds,memory_pressure:host?.memory_pressure??null,env_keys:await readDaemonEnvKeys(paths),generations,crashes:readHostCrashRecords(paths.dir).length,shard:parseShardSocket(options.socket),session_rows:includeWorkers?listing:[],claims_live:claims.filter(claim=>claim.live).length,claims:includeWorkers?claims:[]},answered:host,listing}}async function readSessionCounts(socket,includeWorkers){return countSessions(await readSessionListing(socket,includeWorkers))}async function readSessionListing(socket,includeWorkers,timeoutMs=STATUS_PROBE_TIMEOUT_MS){let reply=await requestOnSocket(socket,{type:"list_sessions",[OBSERVE_REQUEST_FIELD]:!0,...includeWorkers?{include_workers:!0}:{}},timeoutMs);return parseSessionRows(reply)}function countSessions(rows){let attached=rows.filter(row=>row.attachments>0).length,retained=rows.length-attached;return{total:rows.length,interactive:rows.filter(row=>row.kind!=="worker").length,worker:rows.filter(row=>row.kind==="worker").length,retained,foreign_attached:attached,foreign_retained:retained}}function hostSummary(host){return host===void 0?null:{protocolVersion:host.protocolVersion,serverVersion:host.serverVersion,capabilities:host.capabilities,instanceId:host.instanceId??null,generation:host.generation??null,engineVersion:host.engineVersion??null,launchProfileId:host.launch_profile?.profile_id??null}}var UNOBSERVED_METRICS={rss_mb:null,host_rss_mb:null,open_fds:null,zombies:null};import{readdir as readdir2}from"node:fs/promises";var TUI_PROBE_TIMEOUT_MS=1500;function endpointProbeTimeoutMs(kind,requestedMs){return kind==="tui"?Math.min(requestedMs??TUI_PROBE_TIMEOUT_MS,TUI_PROBE_TIMEOUT_MS):requestedMs??DEFAULT_PROBE_TIMEOUT_MS}async function classifyEndpointLiveness(entry,options={}){let host=entry.socket===null?void 0:await observeProtocolInfo(entry.socket,endpointProbeTimeoutMs(entry.endpoint_kind,options.timeoutMs));return judgeEndpointLiveness(hostDaemonDirectoryPaths(entry.dir),host===void 0?void 0:host.instanceId??null)}async function judgeEndpointLiveness(paths,answered){return typeof answered=="string"&&await recordsInstance(paths,answered)?"routable":answered!==void 0||await anyGenerationLive(paths)?"live_unresponsive":"dead"}async function recordsInstance(paths,instanceId){return(await readdir2(paths.generationsDir).catch(()=>[])).includes(instanceId)?await readFileOrUndefined(generationPaths(paths,instanceId).pidFile).catch(()=>{})!==void 0:!1}var STATUS_ALL_MAX_IN_FLIGHT=64;async function readAllHostStatus(options){let endpoints=await listHostEndpoints(options.agentDir),read=options._test?.readEndpoint??(endpoint=>endpointStatus(endpoint,options)),rows=new Array(endpoints.length),next=0,worker=async()=>{for(let index=next++;index<endpoints.length;index=next++){let endpoint=endpoints[index];endpoint!==void 0&&(rows[index]=await read(endpoint))}};return await Promise.all(Array.from({length:Math.min(STATUS_ALL_MAX_IN_FLIGHT,endpoints.length)},worker)),rows}async function endpointStatus(endpoint,options){let located={dir:endpoint.dir,identity:endpoint.identity,endpoint_kind:endpoint.endpoint_kind},paths=hostDaemonDirectoryPaths(endpoint.dir);if(endpoint.socket===null){let verdict2=livenessFields(await judgeEndpointLiveness(paths,void 0)),status=await unaddressableStatus(endpoint.dir),owner2=endpoint.endpoint_kind==="tui"?tuiOwner(status,[]):null;return{...status,socket:null,...located,...verdict2,owner:owner2}}let{report,answered,listing}=await probeHostStatus({socket:endpoint.socket,agentDir:options.agentDir,includeWorkers:options.includeWorkers},{prune:!1,timeoutMs:endpointProbeTimeoutMs(endpoint.endpoint_kind,options.timeoutMs)}),verdict=await judgeEndpointLiveness(paths,answered===void 0?void 0:answered.instanceId??null),owner=endpoint.endpoint_kind==="tui"?tuiOwner(report,listing):null;return{...report,...located,...livenessFields(verdict),owner}}function tuiOwner(status,listing){let row=listing[0];return{pid:status.generations.find(generation=>generation.current)?.pid??null,cwd:row?.cwd??null,session:row===void 0?null:{id:row.id,path:row.session_path,name:row.name}}}function livenessFields(verdict){return verdict==="routable"?{alive:!0,reason:null}:{alive:!1,reason:verdict}}async function unaddressableStatus(dir){let paths=hostDaemonDirectoryPaths(dir),generations=await readGenerationRows(paths,{includeDead:!0}),claims=await readClaimRows(paths,generations);return{reachable:!1,pid:null,instanceId:null,generation:null,engineVersion:null,capabilities:[],launchProfile:null,sessions:{total:0,interactive:0,worker:0,retained:0,foreign_attached:0,foreign_retained:0},zombies:null,rss_mb:null,host_rss_mb:null,open_fds:null,memory_pressure:null,env_keys:[],generations,crashes:readHostCrashRecords(dir).length,shard:null,session_rows:[],claims_live:claims.filter(claim=>claim.live).length,claims:[]}}var HOST_EXIT_OK=0,HOST_EXIT_ERROR=1,HOST_EXIT_USAGE=2,HOST_EXIT_REFUSED=3,HOST_EXIT_FALLBACK=4,PROBE_TIMEOUT_MS=1e4;async function runHostRequest(request){if(request.action==="ensure"||request.action==="handoff"||request.action==="stop"){let{socket,agentDir}=request.target;if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"})}switch(request.action){case"ensure":return ensureOutcome(request.target,request.spec,request.policy);case"status":return request.all===!0?statusAllOutcome(request.target,request.includeWorkers):statusOutcome(request.target,request.includeWorkers);case"stop":return stopOutcome(request.target,request.drain,request.force);case"handoff":return handoffOutcome(request.target,request.spec);case"shard_path":return shardPathOutcome(request.kind,request.owner,request.root);case"gc":return{exitCode:HOST_EXIT_OK,payload:{...await gcHostEndpoints(request.agentDir)}};default:return assertNever3(request)}}async function ensureOutcome(target,spec,policy){let before=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS);if(policy==="fallback"){let decision=decideHostAction(decisionClient(),before,"fallback");if(decision.action==="fallback")return refusal("fallback",before,{reason:decision.reason,socket:target.socket})}let ensured;try{ensured=await ensureHost({socket:target.socket,agentDir:target.agentDir,hostArgs:spec.hostArgs,env:daemonEnvOverrides(process.env,spec.env),policy:spec.policy,upgrade:policy==="upgrade"?"if-engine-differs":"never"})}catch(error){if(!(error instanceof HostEnsureRefusedError))throw error;return refusal("refuse",before,{reason:error.reason,socket:target.socket})}let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS).finally(ensured.release);return ensured.reused||await recordEnvScope(target,spec),{exitCode:HOST_EXIT_OK,payload:{action:ensureAction(ensured.reused,before,host),...identityPayload(target.socket,ensured.pid,host),reused:ensured.reused}}}function ensureAction(reused,before,after){return reused?"reuse":before!==void 0&&before.instanceId!==after?.instanceId?"handoff":"start"}async function statusOutcome(target,includeWorkers){let status=await readHostStatus({socket:target.socket,agentDir:target.agentDir,includeWorkers});return{exitCode:status.reachable?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{...status}}}async function statusAllOutcome(target,includeWorkers){let endpoints=await readAllHostStatus({agentDir:target.agentDir,includeWorkers});return{exitCode:endpoints.some(endpoint=>endpoint.reachable)?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{endpoints}}}function shardPathOutcome(kind,owner,root){let key=shardKey(kind,owner);return{exitCode:HOST_EXIT_OK,payload:{kind,key,socket:shardSocketPathForKey(root,kind,key)}}}async function stopOutcome(target,drain,force){let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS),sessions=await readSessionCounts(target.socket,!0),occupied=sessions.foreign_attached+sessions.foreign_retained>0;if(!drain&&!force&&occupied)return refusal("refuse",host,{reason:"sessions_live",socket:target.socket,sessions});let result=await stopHost({socket:target.socket,agentDir:target.agentDir,drain,force});return result.action==="refuse"?refusal("refuse",host,{reason:result.reason,socket:target.socket,sessions}):{exitCode:HOST_EXIT_OK,payload:{action:result.action,socket:target.socket,pid:result.pid,sessions}}}async function handoffOutcome(target,spec){let before=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS),result=await handoffHost({socket:target.socket,agentDir:target.agentDir,hostArgs:spec.hostArgs,env:daemonEnvOverrides(process.env,spec.env),policy:spec.policy});if(result.action==="refuse")return refusal("refuse",before,{reason:upgradeRefusal(result.reason),socket:target.socket,detail:result.reason,upgradeable:result.upgradeable});await recordEnvScope(target,spec);let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS);return{exitCode:HOST_EXIT_OK,payload:{action:"handoff",...identityPayload(target.socket,result.pid,host),reused:!1}}}function upgradeRefusal(reason){return reason==="handoff_unsupported"?"upgrade_unsupported":reason}function identityPayload(socket,pid,host){return{socket,pid,instanceId:host?.instanceId??null,generation:host?.generation??null,engineVersion:host?.engineVersion??null,engineOrdinal:host?.engineOrdinal??null,capabilities:host?.capabilities??[],launchProfileId:host?.launch_profile?.profile_id??null,upgradeable:decideHostAction(decisionClient(),host,"upgrade").upgradeable}}function refusal(kind,host,body){return{exitCode:kind==="refuse"?HOST_EXIT_REFUSED:HOST_EXIT_FALLBACK,payload:{action:kind,...body,host:hostSummary(host)}}}async function recordEnvScope(target,spec){let paths=createHostDaemonPaths({socket:target.socket,agentDir:target.agentDir});await writeDaemonEnvKeys(paths,daemonEnvKeys(process.env,spec.env))}function decisionClient(){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:REQUIRED_HOST_CAPABILITIES,identity:engineBuildIdentity(),startedByUs:!1,platform:process.platform}}function assertNever3(value){throw new Error(`unreachable host request: ${JSON.stringify(value)}`)}var SUBCOMMANDS=["ensure","status","stop","handoff","shard-path","gc"],POLICIES=["upgrade","fallback","never"],USAGE=`usage: ${APP_NAME} host <ensure|status|stop|handoff|shard-path|gc> [options]
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{APP_NAME,CONFIG_DIR_NAME,agentDirLabel}from"./chunk-WCAKUCN3.js";var CLI_TIPS=[{id:"print-mode",bindings:[],render:()=>`${APP_NAME} -p "question" answers without the TUI, and piped stdin is merged into the prompt.`},{id:"tool-flags",bindings:[],render:()=>"Limit a run's tools with -t read,bash, or drop a few with -xt write,edit."}];function stopChord(){return process.platform==="darwin"?"Control+Option+Command+Escape":"Ctrl+Alt+Shift+Escape"}var COMPUTER_TIPS=[{id:"computer.what-it-is",bindings:[],requiresCommand:"computer",render:()=>"Experimental: your agent can use native apps too: screenshots, windows, clicks and typing. Run /computer to see whether this machine is ready."},{id:"computer.stop-chord",bindings:[],requiresCommand:"computer",render:()=>`Press ${stopChord()} at any moment to stop computer input. It stays stopped until you run /computer resume; the agent cannot resume it.`},{id:"computer.background-input",bindings:[],requiresCommand:"computer",render:()=>"Computer use clicks and types into the target app in the background, so your frontmost app, keyboard focus and cursor stay where you left them."},{id:"computer.look-dont-touch",bindings:[],requiresCommand:"computer",render:()=>"Want the agent to look but not touch? Start with --permission computer:exec=deny: screenshots and accessibility reads still work, clicks and typing are refused."},{id:"computer.permissions",bindings:[],requiresCommand:"computer",render:()=>"On macOS, computer use needs Screen Recording and Accessibility for the app you launch from. /computer status shows which one is missing."}];var DAG_TIPS=[{id:"dag.one-keyword-mastery",bindings:[],requiresCommand:"dag",render:()=>'One keyword makes you a master of graph engineering: say "mass-ulw" and your work becomes a dependency graph that schedules itself.'},{id:"dag.what-it-is",bindings:[],requiresCommand:"dag",render:()=>'Trigger "mass-ulw" when some tasks must wait for others - describe the work, get a graph that runs in the right order.'},{id:"dag.parallel-waves",bindings:[],requiresCommand:"dag",render:()=>"A graph run executes in waves: everything with no pending dependency starts at once, the rest starts the moment it is unblocked."},{id:"dag.depends-on",bindings:[],requiresCommand:"dag",render:()=>"Say what needs what - review after implementation, docs after both - and the ordering is enforced for you."},{id:"dag.categories",bindings:[],requiresCommand:"dag",render:()=>"Each node in the graph picks its own worker category, so cheap steps stay cheap and hard steps get the strong model."},{id:"dag.status-view",bindings:[],requiresCommand:"dag",render:()=>"Use /dag to watch a run: which nodes finished, which are running, and which one failed."},{id:"dag.resume",bindings:[],requiresCommand:"dag",render:()=>"Graph runs are journaled - if the session dies mid-run it resumes later and never redoes the nodes that already finished."},{id:"dag.vs-parallel",bindings:[],requiresCommand:"dag",render:()=>"Fully independent jobs just need parallel subagents; reach for a graph when the ordering between them is the whole point."},{id:"dag.scale",bindings:[],requiresCommand:"dag",render:()=>"Stop hand-running steps in sequence. Describe the dependencies once and let a dozen agents fan out and rejoin on their own."}];var ETHOS_TIPS=[{id:"ethos.tuning-discipline",bindings:[],render:()=>"gpt-5.6-sol used to turn a sprint into a marathon. We tuned the system prompt and killed that habit: 5-minute jobs take 5 minutes, 12-hour jobs take 12."},{id:"ethos.tools-transparent",bindings:[],render:()=>"Don't study our tools. A tool that needs studying is a tool that failed. We just ride shotgun while you keep doing your actual job."},{id:"ethos.only-harness",bindings:[],render:()=>"The only harness that actually knows how to drive gpt-5.6-sol. Same job, feels up to 30% faster. *we counted*"},{id:"ethos.spend-tokens",bindings:[],render:()=>"Stop hoarding tokens. Spend them like they buy your hours back, because they do."},{id:"ethos.deep-work",bindings:[],render:()=>"Using our tools means your work is already the deep, valuable kind. Keep your eyes on the essence of your craft. The rest is our problem now, and we're great at problems."},{id:"ethos.ulw-plan-sage",bindings:[],requiresCommand:"tasks",render:()=>"Try ulw-plan on fable-5.1 xhigh. A patient sage obsessed with the essence does the agonizing for you and fills in every blank you were pretending not to see."},{id:"ethos.ulw-loop-shallow",bindings:[],requiresCommand:"tasks",render:()=>"For days when deep thought sounds awful, run the ulw loop with gpt-6-sol fast/medium. Fair warning: shallow thinking sends invoices."},{id:"ethos.monitor-subscribe",bindings:[],render:()=>"Subscribe to a command's stdout and forget it. CI finishes, server boots, log line lands... you're mid-edit and the news finds *you*. No sleep loops, no polling, no re-reading context like a chump."},{id:"ethos.cache-budget",bindings:[],render:()=>"My harness knows the prompt cache's expiry to the second and never blocks past it. Cold re-read tax? *Refused on your behalf.* Other agents eat that cost, mine declines it."},{id:"ethos.cache-hit-rate",bindings:[],render:()=>"Live cache-hit rate in the footer, plus a running tab of misses, idle gaps, and model swaps. I can point at the exact moment cache broke and why. Watching tokens you never re-pay stack up? Smug doesn't cover it."},{id:"ethos.multimodal-vision",bindings:[],render:()=>`Drop a screenshot, a PDF, a crusty whiteboard photo... ${APP_NAME} actually sees it, reads it, reasons about it. Your agent has eyes now. *Yes, really.*`},{id:"ethos.oauth-multi-account",bindings:[],render:()=>`Hit a rate limit, switch accounts. Wrong org, switch again. ${APP_NAME} treats your Claude logins like a roster, not a single lifeline. *Env vars could never.*`},{id:"ethos.agent-sdk-foundation",bindings:[],render:()=>'Built on the official agent SDK, speaking the protocol natively. No reverse-engineered wrapper, no ToS gray zone, no "will I get banned for this" anxiety. *Sleep easy, ship loud.*'},{id:"ethos.tool-call-repair",bindings:[],render:()=>`${APP_NAME} catches malformed tool calls on the wire, fixes them, and salvages the turn - claude's sloppy invokes, kimi k3's leaked XTML channels, all of it. Other harnesses retry the whole thing and bill you for the privilege. *table stakes, honestly*`}];var INPUT_TIPS=[{id:"click-pending-question",bindings:[],render:()=>"Click a pending question's option to answer. Use the displayed selection-bypass modifier to select terminal text, or disable terminal.mouse in /settings."},{id:"queue-follow-up",bindings:["app.message.followUp"],render:keys=>`While the agent is working, use ${keys("app.message.followUp")} to queue a follow-up for after it finishes.`},{id:"steering-message",bindings:["tui.input.submit","app.message.followUp"],render:keys=>`Press ${keys("tui.input.submit")} while the agent works to steer it after the current tool batch; ${keys("app.message.followUp")} waits until all work is done.`},{id:"edit-queued-message",bindings:["app.message.dequeue"],render:keys=>`Use ${keys("app.message.dequeue")} to bring queued messages back for editing.`},{id:"interrupt-restores-queue",bindings:["app.interrupt"],render:keys=>`Press ${keys("app.interrupt")} to abort the current turn and restore queued messages to the editor.`},{id:"file-reference",bindings:[],render:()=>"Type @ in the editor to fuzzy-search project files and insert their paths."},{id:"path-completion",bindings:["tui.input.tab"],render:keys=>`Press ${keys("tui.input.tab")} to complete file paths while typing.`},{id:"shortcut-overlay",bindings:[],render:()=>"Type ? in an empty editor to pop up the full shortcut grid."},{id:"prompt-history",bindings:["app.history.search"],requiresCommand:"history",render:keys=>`Search prompt history across sessions with ${keys("app.history.search")}.`},{id:"external-editor",bindings:["app.editor.external"],render:keys=>`Open the current prompt in your external editor with ${keys("app.editor.external")}.`},{id:"expand-tool-output",bindings:["app.tools.expand"],render:keys=>`Collapse or expand tool output with ${keys("app.tools.expand")}.`},{id:"thinking-blocks",bindings:["app.thinking.toggle"],render:keys=>`Collapse or expand thinking blocks with ${keys("app.thinking.toggle")}.`},{id:"paste-image",bindings:["app.clipboard.pasteImage"],render:keys=>`Paste an image from the clipboard with ${keys("app.clipboard.pasteImage")}.`},{id:"copy-message",bindings:["app.message.copy"],render:keys=>`Copy the latest assistant message with ${keys("app.message.copy")}.`},{id:"input-newline",bindings:["tui.input.newLine"],render:keys=>`Insert a newline without sending with ${keys("tui.input.newLine")}.`},{id:"bash-prefixes",bindings:[],render:()=>"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context."},{id:"drag-drop-files",bindings:[],render:()=>"Drag and drop files into the terminal to add their paths to your prompt."},{id:"answer-agent-question",bindings:[],render:()=>"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered."},{id:"open-pending-question",bindings:["app.question.answer","app.question.next"],render:keys=>`Pending questions queue above the editor. An empty-composer digit selects an option; ${keys("app.question.answer")} opens the shown request and ${keys("app.question.next")} cycles requests. /answer lists them.`}];var MEMORY_TIPS=[{id:"memory.persistent",bindings:[],requiresCommand:"memory",render:()=>`${APP_NAME} remembers across sessions. Close the terminal, come back tomorrow, and the context is still there.`},{id:"memory.remember-command",bindings:[],requiresCommand:"remember",render:()=>"Use /remember to save something you want kept - a preference, a decision, a fact worth reusing."},{id:"memory.just-tell-it",bindings:[],requiresCommand:"remember",render:()=>'You can also just say it: "remember that we deploy on Fridays" is enough. No syntax, no file to open.'},{id:"memory.search-command",bindings:[],requiresCommand:"search",render:()=>"Use /search to look through everything remembered so far, in plain words."},{id:"memory.memory-command",bindings:[],requiresCommand:"memory",render:()=>"Use /memory to see what is currently remembered about you and this project."},{id:"memory.init-command",bindings:[],requiresCommand:"init",render:()=>"Use /init to start memory for a new project, so it learns this codebase from the first session."},{id:"memory.people-command",bindings:[],requiresCommand:"people",render:()=>"Use /people to keep notes on teammates - who owns what, who to ask, what they prefer."},{id:"memory.reflect-command",bindings:[],requiresCommand:"reflect",render:()=>"Use /reflect to have the session reviewed now and the parts worth keeping written down."},{id:"memory.dream-command",bindings:[],requiresCommand:"dream",render:()=>"Memory tidies itself in the background between turns - /dream shows that work and lets you start it yourself."},{id:"memory.sleeptime-command",bindings:[],requiresCommand:"sleeptime",render:()=>"Use /sleeptime to decide how often memory reorganizes itself while you are not looking."},{id:"memory.memfs-command",bindings:[],requiresCommand:"memfs",render:()=>"Memory is plain files you own - browse them with /memfs and edit anything that looks wrong."},{id:"memory.repository-command",bindings:[],requiresCommand:"memory-repository",render:()=>"Every memory change is a git commit - use /memory-repository to see the history and undo a bad one."},{id:"memory.doctor-command",bindings:[],requiresCommand:"doctor",render:()=>"Use /doctor when memory feels off; it checks the setup and tells you what to fix."},{id:"memory.facts-command",bindings:[],requiresCommand:"facts",render:()=>"Use /facts to see the individual things learned about you, and drop the ones that no longer hold."},{id:"memory.recompile-command",bindings:[],requiresCommand:"recompile",render:()=>"Edited memory files by hand? Run /recompile so this session picks the changes up right away."},{id:"memory.aha-moment",bindings:[],requiresCommand:"memory",render:()=>"Memory speaks up on its own: when something remembered would change the next step, an Aha moment! line surfaces it mid-task. Silence means nothing relevant was found."},{id:"memory.stop-repeating",bindings:[],requiresCommand:"memory",render:()=>"Explain your setup once. Memory means you stop re-explaining it at the start of every session."}];var MODEL_TIPS=[{id:"thinking-level",bindings:["app.thinking.cycle"],render:keys=>`Use /thinking <level> to set the thinking level, /thinking to pick one, or ${keys("app.thinking.cycle")} to cycle through them.`},{id:"efforts-command",bindings:[],requiresCommand:"efforts",render:()=>"Use /efforts <level> to set the reasoning effort for the current model; /efforts alone lists the levels it supports."},{id:"favorite-model-rotation",bindings:["app.model.cycleForward","app.model.cycleBackward"],render:keys=>`Rotate through favorite models with ${keys("app.model.cycleForward")}; go backward with ${keys("app.model.cycleBackward")}.`},{id:"model-selector-favorites",bindings:["app.model.select","app.models.toggleFavorite"],render:keys=>`Open the model selector with ${keys("app.model.select")}, then use ${keys("app.models.toggleFavorite")} to toggle the highlighted favorite.`},{id:"model-command-search",bindings:[],render:()=>"Use /model to open the selector, or /model <pattern> to jump straight to a matching model."},{id:"model-cycling-scope",bindings:["app.model.cycleForward"],render:keys=>`Start ${APP_NAME} with --models "anthropic/*,gpt-5*" to limit which models ${keys("app.model.cycleForward")} cycles through.`},{id:"thinking-budgets",bindings:[],render:()=>"Set thinkingBudgets in settings.json to choose the token budget behind each thinking level."},{id:"prompt-preset",bindings:[],render:()=>"Set promptPreset in settings.json when a model does not auto-detect the system prompt you want."},{id:"provider-login",bindings:[],render:()=>"Use /login to add a subscription or API-key provider, and /logout to remove stored credentials."},{id:"fallback-chains-setting",bindings:[],render:()=>"retry.fallbackChains in settings.json maps a model to ordered fallbacks, so a failed turn retries on the next one."},{id:"fallback-command",bindings:[],requiresCommand:"fallback",render:()=>"Use /fallback to inspect and manage the retry fallback chain for the current model."}];var SESSION_TIPS=[{id:"favorite-models-command",bindings:[],render:()=>"Use /favorite-models to choose and reorder the models in your rotation."},{id:"tree-command",bindings:[],render:()=>"Use /tree to revisit earlier points and switch between session branches."},{id:"fork-command",bindings:[],render:()=>"Use /fork to create a separate session from an earlier user message."},{id:"clone-session",bindings:[],render:()=>"Use /clone to duplicate the current branch into its own session before trying something risky."},{id:"continue-session",bindings:[],render:()=>`Use /resume or /sessions to reopen a past session; from the shell, ${APP_NAME} -r opens the same picker and ${APP_NAME} -c continues the most recent one.`},{id:"session-name",bindings:[],render:()=>"Use /rename [name] to label a session so it is easy to spot in the footer and in /resume."},{id:"session-info",bindings:[],render:()=>"Use /session to see the session file, id, message count, tokens, and cost."},{id:"export-share",bindings:[],render:()=>"Use /export to write the session to HTML or JSONL, or /share to upload it as a private gist link."},{id:"compact-command",bindings:[],render:()=>"Use /compact to compact context now, or /compact <prompt> to tell the summarizer what to keep."},{id:"auto-compaction",bindings:[],render:()=>"Auto-compaction is on by default - the (auto) marker in the footer shows it; tune it with compaction.* in settings.json."}];var SETTINGS_TIPS=[{id:"settings-locations",bindings:[],render:()=>`Use /settings for common options; the rest live in settings.json, with ${CONFIG_DIR_NAME}/settings.json overriding per project.`},{id:"permission-preset",bindings:[],render:()=>'Set permissionPreset to "workspace", "read-only", or "ask" to decide which tool calls need your approval.'},{id:"packages-setting",bindings:[],render:()=>"The packages setting loads skills, extensions, prompts, and themes from an npm or git package."},{id:"custom-themes",bindings:[],render:()=>`Switch themes from /settings, and drop custom theme files in ${agentDirLabel()}/themes.`},{id:"reload-resources",bindings:[],render:()=>"Use /reload to re-read keybindings, extensions, skills, prompts, themes, and context files without restarting."},{id:"project-trust",bindings:[],render:()=>"Use /trust to save a trust decision so this project's settings, skills, and extensions load next time."},{id:"tips-toggle",bindings:[],render:()=>'Set "tips": false in settings.json to stop showing these tips.'}];var SUBAGENT_TIPS=[{id:"workflow-skills.plan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw plan" to get an explored, decision-complete plan under .omo/plans/.'},{id:"workflow-skills.start-work",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "$start-work <plan-name>" to execute a plan end-to-end in a fresh session.'},{id:"workflow-skills.ultrawork",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw" or "ulw loop" for a long, evidence-driven autonomous run in ultrawork mode.'},{id:"workflow-skills.research",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw-research" for a saturating, citation-backed investigation across the codebase, docs, and the web.'},{id:"workflow-skills.hyperplan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "hyperplan" to have adversarial reviewers attack a plan before you commit to it.'},{id:"workflow-skills.review",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "review work" to run parallel goal, quality, security, and hands-on QA reviews.'},{id:"workflow-skills.init-deep",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "/init-deep" to map a project and generate a hierarchical AGENTS.md knowledge base.'},{id:"workflow-skills.debugging",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "debug this" for parallel hypotheses, a failing regression test, a minimal fix, and real-surface QA.'},{id:"workflow-skills.refactor",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "refactor" for codebase-aware cleanup that pins behavior before changing structure.'},{id:"workflow-skills.remove-ai-slops",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "remove AI slop" to lock behavior first, then strip generated-code smells without drive-by rewrites.'},{id:"workflow-skills.visual-qa",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "visual QA" to capture browser or xterm evidence and review web or terminal interfaces.'},{id:"workflow-skills.report-bug",bindings:[],requiresCommand:"tasks",render:()=>'Hit a bug? Say "report a bug" - the report-bug skill finds the session, records the exact provider and model, routes it to the right repository, and files an evidence-backed issue only after you confirm.'},{id:"subagent-categories",bindings:[],requiresCommand:"tasks",render:()=>"Delegate by category - quick, deep, ultrabrain, architect, artistry, git, writing - each runs on its own model."},{id:"subagent-commands",bindings:[],requiresCommand:"tasks",render:()=>"Use /tasks to see this session's background subagents, and /task-kill to stop one."},{id:"subagent-config",bindings:[],requiresCommand:"tasks",render:()=>"~/.omo/omo.jsonc maps every subagent category to its model, reasoning effort, and fallback chain."},{id:"subagent-team",bindings:[],requiresCommand:"tasks",render:()=>"Ask for a team when one task needs several agents at once: members share a tasklist and report back to you."}];var WORKSPACE_TIPS=[{id:"help-command",bindings:[],requiresCommand:"help",render:()=>"Use /help to see available commands and guidance."},{id:"keybindings-command",bindings:[],render:()=>"Use /keybindings to review and customize keyboard shortcuts."},{id:"agents-md-context",bindings:[],render:()=>`${APP_NAME} loads AGENTS.md from your home directory, every parent folder, and the current folder as project instructions.`},{id:"skills-and-prompts",bindings:[],render:()=>`Skills run as /skill:name, and prompt templates in ${agentDirLabel()}/prompts expand as /templatename.`},{id:"files-command",bindings:[],requiresCommand:"files",render:()=>"Use /files to list every file this session read, wrote, or edited."},{id:"diff-command",bindings:[],requiresCommand:"diff",render:()=>"Use /diff to review this session's git changes and open them in a diff view."},{id:"todo-command",bindings:[],requiresCommand:"todo",render:()=>"Use /todo to show or edit the todo list without leaving the session."},{id:"goal-command",bindings:[],requiresCommand:"goal",render:()=>`Use /goal to set a persistent goal ${APP_NAME} keeps pursuing, then pause, resume, or clear it.`},{id:"btw-command",bindings:[],requiresCommand:"btw",render:()=>"Use /btw to ask a side question in a parallel session without disturbing this one."},{id:"lookat-command",bindings:[],requiresCommand:"lookat",render:()=>"Use /lookat to manage the vision-model chain the look_at tool uses for images and screenshots."},{id:"mcp-command",bindings:[],requiresCommand:"mcp",render:()=>"Use /mcp to inspect and manage the MCP servers wired into this session."},{id:"rules-command",bindings:[],requiresCommand:"rules",render:()=>"Use /rules to see which rules are loaded, and /reload-rules to re-read them mid-session."},{id:"hooks-command",bindings:[],requiresCommand:"hooks",render:()=>"Use /hooks to list loaded hook sources and their diagnostics."},{id:"websearch-command",bindings:[],requiresCommand:"websearch",render:()=>"Use /websearch to check which web-search provider is currently active."}];var TIP_DEFINITIONS=[...MODEL_TIPS,...INPUT_TIPS,...SESSION_TIPS,...WORKSPACE_TIPS,...SETTINGS_TIPS,...CLI_TIPS,...SUBAGENT_TIPS,...MEMORY_TIPS,...DAG_TIPS,...COMPUTER_TIPS,...ETHOS_TIPS];export{TIP_DEFINITIONS};
2
+ import{APP_NAME,CONFIG_DIR_NAME,agentDirLabel}from"./chunk-FNCILR4E.js";var CLI_TIPS=[{id:"print-mode",bindings:[],render:()=>`${APP_NAME} -p "question" answers without the TUI, and piped stdin is merged into the prompt.`},{id:"tool-flags",bindings:[],render:()=>"Limit a run's tools with -t read,bash, or drop a few with -xt write,edit."}];function stopChord(){return process.platform==="darwin"?"Control+Option+Command+Escape":"Ctrl+Alt+Shift+Escape"}var COMPUTER_TIPS=[{id:"computer.what-it-is",bindings:[],requiresCommand:"computer",render:()=>"Experimental: your agent can use native apps too: screenshots, windows, clicks and typing. Run /computer to see whether this machine is ready."},{id:"computer.stop-chord",bindings:[],requiresCommand:"computer",render:()=>`Press ${stopChord()} at any moment to stop computer input. It stays stopped until you run /computer resume; the agent cannot resume it.`},{id:"computer.background-input",bindings:[],requiresCommand:"computer",render:()=>"Computer use clicks and types into the target app in the background, so your frontmost app, keyboard focus and cursor stay where you left them."},{id:"computer.look-dont-touch",bindings:[],requiresCommand:"computer",render:()=>"Want the agent to look but not touch? Start with --permission computer:exec=deny: screenshots and accessibility reads still work, clicks and typing are refused."},{id:"computer.permissions",bindings:[],requiresCommand:"computer",render:()=>"On macOS, computer use needs Screen Recording and Accessibility for the app you launch from. /computer status shows which one is missing."}];var DAG_TIPS=[{id:"dag.one-keyword-mastery",bindings:[],requiresCommand:"dag",render:()=>'One keyword makes you a master of graph engineering: say "mass-ulw" and your work becomes a dependency graph that schedules itself.'},{id:"dag.what-it-is",bindings:[],requiresCommand:"dag",render:()=>'Trigger "mass-ulw" when some tasks must wait for others - describe the work, get a graph that runs in the right order.'},{id:"dag.parallel-waves",bindings:[],requiresCommand:"dag",render:()=>"A graph run executes in waves: everything with no pending dependency starts at once, the rest starts the moment it is unblocked."},{id:"dag.depends-on",bindings:[],requiresCommand:"dag",render:()=>"Say what needs what - review after implementation, docs after both - and the ordering is enforced for you."},{id:"dag.categories",bindings:[],requiresCommand:"dag",render:()=>"Each node in the graph picks its own worker category, so cheap steps stay cheap and hard steps get the strong model."},{id:"dag.status-view",bindings:[],requiresCommand:"dag",render:()=>"Use /dag to watch a run: which nodes finished, which are running, and which one failed."},{id:"dag.resume",bindings:[],requiresCommand:"dag",render:()=>"Graph runs are journaled - if the session dies mid-run it resumes later and never redoes the nodes that already finished."},{id:"dag.vs-parallel",bindings:[],requiresCommand:"dag",render:()=>"Fully independent jobs just need parallel subagents; reach for a graph when the ordering between them is the whole point."},{id:"dag.scale",bindings:[],requiresCommand:"dag",render:()=>"Stop hand-running steps in sequence. Describe the dependencies once and let a dozen agents fan out and rejoin on their own."}];var ETHOS_TIPS=[{id:"ethos.tuning-discipline",bindings:[],render:()=>"gpt-5.6-sol used to turn a sprint into a marathon. We tuned the system prompt and killed that habit: 5-minute jobs take 5 minutes, 12-hour jobs take 12."},{id:"ethos.tools-transparent",bindings:[],render:()=>"Don't study our tools. A tool that needs studying is a tool that failed. We just ride shotgun while you keep doing your actual job."},{id:"ethos.only-harness",bindings:[],render:()=>"The only harness that actually knows how to drive gpt-5.6-sol. Same job, feels up to 30% faster. *we counted*"},{id:"ethos.spend-tokens",bindings:[],render:()=>"Stop hoarding tokens. Spend them like they buy your hours back, because they do."},{id:"ethos.deep-work",bindings:[],render:()=>"Using our tools means your work is already the deep, valuable kind. Keep your eyes on the essence of your craft. The rest is our problem now, and we're great at problems."},{id:"ethos.ulw-plan-sage",bindings:[],requiresCommand:"tasks",render:()=>"Try ulw-plan on fable-5.1 xhigh. A patient sage obsessed with the essence does the agonizing for you and fills in every blank you were pretending not to see."},{id:"ethos.ulw-loop-shallow",bindings:[],requiresCommand:"tasks",render:()=>"For days when deep thought sounds awful, run the ulw loop with gpt-6-sol fast/medium. Fair warning: shallow thinking sends invoices."},{id:"ethos.monitor-subscribe",bindings:[],render:()=>"Subscribe to a command's stdout and forget it. CI finishes, server boots, log line lands... you're mid-edit and the news finds *you*. No sleep loops, no polling, no re-reading context like a chump."},{id:"ethos.cache-budget",bindings:[],render:()=>"My harness knows the prompt cache's expiry to the second and never blocks past it. Cold re-read tax? *Refused on your behalf.* Other agents eat that cost, mine declines it."},{id:"ethos.cache-hit-rate",bindings:[],render:()=>"Live cache-hit rate in the footer, plus a running tab of misses, idle gaps, and model swaps. I can point at the exact moment cache broke and why. Watching tokens you never re-pay stack up? Smug doesn't cover it."},{id:"ethos.multimodal-vision",bindings:[],render:()=>`Drop a screenshot, a PDF, a crusty whiteboard photo... ${APP_NAME} actually sees it, reads it, reasons about it. Your agent has eyes now. *Yes, really.*`},{id:"ethos.oauth-multi-account",bindings:[],render:()=>`Hit a rate limit, switch accounts. Wrong org, switch again. ${APP_NAME} treats your Claude logins like a roster, not a single lifeline. *Env vars could never.*`},{id:"ethos.agent-sdk-foundation",bindings:[],render:()=>'Built on the official agent SDK, speaking the protocol natively. No reverse-engineered wrapper, no ToS gray zone, no "will I get banned for this" anxiety. *Sleep easy, ship loud.*'},{id:"ethos.tool-call-repair",bindings:[],render:()=>`${APP_NAME} catches malformed tool calls on the wire, fixes them, and salvages the turn - claude's sloppy invokes, kimi k3's leaked XTML channels, all of it. Other harnesses retry the whole thing and bill you for the privilege. *table stakes, honestly*`}];var INPUT_TIPS=[{id:"click-pending-question",bindings:[],render:()=>"Click a pending question's option to answer. Use the displayed selection-bypass modifier to select terminal text, or disable terminal.mouse in /settings."},{id:"queue-follow-up",bindings:["app.message.followUp"],render:keys=>`While the agent is working, use ${keys("app.message.followUp")} to queue a follow-up for after it finishes.`},{id:"steering-message",bindings:["tui.input.submit","app.message.followUp"],render:keys=>`Press ${keys("tui.input.submit")} while the agent works to steer it after the current tool batch; ${keys("app.message.followUp")} waits until all work is done.`},{id:"edit-queued-message",bindings:["app.message.dequeue"],render:keys=>`Use ${keys("app.message.dequeue")} to bring queued messages back for editing.`},{id:"interrupt-restores-queue",bindings:["app.interrupt"],render:keys=>`Press ${keys("app.interrupt")} to abort the current turn and restore queued messages to the editor.`},{id:"file-reference",bindings:[],render:()=>"Type @ in the editor to fuzzy-search project files and insert their paths."},{id:"path-completion",bindings:["tui.input.tab"],render:keys=>`Press ${keys("tui.input.tab")} to complete file paths while typing.`},{id:"shortcut-overlay",bindings:[],render:()=>"Type ? in an empty editor to pop up the full shortcut grid."},{id:"prompt-history",bindings:["app.history.search"],requiresCommand:"history",render:keys=>`Search prompt history across sessions with ${keys("app.history.search")}.`},{id:"external-editor",bindings:["app.editor.external"],render:keys=>`Open the current prompt in your external editor with ${keys("app.editor.external")}.`},{id:"expand-tool-output",bindings:["app.tools.expand"],render:keys=>`Collapse or expand tool output with ${keys("app.tools.expand")}.`},{id:"thinking-blocks",bindings:["app.thinking.toggle"],render:keys=>`Collapse or expand thinking blocks with ${keys("app.thinking.toggle")}.`},{id:"paste-image",bindings:["app.clipboard.pasteImage"],render:keys=>`Paste an image from the clipboard with ${keys("app.clipboard.pasteImage")}.`},{id:"copy-message",bindings:["app.message.copy"],render:keys=>`Copy the latest assistant message with ${keys("app.message.copy")}.`},{id:"input-newline",bindings:["tui.input.newLine"],render:keys=>`Insert a newline without sending with ${keys("tui.input.newLine")}.`},{id:"bash-prefixes",bindings:[],render:()=>"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context."},{id:"drag-drop-files",bindings:[],render:()=>"Drag and drop files into the terminal to add their paths to your prompt."},{id:"answer-agent-question",bindings:[],render:()=>"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered."},{id:"open-pending-question",bindings:["app.question.answer","app.question.next"],render:keys=>`Pending questions queue above the editor. An empty-composer digit selects an option; ${keys("app.question.answer")} opens the shown request and ${keys("app.question.next")} cycles requests. /answer lists them.`}];var MEMORY_TIPS=[{id:"memory.persistent",bindings:[],requiresCommand:"memory",render:()=>`${APP_NAME} remembers across sessions. Close the terminal, come back tomorrow, and the context is still there.`},{id:"memory.remember-command",bindings:[],requiresCommand:"remember",render:()=>"Use /remember to save something you want kept - a preference, a decision, a fact worth reusing."},{id:"memory.just-tell-it",bindings:[],requiresCommand:"remember",render:()=>'You can also just say it: "remember that we deploy on Fridays" is enough. No syntax, no file to open.'},{id:"memory.search-command",bindings:[],requiresCommand:"search",render:()=>"Use /search to look through everything remembered so far, in plain words."},{id:"memory.memory-command",bindings:[],requiresCommand:"memory",render:()=>"Use /memory to see what is currently remembered about you and this project."},{id:"memory.init-command",bindings:[],requiresCommand:"init",render:()=>"Use /init to start memory for a new project, so it learns this codebase from the first session."},{id:"memory.people-command",bindings:[],requiresCommand:"people",render:()=>"Use /people to keep notes on teammates - who owns what, who to ask, what they prefer."},{id:"memory.reflect-command",bindings:[],requiresCommand:"reflect",render:()=>"Use /reflect to have the session reviewed now and the parts worth keeping written down."},{id:"memory.dream-command",bindings:[],requiresCommand:"dream",render:()=>"Memory tidies itself in the background between turns - /dream shows that work and lets you start it yourself."},{id:"memory.sleeptime-command",bindings:[],requiresCommand:"sleeptime",render:()=>"Use /sleeptime to decide how often memory reorganizes itself while you are not looking."},{id:"memory.memfs-command",bindings:[],requiresCommand:"memfs",render:()=>"Memory is plain files you own - browse them with /memfs and edit anything that looks wrong."},{id:"memory.repository-command",bindings:[],requiresCommand:"memory-repository",render:()=>"Every memory change is a git commit - use /memory-repository to see the history and undo a bad one."},{id:"memory.doctor-command",bindings:[],requiresCommand:"doctor",render:()=>"Use /doctor when memory feels off; it checks the setup and tells you what to fix."},{id:"memory.facts-command",bindings:[],requiresCommand:"facts",render:()=>"Use /facts to see the individual things learned about you, and drop the ones that no longer hold."},{id:"memory.recompile-command",bindings:[],requiresCommand:"recompile",render:()=>"Edited memory files by hand? Run /recompile so this session picks the changes up right away."},{id:"memory.aha-moment",bindings:[],requiresCommand:"memory",render:()=>"Memory speaks up on its own: when something remembered would change the next step, an Aha moment! line surfaces it mid-task. Silence means nothing relevant was found."},{id:"memory.stop-repeating",bindings:[],requiresCommand:"memory",render:()=>"Explain your setup once. Memory means you stop re-explaining it at the start of every session."}];var MODEL_TIPS=[{id:"thinking-level",bindings:["app.thinking.cycle"],render:keys=>`Use /thinking <level> to set the thinking level, /thinking to pick one, or ${keys("app.thinking.cycle")} to cycle through them.`},{id:"efforts-command",bindings:[],requiresCommand:"efforts",render:()=>"Use /efforts <level> to set the reasoning effort for the current model; /efforts alone lists the levels it supports."},{id:"favorite-model-rotation",bindings:["app.model.cycleForward","app.model.cycleBackward"],render:keys=>`Rotate through favorite models with ${keys("app.model.cycleForward")}; go backward with ${keys("app.model.cycleBackward")}.`},{id:"model-selector-favorites",bindings:["app.model.select","app.models.toggleFavorite"],render:keys=>`Open the model selector with ${keys("app.model.select")}, then use ${keys("app.models.toggleFavorite")} to toggle the highlighted favorite.`},{id:"model-command-search",bindings:[],render:()=>"Use /model to open the selector, or /model <pattern> to jump straight to a matching model."},{id:"model-cycling-scope",bindings:["app.model.cycleForward"],render:keys=>`Start ${APP_NAME} with --models "anthropic/*,gpt-5*" to limit which models ${keys("app.model.cycleForward")} cycles through.`},{id:"thinking-budgets",bindings:[],render:()=>"Set thinkingBudgets in settings.json to choose the token budget behind each thinking level."},{id:"prompt-preset",bindings:[],render:()=>"Set promptPreset in settings.json when a model does not auto-detect the system prompt you want."},{id:"provider-login",bindings:[],render:()=>"Use /login to add a subscription or API-key provider, and /logout to remove stored credentials."},{id:"fallback-chains-setting",bindings:[],render:()=>"retry.fallbackChains in settings.json maps a model to ordered fallbacks, so a failed turn retries on the next one."},{id:"fallback-command",bindings:[],requiresCommand:"fallback",render:()=>"Use /fallback to inspect and manage the retry fallback chain for the current model."}];var SESSION_TIPS=[{id:"favorite-models-command",bindings:[],render:()=>"Use /favorite-models to choose and reorder the models in your rotation."},{id:"tree-command",bindings:[],render:()=>"Use /tree to revisit earlier points and switch between session branches."},{id:"fork-command",bindings:[],render:()=>"Use /fork to create a separate session from an earlier user message."},{id:"clone-session",bindings:[],render:()=>"Use /clone to duplicate the current branch into its own session before trying something risky."},{id:"continue-session",bindings:[],render:()=>`Use /resume or /sessions to reopen a past session; from the shell, ${APP_NAME} -r opens the same picker and ${APP_NAME} -c continues the most recent one.`},{id:"session-name",bindings:[],render:()=>"Use /rename [name] to label a session so it is easy to spot in the footer and in /resume."},{id:"session-info",bindings:[],render:()=>"Use /session to see the session file, id, message count, tokens, and cost."},{id:"export-share",bindings:[],render:()=>"Use /export to write the session to HTML or JSONL, or /share to upload it as a private gist link."},{id:"compact-command",bindings:[],render:()=>"Use /compact to compact context now, or /compact <prompt> to tell the summarizer what to keep."},{id:"auto-compaction",bindings:[],render:()=>"Auto-compaction is on by default - the (auto) marker in the footer shows it; tune it with compaction.* in settings.json."}];var SETTINGS_TIPS=[{id:"settings-locations",bindings:[],render:()=>`Use /settings for common options; the rest live in settings.json, with ${CONFIG_DIR_NAME}/settings.json overriding per project.`},{id:"permission-preset",bindings:[],render:()=>'Set permissionPreset to "workspace", "read-only", or "ask" to decide which tool calls need your approval.'},{id:"packages-setting",bindings:[],render:()=>"The packages setting loads skills, extensions, prompts, and themes from an npm or git package."},{id:"custom-themes",bindings:[],render:()=>`Switch themes from /settings, and drop custom theme files in ${agentDirLabel()}/themes.`},{id:"reload-resources",bindings:[],render:()=>"Use /reload to re-read keybindings, extensions, skills, prompts, themes, and context files without restarting."},{id:"project-trust",bindings:[],render:()=>"Use /trust to save a trust decision so this project's settings, skills, and extensions load next time."},{id:"tips-toggle",bindings:[],render:()=>'Set "tips": false in settings.json to stop showing these tips.'}];var SUBAGENT_TIPS=[{id:"workflow-skills.plan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw plan" to get an explored, decision-complete plan under .omo/plans/.'},{id:"workflow-skills.start-work",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "$start-work <plan-name>" to execute a plan end-to-end in a fresh session.'},{id:"workflow-skills.ultrawork",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw" or "ulw loop" for a long, evidence-driven autonomous run in ultrawork mode.'},{id:"workflow-skills.research",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw-research" for a saturating, citation-backed investigation across the codebase, docs, and the web.'},{id:"workflow-skills.hyperplan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "hyperplan" to have adversarial reviewers attack a plan before you commit to it.'},{id:"workflow-skills.review",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "review work" to run parallel goal, quality, security, and hands-on QA reviews.'},{id:"workflow-skills.init-deep",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "/init-deep" to map a project and generate a hierarchical AGENTS.md knowledge base.'},{id:"workflow-skills.debugging",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "debug this" for parallel hypotheses, a failing regression test, a minimal fix, and real-surface QA.'},{id:"workflow-skills.refactor",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "refactor" for codebase-aware cleanup that pins behavior before changing structure.'},{id:"workflow-skills.remove-ai-slops",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "remove AI slop" to lock behavior first, then strip generated-code smells without drive-by rewrites.'},{id:"workflow-skills.visual-qa",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "visual QA" to capture browser or xterm evidence and review web or terminal interfaces.'},{id:"workflow-skills.report-bug",bindings:[],requiresCommand:"tasks",render:()=>'Hit a bug? Say "report a bug" - the report-bug skill finds the session, records the exact provider and model, routes it to the right repository, and files an evidence-backed issue only after you confirm.'},{id:"subagent-categories",bindings:[],requiresCommand:"tasks",render:()=>"Delegate by category - quick, deep, ultrabrain, architect, artistry, git, writing - each runs on its own model."},{id:"subagent-commands",bindings:[],requiresCommand:"tasks",render:()=>"Use /tasks to see this session's background subagents, and /task-kill to stop one."},{id:"subagent-config",bindings:[],requiresCommand:"tasks",render:()=>"~/.omo/omo.jsonc maps every subagent category to its model, reasoning effort, and fallback chain."},{id:"subagent-team",bindings:[],requiresCommand:"tasks",render:()=>"Ask for a team when one task needs several agents at once: members share a tasklist and report back to you."}];var WORKSPACE_TIPS=[{id:"help-command",bindings:[],requiresCommand:"help",render:()=>"Use /help to see available commands and guidance."},{id:"keybindings-command",bindings:[],render:()=>"Use /keybindings to review and customize keyboard shortcuts."},{id:"agents-md-context",bindings:[],render:()=>`${APP_NAME} loads AGENTS.md from your home directory, every parent folder, and the current folder as project instructions.`},{id:"skills-and-prompts",bindings:[],render:()=>`Skills run as /skill:name, and prompt templates in ${agentDirLabel()}/prompts expand as /templatename.`},{id:"files-command",bindings:[],requiresCommand:"files",render:()=>"Use /files to list every file this session read, wrote, or edited."},{id:"diff-command",bindings:[],requiresCommand:"diff",render:()=>"Use /diff to review this session's git changes and open them in a diff view."},{id:"todo-command",bindings:[],requiresCommand:"todo",render:()=>"Use /todo to show or edit the todo list without leaving the session."},{id:"goal-command",bindings:[],requiresCommand:"goal",render:()=>`Use /goal to set a persistent goal ${APP_NAME} keeps pursuing, then pause, resume, or clear it.`},{id:"btw-command",bindings:[],requiresCommand:"btw",render:()=>"Use /btw to ask a side question in a parallel session without disturbing this one."},{id:"lookat-command",bindings:[],requiresCommand:"lookat",render:()=>"Use /lookat to manage the vision-model chain the look_at tool uses for images and screenshots."},{id:"mcp-command",bindings:[],requiresCommand:"mcp",render:()=>"Use /mcp to inspect and manage the MCP servers wired into this session."},{id:"rules-command",bindings:[],requiresCommand:"rules",render:()=>"Use /rules to see which rules are loaded, and /reload-rules to re-read them mid-session."},{id:"hooks-command",bindings:[],requiresCommand:"hooks",render:()=>"Use /hooks to list loaded hook sources and their diagnostics."},{id:"websearch-command",bindings:[],requiresCommand:"websearch",render:()=>"Use /websearch to check which web-search provider is currently active."}];var TIP_DEFINITIONS=[...MODEL_TIPS,...INPUT_TIPS,...SESSION_TIPS,...WORKSPACE_TIPS,...SETTINGS_TIPS,...CLI_TIPS,...SUBAGENT_TIPS,...MEMORY_TIPS,...DAG_TIPS,...COMPUTER_TIPS,...ETHOS_TIPS];export{TIP_DEFINITIONS};