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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundle/chunks/{app-server-command-DVWM37GF.js → app-server-command-N3L2LNP7.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-MT2C4I5R.js → chunk-MP2DMTI7.js} +38 -37
  4. package/dist/bundle/chunks/chunk-USRAHAW4.js +14 -0
  5. package/dist/bundle/chunks/{chunk-CTERKXVZ.js → chunk-ZSYRWQWG.js} +2 -2
  6. package/dist/bundle/chunks/{cli-main-B4S4DGBX.js → cli-main-CHDR33FZ.js} +1 -1
  7. package/dist/bundle/chunks/{interactive-mode-QOFA64JL.js → interactive-mode-RVEM62WX.js} +1 -1
  8. package/dist/bundle/chunks/{multi-session-host-E5RDPWQN.js → multi-session-host-CFND7CXH.js} +1 -1
  9. package/dist/bundle/chunks/{package-manager-cli-YGTWXRG5.js → package-manager-cli-NWNECBF7.js} +1 -1
  10. package/dist/bundle/chunks/{rpc-mode-HDAGQ4X3.js → rpc-mode-JQFUDLNB.js} +1 -1
  11. package/dist/bundle/chunks/session-control-endpoint-HMB5T5VD.js +3 -0
  12. package/dist/bundle/chunks/session-worker.js +53 -52
  13. package/dist/bundle/cli.js +1 -1
  14. package/dist/bundle/index.js +1 -1
  15. package/dist/bundle/rpc-entry.js +1 -1
  16. package/dist/bundle/runtime-manifest.json +1 -1
  17. package/dist/core/extensions/session-control-types.d.ts +25 -0
  18. package/dist/core/extensions/session-control-types.js +16 -0
  19. package/dist/core/external-admission.js +7 -1
  20. package/dist/core/resource-loader.js +63 -2
  21. package/dist/core/session-rebind.js +16 -1
  22. package/dist/modes/interactive/components/extension-editor.js +4 -0
  23. package/dist/modes/interactive/components/remote-delivery-message.d.ts +6 -3
  24. package/dist/modes/interactive/components/remote-delivery-message.js +32 -3
  25. package/dist/modes/interactive/interactive-mode.d.ts +17 -0
  26. package/dist/modes/interactive/interactive-mode.js +58 -29
  27. package/dist/modes/interactive/interactive-stderr-guard.d.ts +8 -0
  28. package/dist/modes/interactive/interactive-stderr-guard.js +70 -0
  29. package/dist/modes/interactive/session-control-commands.d.ts +2 -1
  30. package/dist/modes/interactive/session-control-commands.js +21 -7
  31. package/dist/modes/interactive/session-control-session-commands.d.ts +22 -0
  32. package/dist/modes/interactive/session-control-session-commands.js +47 -0
  33. package/dist/modes/interactive/stdout-fd-redirect.d.ts +12 -0
  34. package/dist/modes/interactive/stdout-fd-redirect.js +114 -0
  35. package/dist/modes/rpc/connection-handler.js +6 -15
  36. package/dist/modes/rpc/rpc-types.d.ts +13 -0
  37. package/dist/modes/rpc/session-control-actions-data.d.ts +17 -0
  38. package/dist/modes/rpc/session-control-actions-data.js +38 -0
  39. package/docs/extensions.md +1 -1
  40. package/docs/rpc.md +38 -4
  41. package/package.json +6 -6
  42. package/dist/bundle/chunks/chunk-PDSG6VER.js +0 -14
  43. package/dist/bundle/chunks/session-control-endpoint-NABTZHCZ.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{watchWithErrorHandler}from"./chunk-JABBHOD5.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{ProjectTrustStore}from"./chunk-RRU5LXMS.js";import{sanitizeProviderDiagnostic}from"./chunk-YOPVJDSU.js";var BROWSER_ENGINES=["connected","builtin","none"];function isBrowserEngine(value){return BROWSER_ENGINES.some(engine=>engine===value)}var clientMessageIdentitySchema=external_exports.object({clientMessageId:external_exports.string().min(1).max(256).optional(),clientTurnId:external_exports.string().min(1).max(256).optional()});function clientMessageIdentity(value={}){return{...value.clientMessageId===void 0?{}:{clientMessageId:value.clientMessageId},...value.clientTurnId===void 0?{}:{clientTurnId:value.clientTurnId}}}function readClientMessageIdentity(value){let parsed=clientMessageIdentitySchema.safeParse(value);return parsed.success?clientMessageIdentity(parsed.data):{}}var MAX_RPC_MESSAGE_CHARACTERS=1e6,SESSION_CONTEXT_LIMITS={keys:32,valueBytes:16*1024,totalBytes:32*1024},SESSION_CONTEXT_KEY_PATTERN=/^[a-z][a-z0-9_]*$/;function validContent(content){return typeof content=="string"?!0:Array.isArray(content)&&content.every(item=>{if(typeof item!="object"||item===null)return!1;let value=item;return value.type==="text"?typeof value.text=="string":value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string"})}function validBaseEntry(entry){return typeof entry.id=="string"&&(entry.parentId===null||typeof entry.parentId=="string")&&typeof entry.timestamp=="string"}function validSessionEntry(entry){if(typeof entry!="object"||entry===null||Array.isArray(entry))return!1;let value=entry;if(!validBaseEntry(value))return!1;switch(value.type){case"message":{let message=value.message;if(typeof message!="object"||message===null)return!1;let item=message;return["user","assistant","tool"].includes(item.role)&&validContent(item.content)}case"thinking_level_change":return typeof value.thinkingLevel=="string";case"model_change":return typeof value.provider=="string"&&typeof value.modelId=="string";case"model_change_rejected":return typeof value.provider=="string"&&typeof value.modelId=="string"&&typeof value.detail=="string";case"compaction":return typeof value.summary=="string"&&typeof value.firstKeptEntryId=="string"&&typeof value.tokensBefore=="number";case"branch_summary":return typeof value.fromId=="string"&&typeof value.summary=="string";case"custom":return typeof value.customType=="string";case"custom_message":return typeof value.customType=="string"&&validContent(value.content)&&typeof value.display=="boolean";case"label":return typeof value.targetId=="string"&&(value.label===void 0||typeof value.label=="string");case"session_info":return value.name===void 0||typeof value.name=="string";default:return!1}}function rpcCommandPayloadError(command){if(rpcCommandShapeError(command))return;let value=command;if((value.type==="prompt"||value.type==="steer"||value.type==="follow_up")&&!clientMessageIdentitySchema.safeParse(value).success)return"clientMessageId and clientTurnId must be non-empty strings of at most 256 characters.";if((value.type==="steer"||value.type==="follow_up")&&value.enqueueOrder!==void 0&&!(typeof value.enqueueOrder=="number"&&Number.isFinite(value.enqueueOrder)))return"enqueueOrder must be a finite number.";if(value.type==="append_user_message"&&!validContent(value.content))return"append_user_message content must be a string or text/image content array.";if(value.type==="append_session_entry"&&!validSessionEntry(value.entry))return"append_session_entry entry is malformed."}function sessionContextError(context){if(context===void 0)return;if(typeof context!="object"||context===null||Array.isArray(context))return"context must be an object of string values.";let entries=Object.entries(context);if(entries.length>SESSION_CONTEXT_LIMITS.keys)return`context has ${entries.length} keys, at most ${SESSION_CONTEXT_LIMITS.keys} are accepted.`;for(let[key,value]of entries){if(!SESSION_CONTEXT_KEY_PATTERN.test(key))return`context key "${key}" must match ${SESSION_CONTEXT_KEY_PATTERN.source}.`;if(typeof value!="string")return`context value for key "${key}" must be a string.`;let valueBytes=Buffer.byteLength(value);if(valueBytes>SESSION_CONTEXT_LIMITS.valueBytes)return`context value for key "${key}" is ${valueBytes} bytes, at most ${SESSION_CONTEXT_LIMITS.valueBytes} bytes are accepted.`}let totalBytes=Buffer.byteLength(JSON.stringify(context));if(totalBytes>SESSION_CONTEXT_LIMITS.totalBytes)return`context is ${totalBytes} bytes of JSON, at most ${SESSION_CONTEXT_LIMITS.totalBytes} bytes are accepted.`}function sessionKindError(kind){if(!(kind===void 0||kind==="interactive"||kind==="worker"))return'kind must be "interactive" or "worker".'}function sessionAutoTitleError(value){if(!(value===void 0||typeof value=="boolean"))return"auto_title must be a boolean."}function sessionPromptSurfaceError(value){if(!(value===void 0||value==="terminal"||value==="app"||value==="chat"))return'promptSurface must be "terminal", "app" or "chat".'}function sessionBrowserEngineError(value){if(!(value===void 0||isBrowserEngine(value)))return'browserEngine must be "connected", "builtin" or "none".'}var MAX_RETRY_FALLBACK_CHAINS=32,MAX_RETRY_FALLBACK_ENTRIES=32,MAX_RETRY_FALLBACK_SELECTOR_LENGTH=512;function sessionRetryFallbackError(value){if(value===void 0)return;let shape="retryFallback must be { modelFallback: boolean, fallbackChains: Record<string, string[]> }.";if(typeof value!="object"||value===null||Array.isArray(value))return shape;let record=value;if(typeof record.modelFallback!="boolean")return shape;let chains=record.fallbackChains;if(typeof chains!="object"||chains===null||Array.isArray(chains))return shape;let entries=Object.entries(chains);if(entries.length>MAX_RETRY_FALLBACK_CHAINS)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_CHAINS} chains.`;for(let[key,selectors]of entries){if(!isSelector(key)||!Array.isArray(selectors)||!selectors.every(isSelector))return shape;if(selectors.length>MAX_RETRY_FALLBACK_ENTRIES)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_ENTRIES} entries per chain.`}}function isSelector(value){return typeof value=="string"&&value.trim().length>0&&value.length<=MAX_RETRY_FALLBACK_SELECTOR_LENGTH}function rpcCommandShapeError(command){if(typeof command!="object"||command===null||Array.isArray(command))return"RPC command must be a JSON object."}function rpcMessageLengthError(command){if(rpcCommandShapeError(command))return;let input=command;if(!(input.type!=="prompt"&&input.type!=="steer"&&input.type!=="follow_up")&&!(typeof input.message!="string"||input.message.length<=MAX_RPC_MESSAGE_CHARACTERS))return`RPC ${input.type} message exceeds ${MAX_RPC_MESSAGE_CHARACTERS} characters.`}import{randomUUID}from"node:crypto";import{mkdir,rm,writeFile}from"node:fs/promises";import{join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{Worker}from"node:worker_threads";var RECURSIVE_WATCH_WORKER_SOURCE=`
2
+ import{watchWithErrorHandler}from"./chunk-JABBHOD5.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{ProjectTrustStore}from"./chunk-RRU5LXMS.js";import{modelSupportsAssistantPrefill}from"./chunk-ODYQK5XJ.js";import{sanitizeProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{getSupportedThinkingLevels,supportsMax,supportsXhigh}from"./chunk-XL5KIYQF.js";function supportsXhigh2(model){return supportsXhigh(model)}function supportsMax2(model){return supportsMax(model)}function getSupportedThinkingLevels2(model){let supportedLevels=getSupportedThinkingLevels(model);return supportedLevels.length>0?supportedLevels:["off"]}function clampThinkingSelection(selection,requested,level,model){if(selection===void 0)return;let{requested:_staleRequested,clampReason:_staleReason,...base}=selection;return requested===level||model===void 0?{...base,level}:{...base,level,requested,clampReason:model.reasoning?"level-unsupported":"model-not-reasoning"}}function getThinkingClampNotice(selection,model){let clamped=selection;if(!(model===void 0||clamped?.requested===void 0||clamped.clampReason===void 0))return{provider:model.provider,modelId:model.id,requestedLevel:clamped.requested,appliedLevel:clamped.level,reason:clamped.clampReason}}function formatThinkingClampWarning(notice){let model=`${notice.provider}/${notice.modelId}`;return notice.reason==="model-not-reasoning"?`Thinking level "${notice.requestedLevel}" was requested, but ${model} is not marked as a reasoning model, so thinking is "${notice.appliedLevel}". If the model supports reasoning, set "reasoning": true for it in models.json.`:`Thinking level "${notice.requestedLevel}" is not available on ${model}; using "${notice.appliedLevel}".`}function classifyReasoningCapability(model){if(!model.reasoning)return{kind:"none",levels:["off"],nonOffLevels:[]};let levels=getSupportedThinkingLevels2(model),nonOffLevels=levels.filter(level=>level!=="off");return levels.includes("off")?nonOffLevels.length===1?{kind:"on-off",levels,nonOffLevels}:nonOffLevels.length===0?{kind:"none",levels,nonOffLevels}:{kind:"graded",levels,nonOffLevels}:{kind:"always-on",levels,nonOffLevels}}var BROWSER_ENGINES=["connected","builtin","none"];function isBrowserEngine(value){return BROWSER_ENGINES.some(engine=>engine===value)}var clientMessageIdentitySchema=external_exports.object({clientMessageId:external_exports.string().min(1).max(256).optional(),clientTurnId:external_exports.string().min(1).max(256).optional()});function clientMessageIdentity(value={}){return{...value.clientMessageId===void 0?{}:{clientMessageId:value.clientMessageId},...value.clientTurnId===void 0?{}:{clientTurnId:value.clientTurnId}}}function readClientMessageIdentity(value){let parsed=clientMessageIdentitySchema.safeParse(value);return parsed.success?clientMessageIdentity(parsed.data):{}}var MAX_RPC_MESSAGE_CHARACTERS=1e6,SESSION_CONTEXT_LIMITS={keys:32,valueBytes:16*1024,totalBytes:32*1024},SESSION_CONTEXT_KEY_PATTERN=/^[a-z][a-z0-9_]*$/;function validContent(content){return typeof content=="string"?!0:Array.isArray(content)&&content.every(item=>{if(typeof item!="object"||item===null)return!1;let value=item;return value.type==="text"?typeof value.text=="string":value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string"})}function validBaseEntry(entry){return typeof entry.id=="string"&&(entry.parentId===null||typeof entry.parentId=="string")&&typeof entry.timestamp=="string"}function validSessionEntry(entry){if(typeof entry!="object"||entry===null||Array.isArray(entry))return!1;let value=entry;if(!validBaseEntry(value))return!1;switch(value.type){case"message":{let message=value.message;if(typeof message!="object"||message===null)return!1;let item=message;return["user","assistant","tool"].includes(item.role)&&validContent(item.content)}case"thinking_level_change":return typeof value.thinkingLevel=="string";case"model_change":return typeof value.provider=="string"&&typeof value.modelId=="string";case"model_change_rejected":return typeof value.provider=="string"&&typeof value.modelId=="string"&&typeof value.detail=="string";case"compaction":return typeof value.summary=="string"&&typeof value.firstKeptEntryId=="string"&&typeof value.tokensBefore=="number";case"branch_summary":return typeof value.fromId=="string"&&typeof value.summary=="string";case"custom":return typeof value.customType=="string";case"custom_message":return typeof value.customType=="string"&&validContent(value.content)&&typeof value.display=="boolean";case"label":return typeof value.targetId=="string"&&(value.label===void 0||typeof value.label=="string");case"session_info":return value.name===void 0||typeof value.name=="string";default:return!1}}function rpcCommandPayloadError(command){if(rpcCommandShapeError(command))return;let value=command;if((value.type==="prompt"||value.type==="steer"||value.type==="follow_up")&&!clientMessageIdentitySchema.safeParse(value).success)return"clientMessageId and clientTurnId must be non-empty strings of at most 256 characters.";if((value.type==="steer"||value.type==="follow_up")&&value.enqueueOrder!==void 0&&!(typeof value.enqueueOrder=="number"&&Number.isFinite(value.enqueueOrder)))return"enqueueOrder must be a finite number.";if(value.type==="append_user_message"&&!validContent(value.content))return"append_user_message content must be a string or text/image content array.";if(value.type==="append_session_entry"&&!validSessionEntry(value.entry))return"append_session_entry entry is malformed."}function sessionContextError(context){if(context===void 0)return;if(typeof context!="object"||context===null||Array.isArray(context))return"context must be an object of string values.";let entries=Object.entries(context);if(entries.length>SESSION_CONTEXT_LIMITS.keys)return`context has ${entries.length} keys, at most ${SESSION_CONTEXT_LIMITS.keys} are accepted.`;for(let[key,value]of entries){if(!SESSION_CONTEXT_KEY_PATTERN.test(key))return`context key "${key}" must match ${SESSION_CONTEXT_KEY_PATTERN.source}.`;if(typeof value!="string")return`context value for key "${key}" must be a string.`;let valueBytes=Buffer.byteLength(value);if(valueBytes>SESSION_CONTEXT_LIMITS.valueBytes)return`context value for key "${key}" is ${valueBytes} bytes, at most ${SESSION_CONTEXT_LIMITS.valueBytes} bytes are accepted.`}let totalBytes=Buffer.byteLength(JSON.stringify(context));if(totalBytes>SESSION_CONTEXT_LIMITS.totalBytes)return`context is ${totalBytes} bytes of JSON, at most ${SESSION_CONTEXT_LIMITS.totalBytes} bytes are accepted.`}function sessionKindError(kind){if(!(kind===void 0||kind==="interactive"||kind==="worker"))return'kind must be "interactive" or "worker".'}function sessionAutoTitleError(value){if(!(value===void 0||typeof value=="boolean"))return"auto_title must be a boolean."}function sessionPromptSurfaceError(value){if(!(value===void 0||value==="terminal"||value==="app"||value==="chat"))return'promptSurface must be "terminal", "app" or "chat".'}function sessionBrowserEngineError(value){if(!(value===void 0||isBrowserEngine(value)))return'browserEngine must be "connected", "builtin" or "none".'}var MAX_RETRY_FALLBACK_CHAINS=32,MAX_RETRY_FALLBACK_ENTRIES=32,MAX_RETRY_FALLBACK_SELECTOR_LENGTH=512;function sessionRetryFallbackError(value){if(value===void 0)return;let shape="retryFallback must be { modelFallback: boolean, fallbackChains: Record<string, string[]> }.";if(typeof value!="object"||value===null||Array.isArray(value))return shape;let record=value;if(typeof record.modelFallback!="boolean")return shape;let chains=record.fallbackChains;if(typeof chains!="object"||chains===null||Array.isArray(chains))return shape;let entries=Object.entries(chains);if(entries.length>MAX_RETRY_FALLBACK_CHAINS)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_CHAINS} chains.`;for(let[key,selectors]of entries){if(!isSelector(key)||!Array.isArray(selectors)||!selectors.every(isSelector))return shape;if(selectors.length>MAX_RETRY_FALLBACK_ENTRIES)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_ENTRIES} entries per chain.`}}function isSelector(value){return typeof value=="string"&&value.trim().length>0&&value.length<=MAX_RETRY_FALLBACK_SELECTOR_LENGTH}function rpcCommandShapeError(command){if(typeof command!="object"||command===null||Array.isArray(command))return"RPC command must be a JSON object."}function rpcMessageLengthError(command){if(rpcCommandShapeError(command))return;let input=command;if(!(input.type!=="prompt"&&input.type!=="steer"&&input.type!=="follow_up")&&!(typeof input.message!="string"||input.message.length<=MAX_RPC_MESSAGE_CHARACTERS))return`RPC ${input.type} message exceeds ${MAX_RPC_MESSAGE_CHARACTERS} characters.`}import{randomUUID}from"node:crypto";import{mkdir,rm,writeFile}from"node:fs/promises";import{join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{Worker}from"node:worker_threads";var RECURSIVE_WATCH_WORKER_SOURCE=`
3
3
  const { watch } = require("node:fs");
4
4
  const { parentPort } = require("node:worker_threads");
5
5
 
@@ -52,4 +52,4 @@ parentPort.on("message", (message) => {
52
52
  });
53
53
  }
54
54
  });
55
- `;function createRecursiveWatchWorker(){return new Worker(RECURSIVE_WATCH_WORKER_SOURCE,{eval:!0})}var recursiveWorkerStates=new Map;function isRecursiveWatchMessage(message){return typeof message!="object"||message===null||!("kind"in message)||!("id"in message)||typeof message.id!="number"?!1:message.kind==="error"?"message"in message&&typeof message.message=="string":message.kind==="event"&&"eventType"in message&&typeof message.eventType=="string"&&"filename"in message&&(message.filename===null||typeof message.filename=="string")}var WORKER_OFFLOADED_WATCH_PLATFORMS=new Set(["linux","darwin"]);function createFsWatchEventSource(onError=()=>{},options={}){let createWorker=options.createRecursiveWorker??createRecursiveWatchWorker,state=recursiveWorkerStates.get(createWorker);state||(state={subscriptions:new Map,nextSubscriptionId:1},recursiveWorkerStates.set(createWorker,state));let recursiveSubscriptions=state.subscriptions,ensureRecursiveWorker=()=>{if(state.worker)return state.worker;let worker=createWorker();return worker.on("message",message=>{if(!isRecursiveWatchMessage(message))return;let subscription=recursiveSubscriptions.get(message.id);if(subscription){if(message.kind==="event"){subscription.listener(message.eventType,message.filename);return}subscription.onError(new Error(message.message),subscription.path)}}),worker.on("error",error=>{for(let subscription of recursiveSubscriptions.values())subscription.onError(error,subscription.path);if(state.worker!==worker||(state.worker=void 0,recursiveSubscriptions.size===0))return;let replacement=ensureRecursiveWorker();for(let[id,subscription]of recursiveSubscriptions)replacement.postMessage({kind:"watch",id,path:subscription.path,recursive:subscription.recursive,active:subscription.active})}),state.worker=worker,worker};return(path,listener,watchOptions)=>{if(WORKER_OFFLOADED_WATCH_PLATFORMS.has(options.platform??process.platform)){let id=state.nextSubscriptionId++,recursive=watchOptions?.recursive??!1,active=new Int32Array(new SharedArrayBuffer(4));Atomics.store(active,0,1),ensureRecursiveWorker().postMessage({kind:"watch",id,path,recursive,active}),recursiveSubscriptions.set(id,{path,listener,recursive,active,onError});let closing;return()=>{if(!recursiveSubscriptions.delete(id))return closing;Atomics.store(active,0,0);let worker=state.worker;if(!worker)return closing;if(worker.postMessage({kind:"unwatch",id}),!(recursiveSubscriptions.size>0))return state.worker=void 0,closing=worker.terminate().then(()=>{},error=>{throw onError(error,path),error}),closing}}let watcher=watchWithErrorHandler(path,listener,()=>onError(new Error(`fs.watch failed for ${path}`),path),{recursive:watchOptions?.recursive??!1});return()=>watcher?.close()}}var REASON_PRIORITY=["submission","draft_cleared","idle","continue","command","emitted","inbox"],EMPTY_RESULT={admitted:[]},WakeScheduler=class{constructor(pass,onError){this.running=!1,this.disposed=!1,this.pass=pass,this.onError=onError}request(reason,deliveryIds){if(this.disposed)return Promise.resolve(EMPTY_RESULT);this.next??={reasons:new Set,deliveryIds:new Set,waiters:[]};let batch=this.next;batch.reasons.add(reason);for(let id of deliveryIds??[])batch.deliveryIds.add(id);let settled=new Promise(resolve=>batch.waiters.push(resolve));return this.running||this.run(),settled}dispose(){this.disposed=!0;let batch=this.next;this.next=void 0;for(let waiter of batch?.waiters??[])waiter(EMPTY_RESULT)}async run(){this.running=!0;try{for(let batch=this.next;batch!==void 0&&!this.disposed;batch=this.next){this.next=void 0;let result=EMPTY_RESULT;try{result=await this.pass(wakeEvent(batch))}catch(error){this.onError(error)}for(let waiter of batch.waiters)waiter(result)}}finally{this.running=!1}}};function wakeEvent(batch){let reasons=REASON_PRIORITY.filter(reason2=>batch.reasons.has(reason2)),reason=reasons[0]??"inbox",ids=[...batch.deliveryIds];return{type:"session_control_wake",reason,reasons,...ids.length>0?{delivery_ids:ids}:{}}}var INBOX_ENGINE_ENTRY_PREFIX=".senpi-",INBOX_ARM_ATTEMPTS=25,INBOX_ARM_ATTEMPT_MS=200;async function watchInbox(inboxDir,onChange,onError){await mkdir(inboxDir,{recursive:!0,mode:448});let sentinel=`${INBOX_ENGINE_ENTRY_PREFIX}armed-${randomUUID()}`,confirmation=Promise.withResolvers(),stopped=!1,unsubscribe=createFsWatchEventSource(error=>onError(error))(inboxDir,(_eventType,filename)=>{filename===sentinel?confirmation.resolve(!0):filename?.startsWith(INBOX_ENGINE_ENTRY_PREFIX)||onChange()},{recursive:!1}),arming=confirmArm(join(inboxDir,sentinel),confirmation.promise,()=>stopped).then(confirmed=>{!confirmed&&!stopped&&onError(new Error(`inbox watch on ${inboxDir} was not confirmed`))},error=>{stopped||onError(error)});return{armed:Promise.race([confirmation.promise.then(confirmed=>confirmed?void 0:arming),arming]),stop:()=>{stopped=!0,confirmation.resolve(!1),Promise.resolve(unsubscribe()).catch(onError)}}}async function confirmArm(sentinelPath,confirmed,stopped){let seen=!1;try{for(let attempt=0;attempt<INBOX_ARM_ATTEMPTS&&!seen&&!stopped();attempt++)await writeFile(sentinelPath,String(attempt),{mode:384}),seen=await Promise.race([confirmed,delay(INBOX_ARM_ATTEMPT_MS,!1)])}finally{await rm(sentinelPath,{force:!0})}return seen}function onProcessContinue(listener){let handler=()=>{setImmediate(listener)};return process.on("SIGCONT",handler),()=>{process.removeListener("SIGCONT",handler)}}function answeredUiRequestId(frame){return typeof frame.uiRequestId=="string"?frame.uiRequestId:typeof frame.id=="string"?frame.id:void 0}function settledQuestionStatus(answers,comment){return comment?.trim()?"comment-submitted":Object.keys(answers).length>0?"answered":void 0}function unansweredQuestionIds(questions,answers){return questions.filter(question=>!answers[question.id]?.selected.length&&!answers[question.id]?.text?.trim()).map(question=>question.id)}function settleExtensionUiResponse(response,targets){let requestId=answeredUiRequestId(response)??response.id,answer=requestId===response.id?response:{...response,id:requestId},question=targets.questions.respond(answer);return typeof question=="string"?refused(response.id,question):question||targets.dialogs.resolve(answer)?{...reply(response.id),success:!0}:targets.routed?refused(response.id,"unknown_extension_ui_request"):void 0}function reply(id){return{id,type:"response",command:"extension_ui_response"}}function refused(id,error){return{...reply(id),success:!1,error}}var sessionQuestionBridges=new WeakMap,ConnectionQuestionBridge=class{constructor(output){this.pending=new Map,this.resolved=new Set,this.output=output}pendingQuestions(){return[...this.pending.values()].map(({frame})=>({...frame,remainingMs:Math.max(0,frame.deadlineAtMs-Date.now())}))}ask(request,opts){let id=crypto.randomUUID(),askedAtMs=Date.now(),timeout=opts?.timeout??request.timeoutMs,frame={type:"extension_ui_request",method:"question",id,requestId:request.requestId,toolCallId:request.requestId,waitForAnswer:request.waitForAnswer,questions:request.questions,timeout,askedAtMs,deadlineAtMs:askedAtMs+timeout,remainingMs:timeout};return new Promise(resolve=>{let answers={},comment,timer,finished=!1,unanswered=()=>unansweredQuestionIds(request.questions,answers),finish=(status,resolvedBy)=>{if(finished)return;finished=!0,clearTimeout(timer),opts?.signal?.removeEventListener("abort",cancel),this.pending.delete(id),this.resolved.add(id);let result={status,...resolvedBy!==void 0?{resolvedBy}:{},answers,comment,unanswered:unanswered(),...status==="timed_out"?{autoResolvedAfterMs:Date.now()-askedAtMs}:{}};this.output({type:"question_resolved",id,requestId:frame.requestId,toolCallId:frame.toolCallId,outcome:status,...result.resolvedBy!==void 0?{resolvedBy:result.resolvedBy}:{},answers,comment,unanswered:result.unanswered,deadlineAtMs:frame.deadlineAtMs}),resolve(result)},cancel=()=>{let reason=opts?.signal?.reason;finish(reason==="timed_out"?"timed_out":"cancelled")},arm=()=>{clearTimeout(timer),frame.deadlineAtMs=Date.now()+timeout,timer=setTimeout(()=>finish("timed_out"),timeout)};this.pending.set(id,{frame,cancel,progress:draft=>{draft.answers!==void 0&&(answers=draft.answers),draft.comment!==void 0&&(comment=draft.comment),arm(),opts?.onProgress?.({answers,comment}),finished||this.output({type:"question_updated",id,deadlineAtMs:frame.deadlineAtMs,remainingMs:Math.max(0,frame.deadlineAtMs-Date.now())})},respond:response=>{if("cancelled"in response)return cancel(),!0;if(!("answers"in response))return!1;answers=response.answers,comment=response.comment;let status=settledQuestionStatus(answers,comment);return status===void 0?!1:(finish(status,"rpc_connection"),!0)}}),arm(),this.output(frame),opts?.signal?.addEventListener("abort",cancel,{once:!0}),opts?.signal?.aborted&&cancel()})}respond(response){let pending=this.pending.get(response.id);return pending?pending.respond(response)||"question_incomplete":this.resolved.has(response.id)?"question_already_resolved":!1}progress(draft){this.pending.get(draft.id)?.progress(draft)}cancelAll(){for(let pending of this.pending.values())pending.cancel()}};async function degradeQuestion(ui,request,opts){let answers={},other="Other (type an answer)";for(let question of request.questions){let selected=await ui.select(question.question,[...question.options.map(option=>option.label),other],opts);if(selected===other){let text=await ui.input(question.question,void 0,opts);text?.trim()&&(answers[question.id]={selected:[],text})}else selected!==void 0&&(answers[question.id]={selected:[selected]})}let comment=await ui.input("Anything else? (optional)",void 0,opts),unanswered=request.questions.filter(q=>!answers[q.id]).map(q=>q.id);return{status:comment?.trim()?"comment-submitted":unanswered.length?"cancelled":"answered",...comment?.trim()||unanswered.length===0?{resolvedBy:"rpc_connection"}:{},answers,comment,unanswered}}import{existsSync}from"node:fs";function buildRpcSessionState(session,lastAbortSource){let cwd=session.sessionManager.getCwd();if(!session.agentDir)throw new Error("RPC session invariant violated: agentDir is required");let projectTrusted=new ProjectTrustStore(session.agentDir).get(cwd)===!0,lastProviderDiagnostic=sanitizeProviderDiagnostic(session.agent.state.providerDiagnostic);return{pendingQuestions:sessionQuestionBridges.get(session)?.pendingQuestions(),model:session.model,pendingModelSwitch:session.pendingModelSwitch?{provider:session.pendingModelSwitch.model.provider,id:session.pendingModelSwitch.model.id}:null,thinkingLevel:session.thinkingLevel,...session.thinkingSelection?{thinkingSelection:session.thinkingSelection}:{},...lastAbortSource?{lastAbortSource}:{},...lastProviderDiagnostic?{lastProviderDiagnostic}:{},serviceTier:session.effectiveServiceTier,fastMode:session.isFastModeActive(),isStreaming:session.isStreaming,isCompacting:session.isCompacting,retryAttempt:session.retryAttempt,isBashRunning:session.isBashRunning,steeringMode:session.steeringMode,followUpMode:session.followUpMode,sessionFile:session.sessionFile,sessionId:session.sessionId,sessionName:session.sessionName,cwd,projectTrusted,...session.sessionFile&&!existsSync(session.sessionFile)&&session.sessionManager.getEntries().some(entry=>entry.type!=="model_change"&&entry.type!=="model_change_rejected"&&entry.type!=="thinking_level_change")?{entries:session.sessionManager.getEntries()}:{},steering:typeof session.getSteeringMessages=="function"?[...session.getSteeringMessages()]:[],followUp:typeof session.getFollowUpMessages=="function"?[...session.getFollowUpMessages()]:[],ordered:[...session._queuedInputOrder??[]].sort((a,b)=>a.enqueueOrder-b.enqueueOrder),autoCompactionEnabled:session.autoCompactionEnabled,messageCount:session.messages.length,pendingMessageCount:session.pendingMessageCount,usageTotals:session.sessionManager.getUsageTotals(),contextUsage:typeof session.getContextUsage=="function"?session.getContextUsage():void 0,favoriteModels:session.favoriteModels?.map(entry=>({...entry}))??[],scopedModels:session.scopedModels?.map(entry=>({...entry}))??[]}}export{clientMessageIdentitySchema,clientMessageIdentity,readClientMessageIdentity,createFsWatchEventSource,answeredUiRequestId,settledQuestionStatus,unansweredQuestionIds,settleExtensionUiResponse,sessionQuestionBridges,ConnectionQuestionBridge,degradeQuestion,buildRpcSessionState,rpcCommandPayloadError,sessionContextError,sessionKindError,sessionAutoTitleError,sessionPromptSurfaceError,sessionBrowserEngineError,sessionRetryFallbackError,rpcCommandShapeError,rpcMessageLengthError,WakeScheduler,watchInbox,onProcessContinue};
55
+ `;function createRecursiveWatchWorker(){return new Worker(RECURSIVE_WATCH_WORKER_SOURCE,{eval:!0})}var recursiveWorkerStates=new Map;function isRecursiveWatchMessage(message){return typeof message!="object"||message===null||!("kind"in message)||!("id"in message)||typeof message.id!="number"?!1:message.kind==="error"?"message"in message&&typeof message.message=="string":message.kind==="event"&&"eventType"in message&&typeof message.eventType=="string"&&"filename"in message&&(message.filename===null||typeof message.filename=="string")}var WORKER_OFFLOADED_WATCH_PLATFORMS=new Set(["linux","darwin"]);function createFsWatchEventSource(onError=()=>{},options={}){let createWorker=options.createRecursiveWorker??createRecursiveWatchWorker,state=recursiveWorkerStates.get(createWorker);state||(state={subscriptions:new Map,nextSubscriptionId:1},recursiveWorkerStates.set(createWorker,state));let recursiveSubscriptions=state.subscriptions,ensureRecursiveWorker=()=>{if(state.worker)return state.worker;let worker=createWorker();return worker.on("message",message=>{if(!isRecursiveWatchMessage(message))return;let subscription=recursiveSubscriptions.get(message.id);if(subscription){if(message.kind==="event"){subscription.listener(message.eventType,message.filename);return}subscription.onError(new Error(message.message),subscription.path)}}),worker.on("error",error=>{for(let subscription of recursiveSubscriptions.values())subscription.onError(error,subscription.path);if(state.worker!==worker||(state.worker=void 0,recursiveSubscriptions.size===0))return;let replacement=ensureRecursiveWorker();for(let[id,subscription]of recursiveSubscriptions)replacement.postMessage({kind:"watch",id,path:subscription.path,recursive:subscription.recursive,active:subscription.active})}),state.worker=worker,worker};return(path,listener,watchOptions)=>{if(WORKER_OFFLOADED_WATCH_PLATFORMS.has(options.platform??process.platform)){let id=state.nextSubscriptionId++,recursive=watchOptions?.recursive??!1,active=new Int32Array(new SharedArrayBuffer(4));Atomics.store(active,0,1),ensureRecursiveWorker().postMessage({kind:"watch",id,path,recursive,active}),recursiveSubscriptions.set(id,{path,listener,recursive,active,onError});let closing;return()=>{if(!recursiveSubscriptions.delete(id))return closing;Atomics.store(active,0,0);let worker=state.worker;if(!worker)return closing;if(worker.postMessage({kind:"unwatch",id}),!(recursiveSubscriptions.size>0))return state.worker=void 0,closing=worker.terminate().then(()=>{},error=>{throw onError(error,path),error}),closing}}let watcher=watchWithErrorHandler(path,listener,()=>onError(new Error(`fs.watch failed for ${path}`),path),{recursive:watchOptions?.recursive??!1});return()=>watcher?.close()}}var REASON_PRIORITY=["submission","draft_cleared","idle","continue","command","emitted","inbox"],EMPTY_RESULT={admitted:[]},WakeScheduler=class{constructor(pass,onError){this.running=!1,this.disposed=!1,this.pass=pass,this.onError=onError}request(reason,deliveryIds){if(this.disposed)return Promise.resolve(EMPTY_RESULT);this.next??={reasons:new Set,deliveryIds:new Set,waiters:[]};let batch=this.next;batch.reasons.add(reason);for(let id of deliveryIds??[])batch.deliveryIds.add(id);let settled=new Promise(resolve=>batch.waiters.push(resolve));return this.running||this.run(),settled}dispose(){this.disposed=!0;let batch=this.next;this.next=void 0;for(let waiter of batch?.waiters??[])waiter(EMPTY_RESULT)}async run(){this.running=!0;try{for(let batch=this.next;batch!==void 0&&!this.disposed;batch=this.next){this.next=void 0;let result=EMPTY_RESULT;try{result=await this.pass(wakeEvent(batch))}catch(error){this.onError(error)}for(let waiter of batch.waiters)waiter(result)}}finally{this.running=!1}}};function wakeEvent(batch){let reasons=REASON_PRIORITY.filter(reason2=>batch.reasons.has(reason2)),reason=reasons[0]??"inbox",ids=[...batch.deliveryIds];return{type:"session_control_wake",reason,reasons,...ids.length>0?{delivery_ids:ids}:{}}}var INBOX_ENGINE_ENTRY_PREFIX=".senpi-",INBOX_ARM_ATTEMPTS=25,INBOX_ARM_ATTEMPT_MS=200;async function watchInbox(inboxDir,onChange,onError){await mkdir(inboxDir,{recursive:!0,mode:448});let sentinel=`${INBOX_ENGINE_ENTRY_PREFIX}armed-${randomUUID()}`,confirmation=Promise.withResolvers(),stopped=!1,unsubscribe=createFsWatchEventSource(error=>onError(error))(inboxDir,(_eventType,filename)=>{filename===sentinel?confirmation.resolve(!0):filename?.startsWith(INBOX_ENGINE_ENTRY_PREFIX)||onChange()},{recursive:!1}),arming=confirmArm(join(inboxDir,sentinel),confirmation.promise,()=>stopped).then(confirmed=>{!confirmed&&!stopped&&onError(new Error(`inbox watch on ${inboxDir} was not confirmed`))},error=>{stopped||onError(error)});return{armed:Promise.race([confirmation.promise.then(confirmed=>confirmed?void 0:arming),arming]),stop:()=>{stopped=!0,confirmation.resolve(!1),Promise.resolve(unsubscribe()).catch(onError)}}}async function confirmArm(sentinelPath,confirmed,stopped){let seen=!1;try{for(let attempt=0;attempt<INBOX_ARM_ATTEMPTS&&!seen&&!stopped();attempt++)await writeFile(sentinelPath,String(attempt),{mode:384}),seen=await Promise.race([confirmed,delay(INBOX_ARM_ATTEMPT_MS,!1)])}finally{await rm(sentinelPath,{force:!0})}return seen}function onProcessContinue(listener){let handler=()=>{setImmediate(listener)};return process.on("SIGCONT",handler),()=>{process.removeListener("SIGCONT",handler)}}function answeredUiRequestId(frame){return typeof frame.uiRequestId=="string"?frame.uiRequestId:typeof frame.id=="string"?frame.id:void 0}function settledQuestionStatus(answers,comment){return comment?.trim()?"comment-submitted":Object.keys(answers).length>0?"answered":void 0}function unansweredQuestionIds(questions,answers){return questions.filter(question=>!answers[question.id]?.selected.length&&!answers[question.id]?.text?.trim()).map(question=>question.id)}function settleExtensionUiResponse(response,targets){let requestId=answeredUiRequestId(response)??response.id,answer=requestId===response.id?response:{...response,id:requestId},question=targets.questions.respond(answer);return typeof question=="string"?refused(response.id,question):question||targets.dialogs.resolve(answer)?{...reply(response.id),success:!0}:targets.routed?refused(response.id,"unknown_extension_ui_request"):void 0}function reply(id){return{id,type:"response",command:"extension_ui_response"}}function refused(id,error){return{...reply(id),success:!1,error}}var sessionQuestionBridges=new WeakMap,ConnectionQuestionBridge=class{constructor(output){this.pending=new Map,this.resolved=new Set,this.output=output}pendingQuestions(){return[...this.pending.values()].map(({frame})=>({...frame,remainingMs:Math.max(0,frame.deadlineAtMs-Date.now())}))}ask(request,opts){let id=crypto.randomUUID(),askedAtMs=Date.now(),timeout=opts?.timeout??request.timeoutMs,frame={type:"extension_ui_request",method:"question",id,requestId:request.requestId,toolCallId:request.requestId,waitForAnswer:request.waitForAnswer,questions:request.questions,timeout,askedAtMs,deadlineAtMs:askedAtMs+timeout,remainingMs:timeout};return new Promise(resolve=>{let answers={},comment,timer,finished=!1,unanswered=()=>unansweredQuestionIds(request.questions,answers),finish=(status,resolvedBy)=>{if(finished)return;finished=!0,clearTimeout(timer),opts?.signal?.removeEventListener("abort",cancel),this.pending.delete(id),this.resolved.add(id);let result={status,...resolvedBy!==void 0?{resolvedBy}:{},answers,comment,unanswered:unanswered(),...status==="timed_out"?{autoResolvedAfterMs:Date.now()-askedAtMs}:{}};this.output({type:"question_resolved",id,requestId:frame.requestId,toolCallId:frame.toolCallId,outcome:status,...result.resolvedBy!==void 0?{resolvedBy:result.resolvedBy}:{},answers,comment,unanswered:result.unanswered,deadlineAtMs:frame.deadlineAtMs}),resolve(result)},cancel=()=>{let reason=opts?.signal?.reason;finish(reason==="timed_out"?"timed_out":"cancelled")},arm=()=>{clearTimeout(timer),frame.deadlineAtMs=Date.now()+timeout,timer=setTimeout(()=>finish("timed_out"),timeout)};this.pending.set(id,{frame,cancel,progress:draft=>{draft.answers!==void 0&&(answers=draft.answers),draft.comment!==void 0&&(comment=draft.comment),arm(),opts?.onProgress?.({answers,comment}),finished||this.output({type:"question_updated",id,deadlineAtMs:frame.deadlineAtMs,remainingMs:Math.max(0,frame.deadlineAtMs-Date.now())})},respond:response=>{if("cancelled"in response)return cancel(),!0;if(!("answers"in response))return!1;answers=response.answers,comment=response.comment;let status=settledQuestionStatus(answers,comment);return status===void 0?!1:(finish(status,"rpc_connection"),!0)}}),arm(),this.output(frame),opts?.signal?.addEventListener("abort",cancel,{once:!0}),opts?.signal?.aborted&&cancel()})}respond(response){let pending=this.pending.get(response.id);return pending?pending.respond(response)||"question_incomplete":this.resolved.has(response.id)?"question_already_resolved":!1}progress(draft){this.pending.get(draft.id)?.progress(draft)}cancelAll(){for(let pending of this.pending.values())pending.cancel()}};async function degradeQuestion(ui,request,opts){let answers={},other="Other (type an answer)";for(let question of request.questions){let selected=await ui.select(question.question,[...question.options.map(option=>option.label),other],opts);if(selected===other){let text=await ui.input(question.question,void 0,opts);text?.trim()&&(answers[question.id]={selected:[],text})}else selected!==void 0&&(answers[question.id]={selected:[selected]})}let comment=await ui.input("Anything else? (optional)",void 0,opts),unanswered=request.questions.filter(q=>!answers[q.id]).map(q=>q.id);return{status:comment?.trim()?"comment-submitted":unanswered.length?"cancelled":"answered",...comment?.trim()||unanswered.length===0?{resolvedBy:"rpc_connection"}:{},answers,comment,unanswered}}import{existsSync}from"node:fs";function buildRpcSessionState(session,lastAbortSource){let cwd=session.sessionManager.getCwd();if(!session.agentDir)throw new Error("RPC session invariant violated: agentDir is required");let projectTrusted=new ProjectTrustStore(session.agentDir).get(cwd)===!0,lastProviderDiagnostic=sanitizeProviderDiagnostic(session.agent.state.providerDiagnostic);return{pendingQuestions:sessionQuestionBridges.get(session)?.pendingQuestions(),model:session.model,pendingModelSwitch:session.pendingModelSwitch?{provider:session.pendingModelSwitch.model.provider,id:session.pendingModelSwitch.model.id}:null,thinkingLevel:session.thinkingLevel,...session.thinkingSelection?{thinkingSelection:session.thinkingSelection}:{},...lastAbortSource?{lastAbortSource}:{},...lastProviderDiagnostic?{lastProviderDiagnostic}:{},serviceTier:session.effectiveServiceTier,fastMode:session.isFastModeActive(),isStreaming:session.isStreaming,isCompacting:session.isCompacting,retryAttempt:session.retryAttempt,isBashRunning:session.isBashRunning,steeringMode:session.steeringMode,followUpMode:session.followUpMode,sessionFile:session.sessionFile,sessionId:session.sessionId,sessionName:session.sessionName,cwd,projectTrusted,...session.sessionFile&&!existsSync(session.sessionFile)&&session.sessionManager.getEntries().some(entry=>entry.type!=="model_change"&&entry.type!=="model_change_rejected"&&entry.type!=="thinking_level_change")?{entries:session.sessionManager.getEntries()}:{},steering:typeof session.getSteeringMessages=="function"?[...session.getSteeringMessages()]:[],followUp:typeof session.getFollowUpMessages=="function"?[...session.getFollowUpMessages()]:[],ordered:[...session._queuedInputOrder??[]].sort((a,b)=>a.enqueueOrder-b.enqueueOrder),autoCompactionEnabled:session.autoCompactionEnabled,messageCount:session.messages.length,pendingMessageCount:session.pendingMessageCount,usageTotals:session.sessionManager.getUsageTotals(),contextUsage:typeof session.getContextUsage=="function"?session.getContextUsage():void 0,favoriteModels:session.favoriteModels?.map(entry=>({...entry}))??[],scopedModels:session.scopedModels?.map(entry=>({...entry}))??[]}}async function availableModelsData(session){return{models:(await session.modelRegistry.modelRuntime.getAvailable()).map(model=>({...model,supportedThinkingLevels:getSupportedThinkingLevels2(model),supportsAssistantPrefill:modelSupportsAssistantPrefill(model,{thinkingEnabled:session.thinkingLevel!=="off"})}))}}function unsupportedThinkingLevel(level){return`Thinking level ${String(level)} is not supported by the active model.`}async function interruptRunningTurn(session,requestedTurnId,stop){if(!session.isStreaming&&session.retryAttempt===0)return{interrupted:!1};let turnId=String(session.externalAdmission.turnEpoch);return typeof requestedTurnId=="string"&&requestedTurnId!==turnId?{interrupted:!1,turnId}:(await stop(),{interrupted:!0,turnId})}export{clientMessageIdentitySchema,clientMessageIdentity,readClientMessageIdentity,supportsXhigh2 as supportsXhigh,supportsMax2 as supportsMax,getSupportedThinkingLevels2 as getSupportedThinkingLevels,clampThinkingSelection,getThinkingClampNotice,formatThinkingClampWarning,classifyReasoningCapability,createFsWatchEventSource,answeredUiRequestId,settledQuestionStatus,unansweredQuestionIds,settleExtensionUiResponse,sessionQuestionBridges,ConnectionQuestionBridge,degradeQuestion,buildRpcSessionState,rpcCommandPayloadError,sessionContextError,sessionKindError,sessionAutoTitleError,sessionPromptSurfaceError,sessionBrowserEngineError,sessionRetryFallbackError,rpcCommandShapeError,rpcMessageLengthError,availableModelsData,unsupportedThinkingLevel,interruptRunningTurn,WakeScheduler,watchInbox,onProcessContinue};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-MT2C4I5R.js";import"./chunk-PDSG6VER.js";import"./chunk-QNAG7FYM.js";import"./chunk-Z7MMKKIY.js";import{configureHttpDispatcher}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-CTERKXVZ.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
3
+ import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-MP2DMTI7.js";import"./chunk-USRAHAW4.js";import"./chunk-QNAG7FYM.js";import"./chunk-Z7MMKKIY.js";import{configureHttpDispatcher}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-MT2C4I5R.js";import{isApiKeyLoginProvider}from"./chunk-PDSG6VER.js";import"./chunk-QNAG7FYM.js";import"./chunk-Z7MMKKIY.js";import"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-CTERKXVZ.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
2
+ import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-MP2DMTI7.js";import{isApiKeyLoginProvider}from"./chunk-USRAHAW4.js";import"./chunk-QNAG7FYM.js";import"./chunk-Z7MMKKIY.js";import"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
@@ -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{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,runWithProviderScope,startHostChildReaper}from"./chunk-MT2C4I5R.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,createRpcConnectionHandler,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint}from"./chunk-PDSG6VER.js";import"./chunk-QNAG7FYM.js";import{SessionManager,assertValidSessionId,liveToolMediaScope,omitInlineMedia,toolMediaPersister}from"./chunk-Z7MMKKIY.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-CTERKXVZ.js";import"./chunk-JABBHOD5.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,GENERATION_HANDOFF_CAPABILITY,HostIdleHandover,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,beginHandoverResponse,computeRuntimeBuildId,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-7GVD54RM.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import{killTrackedDetachedChildren}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-RADHRQ4K.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);return beginHandoverResponse(parsed.id,typeof request=="string"?request:await this.handover.begin(request))}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.readKernels=options.readKernels??readCodemodeKernelRows,this.readMainHeap=options.readMainHeap??readMainThreadHeapBytes,this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE),main:{heapBytes:this.readMainHeap()},kernels:this.readKernels()};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions,main:reading.main,kernels:reading.kernels});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
2
+ import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,runWithProviderScope,startHostChildReaper}from"./chunk-MP2DMTI7.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,createRpcConnectionHandler,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint}from"./chunk-USRAHAW4.js";import"./chunk-QNAG7FYM.js";import{SessionManager,assertValidSessionId,liveToolMediaScope,omitInlineMedia,toolMediaPersister}from"./chunk-Z7MMKKIY.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,GENERATION_HANDOFF_CAPABILITY,HostIdleHandover,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,beginHandoverResponse,computeRuntimeBuildId,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-7GVD54RM.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-IZOTKUWG.js";import"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import{killTrackedDetachedChildren}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-RADHRQ4K.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);return beginHandoverResponse(parsed.id,typeof request=="string"?request:await this.handover.begin(request))}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.readKernels=options.readKernels??readCodemodeKernelRows,this.readMainHeap=options.readMainHeap??readMainThreadHeapBytes,this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE),main:{heapBytes:this.readMainHeap()},kernels:this.readKernels()};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions,main:reading.main,kernels:reading.kernels});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
3
3
  `))}};var ZERO_SESSION_TRIM_TICK_MS=1e3,ZERO_SESSION_TRIM_MIN_INTERVAL_MS=6e4,BYTES_PER_MEGABYTE2=1024*1024,ZeroSessionTrimmer=class{constructor(options){this.heldSessions=!1,this.options=options,this.now=options.now??Date.now}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.check(),ZERO_SESSION_TRIM_TICK_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}observe(size){size>0&&(this.heldSessions=!0)}check(){if(this.pending!==void 0&&this.report(this.pending),this.options.sessions()>0){this.heldSessions=!0;return}this.heldSessions&&(this.heldSessions=!1,!(this.lastTrimAt!==void 0&&this.now()-this.lastTrimAt<ZERO_SESSION_TRIM_MIN_INTERVAL_MS)&&this.trim())}trim(){let beforeBytes=this.readFootprint().bytes;this.pending={beforeBytes,collected:(this.options.collect??collectFully)()},this.lastTrimAt=this.now()}report(pending){this.pending=void 0;let after=this.readFootprint();this.options.emit({type:"host_trimmed",footprintBeforeMb:Math.round(pending.beforeBytes/BYTES_PER_MEGABYTE2),footprintAfterMb:Math.round(after.bytes/BYTES_PER_MEGABYTE2),measure:after.measure,collected:pending.collected})}readFootprint(){return(this.options.readFootprint??readOwnFootprint)()}};function collectFully(){let bun=Reflect.get(globalThis,"Bun"),bunGc=typeof bun=="object"&&bun!==null?Reflect.get(bun,"gc"):void 0;if(typeof bunGc=="function")return Reflect.apply(bunGc,bun,[!0]),!0;let nodeGc=Reflect.get(globalThis,"gc");return typeof nodeGc!="function"?!1:(Reflect.apply(nodeGc,globalThis,[]),!0)}var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
4
4
  `))}};function startHostObservers(router,writer,options){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),kernels=readCodemodeKernelRows,memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),readKernels:kernels,...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});router.setHostMemoryView({mainHeapBytes:readMainThreadHeapBytes,kernels});let{trim}=options;return loopLag.start(),memory.start(),trim.start(),{stop:()=>{loopLag.stop(),memory.stop(),trim.stop()}}}function createZeroSessionTrim(writer,sessions){return new ZeroSessionTrimmer({emit:record=>writer.broadcastHostRecord(record),sessions})}import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code){return{id:command.id,type:"response",command:"warm",success:!1,error:code}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
5
5
  `)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}import{existsSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";var observations=new Set(["get_state","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_fast_mode","get_commands","get_loaded_surfaces","get_media","get_auth_providers","get_provider_accounts","memory_report"]);function refreshesSessionActivity(command){return!observations.has(command)}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{},...profile.retryFallback?{retryFallback:Object.freeze({modelFallback:profile.retryFallback.modelFallback,fallbackChains:Object.freeze(Object.fromEntries(Object.entries(profile.retryFallback.fallbackChains).map(([key,entries])=>[key,Object.freeze([...entries])])))})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,entry.detachedAt=void 0,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve=>{deadline=setTimeout(resolve,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-MT2C4I5R.js";import"./chunk-PDSG6VER.js";import"./chunk-QNAG7FYM.js";import{DefaultPackageManager,DynamicBorder,keyHint,rawKeyHint}from"./chunk-Z7MMKKIY.js";import{SettingsManager,appendHiddenTuiStdout,initTheme,stopThemeWatcher,theme}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-CTERKXVZ.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import{killProcessTree}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
2
+ import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-MP2DMTI7.js";import"./chunk-USRAHAW4.js";import"./chunk-QNAG7FYM.js";import{DefaultPackageManager,DynamicBorder,keyHint,rawKeyHint}from"./chunk-Z7MMKKIY.js";import{SettingsManager,appendHiddenTuiStdout,initTheme,stopThemeWatcher,theme}from"./chunk-H4UIUFU5.js";import"./chunk-LYYI74CY.js";import"./chunk-M2IHGL3M.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-J5MUMVWB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import"./chunk-7GVD54RM.js";import"./chunk-IZOTKUWG.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-H67EVDWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-4TK7VCZZ.js";import"./chunk-F6EQ7EV3.js";import{killProcessTree}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-3A3C5VVO.js";import"./chunk-CIRZTP7W.js";import"./chunk-RADHRQ4K.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-UMJL74VN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-I5HLTDT4.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
3
3
  `)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
4
4
  `,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
5
5
  `)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
@@ -1,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{runRpcMode}from"./chunk-PDSG6VER.js";import"./chunk-H4UIUFU5.js";import"./chunk-J5MUMVWB.js";import"./chunk-CTERKXVZ.js";import"./chunk-JABBHOD5.js";import"./chunk-IZOTKUWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-CIRZTP7W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
2
+ import{runRpcMode}from"./chunk-USRAHAW4.js";import"./chunk-H4UIUFU5.js";import"./chunk-J5MUMVWB.js";import"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import"./chunk-IZOTKUWG.js";import"./chunk-ZJHRDQCH.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-CIRZTP7W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-RRU5LXMS.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-PELNNWGO.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
+ import{WakeScheduler,answeredUiRequestId,availableModelsData,buildRpcSessionState,interruptRunningTurn,onProcessContinue,rpcCommandShapeError,settledQuestionStatus,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-ZSYRWQWG.js";import"./chunk-JABBHOD5.js";import{acquireHostEnsureLock,gcHostEndpoints,tuiSocketName}from"./chunk-H67EVDWG.js";import{engineBuildIdentity}from"./chunk-ZJHRDQCH.js";import"./chunk-KUPQO7MC.js";import{MAX_SOCKET_PATH_BYTES,authenticateSocket,createDaemonDirectories,createHostDaemonPaths,createSocketSecret,socketSecretPath,thisProcessStartTime,writeHostRegistration}from"./chunk-RADHRQ4K.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import"./chunk-RRU5LXMS.js";import"./chunk-ODYQK5XJ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{VERSION}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{randomUUID}from"node:crypto";import{rm as rm2}from"node:fs/promises";import{chmod}from"node:fs/promises";import{createServer}from"node:net";async function listenControlSocket(socketPath,secret,handlers){let clients=new Set,nextConnection=0,server=createServer(socket=>{clients.add(socket),socket.once("close",()=>clients.delete(socket)),socket.on("error",()=>socket.destroy()),authenticateSocket(socket,secret,()=>acceptConnection(socket,++nextConnection,handlers))});return await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(socketPath,()=>{server.off("error",reject),resolve()})}),server.on("error",error=>handlers.listenerError(error)),await chmod(socketPath,384),{close:()=>closeServer(server,clients)}}function acceptConnection(socket,id,handlers){let connection={id,send:record=>{socket.destroyed||socket.write(serializeJsonLine(record))}},detach=attachJsonlLineReader(socket,line=>{answer(connection,line,handlers)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>connection.send(failure(void 0,"parse","RPC line exceeds the size limit."))});socket.once("close",()=>{detach(),handlers.closed(connection)})}async function answer(connection,line,handlers){let parsed;try{parsed=JSON.parse(line)}catch{connection.send(failure(void 0,"parse","Invalid JSON."));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError!==void 0||!isCommand(parsed)){connection.send(failure(void 0,"parse",shapeError??"RPC command needs a string `type`."));return}connection.send(await handlers.command(connection,parsed))}function isCommand(value){return typeof value=="object"&&value!==null&&"type"in value&&typeof value.type=="string"}function failure(id,command,error){return{...id===void 0?{}:{id},type:"response",command,success:!1,error}}function success(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,...data===void 0?{}:{data}}}function closeServer(server,clients){for(let client of clients)client.destroy();return new Promise(resolve=>server.close(()=>resolve()))}var SESSION_CONTROL_COMMANDS=["get_available_models","get_available_thinking_levels","set_model","set_thinking_level","interrupt"];async function runSessionControlCommand(session,controls,command){let{id,type}=command;switch(type){case"get_available_models":return success(id,type,await availableModelsData(session));case"get_available_thinking_levels":return success(id,type,{levels:session.getAvailableThinkingLevels()});case"set_model":return await setModel(session,controls,command);case"set_thinking_level":{let level=session.getAvailableThinkingLevels().find(candidate=>candidate===command.level);return level===void 0?failure(id,type,unsupportedThinkingLevel(command.level)):(controls.selectThinkingLevel(level,command.scope!=="turn"),success(id,type))}case"interrupt":return success(id,type,await interruptRunningTurn(session,command.turnId,()=>controls.interruptTurn()));default:return}}async function setModel(session,controls,command){let{id,type}=command,model=(await session.modelRegistry.getAvailable()).find(candidate=>candidate.provider===command.provider&&candidate.id===command.modelId);if(model===void 0)return failure(id,type,`Model not found: ${String(command.provider)}/${String(command.modelId)}`);try{let change=await controls.selectModel(model);return success(id,type,{...model,systemPromptName:change?.systemPromptName})}catch(error){return failure(id,type,error instanceof Error?error.message:String(error))}}var TUI_CONTROL_CAPABILITY="tui_control",TUI_CONTROL_COMMANDS=["get_protocol_info","list_sessions","get_state","get_messages","set_session_name","subscribe","wake","extension_ui_response",...SESSION_CONTROL_COMMANDS];async function runControlCommand(context,connection,command){let{id,type}=command,{session}=context;switch(type){case"get_protocol_info":{let build=engineBuildIdentity();return success(id,type,{protocolVersion:1,serverVersion:VERSION,capabilities:[TUI_CONTROL_CAPABILITY],mode:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS})}case"list_sessions":return success(id,type,{sessions:[sessionRow(session)]});case"get_state":return success(id,type,{...buildRpcSessionState(session),turn_epoch:session.externalAdmission.turnEpoch,blocking_question:context.surface.blockingQuestion(),compacting:session.isCompacting,editor_has_draft:context.surface.draftHold()!==void 0,state_version:context.feed.stateVersion});case"get_messages":return success(id,type,{messages:session.messages});case"set_session_name":{let name=typeof command.name=="string"?command.name.trim():"";return name===""?failure(id,type,"Session name cannot be empty"):(session.setSessionName(name),success(id,type))}case"subscribe":{let cursor=typeof command.cursor=="number"?command.cursor:void 0;return success(id,type,{cursor:context.feed.subscribe(connection.id,cursor,connection.send)})}case"wake":{let ids=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry=>typeof entry=="string"):void 0,result=await context.wake(ids);return success(id,type,{admitted:result.admitted??[]})}case"extension_ui_response":return answerQuestion(context.surface,command);default:return await runSessionControlCommand(session,context.surface,command)??failure(id,type,"unsupported")}}function sessionRow(session){let manager=session.sessionManager,created=manager.getHeader()?.timestamp??null,last=manager.getEntries().at(-1);return{sessionId:session.sessionId,sessionPath:session.sessionFile??null,session_file:session.sessionFile??null,kind:"interactive",surface:"tui",cwd:manager.getCwd(),name:session.sessionName??null,created_at:created,updated_at:last?.timestamp??created,attachments:1}}function answerQuestion(surface,command){let frameId=command.id,requestId=answeredUiRequestId(command),request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return failure(frameId,"extension_ui_response","unknown_request");let response=questionResponse(command,request.questions);return response==="question_incomplete"?failure(frameId,"extension_ui_response",response):response===void 0||!surface.answerQuestion(requestId,response)?failure(frameId,"extension_ui_response","invalid_response"):success(frameId,"extension_ui_response")}function questionResponse(command,questions){if(command.cancelled===!0)return{status:"cancelled",answers:{},unanswered:[]};let answers=command.answers;if(typeof answers!="object"||answers===null||Array.isArray(answers))return;let parsed={};for(let[question,value]of Object.entries(answers)){if(typeof value!="object"||value===null||!("selected"in value)||!Array.isArray(value.selected))return;let selected=value.selected.filter(entry=>typeof entry=="string"),text="text"in value&&typeof value.text=="string"?value.text:void 0;parsed[question]=text===void 0?{selected}:{selected,text}}let comment=typeof command.comment=="string"?command.comment:void 0,status=settledQuestionStatus(parsed,comment);if(status===void 0)return"question_incomplete";let unanswered=unansweredQuestionIds(questions,parsed);return{status,resolvedBy:"control_endpoint",answers:parsed,unanswered,...comment===void 0?{}:{comment}}}var ControlFeed=class{constructor(){this.seq=0,this.stateVersionValue=0,this.ring=[],this.subscribers=new Map}get stateVersion(){return this.stateVersionValue}publish(kind,data={}){kind==="state"&&(this.stateVersionValue+=1);let event={type:"session_control_event",seq:++this.seq,kind,data:kind==="state"?{...data,state_version:this.stateVersionValue}:data};this.ring.push(event),this.ring.length>256&&this.ring.shift();for(let send of this.subscribers.values())send(event)}subscribe(connection,cursor,send){if(this.subscribers.set(connection,send),cursor!==void 0)for(let event of this.ring)event.seq>cursor&&send(event);return this.seq}unsubscribe(connection){this.subscribers.delete(connection)}clear(){this.subscribers.clear()}};import{createHash}from"node:crypto";import{rmSync}from"node:fs";import{chmod as chmod2,lstat,mkdir,realpath,rm}from"node:fs/promises";import{dirname,join}from"node:path";var PRIVATE_DIRECTORY_MODE=448,REGISTRY_LOCK_WAIT_MS=5e3;async function resolveTuiSocket(agentDir,instanceId){let name=tuiSocketName(instanceId),primary=join(agentDir,"rpc","tui",name);if(Buffer.byteLength(primary)<=MAX_SOCKET_PATH_BYTES)return await makePrivateDirectory(dirname(primary)),primary;let root=join("/tmp",`senpi-rpc-${createHash("sha256").update(agentDir).digest("hex").slice(0,8)}`),tuiRoot=join(root,"tui");await makePrivateDirectory(tuiRoot);for(let directory of[root,tuiRoot])await assertPrivateDirectory(directory);let fallback=join(tuiRoot,name);if(Buffer.byteLength(fallback)>MAX_SOCKET_PATH_BYTES)throw new Error(`socket path ${fallback} exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);return fallback}async function makePrivateDirectory(directory){await mkdir(directory,{recursive:!0,mode:PRIVATE_DIRECTORY_MODE}),await chmod2(directory,PRIVATE_DIRECTORY_MODE)}async function assertPrivateDirectory(directory){let stat=await lstat(await realpath(directory)),ownedByUs=process.getuid===void 0||stat.uid===process.getuid();if(!stat.isDirectory()||!ownedByUs||(stat.mode&63)!==0)throw new Error(`alt_root_unsafe: ${directory} is not a private directory of this user`)}async function registerTuiEndpoint(options){let paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir}),release=await acquireHostEnsureLock(options.socket,REGISTRY_LOCK_WAIT_MS);try{await writeHostRegistration(paths,{record:{pid:process.pid,processStartTime:await thisProcessStartTime()},socket:options.socket,instanceId:options.instanceId,generation:0,launchProfileId:"tui",build:engineBuildIdentity()},{fresh:!0}),await createDaemonDirectories(paths,{kind:"tui"})}finally{await release()}return{paths,socket:options.socket}}async function unregisterTuiEndpoint(entry){let release=await acquireHostEnsureLock(entry.socket,REGISTRY_LOCK_WAIT_MS).catch(()=>{});try{await rm(entry.socket,{force:!0}),await rm(socketSecretPath(entry.socket),{force:!0}),await rm(entry.paths.dir,{recursive:!0,force:!0})}finally{await release?.()}}function unregisterTuiEndpointSync(entry){rmSync(entry.socket,{force:!0}),rmSync(socketSecretPath(entry.socket),{force:!0}),rmSync(entry.paths.dir,{recursive:!0,force:!0})}var REPORT_TEXT_LIMIT=4e3;function activateControlEndpoint(parts){let{context,feed,wake}=parts,{session,surface}=context;session.externalAdmission.setEditorSource(()=>editorHold(context));let unsubscribeSession=session.subscribe(event=>{event.type==="agent_start"?feed.publish("state"):event.type==="agent_idle"?(feed.publish("completion",{turn_epoch:session.externalAdmission.turnEpoch}),feed.publish("state"),wake("idle")):event.type==="agent_end"||event.type==="queue_update"||event.type==="compaction_start"||event.type==="compaction_end"?feed.publish("state"):event.type==="message_end"&&event.message.role==="assistant"&&feed.publish("report",{text:assistantText(event.message).slice(0,REPORT_TEXT_LIMIT)})}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>{wake("emitted")}),unsubscribeInputs=session.externalAdmission.onInputsSettled(()=>queueMicrotask(()=>{wake("submission")})),stopContinue=onProcessContinue(()=>{wake("continue")}),exitCleanup=()=>unregisterTuiEndpointSync(parts.entry);process.once("exit",exitCleanup);let disposing,dispose=()=>(disposing??=(async()=>{process.removeListener("exit",exitCleanup),unsubscribeSession(),unsubscribeEmitted(),unsubscribeInputs(),stopContinue(),parts.stopInbox(),parts.scheduler.dispose(),feed.clear(),session.externalAdmission.setEditorSource(void 0),await parts.server.close(),await sessionReferenced(parts.options,surface)||await session.sessionManager.discardHeaderOnlyFile(),await unregisterTuiEndpoint(parts.entry)})(),disposing);return{socket:parts.entry.socket,wake:reason=>{wake(reason)},noteState:()=>feed.publish("state"),noteQuestions:()=>feed.publish("question",{pending:[...surface.pendingQuestionIds()]}),dispose}}function editorHold(context){let hold=context.surface.draftHold(),revision=context.editorRevision();return hold===void 0?{revision}:{hold_reason:hold,revision}}async function sessionReferenced(options,surface){if(options.isSessionReferenced===void 0)return!1;try{return await options.isSessionReferenced()}catch(error){return surface.notice(`control endpoint kept the session file: ${error instanceof Error?error.message:String(error)}`),!0}}function assistantText(message){return message.role!=="assistant"?"":message.content.flatMap(part=>part.type==="text"?[part.text]:[]).join(`
3
+ `)}async function registerSessionControlEndpoint(context,options){let cleanups=[];try{let endpoint=await openEndpoint(context,options,cleanups);return{registration:{status:"registered",socket:endpoint.socket,dispose:endpoint.dispose},endpoint}}catch(error){for(let cleanup of cleanups.reverse())await Promise.resolve(cleanup()).catch(()=>{});let reason=errorText(error);return context.surface.notice(`control endpoint unavailable: ${reason}`),{registration:{status:"failed",reason}}}}async function openEndpoint(context,options,cleanups){let{session,agentDir,surface}=context;thisProcessStartTime();let headerDurable=session.sessionManager.persistHeaderNow();headerDurable.catch(()=>{});let instanceId=randomUUID(),socket=await resolveTuiSocket(agentDir,instanceId);cleanups.push(()=>rm2(socket,{force:!0}),()=>rm2(socketSecretPath(socket),{force:!0}));let secret=await createSocketSecret(socketSecretPath(socket)),feed=new ControlFeed,scheduler=new WakeScheduler(async event=>(await session.extensionRunner.emit(event),await options.drain(event)??{admitted:[]}),error=>surface.notice(`control endpoint drain failed: ${errorText(error)}`));cleanups.push(()=>scheduler.dispose());let wake=(reason,ids)=>scheduler.request(reason,ids),commandContext={instanceId,session,surface,feed,wake:ids=>wake("command",ids)},server=await listenControlSocket(socket,secret,{command:(connection,command)=>runControlCommand(commandContext,connection,command),closed:connection=>feed.unsubscribe(connection.id),listenerError:error=>surface.notice(`control endpoint listener failed: ${error.message}`)});cleanups.push(()=>server.close()),await headerDurable;let entry=await registerTuiEndpoint({agentDir,socket,instanceId});cleanups.push(()=>unregisterTuiEndpoint(entry));let inbox=await watchInbox(options.inboxDir,()=>{wake("inbox")},error=>surface.notice(`control endpoint inbox watch failed: ${errorText(error)}`));cleanups.push(()=>inbox.stop());let endpoint=activateControlEndpoint({context,options,entry,server,scheduler,feed,stopInbox:inbox.stop,wake});return endpoint.wake("inbox"),inbox.armed.then(()=>endpoint.wake("inbox")),setImmediate(()=>{gcHostEndpoints(agentDir,{kinds:["tui"]}).catch(error=>surface.notice(`control endpoint gc of dead terminals failed: ${errorText(error)}`))}),endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};