@code-yeongyu/senpi 2026.11.6-3 → 2026.11.9-2

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 (147) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/bundle/chunks/{chunk-5LKB732P.js → chunk-3TZQXZKH.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-X53PD4ZC.js → chunk-45MVD7BU.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-L7ZIS3MC.js → chunk-4JIBEZZE.js} +3 -3
  5. package/dist/bundle/chunks/{chunk-CF5OGBC4.js → chunk-4NYNMAYF.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6CEDL5S2.js → chunk-4UR6UFBH.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-F5JLDCYD.js → chunk-527Q2UYM.js} +5 -5
  8. package/dist/bundle/chunks/{chunk-7DRWPZ3N.js → chunk-622VYTRI.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-V2QAYGOK.js → chunk-7CFORZPE.js} +22 -22
  10. package/dist/bundle/chunks/{chunk-GKAYPJ4E.js → chunk-7PROV6BB.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-4E7GDG4H.js → chunk-7VMEE62L.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-4BATXPB7.js → chunk-K3UHGDUQ.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-MJTCZUXS.js → chunk-LHSWAJJL.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-SB6MXNO5.js → chunk-M7GF73FO.js} +2 -2
  15. package/dist/bundle/chunks/{chunk-CFEHJ4VU.js → chunk-NDSWTAYJ.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-JMQOLOC2.js → chunk-Q6NR6644.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-EO2VPZ2K.js → chunk-SGAFIMAU.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-BASS47UD.js → chunk-STGOYIXC.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-DSWDJ7HT.js → chunk-WQ4RBPMS.js} +1 -1
  20. package/dist/bundle/chunks/chunk-XZDCMDUH.js +2 -0
  21. package/dist/bundle/chunks/{chunk-LUZVGPQ7.js → chunk-Y5L4UFMI.js} +1 -1
  22. package/dist/bundle/chunks/{cli-main-RWHDZKTQ.js → cli-main-XBEFQW5A.js} +1 -1
  23. package/dist/bundle/chunks/{hand-entry-G5LYF62Q.js → hand-entry-QFEY3JMQ.js} +1 -1
  24. package/dist/bundle/chunks/{headless-host-ES74ZB6M.js → headless-host-YXUGONR3.js} +1 -1
  25. package/dist/bundle/chunks/{host-command-I2JZ5JM7.js → host-command-VHX2ILLM.js} +1 -1
  26. package/dist/bundle/chunks/{host-session-command-Y52NFPP2.js → host-session-command-P3MRW63Z.js} +1 -1
  27. package/dist/bundle/chunks/{interactive-mode-PA7DGVS6.js → interactive-mode-YGL3QHU6.js} +1 -1
  28. package/dist/bundle/chunks/{main-OBL6375C.js → main-5SD4DHMC.js} +1 -1
  29. package/dist/bundle/chunks/{multi-session-host-NM6I5BWZ.js → multi-session-host-PGRHY3JP.js} +1 -1
  30. package/dist/bundle/chunks/{package-manager-cli-GNRQ5MVR.js → package-manager-cli-SADLU7QX.js} +1 -1
  31. package/dist/bundle/chunks/{role-F56BS2ZQ.js → role-4BUU46VW.js} +3 -3
  32. package/dist/bundle/chunks/{rotation-stream-BN2YK2MC.js → rotation-stream-TODBIHXJ.js} +1 -1
  33. package/dist/bundle/chunks/{rpc-mode-G4KIP7XS.js → rpc-mode-27TC7W6K.js} +1 -1
  34. package/dist/bundle/chunks/{run-attached-tui-XTGPAGYM.js → run-attached-tui-MXCC5IZR.js} +1 -1
  35. package/dist/bundle/chunks/{schedule-command-L4M3TSQ3.js → schedule-command-MX56D6UE.js} +1 -1
  36. package/dist/bundle/chunks/{session-control-endpoint-V46WMCDF.js → session-control-endpoint-IL6ERD4U.js} +1 -1
  37. package/dist/bundle/chunks/{session-picker-AG6KSR5A.js → session-picker-6VRC25MJ.js} +1 -1
  38. package/dist/bundle/chunks/session-worker.js +44 -44
  39. package/dist/bundle/cli.js +2 -2
  40. package/dist/bundle/index.js +1 -1
  41. package/dist/bundle/rpc-entry.js +1 -1
  42. package/dist/bundle/runtime-manifest.json +1 -1
  43. package/dist/core/agent-session-services.d.ts +2 -0
  44. package/dist/core/agent-session-services.js +1 -0
  45. package/dist/core/agent-session.d.ts +8 -0
  46. package/dist/core/agent-session.js +51 -4
  47. package/dist/core/egress/classify.d.ts +8 -3
  48. package/dist/core/egress/classify.js +177 -158
  49. package/dist/core/egress/console-redactor.d.ts +7 -0
  50. package/dist/core/egress/console-redactor.js +74 -0
  51. package/dist/core/egress/credentials.d.ts +73 -0
  52. package/dist/core/egress/credentials.js +20 -0
  53. package/dist/core/egress/device-custody.d.ts +1 -1
  54. package/dist/core/egress/device-custody.js +18 -15
  55. package/dist/core/egress/device-proxy-call.d.ts +59 -0
  56. package/dist/core/egress/device-proxy-call.js +148 -0
  57. package/dist/core/egress/device-proxy-lost-calls.d.ts +27 -0
  58. package/dist/core/egress/device-proxy-lost-calls.js +28 -0
  59. package/dist/core/egress/device-proxy-ports.d.ts +49 -0
  60. package/dist/core/egress/device-proxy-ports.js +2 -0
  61. package/dist/core/egress/device-proxy-request.d.ts +34 -0
  62. package/dist/core/egress/device-proxy-request.js +69 -0
  63. package/dist/core/egress/device-proxy-waits.d.ts +40 -0
  64. package/dist/core/egress/device-proxy-waits.js +67 -0
  65. package/dist/core/egress/device-proxy.d.ts +3 -0
  66. package/dist/core/egress/device-proxy.js +214 -0
  67. package/dist/core/egress/endpoint.js +2 -1
  68. package/dist/core/egress/entry-verify.d.ts +13 -0
  69. package/dist/core/egress/entry-verify.js +33 -0
  70. package/dist/core/egress/hpke.js +13 -9
  71. package/dist/core/egress/key-policy-template.d.ts +7 -1
  72. package/dist/core/egress/ledger-schema.d.ts +80 -0
  73. package/dist/core/egress/ledger-schema.js +117 -0
  74. package/dist/core/egress/ledger.d.ts +55 -0
  75. package/dist/core/egress/ledger.js +159 -0
  76. package/dist/core/egress/pinned-infra.d.ts +23 -2
  77. package/dist/core/egress/pinned-infra.js +9 -2
  78. package/dist/core/egress/redact.d.ts +10 -0
  79. package/dist/core/egress/redact.js +134 -0
  80. package/dist/core/egress/sealed-source.d.ts +35 -0
  81. package/dist/core/egress/sealed-source.js +140 -0
  82. package/dist/core/egress/verified-keys.js +1 -1
  83. package/dist/core/egress/wire.d.ts +5 -3
  84. package/dist/core/egress/wire.js +5 -3
  85. package/dist/core/extensions/builtin/monitor-state-event.d.ts +26 -0
  86. package/dist/core/extensions/builtin/monitor-state-event.js +2 -0
  87. package/dist/core/extensions/builtin/terminal/background-age.d.ts +25 -0
  88. package/dist/core/extensions/builtin/terminal/background-age.js +91 -0
  89. package/dist/core/extensions/builtin/terminal/extension-state.d.ts +1 -1
  90. package/dist/core/extensions/builtin/terminal/extension-state.js +21 -3
  91. package/dist/core/extensions/builtin/terminal/notify.d.ts +6 -0
  92. package/dist/core/extensions/builtin/terminal/notify.js +39 -5
  93. package/dist/core/extensions/builtin/terminal/session-bundle.d.ts +9 -2
  94. package/dist/core/extensions/builtin/terminal/session-bundle.js +36 -1
  95. package/dist/core/extensions/builtin/terminal/settings.d.ts +2 -0
  96. package/dist/core/extensions/builtin/terminal/settings.js +8 -0
  97. package/dist/core/extensions/builtin/terminal/tools/background-auto-reap.d.ts +15 -0
  98. package/dist/core/extensions/builtin/terminal/tools/background-auto-reap.js +87 -0
  99. package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +2 -0
  100. package/dist/core/extensions/builtin/terminal/tools/bash.js +6 -6
  101. package/dist/core/extensions/builtin/terminal/tools/child-placement.d.ts +8 -0
  102. package/dist/core/extensions/builtin/terminal/tools/child-placement.js +43 -6
  103. package/dist/core/extensions/builtin/terminal/tools/context.d.ts +11 -2
  104. package/dist/core/extensions/session-control-types.d.ts +15 -0
  105. package/dist/core/extensions/session-control-types.js +11 -0
  106. package/dist/core/external-admission.d.ts +16 -2
  107. package/dist/core/external-admission.js +22 -4
  108. package/dist/core/retry-fallback/controller.d.ts +1 -0
  109. package/dist/core/retry-fallback/controller.js +3 -0
  110. package/dist/core/retry-fallback/unusable.d.ts +2 -0
  111. package/dist/core/retry-fallback/unusable.js +7 -1
  112. package/dist/core/retry-fallback/usage-limit.d.ts +6 -1
  113. package/dist/core/retry-fallback/usage-limit.js +9 -4
  114. package/dist/core/sdk.d.ts +6 -1
  115. package/dist/core/sdk.js +1 -0
  116. package/dist/core/terminal-settings.d.ts +1 -0
  117. package/dist/core/turn-origin.d.ts +4 -0
  118. package/dist/core/turn-origin.js +10 -0
  119. package/dist/modes/interactive/components/remote-delivery-message.d.ts +2 -1
  120. package/dist/modes/interactive/components/remote-delivery-message.js +13 -5
  121. package/dist/modes/rpc/admit-external-message-command.d.ts +37 -0
  122. package/dist/modes/rpc/admit-external-message-command.js +61 -0
  123. package/dist/modes/rpc/admit-external-message-wire.d.ts +42 -0
  124. package/dist/modes/rpc/admit-external-message-wire.js +55 -0
  125. package/dist/modes/rpc/connection-handler.js +14 -0
  126. package/dist/modes/rpc/effect-commands.d.ts +1 -1
  127. package/dist/modes/rpc/host-idle-handover.js +1 -0
  128. package/dist/modes/rpc/method-classes-schema-delivery.d.ts +32 -0
  129. package/dist/modes/rpc/method-classes-schema-delivery.js +22 -0
  130. package/dist/modes/rpc/method-classes-schema-session.d.ts +27 -0
  131. package/dist/modes/rpc/method-classes-schema-session.js +2 -0
  132. package/dist/modes/rpc/method-classes-schema.d.ts +27 -0
  133. package/dist/modes/rpc/method-classes.d.ts +1 -0
  134. package/dist/modes/rpc/method-classes.js +2 -0
  135. package/dist/modes/rpc/rpc-input-validation.js +4 -3
  136. package/dist/modes/rpc/rpc-response-types.d.ts +2 -1
  137. package/dist/modes/rpc/rpc-session-command-types.d.ts +2 -1
  138. package/dist/modes/rpc/tool-child/terminal-jobs.d.ts +1 -0
  139. package/dist/modes/rpc/tool-child/terminal-jobs.js +17 -1
  140. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  141. package/docs/engine-socket/fixtures/rpc-inbound-samples.json +19 -2
  142. package/docs/rpc.md +57 -0
  143. package/docs/terminal-tools.md +25 -1
  144. package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
  145. package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
  146. package/package.json +6 -6
  147. package/dist/bundle/chunks/chunk-UODSYQ2D.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{COMPACT_LEAF_CODE_UNITS,CatalogNodeWriter,CompactComponentRoots,CompactContentStore,CompactReadError,CompactReadLease,CompactSelection,CompactValues,CompactWriteError,DEFAULT_TRANSCRIPT_ANCESTRY_BYTES,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,FRAGMENT_MAX_BYTES,McpPresenterAuthority,SECRET_INPUT_FEATURE,SEQUENCED,SocketPeerRecovery,StagedReadError,TransferStaging,TransferStagingError,answerSealedFrame,applyContextPatch,assertRange,attachMcpGrantPresentation,baseRef,catalogDigest,catalogDigester,catalogRootRef,checkSealedAnswer,childRef,createAuthority,declarationReply,decodeCatalogNode,effectStatusRecord,features,isCorrelatedReply,maskOfRoles,nextIncarnation,observeLifecycleDelivery,openFrozenBytes,parseBoundedId,parseContentDigest,parseContentRef,parseDeclaration,parsePageRef,privateRootStat,producePage,protocolId,publishedSessionContext,readAuthority,readRootMarker,refSteps,remoteOriginField,rolesOfMask,rootOwnerState,samePrincipal,secretBinding,secretRequestHash,secretRequestTranscript,sessionQuestionBridges,startAtOrBefore,storeNarrowed,storeRetired,storedBytes,unvouchedCall,withReceipt}from"./chunk-L7ZIS3MC.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_RESPONSE_UNWRITABLE,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-SJI6UB23.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-436DNN4Z.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-J2I56WLK.js";import{bindPrivateMcpForms,isRecord}from"./chunk-MOVB6H22.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RAISER_NOTICE_CAPABILITY,RPC_METHOD_CLASS,RPC_METHOD_CLASSES_DIGEST,RPC_METHOD_CLASSES_VERSION,classifyRpcMethod,hostGeneration,hostInstanceId}from"./chunk-7DRWPZ3N.js";import{PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS}from"./chunk-7WYJAYHH.js";import{RPC_LAUNCH_PROOF_RECORD}from"./chunk-DBQBJTMF.js";import{LegacyRecordDepthError,attachJsonlLineReader,isStackOverflow,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{randomUUID}from"node:crypto";import{tmpdir}from"node:os";import{join}from"node:path";var SKIPPED=new Set(["undefined","function","symbol"]),isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord2(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join(tmpdir(),`senpi-event-leases-${randomUUID()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
2
+ import{COMPACT_LEAF_CODE_UNITS,CatalogNodeWriter,CompactComponentRoots,CompactContentStore,CompactReadError,CompactReadLease,CompactSelection,CompactValues,CompactWriteError,DEFAULT_TRANSCRIPT_ANCESTRY_BYTES,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,FRAGMENT_MAX_BYTES,McpPresenterAuthority,SECRET_INPUT_FEATURE,SEQUENCED,SocketPeerRecovery,StagedReadError,TransferStaging,TransferStagingError,answerSealedFrame,applyContextPatch,assertRange,attachMcpGrantPresentation,baseRef,catalogDigest,catalogDigester,catalogRootRef,checkSealedAnswer,childRef,createAuthority,declarationReply,decodeCatalogNode,effectStatusRecord,features,isCorrelatedReply,maskOfRoles,nextIncarnation,observeLifecycleDelivery,openFrozenBytes,parseBoundedId,parseContentDigest,parseContentRef,parseDeclaration,parsePageRef,privateRootStat,producePage,protocolId,publishedSessionContext,readAuthority,readRootMarker,refSteps,remoteOriginField,rolesOfMask,rootOwnerState,samePrincipal,secretBinding,secretRequestHash,secretRequestTranscript,sessionQuestionBridges,startAtOrBefore,storeNarrowed,storeRetired,storedBytes,unvouchedCall,withReceipt}from"./chunk-4JIBEZZE.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_RESPONSE_UNWRITABLE,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-SJI6UB23.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-436DNN4Z.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-J2I56WLK.js";import{bindPrivateMcpForms,isRecord}from"./chunk-MOVB6H22.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RAISER_NOTICE_CAPABILITY,RPC_METHOD_CLASS,RPC_METHOD_CLASSES_DIGEST,RPC_METHOD_CLASSES_VERSION,classifyRpcMethod,hostGeneration,hostInstanceId}from"./chunk-622VYTRI.js";import{PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS}from"./chunk-7WYJAYHH.js";import{RPC_LAUNCH_PROOF_RECORD}from"./chunk-DBQBJTMF.js";import{LegacyRecordDepthError,attachJsonlLineReader,isStackOverflow,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{randomUUID}from"node:crypto";import{tmpdir}from"node:os";import{join}from"node:path";var SKIPPED=new Set(["undefined","function","symbol"]),isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord2(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join(tmpdir(),`senpi-event-leases-${randomUUID()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
3
3
  `);return}throw cause}}remember(peer,held,admissionId){let admissions=new Set([...peer.released.get(held.lease.id)?.admissions??[],admissionId]);peer.released.set(held.lease.id,{sessionId:held.sessionId,admissions});for(let oldest of peer.released.keys()){if(peer.released.size<=RELEASED_LEASES_REMEMBERED)break;peer.released.delete(oldest)}}dispose(peer,held){peer.held.delete(held.lease.id),this.open-=1,held.shared.holders-=1,held.shared.holders===0&&this.staging&&(this.staging.release(held.shared.content),this.contentBytes-=held.shared.content.ref.entry.length);for(let listener of this.ended)listener(held.lease.id)}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,reason}}};var MESSAGE_KEY="message",COMPACT_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function compactDelta(value){if(value.type!=="message_update"||!Object.hasOwn(value,"message"))return;let event=value.assistantMessageEvent;if(typeof event!="object"||event===null)return;let{type,contentIndex,delta}=event;if(!(typeof type!="string"||!COMPACT_DELTA_TYPES.has(type)||typeof contentIndex!="number"||typeof delta!="string"))return{type,contentIndex,delta}}function demoteToDeltaOnly(value){let event=value.assistantMessageEvent;return{...value,message:null,assistantMessageEvent:{...event,partial:null}}}function toolUpdateKey(value){return value.type==="tool_execution_update"&&typeof value.toolCallId=="string"?`tool:${value.toolCallId}`:void 0}import{AsyncLocalStorage}from"node:async_hooks";var requests=new AsyncLocalStorage;function captureAdmissionReply(){let scope=requests.getStore();return scope&&{id:scope.command.id,admissionId:scope.command.admissionId,peer:scope.peer}}function withAdmissionReply(scope,action){return scope===void 0?action():requests.run({command:scope,peer:scope.peer},action)}function withAdmissionRequest(command,peer,action){return compactUpdatesEnabled()?requests.run({command,peer},action):action()}function replyAdmission(id,peer,routes){let request=requests.getStore();if(!request||request.command.id!==id||request.peer!==peer)return null;let admissionId=request.command.admissionId;return admissionId===void 0?void 0:routes.find(route=>route===admissionId)??null}var BaselineBarrier=class{constructor(cursor,live){this.cancelled=!1,this.ended=!1,this.cursor=cursor,this.live=live}get active(){return!this.cancelled&&!this.ended&&this.live()}cancel(){this.cancelled=!0,this.end()}end(){this.ended||(this.ended=!0,this.cursor.release())}async deliver(write,head){try{if(!this.active)return;let line=await this.cursor.next();for(head!==void 0&&this.active&&await write(head);line!==void 0&&this.active;)await write(line),line=await this.cursor.next()}finally{this.end()}}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var SocketEventQueueStallError=class extends Error{constructor(pendingBytes,stallMs){super(`socket event queue stalled: peer did not drain ${pendingBytes} queued bytes within ${stallMs}ms`),this.name="SocketEventQueueStallError",this.pendingBytes=pendingBytes,this.stallMs=stallMs}},SocketEventQueueOverflowError=class extends Error{constructor(queuedBytes,incomingBytes,maxQueueBytes,incomingPreview){super(`socket event queue overflow: ${queuedBytes} queued + ${incomingBytes} incoming > ${maxQueueBytes} (incoming: ${incomingPreview})`),this.name="SocketEventQueueOverflowError",this.queuedBytes=queuedBytes,this.incomingBytes=incomingBytes,this.maxQueueBytes=maxQueueBytes,this.incomingPreview=incomingPreview}};function waitForDrainOrStall(peer,writtenBytes){return new Promise((resolve2,reject)=>{let timer,blockedMark=loopBlockedMark(),cleanup=()=>{clearTimeout(timer),peer.stopped.removeEventListener("abort",onStop)},onStop=()=>{cleanup(),resolve2()},onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,peer.stallMs));return}try{if(peer.shedAndPing()){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,peer.stallMs);return}}catch(cause){cleanup(),reject(cause);return}let stall=new SocketEventQueueStallError(peer.queuedBytes()+writtenBytes,peer.stallMs);try{peer.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
4
4
  `)}catch{}cleanup(),reject(stall)};timer=setTimeout(onDeadline,peer.stallMs),peer.stopped.addEventListener("abort",onStop,{once:!0}),peer.sink.waitForBackpressure().then(()=>{cleanup(),resolve2()},cause=>{cleanup(),reject(cause)})})}var isBarrier=item=>"kind"in item,SocketEventQueue=class{constructor(){this.items=[],this.charged=0}get bytes(){return this.charged}get length(){return this.items.length}push(item){this.items.push(item),isBarrier(item)||(this.charged+=item.bytes)}shift(){let item=this.items.shift();return item!==void 0&&!isBarrier(item)&&(this.charged-=item.bytes),item}insertBefore(before,entry){let at=this.items.indexOf(before);at<0?this.items.push(entry):this.items.splice(at,0,entry),this.charged+=entry.bytes}supersede(key){let existing=this.items.find(item=>!isBarrier(item)&&item.key===key);existing===void 0||isBarrier(existing)||(existing.demotedLine!==void 0&&(this.charged-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.charged+=existing.bytes,existing.demotedLine=void 0,existing.onWritten?.(!1),existing.onWritten=void 0),existing.key=void 0)}retain(keep){let kept=[];for(let item of this.items)keep(item)?kept.push(item):isBarrier(item)?item.barrier.cancel():item.onWritten?.(!1);this.items=kept,this.charged=kept.reduce((bytes,item)=>isBarrier(item)?bytes:bytes+item.bytes,0)}clear(){for(let item of this.items)isBarrier(item)&&item.barrier.cancel();this.items.length=0,this.charged=0}};var SocketPeerShed=class{constructor(queue,mode){this.queue=queue,this.mode=mode}get isPending(){return this.pending!==void 0}get dropsRecords(){return this.pending!==void 0&&(this.mode==="drop"||this.pending.stale)}cut(reason,snapshot,live){this.queue.retain(item=>!isBarrier(item)&&item.reply);let cut=snapshot(reason);this.pending={kind:"recovery",reason,sessions:cut.sessions,barrier:new BaselineBarrier(cut,live),stale:!1},this.queue.push(this.pending)}supersede(){if(!this.pending||this.pending.stale)return;let recovery=this.pending;this.queue.retain(item=>isBarrier(item)?item===recovery:item.reply),recovery.barrier.cancel(),recovery.stale=!0}admitReply(entry){this.pending&&this.mode==="drop"?this.queue.insertBefore(this.pending,entry):this.queue.push(entry)}take(entry,snapshot,live){return entry.stale&&snapshot&&(entry.barrier=new BaselineBarrier(snapshot(entry.reason,entry.sessions),live)),this.pending===entry&&(this.pending=void 0),entry.barrier}clear(){this.pending=void 0}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS,shedMode="drop"){this.queue=new SocketEventQueue,this.closed=!1,this.recoveryEnabled=!1,this.frameBytes=0,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.shed=new SocketPeerShed(this.queue,shedMode),this.stallPeer={sink,stallMs,stopped:this.stopped.signal,queuedBytes:()=>this.queue.bytes,shedAndPing:()=>!this.recovery||!this.recoveryEnabled?!1:(this.cutOnce("stall"),this.recovery.ping(),!0)}}enableRecovery(snapshot){this.recoveryEnabled=!0,this.snapshot=snapshot,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line)),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}installBaseline(cursor,live){if(this.closed||cursor.empty||this.shed.dropsRecords){cursor.release();return}this.queue.push({kind:"attach",barrier:new BaselineBarrier(cursor,live)}),this.drain()}enqueue(line,key,onWritten,demotedLine,reply=!1,held,current){if(this.closed)return;let bytes=Buffer.byteLength(line);if(this.shed.dropsRecords){reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1);return}if(key!==void 0&&this.queue.supersede(key),!this.fits(bytes)){if(this.recovery&&this.recoveryEnabled){this.shed.isPending?this.shed.supersede():this.cut("overflow"),reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1),this.drain();return}this.failOverflow(bytes,line);return}this.queue.push({line,bytes,key,demotedLine,onWritten,reply,held:this.shed.isPending?held:void 0,current}),this.drain()}async flush(){for(;this.draining;)await this.draining;if(this.failure!==void 0)throw this.failure}waitForAcceptance(){return Promise.resolve()}close(){this.closed=!0,this.dropQueue(),this.stopped.abort()}fits(bytes){return this.queue.bytes+this.frameBytes+bytes<=this.maxQueueBytes}admitReply(entry){if(!this.fits(entry.bytes)){this.recovery?.loseReply(),entry.onWritten?.(!1);return}this.shed.admitReply(entry),this.drain()}failOverflow(bytes,line){let overflow=new SocketEventQueueOverflowError(this.queue.bytes+this.frameBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.dropQueue();try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
5
5
  `)}catch(cause){this.onFailure(cause)}this.onFailure(overflow)}dropQueue(){this.queue.clear(),this.attempt?.cancel(),this.shed.clear()}cutOnce(reason){this.recovery?.pending||this.cut(reason)}cut(reason){!this.recovery||!this.snapshot||(this.attempt?.cancel(),this.recovery.shed(reason),this.shed.cut(reason,this.snapshot,()=>!this.closed))}async write(line){this.sink.writeRaw(line),await waitForDrainOrStall(this.stallPeer,Buffer.byteLength(line))}async writeFrame(line){let bytes=Buffer.byteLength(line);if(!this.fits(bytes)){this.recovery&&this.recoveryEnabled?this.cutOnce("overflow"):this.failOverflow(bytes,line);return}this.frameBytes=bytes;try{await this.write(line)}finally{this.frameBytes=0}}async deliver(entry){if(entry.kind==="attach"){await this.stream(entry.barrier,line=>this.writeFrame(line));return}if(await waitForDrainOrStall(this.stallPeer,0),this.closed||!this.recovery)return;let barrier=this.shed.take(entry,this.snapshot,()=>!this.closed),gap=this.recovery.takeGap();this.recoveryEnabled||(this.recovery=void 0),await this.stream(barrier,line=>this.write(line),gap)}async stream(barrier,write,head){this.attempt=barrier;try{await barrier.deliver(write,head)}finally{barrier.end(),this.attempt===barrier&&(this.attempt=void 0)}}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&this.queue.length>0;){let item=this.queue.shift();if(item===void 0)break;if(isBarrier(item)){try{await this.deliver(item)}finally{item.barrier.end()}continue}let written=(item.held?.()??!0)&&(item.current?.()??!0);written&&await this.write(item.line),item.onWritten?.(written)}}catch(cause){this.failure=cause,this.closed=!0,this.dropQueue(),this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&this.queue.length>0&&this.drain()}),this.draining)}};var AdmissionRoutingActor=class extends SocketEventSinkActor{constructor(){super(...arguments),this.admissions=new Set,this.subscriptions=new Map,this.mirrorOwners=new Map,this.pendingMirrors=new Map,this.opened=new Map,this.retireAfterReply=new Map,this.terminal=new Map}close(){this.subscriptions.clear(),this.mirrorOwners.clear();for(let pending of this.pendingMirrors.values())pending.retire();this.pendingMirrors.clear(),this.admissions.clear(),this.opened.clear(),this.retireAfterReply.clear(),this.terminal.clear(),super.close()}remember(sessionId,checkpoints,socketEpoch){let stream=checkpoints.stream({socketEpoch,sessionId}),remembered=stream??this.terminal.get(sessionId),routes=remembered?.routes.filter(id=>this.admissions.has(id)||[...this.mirrorOwners.values()].includes(id))??[];return stream&&routes.length>0&&this.terminal.set(sessionId,{...stream,routes}),remembered?{...remembered,routes}:void 0}route(line,checkpoints,socketEpoch){if(this.admissions.size===0&&this.subscriptions.size===0&&this.mirrorOwners.size===0)return[line];let record=JSON.parse(line);if(typeof record.sessionId!="string"||record.admissionId!==void 0)return[line];if(typeof record.subscriptionId=="string"){let subscription=this.subscriptions.get(record.subscriptionId);return subscription===void 0?[line]:[serializeJsonLine({...record,admissionId:subscription,generation:0})]}let mirrors=record.type==="response"?[]:this.mirrorAdmissions?.(record.sessionId,String(record.type))??[],stream=this.remember(record.sessionId,checkpoints,socketEpoch),terminal=record.type==="session_closed"||record.type==="session_parked",routes=[...new Set([...(stream?.routes??[]).filter(id=>this.admissions.has(id)||terminal&&[...this.mirrorOwners.values()].includes(id)),...mirrors])];if(record.type==="response"&&typeof record.id=="string"){let admissionId=replyAdmission(record.id,this.peer,routes);return admissionId===null?[]:admissionId===void 0?[line]:[serializeJsonLine({...record,admissionId,generation:stream?.generation})]}return routes.length===0?[line]:routes.map(admissionId=>serializeJsonLine({...record,admissionId,generation:stream?.generation}))}deferRetire(id,retire){this.retireAfterReply.set(id,retire)}retireReplied(line){if(this.retireAfterReply.size===0)return;let record=JSON.parse(line);if(record.type!=="response"||typeof record.id!="string")return;let retire=this.retireAfterReply.get(record.id);this.retireAfterReply.delete(record.id),retire?.()}bind(checkpoints,socketEpoch,peer){this.peer=peer;let enqueue=super.enqueue.bind(this);this.enqueue=(line,key,written,demoted,reply,held)=>{let lines2=this.route(line,checkpoints,socketEpoch);if(this.retireReplied(line),lines2.length===0){written?.(!1);return}let replacements=demoted===void 0?void 0:this.route(demoted,checkpoints,socketEpoch),remaining=lines2.length,delivered=!1,receipt=ok=>{delivered||=ok,--remaining===0&&written?.(delivered)};for(let i=0;i<lines2.length;i++){let line2=lines2[i]??"",admissionId=Reflect.get(JSON.parse(line2),"admissionId"),pending=typeof admissionId=="string"?this.pendingMirrors.get(admissionId):void 0,deliver=()=>enqueue(lines2[i]??line2,key===void 0?void 0:`${key}:${i}`,receipt,replacements?.[i],reply,held);pending&&!reply?pending.enqueue(line2,deliver,()=>receipt(!1)):deliver()}}}};var CompactRequiredStreams=class{constructor(fanout,status){this.states=new WeakMap,this.fanout=fanout,this.status=status}sessions(peer){return this.status.requiredSessions(peer)}routes(peer,sessionId,type){let registered=this.fanout.get(peer),actor=registered?.actor;return!(actor instanceof AdmissionRoutingActor)||!registered?[]:[...new Set([...(this.fanout.checkpoints.stream({socketEpoch:registered.socketEpoch,sessionId})?.routes??[]).filter(id=>actor.admissions.has(id)),...this.status.mirrorAdmissions(peer,sessionId,type)])]}prepare(sessionId,record){let lane=this.fanout.acceptance.get(sessionId);if(!(!lane||lane.retired))for(let peer of this.fanout.connectionIds()){if(!this.fanout.connectionHas(peer,COMPACT_EVENTS_CAPABILITY))continue;let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)continue;let routes=this.status.requiredAdmissions(peer,sessionId),caller={socketEpoch:registered.socketEpoch,sessionId};for(let admissionId of routes){if(this.fanout.checkpoints.stream(caller)?.routes.includes(admissionId))continue;let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId,routeKind:"mirror"},lane,!0);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}}let stream=this.fanout.checkpoints.stream(caller);if(!stream?.routes.length)continue;let states=this.states.get(actor)??new Map;this.states.set(actor,states);let state=states.get(sessionId);if(state?.epoch!==lane.sessionEpoch&&(state={epoch:lane.sessionEpoch,dirty:!1},states.set(sessionId,state),state.seed=this.fanout.checkpoints.tokens().find(t=>t.admission.socketEpoch===caller.socketEpoch&&t.admission.sessionId===sessionId)),!record)continue;let type=String(Reflect.get(record,"type"));if(!(stream.routes.some(id=>actor.admissions.has(id))||this.status.mirrorAdmissions(peer,sessionId,type).length>0)){state.dirty=!0;continue}if(state.dirty){let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId:stream.routes[0],routeKind:routes.length?"mirror":"ordinary"},lane);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}state.seed=frozen.value.token,state.dirty=!1}}}takeSeed(peer,sessionId){let actor=this.fanout.get(peer)?.actor,state=actor instanceof AdmissionRoutingActor?this.states.get(actor)?.get(sessionId):void 0,seed=state?.seed;return state&&(state.seed=void 0),seed}forgetSession(sessionId){for(let peer of this.fanout.connectionIds()){let actor=this.fanout.get(peer)?.actor;actor instanceof AdmissionRoutingActor&&this.states.get(actor)?.delete(sessionId)}}};function causeLine(cause){let text=cause instanceof Error?`${cause.name}: ${cause.message}`:String(cause);return text.split(`
@@ -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"./chunk-POTKWOUB.js";import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunk-MJTCZUXS.js";import"./chunk-EO2VPZ2K.js";import{installStaleExtensionContainment}from"./chunk-JMQOLOC2.js";import{configureHttpDispatcher}from"./chunk-FEQDJBDL.js";import"./chunk-R2Z7CX77.js";import"./chunk-MSDBBOB2.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-CFEHJ4VU.js";import"./chunk-ZFIC2DZV.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-FQXWKEVK.js";import"./chunk-IKOFCODM.js";await dispatchAgentDirectoryCommand(process.argv.slice(2));await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();var{main}=await import("./main-OBL6375C.js");await main(process.argv.slice(2));
3
+ import"./chunk-POTKWOUB.js";import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunk-LHSWAJJL.js";import"./chunk-SGAFIMAU.js";import{installStaleExtensionContainment}from"./chunk-Q6NR6644.js";import{configureHttpDispatcher}from"./chunk-FEQDJBDL.js";import"./chunk-R2Z7CX77.js";import"./chunk-MSDBBOB2.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-NDSWTAYJ.js";import"./chunk-ZFIC2DZV.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-FQXWKEVK.js";import"./chunk-IKOFCODM.js";await dispatchAgentDirectoryCommand(process.argv.slice(2));await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();var{main}=await import("./main-5SD4DHMC.js");await main(process.argv.slice(2));
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{PresentationBroker,bootstrapRuntime,buildToolRegistry,builtInExtensions,canonicalizeFilesystemPath,childModuleRoots,createAgentSessionServices,createProjectTrustContext,createToolChildRuntime,forwardToolEvents,presetTrustsProject,resolveProjectTrusted,sessionExtensionFlagValues,toolChildModuleRoots,toolInfoOf,withFileMutationQueue,withFileMutationQueues}from"./chunk-V2QAYGOK.js";import"./chunk-6CEDL5S2.js";import"./chunk-BASS47UD.js";import"./chunk-JMQOLOC2.js";import{SettingsManager}from"./chunk-X53PD4ZC.js";import"./chunk-CF5OGBC4.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import"./chunk-4BATXPB7.js";import"./chunk-H33A33M4.js";import"./chunk-5LKB732P.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-L7ZIS3MC.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-UODSYQ2D.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import{ProjectTrustStore,getSavedProjectTrust,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-SB6MXNO5.js";import"./chunk-7DRWPZ3N.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import{closeServer,listen,prepareSocketPath}from"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-4E7GDG4H.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-F5JLDCYD.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import{localDeviceFiles}from"./chunk-DSWDJ7HT.js";import{DeviceFileError,FILE_CHANNEL_MAX_BYTES,base64Length,createReliableTransport,createRemoteExecutor,decodeBase64,decodeDeviceFileArgs,encodeBase64,fileRefusal,fileResult,serveLoopHooks}from"./chunk-GKAYPJ4E.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import{validateToolArguments}from"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-CFEHJ4VU.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import{shieldSocketDuringClose,unlinkOwnedSocket}from"./chunk-5XHOHZIR.js";import{authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{isLocalPath,resolvePath}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer}from"node:net";import{posix as posix2,win32}from"node:path";import{isAbsolute as isAbsolute2}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{basename as basename4,dirname as dirname4,join as join4,resolve as resolve3}from"node:path";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync}from"node:fs";import{constants as fsConstants}from"node:fs";import{open}from"node:fs/promises";import{constants as osConstants}from"node:os";import{basename,dirname,join,resolve}from"node:path";var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,RETRY_MS=5,LOCK_SH=1,LOCK_NB=4;function classifyFlockErrno(errno){let{EAGAIN,EWOULDBLOCK,ENOLCK,EOPNOTSUPP,ENOSYS}=osConstants.errno;return errno===EAGAIN||errno===EWOULDBLOCK?"busy":errno===ENOLCK||errno===EOPNOTSUPP||errno===ENOSYS?"no-lock":"failed"}function identityLocksDir(repoDir){let repo=resolve(repoDir);if(!(basename(repo)!=="repo"||basename(dirname(dirname(repo)))!=="agents"))return join(dirname(repo),"runtime","locks")}var NO_HOLD={fd:void 0,release:async()=>{}},delay=ms=>new Promise(done=>setTimeout(done,ms));async function holdActivityLock(cwd,flock,waitMs=GIT_ACTIVITY_SHARED_WAIT_MS){let locksDir=identityLocksDir(cwd);if(locksDir===void 0||flock===void 0)return NO_HOLD;if(!existsSync(locksDir))throw new DeviceFileError("not_found","the identity's locks directory does not exist");let handle=await open(join(locksDir,GIT_ACTIVITY_LOCK_NAME),fsConstants.O_RDWR|fsConstants.O_CREAT,384),deadline=Date.now()+waitMs;try{for(;;){let{rc,errno}=flock(handle.fd,LOCK_SH|LOCK_NB);if(rc===0)return{fd:handle.fd,release:()=>handle.close()};let kind=classifyFlockErrno(errno);if(kind==="no-lock")return await handle.close(),NO_HOLD;if(kind==="failed")throw new DeviceFileError("io",`flock on the git-activity lock failed (errno ${errno})`);if(Date.now()>=deadline)throw new DeviceFileError("io",`the git-activity lock stayed exclusively held for ${waitMs} ms`);await delay(RETRY_MS)}}catch(error){throw await handle.close(),error}}import{posix}from"node:path";var k=kind=>({kind}),eq=(prefix,kind)=>({prefix,kind}),opt=(...optional)=>({optional}),rep=(min,...repeat)=>({repeat,min}),NUL=/\0/,REV=/^(?![-./~:])[A-Za-z0-9._/@{}^~+-]+$/,REL=/^(?![/-])(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/,rev=value=>REV.test(value)&&!value.includes("..")&&!value.includes("//"),range=value=>{let parts=value.split("..");return parts.length===2&&parts.every(rev)},blobref=value=>{let at=value.indexOf(":");return at>=0&&(at===0||rev(value.slice(0,at)))&&REL.test(value.slice(at+1))},filesystem=value=>value.length>0&&!NUL.test(value)&&!/^[-:]/.test(value);function scheme(value){return/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(value)?.[1]}function urlIsLocal(value){let colon=value.indexOf(":"),slash=value.indexOf("/");return colon<0||slash>=0&&slash<colon||process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(value)}var unsafeUrl=value=>value.length===0||NUL.test(value)||/\s/.test(value)||value.startsWith("-")||value.includes("::");function remote(value){if(unsafeUrl(value))return!1;let named=scheme(value);return named!==void 0?named==="https"||named==="ssh":!urlIsLocal(value)}function localUrlPath(value){if(unsafeUrl(value)||scheme(value)!=="file")return;let rest=value.slice(7);if(!rest.startsWith("/")||/[?#]/.test(rest))return;let path;try{path=decodeURIComponent(rest)}catch{return}return path.length>1&&!NUL.test(path)&&!path.endsWith("/")&&posix.normalize(path)===path&&path.split("/").slice(1).every(part=>part!==""&&part!=="."&&part!=="..")?path:void 0}var localCandidate=value=>!unsafeUrl(value)&&(scheme(value)==="file"||scheme(value)===void 0&&urlIsLocal(value)),KINDS={rev,range,revish:value=>rev(value)||range(value),object:value=>rev(value)||blobref(value),blobref,ref:value=>value==="HEAD"||/^refs\/[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refpat:value=>/^refs\/[A-Za-z0-9._/-]+\*?$/.test(value)&&!value.includes(".."),branch:value=>/^(?![-./])[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refspec:value=>/^[A-Za-z0-9._/]+(?:-[A-Za-z0-9._/]+)*:[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),msg:value=>!NUL.test(value),count:value=>/^\d{1,9}$/.test(value),mode:value=>/^(?:100644|100755|120000|160000)$/.test(value),oid:value=>/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(value),filter:value=>/^[ACDMRTUXB]+$/i.test(value),fmt:value=>!NUL.test(value),iso:value=>/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value),relpath:value=>REL.test(value),gitpath:value=>value==="index"||value==="MERGE_HEAD",path:filesystem,worktree:filesystem,source:value=>remote(value)||localCandidate(value),target:value=>remote(value)||localCandidate(value)},FORMAT=eq("--format=","fmt"),LOG_RECORD="--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI",SHAPES={add:[["-A","--",rep(1,k("path"))]],branch:[["--show-current"],["-D",k("branch")]],"cat-file":[["blob",k("object")],["--batch"],["-e",k("blobref")]],checkout:[[k("rev"),"--",k("path")]],commit:[["-q","--no-verify","-m",k("msg")]],"commit-tree":[[k("rev"),opt("-p",k("rev")),"-F","-"]],"count-objects":[["-v"]],diff:[["--cached","-M","-C","-z","--raw","--no-abbrev"],["--name-only","-z",eq("--diff-filter=","filter"),k("rev"),k("rev"),"--"],["--name-status","-M","-z",k("range"),"--"],["--cached","--quiet",k("rev"),"--"],["--no-renames","--name-only","-z",k("range"),"--",k("path")],["--name-only","-z",k("range"),"--"],["--name-only",eq("--diff-filter=","filter")]],"diff-files":[["--name-only","-z"]],"diff-tree":[["-r","-m","--no-commit-id","--no-renames",eq("--diff-filter=","filter"),"--raw","-z",k("rev")]],"for-each-ref":[[FORMAT,rep(1,k("refpat"))]],"hash-object":[[opt("-w"),"--no-filters","--stdin"],[opt("-w"),eq("--path=","relpath"),"--stdin"]],init:[["--template="]],log:[["-1",FORMAT,k("rev")],[{prefix:"-",kind:"count"},FORMAT,k("rev")],[FORMAT,"--name-only","-z","--no-renames","--diff-merges=first-parent",eq("--diff-filter=","filter"),rep(0,k("revish")),"--"],[LOG_RECORD,opt("--name-only","-z","--no-renames","--full-diff"),opt("--fixed-strings","--all-match",rep(1,eq("--grep=","msg"))),opt("-n",k("count")),opt(eq("--since=","iso")),opt(k("revish")),opt("--",rep(1,k("path")))]],"ls-files":[["--stage","-z","--",k("path")],["--eol","-z"]],"ls-remote":[[k("source"),k("ref")]],"ls-tree":[["-r","--name-only","-z",k("rev"),opt("--",k("path"))],["-r","-l","-z",k("rev")],["-r","-z",k("rev")],["-z",k("rev"),"--",k("path")]],maintenance:[["run","--task=loose-objects","--quiet"]],merge:[[],["--abort"],[opt("--no-ff"),opt("-m",k("msg")),k("rev")],["--no-ff",k("rev"),rep(1,"-m",k("msg"))]],"merge-base":[["--is-ancestor",k("rev"),k("rev")]],"prune-packed":[["--quiet"]],push:[["--quiet",k("target"),k("refspec")]],"read-tree":[["--empty"],[k("rev")]],remote:[["-v"]],reset:[["--soft",k("rev")]],restore:[["--source=HEAD","--staged",opt("--worktree"),"--",rep(1,k("path"))]],"rev-list":[[opt("--count"),k("range")],["--reverse",k("range")]],"rev-parse":[["--verify",opt("--quiet"),k("rev")],["-q","--verify",k("rev")],["--git-path",k("gitpath")],["--git-common-dir"]],rm:[["-q","--cached",opt("-f"),"--ignore-unmatch","--",rep(1,k("path"))],["-rf","-q","--ignore-unmatch","--",k("path")]],show:[["-s",FORMAT,k("rev")],[k("blobref")]],"show-ref":[["--verify",k("ref")]],status:[["--porcelain",opt("--untracked-files=all",opt("--",rep(1,k("path"))))]],"symbolic-ref":[["HEAD",k("ref")]],"update-index":[["--force-remove","--",k("path")],["--add","--cacheinfo",k("mode"),k("oid"),k("path")],["-q","-z","--stdin"]],"update-ref":[["-m",k("msg"),"HEAD",k("rev"),k("rev")]],worktree:[["add","-b",k("branch"),k("worktree"),k("rev")],["remove",opt("--force"),k("worktree")],["list","--porcelain"],["prune"]],"write-tree":[[]]};function match(items,args,at,paths,then){let[item,...rest]=items;if(item===void 0)return then(at);let next=to=>match(rest,args,to,paths,then);if(typeof item=="string")return args[at]===item&&next(at+1);if("optional"in item)return match(item.optional,args,at,paths,next)||next(at);if("repeat"in item){let again=(count,from)=>count>=item.min&&next(from)||match(item.repeat,args,from,paths,to=>to>from&&again(count+1,to));return again(0,at)}let arg=args[at];if(arg===void 0)return!1;let value="prefix"in item?arg.startsWith(item.prefix)?arg.slice(item.prefix.length):void 0:arg;if(value===void 0||!KINDS[item.kind](value))return!1;let kind=item.kind,typed=kind==="path"||kind==="worktree"||(kind==="source"||kind==="target")&&localCandidate(value);return typed&&paths.push({kind,value}),next(at+1)?!0:(typed&&paths.pop(),!1)}function matchShape(sub,args){for(let shape of SHAPES[sub]??[]){let paths=[];if(match(shape,args,0,paths,at=>at===args.length))return paths}}var HAND_GIT_PREFIX=["-c","core.fsmonitor=false","-c","protocol.file.allow=always"],SUBCOMMANDS=new Set(["add","branch","cat-file","checkout","commit","commit-tree","config","count-objects","diff","diff-files","diff-tree","for-each-ref","hash-object","init","log","ls-files","ls-remote","ls-tree","maintenance","merge","merge-base","prune-packed","push","read-tree","remote","reset","restore","rev-list","rev-parse","rm","show","show-ref","status","symbolic-ref","update-index","update-ref","worktree","write-tree"]);function configKey(key){let parts=key.split(".");if(parts.length<2)return key;let section=parts[0]?.toLowerCase()??"",name=parts[parts.length-1]?.toLowerCase()??"";return[section,...parts.slice(1,-1),name].join(".")}var keySet=keys=>new Set(keys.map(configKey)),CALLER_C_KEYS=keySet(["maintenance.auto","gc.auto","user.name","user.email","core.autocrlf","log.showRoot","core.quotePath","log.showSignature","log.follow"]),CONFIG_KEYS=keySet(["omo.agentId","user.name","user.email","commit.gpgsign","gc.auto","core.autocrlf","omo.memoryRepository.url","omo.sync.binding","omo.sync.space"]);function subcommandArgs(sub,rest){if(sub==="config"){let[scope,first,second,extra]=rest;if(scope!=="--local"||first===void 0||extra!==void 0)return"config shape";let key=first==="--get"||first==="--unset-all"?second:first;return key===void 0||first!=="--get"&&first!=="--unset-all"&&(second??"-").startsWith("-")?"config shape":CONFIG_KEYS.has(configKey(key))?[]:`config key ${key}`}return matchShape(sub,rest)??`${sub} shape`}function planGit(argv){let index=0;for(;argv[index]?.startsWith("-");){let arg=argv[index]??"";if(arg==="--literal-pathspecs"){index++;continue}if(arg!=="-c")return arg;let setting=argv[index+1]??"",separator=setting.indexOf("=");if(separator<=0||!CALLER_C_KEYS.has(configKey(setting.slice(0,separator))))return`-c ${setting}`;index+=2}let sub=argv[index];if(sub===void 0||!SUBCOMMANDS.has(sub))return`subcommand ${sub??"(none)"}`;let paths=subcommandArgs(sub,argv.slice(index+1));return typeof paths=="string"?paths:{argv:[...HAND_GIT_PREFIX,...argv],paths}}var equal=(args,expected)=>args.length===expected.length&&args.every((arg,index)=>arg===expected[index]);function planLsof(argv,uid){let holders=argv.length===3&&argv[0]==="-t"&&argv[1]==="--"&&(argv[2]??"").length>0,inUse=equal(argv,["-w","-a","-d","cwd","-u",String(uid),"-Fpn"]);return holders||inUse?[...argv]:"lsof shape"}var CALLER_ENV={GIT_TERMINAL_PROMPT:value=>value==="0",GIT_INDEX_FILE:value=>value.length>0,GIT_GLOB_PATHSPECS:value=>value==="0"||value==="1",GIT_AUTHOR_NAME:()=>!0,GIT_AUTHOR_EMAIL:()=>!0,GIT_COMMITTER_NAME:()=>!0,GIT_COMMITTER_EMAIL:()=>!0},WIN32_BASELINE=["SYSTEMROOT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","PATHEXT"];function baseline(context){let env={},keep=key=>{let value=context.ownEnv[key];value!==void 0&&(env[key]=value)};for(let key of["PATH","HOME","SSH_AUTH_SOCK"])keep(key);if(context.platform==="win32")for(let key of WIN32_BASELINE)keep(key);else keep("TMPDIR"),env.LANG="C";return env.GIT_PROTOCOL_FROM_USER="0",env}function planRun(request,context){let env=baseline(context);for(let[key,value]of Object.entries(request.env)){let allowed2=Object.hasOwn(CALLER_ENV,key)?CALLER_ENV[key]:void 0;if(allowed2===void 0||!allowed2(value))return{ok:!1,reason:`not in the run allowlist: env ${key}`};env[key]=value}let planned=request.exe==="git"?planGit(request.argv):request.exe==="lsof"?planLsof(request.argv,context.uid):`executable ${request.exe}`;return typeof planned=="string"?{ok:!1,reason:`not in the run allowlist: ${planned}`}:Array.isArray(planned)?{ok:!0,exe:"lsof",argv:planned,env,paths:[]}:{ok:!0,exe:"git",argv:planned.argv,env,paths:planned.paths}}var SAFE=/^[A-Za-z0-9@%+=:,./_-]+$/;function renderCommand(exe,argv){return[exe,...argv].map(arg=>SAFE.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" ")}import{execFile as execFile2}from"node:child_process";import{lstat as lstat2,stat}from"node:fs/promises";import{basename as basename3,dirname as dirname3,isAbsolute,join as join3,resolve as resolve2,sep}from"node:path";import{execFile}from"node:child_process";import{lstat,readdir,realpath}from"node:fs/promises";import{basename as basename2,dirname as dirname2,join as join2}from"node:path";var SHAPE="local_repo_shape_unsupported",WALK_BOUND=2e4,refuse=detail=>{throw new DeviceFileError("refused_by_policy",`${SHAPE}: ${detail}`)};async function kindOf(path){let entry=await lstat(path).catch(()=>{});if(entry!==void 0)return entry.isSymbolicLink()?"link":entry.isFile()?"file":entry.isDirectory()?"dir":"other"}async function noLinks(path,recursive,budget){let kind=await kindOf(path);if(kind!==void 0&&(kind==="link"&&refuse(`symlink at ${path}`),kind==="dir"))for(let name of await readdir(path)){budget.left-=1,budget.left<0&&refuse(`more than ${WALK_BOUND} entries under the repository`);let child=join2(path,name),childKind=await kindOf(child);childKind==="link"&&refuse(`symlink at ${child}`),recursive&&childKind==="dir"&&await noLinks(child,!0,budget)}}async function plainGitDir(dir){let[head,objects,refs,commondir,alternates]=await Promise.all(["HEAD","objects","refs","commondir","objects/info/alternates"].map(entry=>kindOf(join2(dir,entry))));(head!=="file"||objects!=="dir"||refs!=="dir")&&refuse(`${dir} is not a plain git directory`),(commondir!==void 0||alternates!==void 0)&&refuse(`${dir} redirects through commondir or alternates`);let budget={left:WALK_BOUND};for(let entry of["HEAD","config","packed-refs"])await noLinks(join2(dir,entry),!1,budget);await noLinks(join2(dir,"refs"),!0,budget),await noLinks(join2(dir,"hooks"),!0,budget),await noLinks(join2(dir,"logs"),!0,budget),await noLinks(join2(dir,"worktrees"),!1,budget),await noLinks(join2(dir,"objects"),!1,budget);for(let sub of["info","pack"])await noLinks(join2(dir,"objects",sub),!1,budget)}function gitConfig(file){let env={PATH:process.env.PATH??"/usr/bin:/bin",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",LANG:"C"};return new Promise((done,fail)=>{execFile("git",["config","--file",file,"--no-includes","--list","-z"],{env,timeout:3e4},(error,stdout)=>{if(error)return fail(error);let records=String(stdout).split("\0").filter(Boolean);done(records.map(record=>{let at=record.indexOf(`
2
+ import{PresentationBroker,bootstrapRuntime,buildToolRegistry,builtInExtensions,canonicalizeFilesystemPath,childModuleRoots,createAgentSessionServices,createProjectTrustContext,createToolChildRuntime,forwardToolEvents,presetTrustsProject,resolveProjectTrusted,sessionExtensionFlagValues,toolChildModuleRoots,toolInfoOf,withFileMutationQueue,withFileMutationQueues}from"./chunk-7CFORZPE.js";import"./chunk-4UR6UFBH.js";import"./chunk-STGOYIXC.js";import"./chunk-Q6NR6644.js";import{SettingsManager}from"./chunk-45MVD7BU.js";import"./chunk-4NYNMAYF.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import"./chunk-K3UHGDUQ.js";import"./chunk-H33A33M4.js";import"./chunk-3TZQXZKH.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-4JIBEZZE.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-XZDCMDUH.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import{ProjectTrustStore,getSavedProjectTrust,hasTrustRequiringProjectResources}from"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-M7GF73FO.js";import"./chunk-622VYTRI.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import{closeServer,listen,prepareSocketPath}from"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-7VMEE62L.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-527Q2UYM.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import{localDeviceFiles}from"./chunk-WQ4RBPMS.js";import{DeviceFileError,FILE_CHANNEL_MAX_BYTES,base64Length,createReliableTransport,createRemoteExecutor,decodeBase64,decodeDeviceFileArgs,encodeBase64,fileRefusal,fileResult,serveLoopHooks}from"./chunk-7PROV6BB.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import{validateToolArguments}from"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-NDSWTAYJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import{shieldSocketDuringClose,unlinkOwnedSocket}from"./chunk-5XHOHZIR.js";import{authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import{isLocalPath,resolvePath}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer}from"node:net";import{posix as posix2,win32}from"node:path";import{isAbsolute as isAbsolute2}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{basename as basename4,dirname as dirname4,join as join4,resolve as resolve3}from"node:path";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync}from"node:fs";import{constants as fsConstants}from"node:fs";import{open}from"node:fs/promises";import{constants as osConstants}from"node:os";import{basename,dirname,join,resolve}from"node:path";var GIT_ACTIVITY_LOCK_NAME="git-activity.flock",GIT_ACTIVITY_SHARED_WAIT_MS=1e4,RETRY_MS=5,LOCK_SH=1,LOCK_NB=4;function classifyFlockErrno(errno){let{EAGAIN,EWOULDBLOCK,ENOLCK,EOPNOTSUPP,ENOSYS}=osConstants.errno;return errno===EAGAIN||errno===EWOULDBLOCK?"busy":errno===ENOLCK||errno===EOPNOTSUPP||errno===ENOSYS?"no-lock":"failed"}function identityLocksDir(repoDir){let repo=resolve(repoDir);if(!(basename(repo)!=="repo"||basename(dirname(dirname(repo)))!=="agents"))return join(dirname(repo),"runtime","locks")}var NO_HOLD={fd:void 0,release:async()=>{}},delay=ms=>new Promise(done=>setTimeout(done,ms));async function holdActivityLock(cwd,flock,waitMs=GIT_ACTIVITY_SHARED_WAIT_MS){let locksDir=identityLocksDir(cwd);if(locksDir===void 0||flock===void 0)return NO_HOLD;if(!existsSync(locksDir))throw new DeviceFileError("not_found","the identity's locks directory does not exist");let handle=await open(join(locksDir,GIT_ACTIVITY_LOCK_NAME),fsConstants.O_RDWR|fsConstants.O_CREAT,384),deadline=Date.now()+waitMs;try{for(;;){let{rc,errno}=flock(handle.fd,LOCK_SH|LOCK_NB);if(rc===0)return{fd:handle.fd,release:()=>handle.close()};let kind=classifyFlockErrno(errno);if(kind==="no-lock")return await handle.close(),NO_HOLD;if(kind==="failed")throw new DeviceFileError("io",`flock on the git-activity lock failed (errno ${errno})`);if(Date.now()>=deadline)throw new DeviceFileError("io",`the git-activity lock stayed exclusively held for ${waitMs} ms`);await delay(RETRY_MS)}}catch(error){throw await handle.close(),error}}import{posix}from"node:path";var k=kind=>({kind}),eq=(prefix,kind)=>({prefix,kind}),opt=(...optional)=>({optional}),rep=(min,...repeat)=>({repeat,min}),NUL=/\0/,REV=/^(?![-./~:])[A-Za-z0-9._/@{}^~+-]+$/,REL=/^(?![/-])(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/,rev=value=>REV.test(value)&&!value.includes("..")&&!value.includes("//"),range=value=>{let parts=value.split("..");return parts.length===2&&parts.every(rev)},blobref=value=>{let at=value.indexOf(":");return at>=0&&(at===0||rev(value.slice(0,at)))&&REL.test(value.slice(at+1))},filesystem=value=>value.length>0&&!NUL.test(value)&&!/^[-:]/.test(value);function scheme(value){return/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(value)?.[1]}function urlIsLocal(value){let colon=value.indexOf(":"),slash=value.indexOf("/");return colon<0||slash>=0&&slash<colon||process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(value)}var unsafeUrl=value=>value.length===0||NUL.test(value)||/\s/.test(value)||value.startsWith("-")||value.includes("::");function remote(value){if(unsafeUrl(value))return!1;let named=scheme(value);return named!==void 0?named==="https"||named==="ssh":!urlIsLocal(value)}function localUrlPath(value){if(unsafeUrl(value)||scheme(value)!=="file")return;let rest=value.slice(7);if(!rest.startsWith("/")||/[?#]/.test(rest))return;let path;try{path=decodeURIComponent(rest)}catch{return}return path.length>1&&!NUL.test(path)&&!path.endsWith("/")&&posix.normalize(path)===path&&path.split("/").slice(1).every(part=>part!==""&&part!=="."&&part!=="..")?path:void 0}var localCandidate=value=>!unsafeUrl(value)&&(scheme(value)==="file"||scheme(value)===void 0&&urlIsLocal(value)),KINDS={rev,range,revish:value=>rev(value)||range(value),object:value=>rev(value)||blobref(value),blobref,ref:value=>value==="HEAD"||/^refs\/[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refpat:value=>/^refs\/[A-Za-z0-9._/-]+\*?$/.test(value)&&!value.includes(".."),branch:value=>/^(?![-./])[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),refspec:value=>/^[A-Za-z0-9._/]+(?:-[A-Za-z0-9._/]+)*:[A-Za-z0-9._/-]+$/.test(value)&&!value.includes(".."),msg:value=>!NUL.test(value),count:value=>/^\d{1,9}$/.test(value),mode:value=>/^(?:100644|100755|120000|160000)$/.test(value),oid:value=>/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(value),filter:value=>/^[ACDMRTUXB]+$/i.test(value),fmt:value=>!NUL.test(value),iso:value=>/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value),relpath:value=>REL.test(value),gitpath:value=>value==="index"||value==="MERGE_HEAD",path:filesystem,worktree:filesystem,source:value=>remote(value)||localCandidate(value),target:value=>remote(value)||localCandidate(value)},FORMAT=eq("--format=","fmt"),LOG_RECORD="--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI",SHAPES={add:[["-A","--",rep(1,k("path"))]],branch:[["--show-current"],["-D",k("branch")]],"cat-file":[["blob",k("object")],["--batch"],["-e",k("blobref")]],checkout:[[k("rev"),"--",k("path")]],commit:[["-q","--no-verify","-m",k("msg")]],"commit-tree":[[k("rev"),opt("-p",k("rev")),"-F","-"]],"count-objects":[["-v"]],diff:[["--cached","-M","-C","-z","--raw","--no-abbrev"],["--name-only","-z",eq("--diff-filter=","filter"),k("rev"),k("rev"),"--"],["--name-status","-M","-z",k("range"),"--"],["--cached","--quiet",k("rev"),"--"],["--no-renames","--name-only","-z",k("range"),"--",k("path")],["--name-only","-z",k("range"),"--"],["--name-only",eq("--diff-filter=","filter")]],"diff-files":[["--name-only","-z"]],"diff-tree":[["-r","-m","--no-commit-id","--no-renames",eq("--diff-filter=","filter"),"--raw","-z",k("rev")]],"for-each-ref":[[FORMAT,rep(1,k("refpat"))]],"hash-object":[[opt("-w"),"--no-filters","--stdin"],[opt("-w"),eq("--path=","relpath"),"--stdin"]],init:[["--template="]],log:[["-1",FORMAT,k("rev")],[{prefix:"-",kind:"count"},FORMAT,k("rev")],[FORMAT,"--name-only","-z","--no-renames","--diff-merges=first-parent",eq("--diff-filter=","filter"),rep(0,k("revish")),"--"],[LOG_RECORD,opt("--name-only","-z","--no-renames","--full-diff"),opt("--fixed-strings","--all-match",rep(1,eq("--grep=","msg"))),opt("-n",k("count")),opt(eq("--since=","iso")),opt(k("revish")),opt("--",rep(1,k("path")))]],"ls-files":[["--stage","-z","--",k("path")],["--eol","-z"]],"ls-remote":[[k("source"),k("ref")]],"ls-tree":[["-r","--name-only","-z",k("rev"),opt("--",k("path"))],["-r","-l","-z",k("rev")],["-r","-z",k("rev")],["-z",k("rev"),"--",k("path")]],maintenance:[["run","--task=loose-objects","--quiet"]],merge:[[],["--abort"],[opt("--no-ff"),opt("-m",k("msg")),k("rev")],["--no-ff",k("rev"),rep(1,"-m",k("msg"))]],"merge-base":[["--is-ancestor",k("rev"),k("rev")]],"prune-packed":[["--quiet"]],push:[["--quiet",k("target"),k("refspec")]],"read-tree":[["--empty"],[k("rev")]],remote:[["-v"]],reset:[["--soft",k("rev")]],restore:[["--source=HEAD","--staged",opt("--worktree"),"--",rep(1,k("path"))]],"rev-list":[[opt("--count"),k("range")],["--reverse",k("range")]],"rev-parse":[["--verify",opt("--quiet"),k("rev")],["-q","--verify",k("rev")],["--git-path",k("gitpath")],["--git-common-dir"]],rm:[["-q","--cached",opt("-f"),"--ignore-unmatch","--",rep(1,k("path"))],["-rf","-q","--ignore-unmatch","--",k("path")]],show:[["-s",FORMAT,k("rev")],[k("blobref")]],"show-ref":[["--verify",k("ref")]],status:[["--porcelain",opt("--untracked-files=all",opt("--",rep(1,k("path"))))]],"symbolic-ref":[["HEAD",k("ref")]],"update-index":[["--force-remove","--",k("path")],["--add","--cacheinfo",k("mode"),k("oid"),k("path")],["-q","-z","--stdin"]],"update-ref":[["-m",k("msg"),"HEAD",k("rev"),k("rev")]],worktree:[["add","-b",k("branch"),k("worktree"),k("rev")],["remove",opt("--force"),k("worktree")],["list","--porcelain"],["prune"]],"write-tree":[[]]};function match(items,args,at,paths,then){let[item,...rest]=items;if(item===void 0)return then(at);let next=to=>match(rest,args,to,paths,then);if(typeof item=="string")return args[at]===item&&next(at+1);if("optional"in item)return match(item.optional,args,at,paths,next)||next(at);if("repeat"in item){let again=(count,from)=>count>=item.min&&next(from)||match(item.repeat,args,from,paths,to=>to>from&&again(count+1,to));return again(0,at)}let arg=args[at];if(arg===void 0)return!1;let value="prefix"in item?arg.startsWith(item.prefix)?arg.slice(item.prefix.length):void 0:arg;if(value===void 0||!KINDS[item.kind](value))return!1;let kind=item.kind,typed=kind==="path"||kind==="worktree"||(kind==="source"||kind==="target")&&localCandidate(value);return typed&&paths.push({kind,value}),next(at+1)?!0:(typed&&paths.pop(),!1)}function matchShape(sub,args){for(let shape of SHAPES[sub]??[]){let paths=[];if(match(shape,args,0,paths,at=>at===args.length))return paths}}var HAND_GIT_PREFIX=["-c","core.fsmonitor=false","-c","protocol.file.allow=always"],SUBCOMMANDS=new Set(["add","branch","cat-file","checkout","commit","commit-tree","config","count-objects","diff","diff-files","diff-tree","for-each-ref","hash-object","init","log","ls-files","ls-remote","ls-tree","maintenance","merge","merge-base","prune-packed","push","read-tree","remote","reset","restore","rev-list","rev-parse","rm","show","show-ref","status","symbolic-ref","update-index","update-ref","worktree","write-tree"]);function configKey(key){let parts=key.split(".");if(parts.length<2)return key;let section=parts[0]?.toLowerCase()??"",name=parts[parts.length-1]?.toLowerCase()??"";return[section,...parts.slice(1,-1),name].join(".")}var keySet=keys=>new Set(keys.map(configKey)),CALLER_C_KEYS=keySet(["maintenance.auto","gc.auto","user.name","user.email","core.autocrlf","log.showRoot","core.quotePath","log.showSignature","log.follow"]),CONFIG_KEYS=keySet(["omo.agentId","user.name","user.email","commit.gpgsign","gc.auto","core.autocrlf","omo.memoryRepository.url","omo.sync.binding","omo.sync.space"]);function subcommandArgs(sub,rest){if(sub==="config"){let[scope,first,second,extra]=rest;if(scope!=="--local"||first===void 0||extra!==void 0)return"config shape";let key=first==="--get"||first==="--unset-all"?second:first;return key===void 0||first!=="--get"&&first!=="--unset-all"&&(second??"-").startsWith("-")?"config shape":CONFIG_KEYS.has(configKey(key))?[]:`config key ${key}`}return matchShape(sub,rest)??`${sub} shape`}function planGit(argv){let index=0;for(;argv[index]?.startsWith("-");){let arg=argv[index]??"";if(arg==="--literal-pathspecs"){index++;continue}if(arg!=="-c")return arg;let setting=argv[index+1]??"",separator=setting.indexOf("=");if(separator<=0||!CALLER_C_KEYS.has(configKey(setting.slice(0,separator))))return`-c ${setting}`;index+=2}let sub=argv[index];if(sub===void 0||!SUBCOMMANDS.has(sub))return`subcommand ${sub??"(none)"}`;let paths=subcommandArgs(sub,argv.slice(index+1));return typeof paths=="string"?paths:{argv:[...HAND_GIT_PREFIX,...argv],paths}}var equal=(args,expected)=>args.length===expected.length&&args.every((arg,index)=>arg===expected[index]);function planLsof(argv,uid){let holders=argv.length===3&&argv[0]==="-t"&&argv[1]==="--"&&(argv[2]??"").length>0,inUse=equal(argv,["-w","-a","-d","cwd","-u",String(uid),"-Fpn"]);return holders||inUse?[...argv]:"lsof shape"}var CALLER_ENV={GIT_TERMINAL_PROMPT:value=>value==="0",GIT_INDEX_FILE:value=>value.length>0,GIT_GLOB_PATHSPECS:value=>value==="0"||value==="1",GIT_AUTHOR_NAME:()=>!0,GIT_AUTHOR_EMAIL:()=>!0,GIT_COMMITTER_NAME:()=>!0,GIT_COMMITTER_EMAIL:()=>!0},WIN32_BASELINE=["SYSTEMROOT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","PATHEXT"];function baseline(context){let env={},keep=key=>{let value=context.ownEnv[key];value!==void 0&&(env[key]=value)};for(let key of["PATH","HOME","SSH_AUTH_SOCK"])keep(key);if(context.platform==="win32")for(let key of WIN32_BASELINE)keep(key);else keep("TMPDIR"),env.LANG="C";return env.GIT_PROTOCOL_FROM_USER="0",env}function planRun(request,context){let env=baseline(context);for(let[key,value]of Object.entries(request.env)){let allowed2=Object.hasOwn(CALLER_ENV,key)?CALLER_ENV[key]:void 0;if(allowed2===void 0||!allowed2(value))return{ok:!1,reason:`not in the run allowlist: env ${key}`};env[key]=value}let planned=request.exe==="git"?planGit(request.argv):request.exe==="lsof"?planLsof(request.argv,context.uid):`executable ${request.exe}`;return typeof planned=="string"?{ok:!1,reason:`not in the run allowlist: ${planned}`}:Array.isArray(planned)?{ok:!0,exe:"lsof",argv:planned,env,paths:[]}:{ok:!0,exe:"git",argv:planned.argv,env,paths:planned.paths}}var SAFE=/^[A-Za-z0-9@%+=:,./_-]+$/;function renderCommand(exe,argv){return[exe,...argv].map(arg=>SAFE.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" ")}import{execFile as execFile2}from"node:child_process";import{lstat as lstat2,stat}from"node:fs/promises";import{basename as basename3,dirname as dirname3,isAbsolute,join as join3,resolve as resolve2,sep}from"node:path";import{execFile}from"node:child_process";import{lstat,readdir,realpath}from"node:fs/promises";import{basename as basename2,dirname as dirname2,join as join2}from"node:path";var SHAPE="local_repo_shape_unsupported",WALK_BOUND=2e4,refuse=detail=>{throw new DeviceFileError("refused_by_policy",`${SHAPE}: ${detail}`)};async function kindOf(path){let entry=await lstat(path).catch(()=>{});if(entry!==void 0)return entry.isSymbolicLink()?"link":entry.isFile()?"file":entry.isDirectory()?"dir":"other"}async function noLinks(path,recursive,budget){let kind=await kindOf(path);if(kind!==void 0&&(kind==="link"&&refuse(`symlink at ${path}`),kind==="dir"))for(let name of await readdir(path)){budget.left-=1,budget.left<0&&refuse(`more than ${WALK_BOUND} entries under the repository`);let child=join2(path,name),childKind=await kindOf(child);childKind==="link"&&refuse(`symlink at ${child}`),recursive&&childKind==="dir"&&await noLinks(child,!0,budget)}}async function plainGitDir(dir){let[head,objects,refs,commondir,alternates]=await Promise.all(["HEAD","objects","refs","commondir","objects/info/alternates"].map(entry=>kindOf(join2(dir,entry))));(head!=="file"||objects!=="dir"||refs!=="dir")&&refuse(`${dir} is not a plain git directory`),(commondir!==void 0||alternates!==void 0)&&refuse(`${dir} redirects through commondir or alternates`);let budget={left:WALK_BOUND};for(let entry of["HEAD","config","packed-refs"])await noLinks(join2(dir,entry),!1,budget);await noLinks(join2(dir,"refs"),!0,budget),await noLinks(join2(dir,"hooks"),!0,budget),await noLinks(join2(dir,"logs"),!0,budget),await noLinks(join2(dir,"worktrees"),!1,budget),await noLinks(join2(dir,"objects"),!1,budget);for(let sub of["info","pack"])await noLinks(join2(dir,"objects",sub),!1,budget)}function gitConfig(file){let env={PATH:process.env.PATH??"/usr/bin:/bin",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",LANG:"C"};return new Promise((done,fail)=>{execFile("git",["config","--file",file,"--no-includes","--list","-z"],{env,timeout:3e4},(error,stdout)=>{if(error)return fail(error);let records=String(stdout).split("\0").filter(Boolean);done(records.map(record=>{let at=record.indexOf(`
3
3
  `);return at<0?[record,""]:[record.slice(0,at),record.slice(at+1)]}))})})}var INIT_KEYS=new Set(["core.repositoryformatversion","core.filemode","core.bare","core.ignorecase","core.precomposeunicode","core.logallrefupdates"]),CLONE_KEY=/^remote\..+\.(?:url|fetch|mirror|tagopt)$/,WORKING_CLONE_KEY=/^branch\..+\.(?:remote|merge)$|^user\.(?:name|email)$/;async function allowlistedConfig(dir,bare){let config=join2(dir,"config");await kindOf(config)!=="file"&&refuse(`${dir} has no config file`);let entries=await gitConfig(config).catch(()=>refuse("target config is unreadable"));for(let[key,value]of entries){if(key==="core.bare"){value!==String(bare)&&refuse(`core.bare=${value} on a ${bare?"bare":"working-clone"} target`);continue}INIT_KEYS.has(key)||CLONE_KEY.test(key)||!bare&&WORKING_CLONE_KEY.test(key)||refuse(`target config key ${key} is not allowlisted`)}}async function canonicalLocalRepo(path){let parent=await realpath(dirname2(path)).catch(()=>refuse(`no repository at ${path}`)),real=join2(parent,basename2(path)),self=await kindOf(real);self==="link"&&refuse(`${path} is a symlink`),self!=="dir"&&refuse(`no repository at ${path}`),await kindOf(`${real}.git`)!==void 0&&refuse(`${path}.git exists`);let dotGit=await kindOf(join2(real,".git"));dotGit!==void 0&&dotGit!=="dir"&&refuse(`${path}/.git is not a directory`);let gitDir=dotGit==="dir"?join2(real,".git"):real;return await plainGitDir(gitDir),await allowlistedConfig(gitDir,dotGit!=="dir"),gitDir}var MIN_GIT=[2,29];function git(argv,cwd,env){return new Promise((done,fail)=>{execFile2("git",[...argv],{cwd,env,timeout:3e4,windowsHide:!0},(error,stdout)=>error?fail(error):done(String(stdout)))})}var versionChecked;function gitIsSupported(env){return versionChecked??=git(["--version"],process.cwd(),env).then(output=>{let match2=/git version (\d+)\.(\d+)/.exec(output);if(match2===null)return!1;let[major,minor]=[Number(match2[1]),Number(match2[2])];return major>MIN_GIT[0]||major===MIN_GIT[0]&&minor>=MIN_GIT[1]},()=>!1),versionChecked}async function runDirectory(root,cwd){let canonical=await canonicalizeFilesystemPath(resolve2(root,cwd)),entry=await stat(canonical).catch(()=>{});if(entry===void 0)throw new DeviceFileError("not_found",cwd);if(!entry.isDirectory())throw new DeviceFileError("not_a_file",cwd);return canonical}var inside=(path,dir)=>path===dir||path.startsWith(`${dir}${sep}`);async function confinedIndexFile(value,cwd,env){if(!isAbsolute(value))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE must be absolute");let dirs=await gitDirs(cwd,env),parent=await canonicalizeFilesystemPath(dirname3(value));if(!dirs.some(dir=>inside(parent,dir)))throw new DeviceFileError("refused_by_policy","GIT_INDEX_FILE is outside the repository's git directory");return join3(parent,basename3(value))}async function hasUrlRewrites(cwd,env){return(await git(["config","--get-regexp","^url\\."],cwd,env).catch(error=>error.code===1?"":Promise.reject(error))).trim().length>0}async function gitDirs(cwd,env){let[gitDir,commonDir]=(await git(["rev-parse","--absolute-git-dir","--git-common-dir"],cwd,env)).trim().split(`
4
4
  `);if(gitDir===void 0||commonDir===void 0)throw new DeviceFileError("refused_by_policy","no repository at cwd");return Promise.all([gitDir,resolve2(cwd,commonDir)].map(dir=>canonicalizeFilesystemPath(dir)))}async function canonicalTarget(raw,cwd){let target=resolve2(cwd,raw);if((await lstat2(target).catch(()=>{}))?.isSymbolicLink()===!0)throw new DeviceFileError("refused_by_policy",`symlink: ${raw}`);return join3(await canonicalizeFilesystemPath(dirname3(target)),basename3(target))}async function confinePaths(paths,cwd,env){if(paths.length===0)return[];let dirs=await gitDirs(cwd,env),top=await git(["rev-parse","--show-toplevel"],cwd,env).then(output=>canonicalizeFilesystemPath(output.trim()),()=>{}),targets=[];for(let{kind,value}of paths){if(kind==="source"||kind==="target"){let local=localUrlPath(value);if(local===void 0)throw new DeviceFileError("refused_by_policy",`local_repo_shape_unsupported: only an absolute file:// url: ${value}`);let operation=kind==="source"?"read":"write";targets.push({operation,canonicalPath:await canonicalLocalRepo(local)});continue}let canonical=await canonicalTarget(value,cwd),inGitDir=dirs.some(dir=>inside(canonical,dir)||kind==="worktree"&&inside(dir,canonical));if(kind==="worktree"){if(inGitDir)throw new DeviceFileError("refused_by_policy","worktree path is inside the repository's git directory");targets.push({operation:"write",canonicalPath:canonical})}else if(!inGitDir&&(top===void 0||!inside(canonical,top)))throw new DeviceFileError("refused_by_policy",`path outside the repository: ${value}`)}return targets}var HARDENED_RECEIVE_PACK=["git","-c core.hooksPath=/dev/null","-c receive.denyCurrentBranch=refuse","-c core.fsmonitor=false","-c receive.autogc=false","-c gc.auto=0","-c maintenance.auto=false","receive-pack"].join(" "),CLIENT_LOCAL_GUARDS=["-c","core.hooksPath=/dev/null"],REMOTE_GUARDS=["-c","protocol.file.allow=never","-c","protocol.ext.allow=never","-c","protocol.fd.allow=never"];function subcommandAt(argv){let index=0;for(;index<argv.length&&(argv[index]??"").startsWith("-");)index+=argv[index]==="-c"?2:1;return index}function transportFor(argv,env,paths){let at=subcommandAt(argv),sub=argv[at];if(paths.some(path=>path.kind==="source"||path.kind==="target")){let pushed=sub==="push"?[`--receive-pack=${HARDENED_RECEIVE_PACK}`]:[];return{argv:[...argv.slice(0,at),...CLIENT_LOCAL_GUARDS,argv[at]??"",...pushed,...argv.slice(at+1)],env:{...env,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"},local:!0}}return sub==="ls-remote"||sub==="push"?{argv:[...argv.slice(0,at),...REMOTE_GUARDS,...argv.slice(at)],env,local:!1}:{argv:[...argv],env,local:!1}}var RUN_TIMEOUT_CAP_MS=3e5,DEFAULT_TIMEOUT_MS=3e4,KILL_GRACE_MS=1e4;async function judged(guards,command,nested){let input={command},decision;try{decision=await guards.beforeToolCall("bash",`run-${randomUUID()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.command!==command)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the command")}async function runOnHand(args,deps,signal){let plan=planRun({exe:args.exe,argv:args.argv,env:args.env},deps.context);if(!plan.ok)throw new DeviceFileError("refused_by_policy",plan.reason);if(args.stdin!==void 0&&base64Length(args.stdin)>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large","stdin");let cwd=await runDirectory(deps.root,args.cwd),verdict=await deps.guards.filesystemPolicy()?.({operation:"write",canonicalPath:cwd,toolName:"bash"});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);let transport=plan.exe==="git"?transportFor(plan.argv,plan.env,plan.paths):{argv:plan.argv,env:plan.env,local:!1},env={...transport.env};if(plan.exe==="git"){if(!await gitIsSupported(env))throw new DeviceFileError("unsupported","git 2.29 or newer is required");if(transport.local&&await hasUrlRewrites(cwd,env))throw new DeviceFileError("refused_by_policy","local_url_rewritten: a url.* rewrite is configured")}if(await judged(deps.guards,renderCommand(plan.exe,transport.argv),deps.nested),plan.exe==="git"){env.GIT_INDEX_FILE!==void 0&&(env.GIT_INDEX_FILE=await confinedIndexFile(env.GIT_INDEX_FILE,cwd,env));for(let{operation,canonicalPath}of await confinePaths(plan.paths,cwd,env)){let decision=await deps.guards.filesystemPolicy()?.({operation,canonicalPath,toolName:"bash"});if(decision!==void 0&&!decision.allow)throw new DeviceFileError("refused_by_policy",decision.reason)}}let hold=args.activityLock===!0&&plan.exe==="git"?await holdActivityLock(cwd,deps.flock):void 0;try{return await spawnBounded(plan.exe,transport.argv,cwd,env,args,hold?.fd,signal)}finally{await hold?.release()}}function spawnBounded(exe,argv,cwd,env,args,lockFd,signal){return new Promise((done,fail)=>{let child=spawn(exe,[...argv],{cwd,env,shell:!1,windowsHide:!0,stdio:["pipe","pipe","pipe",lockFd??"ignore"]}),out=[],err=[],size={out:0,err:0},overflow=!1,killTimer,stop=()=>{child.exitCode===null&&child.signalCode===null&&child.kill("SIGTERM"),killTimer??=setTimeout(()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stderr?.destroy()},KILL_GRACE_MS)},timeout=setTimeout(stop,Math.min(args.timeoutMs??DEFAULT_TIMEOUT_MS,RUN_TIMEOUT_CAP_MS)),onAbort=()=>stop();signal.addEventListener("abort",onAbort,{once:!0});let collect=(into,key)=>chunk=>{if(size={...size,[key]:size[key]+chunk.length},size[key]>FILE_CHANNEL_MAX_BYTES){overflow=!0,stop();return}into.push(chunk)};child.stdout?.on("data",collect(out,"out")),child.stderr?.on("data",collect(err,"err")),child.on("error",error=>fail(new DeviceFileError("io",error.message))),child.on("close",(code,exitSignal)=>{if(clearTimeout(timeout),killTimer!==void 0&&clearTimeout(killTimer),signal.removeEventListener("abort",onAbort),signal.aborted)return fail(new DeviceFileError("aborted","the run was aborted"));if(overflow)return fail(new DeviceFileError("too_large","the run's output passed the limit"));done({code,signal:exitSignal,stdout:encodeBase64(new Uint8Array(Buffer.concat(out))),stderr:Buffer.concat(err).toString("utf8")})}),child.stdin?.on("error",()=>{}),child.stdin?.end(args.stdin===void 0?void 0:Buffer.from(decodeBase64(args.stdin)))})}function checksOf(args){switch(args.op){case"read":return[{toolName:"read",operation:"read",path:args.path}];case"list":return[{toolName:"ls",operation:"enumerate",path:args.path}];case"stat":return[{toolName:"ls",operation:"enumerate",path:args.path,entry:!0}];case"write":return[{toolName:"write",operation:"write",path:args.path,content:new TextDecoder().decode(decodeBase64(args.data))}];case"rename":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0},{toolName:"write",operation:"write",path:args.to,content:"",entry:!0}];case"remove":return[{toolName:"write",operation:"write",path:args.path,content:"",entry:!0}];case"mkdir":return[{toolName:"write",operation:"write",path:args.path,content:""}]}}async function canonicalOf(path,entry){return entry?join4(await canonicalizeFilesystemPath(dirname4(path)),basename4(path)):canonicalizeFilesystemPath(path)}async function allowed(guards,root,check,nested){let content=check.content??"",input=check.toolName==="write"?{path:check.path,content}:{path:check.path},decision;try{decision=await guards.beforeToolCall(check.toolName,`file-${randomUUID2()}`,input,nested)}catch(error){throw new DeviceFileError("refused_by_policy",error instanceof Error?error.message:String(error))}if(decision?.block===!0)throw new DeviceFileError("refused_by_policy",decision.reason??"blocked");if(input.path!==check.path||check.toolName==="write"&&input.content!==content)throw new DeviceFileError("refused_by_policy","a tool_call handler rewrote the operation");let canonicalPath=await canonicalOf(resolve3(root,check.path),check.entry===!0),verdict=await guards.filesystemPolicy()?.({operation:check.operation,canonicalPath,toolName:check.toolName});if(verdict!==void 0&&!verdict.allow)throw new DeviceFileError("refused_by_policy",verdict.reason);return canonicalPath}function createHandFileOps(root,guards,run){let files=localDeviceFiles();return async(op,rawArgs,signal,nested)=>{let args=decodeDeviceFileArgs(op,rawArgs);if(args===void 0)return fileRefusal("protocol",`malformed ${op} arguments`);if(args.op==="run"){if(run===void 0)return fileRefusal("unsupported","this hand serves no run channel");try{let{exe,argv,env,stdin,timeoutMs,activityLock}=args,request={exe,argv,cwd:args.path,env,activityLock,...stdin===void 0?{}:{stdin},...timeoutMs===void 0?{}:{timeoutMs}},outcome=await runOnHand(request,{root,guards,context:run.context,flock:run.flock,...nested?{nested}:{}},signal);return fileResult({ok:!0,value:{...outcome}})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}if(args.op==="write"&&base64Length(args.data)>FILE_CHANNEL_MAX_BYTES)return fileRefusal("too_large",args.path);try{let[target,destination]=await Promise.all(checksOf(args).map(check=>allowed(guards,root,check,nested)));if(target===void 0)return fileRefusal("protocol","no target");let options={signal};switch(args.op){case"read":return fileResult({ok:!0,value:encodeBase64(await files.read(target,options))});case"list":return fileResult({ok:!0,value:[...await files.list(target,options)]});case"stat":return fileResult({ok:!0,value:{...await files.stat(target,options)}});case"write":{let data=decodeBase64(args.data);await withFileMutationQueue(target,()=>files.write(target,data,{...options,exclusive:args.exclusive}));break}case"rename":await withFileMutationQueues([target,destination??target],()=>files.rename(target,destination??target,options));break;case"remove":await withFileMutationQueue(target,()=>files.remove(target,options));break;case"mkdir":await files.mkdir(target,options);break}return fileResult({ok:!0,value:null})}catch(error){return error instanceof DeviceFileError?fileRefusal(error.code,error.message):fileRefusal("io",error instanceof Error?error.message:String(error))}}}var bound;function loadFlock(){return bound===void 0&&(bound=bindFlock()??null),bound??void 0}function bindFlock(){if(process.platform!=="darwin"&&process.platform!=="linux")return;let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return;let errnoSymbol=process.platform==="darwin"?"__error":"__errno_location";try{let library=ffi.dlopen(process.platform==="darwin"?"libSystem.B.dylib":"libc.so.6",{flock:{args:[ffi.FFIType.i32,ffi.FFIType.i32],returns:ffi.FFIType.i32},[errnoSymbol]:{args:[],returns:ffi.FFIType.ptr}}),errnoPointer=library.symbols[errnoSymbol];return(fd,operation)=>{let rc=Number(library.symbols.flock(fd,operation));if(rc===0||errnoPointer===void 0)return{rc,errno:0};let pointer=errnoPointer();return{rc,errno:typeof pointer=="number"&&pointer!==0?ffi.read.i32(pointer,0):-1}}}catch{return}}var LOOPLESS_EXECUTE_CALLERS=["in-process-test-harness","remote-tool-executor"],issued=new WeakSet,LooplessExecuteRefusedError=class extends Error{constructor(reason){super(`loopless_execute_refused: ${reason}`)}};function grantLooplessExecuteToRemoteExecutor(){let grant=Object.freeze({caller:"remote-tool-executor"});return issued.add(grant),grant}function looplessGrantRunsToolHandlers(grant){return isLooplessExecuteGranted(grant)&&grant?.caller==="remote-tool-executor"}function isLooplessExecuteGranted(grant){return grant!==void 0&&issued.has(grant)&&LOOPLESS_EXECUTE_CALLERS.includes(grant.caller)}import{randomUUID as randomUUID3}from"node:crypto";async function resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics){let{parsed,agentDir,appMode}=configuration,{cwd,launchProfile}=profile,trustStore=new ProjectTrustStore(agentDir),flagValues=sessionExtensionFlagValues(parsed.unknownFlags,launchProfile),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd),savedProjectTrust=await getSavedProjectTrust(trustStore,cwd),globalPreset=startupSettingsManager.getGlobalSettings().permissionPreset,fullAccessTrust=presetTrustsProject(flagValues.get("permission-preset"),globalPreset)&&savedProjectTrust!==!1,shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&!fullAccessTrust&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:parsed.projectTrustOverride??(fullAccessTrust||!hasTrustRequiringResources||savedProjectTrust===!0),trustFromFullAccess=fullAccessTrust&&hasTrustRequiringResources&&parsed.projectTrustOverride===void 0&&savedProjectTrust!==!0;return{settingsManager:SettingsManager.create(cwd,agentDir,{projectTrusted,trustFromFullAccess,projectTrustLocked:parsed.projectTrustOverride!==void 0}),flagValues,reloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:({extensionsResult})=>resolveProjectTrusted({cwd,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd,mode:appMode,settingsManager:startupSettingsManager,hasUI:!1}),onExtensionError:message=>diagnostics.push({type:"warning",message})})}:void 0}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}function looplessToolFilters(parsed,settingsManager){let noTools=parsed.noTools?"all":parsed.noBuiltinTools?"builtin":void 0,defaultToolNames=parsed.tools===void 0&&noTools===void 0?settingsManager.getDefaultTools():void 0,allowedToolNames=parsed.tools??(noTools==="all"?[]:void 0);return{...defaultToolNames===void 0?{}:{defaultToolNames:new Set(defaultToolNames)},...allowedToolNames===void 0?{}:{allowedToolNames:new Set(allowedToolNames)},...parsed.excludeTools===void 0?{}:{excludedToolNames:new Set(parsed.excludeTools)}}}function errorResult(message){return{content:[{type:"text",text:message}],details:void 0,isError:!0}}function withOverride(result,override){let structuredContent=override.structuredContent??(override.content?void 0:result.structuredContent),next={...result,content:override.content??result.content,details:override.details??result.details,usage:override.usage??result.usage,isError:override.isError??result.isError===!0};return structuredContent===void 0?delete next.structuredContent:next.structuredContent=structuredContent,next}async function runLooplessToolCall(tool,call,handlers){let{toolCallId,signal}=call,nested=call.nested===void 0?{}:{nested:call.nested},args;try{let prepared=tool.prepareArguments?tool.prepareArguments(call.params):call.params,toolCall={type:"toolCall",id:toolCallId,name:tool.name,arguments:prepared};args=validateToolArguments(tool,toolCall)}catch(error){return errorResult(error instanceof Error?error.message:String(error))}if(handlers){let before;try{before=await handlers.beforeToolCall({toolName:tool.name,toolCallId,input:args,...nested})}catch(error){return errorResult(error instanceof Error?error.message:`Extension failed, blocking execution: ${String(error)}`)}if(signal?.aborted)return errorResult("Operation aborted");if(before?.block){let blocked=errorResult(before.reason||"Tool execution was blocked");return before.terminate===!0&&(blocked.terminate=!0),blocked}}let result;try{result=await tool.execute(toolCallId,args,signal,void 0)}catch(error){result=errorResult(error instanceof Error?error.message:String(error))}if(!handlers)return result;try{let override=await handlers.afterToolCall({toolName:tool.name,toolCallId,input:args,result,isError:result.isError===!0,...nested});return override?withOverride(result,override):result}catch(error){return errorResult(error instanceof Error?error.message:String(error))}}import{AsyncLocalStorage}from"node:async_hooks";function extensionToolHandlers(runner,twoSidedHome="loop"){let twoSided=twoSidedHome==="loop"?runner.twoSidedExtensionPaths():new Set,options=nested=>nested===void 0||twoSided.size===0?{}:{forward:forwardToolEvents(twoSided,nested)};return{beforeToolCall:({toolName,toolCallId,input,nested})=>runner.hasHandlers("tool_call")?runner.emitToolCall({type:"tool_call",toolName,toolCallId,input},options(nested)):Promise.resolve(void 0),afterToolCall:({toolName,toolCallId,input,result,isError,nested})=>runner.hasHandlers("tool_result")?runner.emitToolResult({type:"tool_result",toolName,toolCallId,input,content:result.content,details:result.details,...result.structuredContent===void 0?{}:{structuredContent:result.structuredContent},isError,usage:result.usage},options(nested)):Promise.resolve(void 0)}}var isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function extensionLoopHooks(runner,twoSidedHome,cwd,call){return async(event,payload)=>{if(twoSidedHome!=="hand")throw new Error("this hand is not the home of its extensions' loop hooks");if(!isRecord(payload)||typeof payload.sessionId!="string"||typeof payload.idle!="boolean")throw new Error(`malformed ${event} payload`);let{sessionId,idle}=payload,images=imagesOf(payload.images);if(images===null)throw new Error(`malformed ${event} payload: images`);if(event==="input"){let{inputId,text,source,attribution,streamingBehavior}=payload;if(typeof inputId!="string"||typeof text!="string"||!isOneOf(source,INPUT_SOURCES)||!isOneOf(attribution,INPUT_ATTRIBUTIONS)||!(streamingBehavior===void 0||isOneOf(streamingBehavior,STREAMING_BEHAVIORS)))throw new Error("malformed input payload");return call.run(sessionId,cwd,idle,effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitInput(text,images,source,streamingBehavior,inputId,attribution,isUserLoopHook)))}if(event==="before_agent_start"){let{prompt,systemPrompt,trigger,preview,systemPromptOptions}=payload;if(typeof prompt!="string"||typeof systemPrompt!="string"||!isOneOf(trigger,TRIGGERS)||!(preview===void 0||typeof preview=="boolean")||!isRecord(systemPromptOptions))throw new Error("malformed before_agent_start payload");let options={...systemPromptOptions,cwd};return call.run(sessionId,cwd,idle,effects=>dispatchLoopHook(runner,call,effects,()=>runner.emitBeforeAgentStart(prompt,images,systemPrompt,options,{only:isUserLoopHook,trigger,...preview===void 0?{}:{preview}})))}throw new Error(`no loop hooks run on a hand for ${event}`)}}var isUserLoopHook=extensionPath=>!extensionPath.startsWith("<builtin:")||extensionPath==="<builtin:hooks>",INPUT_SOURCES=["interactive","rpc","extension"],INPUT_ATTRIBUTIONS=["user","agent"],STREAMING_BEHAVIORS=["steer","followUp"],TRIGGERS=["prompt","delivery","extension"],isOneOf=(value,allowed2)=>typeof value=="string"&&allowed2.includes(value),imagesOf=value=>value===void 0?void 0:Array.isArray(value)&&value.every(isImage)?value:null,isImage=value=>isRecord(value)&&value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string";async function dispatchLoopHook(runner,call,effects,dispatch){let own=call.current(),errors=[],stop=runner.onError(({extensionPath,event,error})=>{own!==void 0&&call.current()===own&&errors.push({extensionPath,event,error})});try{let result=await dispatch(),{sent,notices}=effects;return JSON.parse(JSON.stringify({...result,...sent.length>0?{sent}:{},...notices.length>0?{notices}:{},...effects.dropped>0?{droppedLate:effects.dropped}:{},...errors.length>0?{errors}:{}}))}finally{stop()}}var LATE_PER_SESSION=256;function createLoopHookCall(){let calls=new AsyncLocalStorage,late=new Map,holdLate=(sessionId,add)=>{let held=late.get(sessionId)??{sent:[],notices:[],dropped:0};for(add(held);held.sent.length+held.notices.length>LATE_PER_SESSION;)(held.notices.length>0?held.notices:held.sent).shift(),held.dropped++;late.set(sessionId,held)};return{current:()=>{let call=calls.getStore();return call?.live()===!0?call.facts:void 0},sender:()=>calls.getStore()?.facts.sendMessage,async run(sessionId,cwd,idle,dispatch){let live=!0,controller=new AbortController,effects=late.get(sessionId)??{sent:[],notices:[],dropped:0};late.delete(sessionId);let facts=Object.freeze({sessionManager:readOnlySession(sessionId,cwd,()=>live),signal:controller.signal,isIdle:()=>idle,sendMessage:(message,options)=>{let entry=options===void 0?{message}:{message,options};live?effects.sent.push(entry):holdLate(sessionId,held=>held.sent.push(entry))},notify:(message,type)=>{let entry=type===void 0?{message}:{message,type};live?effects.notices.push(entry):holdLate(sessionId,held=>held.notices.push(entry))}});try{return await calls.run({live:()=>live,facts},()=>dispatch(effects))}finally{live=!1,controller.abort()}}}}var LoopHookCallEndedError=class extends Error{constructor(member){super(`this loop-hook call has ended; ${member} is bound to that call only`),this.name="LoopHookCallEndedError",this.member=member}};function readOnlySession(sessionId,cwd,live){let bound2=(member,read)=>()=>{if(!live())throw new LoopHookCallEndedError(`sessionManager.${member}`);return read()},unbound=member=>()=>{throw new Error(`sessionManager.${member} is loop-side: a loop-hook call on a hand carries only the session's id`)};return Object.freeze({getSessionId:bound2("getSessionId",()=>sessionId),getSessionFile:bound2("getSessionFile",()=>{}),getCwd:bound2("getCwd",()=>cwd),getSessionDir:unbound("getSessionDir"),getLeafId:unbound("getLeafId"),getLeafEntry:unbound("getLeafEntry"),getEntry:unbound("getEntry"),getLabel:unbound("getLabel"),getBranch:unbound("getBranch"),getFullBranch:unbound("getFullBranch"),buildContextEntries:unbound("buildContextEntries"),buildSessionContext:unbound("buildSessionContext"),buildSessionProjection:unbound("buildSessionProjection"),getHeader:unbound("getHeader"),getEntries:unbound("getEntries"),reduceHistory:unbound("reduceHistory"),getTree:unbound("getTree"),getSessionName:unbound("getSessionName")})}var LooplessToolNotFoundError=class extends Error{constructor(toolName){super(`loopless_tool_not_found: ${toolName}`),this.toolName=toolName}};function createLooplessRuntimeFactory(configuration,local={}){let{parsed,agentDir,toolRuntime}=configuration,extensionFactories=local.extensionFactories??builtInExtensions,startupSettingsManager=local.startupSettingsManager??SettingsManager.create(configuration.cwd,configuration.agentDir);return async profile=>{let{cwd}=profile,diagnostics=[],{settingsManager,flagValues,reloadOptions}=await resolveLooplessSettings(configuration,startupSettingsManager,profile,diagnostics),services=await createAgentSessionServices({cwd,agentDir,settingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:flagValues,...reloadOptions?{resourceLoaderReloadOptions:reloadOptions}:{},resourceLoaderOptions:{sessionKind:profile.launchProfile?.sessionKind,sessionContext:profile.launchProfile?.sessionContext,additionalExtensionPaths:resolveCliPaths(cwd,parsed.extensions),additionalSkillPaths:resolveCliPaths(cwd,parsed.skills),additionalPromptTemplatePaths:resolveCliPaths(cwd,parsed.promptTemplates),additionalThemePaths:resolveCliPaths(cwd,parsed.themes),noExtensions:parsed.noExtensions,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,extensionFactories}}),extensionsResult=services.resourceLoader.getExtensions();diagnostics.push(...services.diagnostics,...extensionsResult.errors.map(({path,error})=>({type:"warning",message:`Failed to load extension "${path}": ${error}`})),...(extensionsResult.warnings??[]).map(({path,warning})=>({type:"warning",message:`Extension package "${path}": ${warning}`})));let execute=()=>Promise.reject(new Error("Loopless runtime is not ready")),toolNames=()=>[],toolChildRuntime=createToolChildRuntime({toolRuntime:toolRuntime??"in-process",agentDir,scopeId:`loopless-${randomUUID3()}`,cwd:services.cwd,moduleRoots:()=>[...toolChildModuleRoots(runtime.extensionRunner.getAllRegisteredTools()),...childModuleRoots(runtime.extensionRunner.getAllChildModules())],hostCallDeps:{cwd:services.cwd,executeNested:async(_parentToolCallId,name,args,signal)=>{let toolCall={type:"toolCall",id:`nested-${randomUUID3()}`,name,arguments:{}},result=await execute(name,toolCall.id,args,signal);return{toolCall,result,isError:result.isError===!0}},callableToolNames:()=>toolNames(),target:()=>{},filesystemPolicy:()=>runtime.filesystemPolicy},onRecord:()=>{}}),{dispatcher,toolChild}=toolChildRuntime,runtime=bootstrapRuntime({cwd:services.cwd,settingsManager:services.settingsManager,extensionsResult,modelRegistry:services.modelRegistry,toolDispatcher:dispatcher}),registry=buildToolRegistry({baseToolDefinitions:runtime.baseToolDefinitions,runner:runtime.extensionRunner,dispatcher,...looplessToolFilters(parsed,services.settingsManager)});toolNames=()=>[...registry.toolRegistry.keys()];let getLoadedHookSources=services.resourceLoader.getLoadedHookSources?.bind(services.resourceLoader),loopHookCall=createLoopHookCall();runtime.extensionRunner.bindSessionlessFacts({getAllTools:()=>Array.from(registry.definitions.values(),toolInfoOf),loopHookCall:()=>loopHookCall.current(),loopHookSend:()=>loopHookCall.sender(),...getLoadedHookSources?{getLoadedHookSources}:{}});let presentation=new PresentationBroker(error=>runtime.extensionRunner.emitError({extensionPath:"<presentation-port>",event:"ui_presentation",error:`A presentation could not reach the attached client: ${error instanceof Error?error.message:String(error)}`}));runtime.extensionRunner.setUiBroker(presentation);let toolHandlers=looplessGrantRunsToolHandlers(local.executeGrant)?extensionToolHandlers(runtime.extensionRunner,local.twoSidedHome):void 0;execute=(name,toolCallId,params,signal,nested)=>{if(!isLooplessExecuteGranted(local.executeGrant))return Promise.reject(new LooplessExecuteRefusedError("no executor runs the tool_call/tool_result handlers for this runtime yet"));let tool=registry.toolRegistry.get(name);return tool===void 0?Promise.reject(new LooplessToolNotFoundError(name)):presentation.present(nested,()=>runLooplessToolCall(tool,{toolCallId,params,...signal?{signal}:{},...nested?{nested}:{}},toolHandlers))};let fileGuards=toolHandlers!==void 0&&isLooplessExecuteGranted(local.executeGrant)?{beforeToolCall:(toolName,toolCallId,input,nested)=>presentation.present(nested,()=>toolHandlers.beforeToolCall({toolName,toolCallId,input,...nested?{nested}:{}})),filesystemPolicy:()=>runtime.filesystemPolicy}:void 0;return{cwd:services.cwd,definitions:registry.definitions,diagnostics,fileGuards,execute:(name,toolCallId,params,signal,nested)=>execute(name,toolCallId,params,signal,nested),runLoopHooks:extensionLoopHooks(runtime.extensionRunner,local.twoSidedHome??"loop",services.cwd,loopHookCall),dispose:async()=>{runtime.extensionRunner.invalidate("This loopless runtime was disposed.");let failure=(await Promise.allSettled([dispatcher.dispose(),toolChild?.close()])).find(outcome=>outcome.status==="rejected");if(failure!==void 0)throw failure.reason}}}}var handRun={context:{uid:process.getuid?.()??-1,platform:process.platform,ownEnv:process.env},flock:loadFlock()};function notFound(name){return{content:[{type:"text",text:`Tool ${name} not found`}],details:{},isError:!0}}var isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function scopeOf(payload){let scope=isRecord2(payload)?payload.scope:void 0;if(!isRecord2(scope)||typeof scope.id!="string"||typeof scope.root!="string")throw new Error("a loop-hook call names no scope");return{id:scope.id,root:scope.root}}function createLooplessHand(configuration,local={}){let factory=createLooplessRuntimeFactory(configuration,{...local,executeGrant:grantLooplessExecuteToRemoteExecutor()}),runtimes=new Map,disposed=new Set,closed=!1,disposals=new WeakMap,disposeOnce=runtime=>{let known=disposals.get(runtime);if(known!==void 0)return known;let disposing=runtime.dispose();return disposals.set(runtime,disposing),disposing},runtimeOf=(scope,reopen)=>{if(closed)return Promise.reject(new Error("this hand is closed"));if(!isAbsolute2(scope.root))return Promise.reject(new Error(`scope root must be an absolute path: ${JSON.stringify(scope.root)}`));let known=runtimes.get(scope.id);if(known!==void 0)return known.root===scope.root?known.runtime:Promise.reject(new Error(`scope_binding_mismatch: scope ${JSON.stringify(scope.id)} is bound to another root`));if(!reopen&&disposed.has(scope.id))return Promise.reject(new Error(`scope ${JSON.stringify(scope.id)} was disposed; its extensions' loop-hook state is gone`));disposed.delete(scope.id);let opened=factory({cwd:scope.root});return runtimes.set(scope.id,{root:scope.root,runtime:opened}),opened.catch(()=>runtimes.delete(scope.id)),opened};return{async openScope(scope){let runtime=await runtimeOf(scope,!0);return{run:call=>runtime.definitions.has(call.name)?runtime.execute(call.name,call.toolCallId,call.arguments,call.signal,call.nested):Promise.resolve(notFound(call.name)),isSequential:name=>runtime.definitions.get(name)?.definition.executionMode==="sequential",...runtime.fileGuards===void 0?{}:{file:createHandFileOps(scope.root,runtime.fileGuards,handRun)},dispose:()=>(runtimes.delete(scope.id),disposed.add(scope.id),disposeOnce(runtime))}},runLoopHooks:async(scope,event,payload)=>(await runtimeOf(scope,!1)).runLoopHooks(event,payload),loopHooks:async(event,payload)=>(await runtimeOf(scopeOf(payload),!1)).runLoopHooks(event,payload),async close(){closed=!0;let open2=[...runtimes.values()];runtimes.clear();let failures=(await Promise.allSettled(open2.map(({runtime})=>runtime.then(opened=>disposeOnce(opened),()=>{})))).flatMap(outcome=>outcome.status==="rejected"?[outcome.reason]:[]);if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,"disposing this hand's runtimes failed")}}}var isRecord3=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function encodeCarrierLine(message){if(!isRecord3(message)||typeof message.lane!="string"||typeof message.seq!="number")return;if(message.kind==="ack")return`${JSON.stringify({kind:"ack",lane:message.lane,seq:message.seq})}
5
5
  `;if(message.kind!=="data"||!(message.payload instanceof Uint8Array))return;let payload=Buffer.from(message.payload).toString("base64");return`${JSON.stringify({kind:"data",lane:message.lane,seq:message.seq,payload})}
@@ -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{createReliableTransport,createRemoteToolHost}from"./chunk-GKAYPJ4E.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{posix,win32}from"node:path";var HAND_SELECTION_ENTRY="hand_selection";function unreachableHost(){let transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:()=>()=>{}},onHandlerError:()=>{}});return transport.close(),createRemoteToolHost({transport,placement:"cross-machine"})}function recordedDevice(session){let device=null;for(let entry of session.sessionManager.getEntries()){if(entry.type!=="custom"||entry.customType!==HAND_SELECTION_ENTRY)continue;let recorded=Reflect.get(Object(entry.data),"device");device=typeof recorded=="string"?recorded:null}return device}function createHandSelection(directory,options={}){let sessions=new Map,gate=options.gate??((_id,host)=>host),stateOf=(durableSessionId,session)=>{let known=sessions.get(durableSessionId);if(known!==void 0)return known;let fresh={own:session.agent.toolHost,device:null,remote:void 0,linked:!1};return sessions.set(durableSessionId,fresh),fresh},install=(durableSessionId,session,device,remote)=>{let state=stateOf(durableSessionId,session);state.remote?.close(),sessions.set(durableSessionId,{own:state.own,device,remote:remote?.host,linked:remote?.linked??!1}),session.agent.toolHost=remote===void 0?state.own:gate(durableSessionId,remote.host),options.onChange?.(durableSessionId,device)},unreachable=()=>({host:unreachableHost(),linked:!1}),linkTo=device=>{try{return{host:createRemoteToolHost(directory.link(device)),linked:!0}}catch{return unreachable()}};return{hands:()=>directory.list(),selected:durableSessionId=>sessions.get(durableSessionId)?.device??null,select:(durableSessionId,session,device)=>{let current=stateOf(durableSessionId,session);if(current.device===device&&(device===null||current.linked))return{ok:!0};if(session.isStreaming)return{ok:!1,refusal:"session_busy"};let remote;if(device!==null){let row=directory.list().find(hand=>hand.device===device);if(row===void 0)return{ok:!1,refusal:"hand_not_listed"};if(!row.reachable)return{ok:!1,refusal:"hand_unreachable"};if(remote=linkTo(device),!remote.linked)return remote.host.close(),{ok:!1,refusal:"hand_unreachable"}}try{current.device!==device&&session.sessionManager.appendCustomEntry(HAND_SELECTION_ENTRY,{device})}catch(cause){throw remote?.host.close(),cause}return install(durableSessionId,session,device,remote),{ok:!0}},restore:(durableSessionId,session)=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),stateOf(durableSessionId,session);let device=recordedDevice(session);if(device===null)return;let row=directory.list().find(hand=>hand.device===device);install(durableSessionId,session,device,row?.reachable===!0?linkTo(device):unreachable())},release:durableSessionId=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),options.onRelease?.(durableSessionId)}}}function gatePresence(agent,presence,sessionId){let prepareRequest=agent.prepareRequest;agent.prepareRequest=async(request,signal)=>(await presence.ready(sessionId,"request",signal),await prepareRequest?.(request,signal)??void 0);let host=agent.toolHost;if(host===void 0)return;let deviceFiles=host.deviceFiles?.bind(host);agent.toolHost={execute:async(call,options)=>(await presence.ready(sessionId,"tools",options.signal),host.execute(call,options)),...deviceFiles===void 0?{}:{deviceFiles}}}var HEADLESS_SOCKET_FILE="headless.sock";function headlessSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix).join(agentDir,"rpc",HEADLESS_SOCKET_FILE)}function headlessEndpoint(agentDir,platform=process.platform,secret){return resolveSocketTransportAddress(headlessSocketPath(agentDir,platform),platform,secret)}function headlessHostOptions(options){let{presence,hands,...host}=options,runtimes=new Map,handSelection=hands===void 0?void 0:createHandSelection(hands,presence===void 0?{}:presenceHooks(presence,runtimes)),gated=presence===void 0?host.createRuntime:presenceRuntime(host.createRuntime,presence);return{...host,sessionOwner:"machine",listen:options.listen??`unix://${headlessSocketPath(options.agentDir)}`,createRuntime:handSelection===void 0?gated:handRuntime(gated,handSelection,runtimes),...presence===void 0?{}:{sessionPresence:presence.presence},...handSelection===void 0?{}:{handSelection}}}function presenceHooks(binding,runtimes){let tracking=new Map;return{gate:(sessionId,host)=>({execute:async(call,options)=>(await tracking.get(sessionId),await binding.presence.ready(sessionId,"tools",options.signal),host.execute(call,options))}),onChange:(sessionId,device)=>{let runtime=runtimes.get(sessionId),sessionHands=device!==null?[device]:runtime===void 0?[]:binding.handsOf(runtime),update=binding.presence.track(sessionId,sessionHands);update.catch(()=>{}),tracking.set(sessionId,update)},onRelease:sessionId=>{tracking.delete(sessionId)}}}function handRuntime(createRuntime,selection,runtimes){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime,sessionId=session.sessionId;runtimes.set(sessionId,runtime),selection.restore(sessionId,session);let dispose=session.dispose.bind(session);return session.dispose=()=>{runtimes.get(sessionId)===runtime&&(runtimes.delete(sessionId),selection.release(sessionId)),dispose()},runtime},createRuntime)}function presenceRuntime(createRuntime,binding){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime;return await binding.presence.track(session.sessionId,binding.handsOf(runtime)),gatePresence(session.agent,binding.presence,session.sessionId),runtime},createRuntime)}export{headlessEndpoint,headlessHostOptions,headlessSocketPath};
2
+ import{createReliableTransport,createRemoteToolHost}from"./chunk-7PROV6BB.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{posix,win32}from"node:path";var HAND_SELECTION_ENTRY="hand_selection";function unreachableHost(){let transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:()=>()=>{}},onHandlerError:()=>{}});return transport.close(),createRemoteToolHost({transport,placement:"cross-machine"})}function recordedDevice(session){let device=null;for(let entry of session.sessionManager.getEntries()){if(entry.type!=="custom"||entry.customType!==HAND_SELECTION_ENTRY)continue;let recorded=Reflect.get(Object(entry.data),"device");device=typeof recorded=="string"?recorded:null}return device}function createHandSelection(directory,options={}){let sessions=new Map,gate=options.gate??((_id,host)=>host),stateOf=(durableSessionId,session)=>{let known=sessions.get(durableSessionId);if(known!==void 0)return known;let fresh={own:session.agent.toolHost,device:null,remote:void 0,linked:!1};return sessions.set(durableSessionId,fresh),fresh},install=(durableSessionId,session,device,remote)=>{let state=stateOf(durableSessionId,session);state.remote?.close(),sessions.set(durableSessionId,{own:state.own,device,remote:remote?.host,linked:remote?.linked??!1}),session.agent.toolHost=remote===void 0?state.own:gate(durableSessionId,remote.host),options.onChange?.(durableSessionId,device)},unreachable=()=>({host:unreachableHost(),linked:!1}),linkTo=device=>{try{return{host:createRemoteToolHost(directory.link(device)),linked:!0}}catch{return unreachable()}};return{hands:()=>directory.list(),selected:durableSessionId=>sessions.get(durableSessionId)?.device??null,select:(durableSessionId,session,device)=>{let current=stateOf(durableSessionId,session);if(current.device===device&&(device===null||current.linked))return{ok:!0};if(session.isStreaming)return{ok:!1,refusal:"session_busy"};let remote;if(device!==null){let row=directory.list().find(hand=>hand.device===device);if(row===void 0)return{ok:!1,refusal:"hand_not_listed"};if(!row.reachable)return{ok:!1,refusal:"hand_unreachable"};if(remote=linkTo(device),!remote.linked)return remote.host.close(),{ok:!1,refusal:"hand_unreachable"}}try{current.device!==device&&session.sessionManager.appendCustomEntry(HAND_SELECTION_ENTRY,{device})}catch(cause){throw remote?.host.close(),cause}return install(durableSessionId,session,device,remote),{ok:!0}},restore:(durableSessionId,session)=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),stateOf(durableSessionId,session);let device=recordedDevice(session);if(device===null)return;let row=directory.list().find(hand=>hand.device===device);install(durableSessionId,session,device,row?.reachable===!0?linkTo(device):unreachable())},release:durableSessionId=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),options.onRelease?.(durableSessionId)}}}function gatePresence(agent,presence,sessionId){let prepareRequest=agent.prepareRequest;agent.prepareRequest=async(request,signal)=>(await presence.ready(sessionId,"request",signal),await prepareRequest?.(request,signal)??void 0);let host=agent.toolHost;if(host===void 0)return;let deviceFiles=host.deviceFiles?.bind(host);agent.toolHost={execute:async(call,options)=>(await presence.ready(sessionId,"tools",options.signal),host.execute(call,options)),...deviceFiles===void 0?{}:{deviceFiles}}}var HEADLESS_SOCKET_FILE="headless.sock";function headlessSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix).join(agentDir,"rpc",HEADLESS_SOCKET_FILE)}function headlessEndpoint(agentDir,platform=process.platform,secret){return resolveSocketTransportAddress(headlessSocketPath(agentDir,platform),platform,secret)}function headlessHostOptions(options){let{presence,hands,...host}=options,runtimes=new Map,handSelection=hands===void 0?void 0:createHandSelection(hands,presence===void 0?{}:presenceHooks(presence,runtimes)),gated=presence===void 0?host.createRuntime:presenceRuntime(host.createRuntime,presence);return{...host,sessionOwner:"machine",listen:options.listen??`unix://${headlessSocketPath(options.agentDir)}`,createRuntime:handSelection===void 0?gated:handRuntime(gated,handSelection,runtimes),...presence===void 0?{}:{sessionPresence:presence.presence},...handSelection===void 0?{}:{handSelection}}}function presenceHooks(binding,runtimes){let tracking=new Map;return{gate:(sessionId,host)=>({execute:async(call,options)=>(await tracking.get(sessionId),await binding.presence.ready(sessionId,"tools",options.signal),host.execute(call,options))}),onChange:(sessionId,device)=>{let runtime=runtimes.get(sessionId),sessionHands=device!==null?[device]:runtime===void 0?[]:binding.handsOf(runtime),update=binding.presence.track(sessionId,sessionHands);update.catch(()=>{}),tracking.set(sessionId,update)},onRelease:sessionId=>{tracking.delete(sessionId)}}}function handRuntime(createRuntime,selection,runtimes){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime,sessionId=session.sessionId;runtimes.set(sessionId,runtime),selection.restore(sessionId,session);let dispose=session.dispose.bind(session);return session.dispose=()=>{runtimes.get(sessionId)===runtime&&(runtimes.delete(sessionId),selection.release(sessionId)),dispose()},runtime},createRuntime)}function presenceRuntime(createRuntime,binding){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime;return await binding.presence.track(session.sessionId,binding.handsOf(runtime)),gatePresence(session.agent,binding.presence,session.sessionId),runtime},createRuntime)}export{headlessEndpoint,headlessHostOptions,headlessSocketPath};
@@ -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{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-SB6MXNO5.js";import"./chunk-7DRWPZ3N.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-ADT36P7E.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-EVTTLPIY.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
2
+ import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-M7GF73FO.js";import"./chunk-622VYTRI.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-ADT36P7E.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-EVTTLPIY.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
@@ -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{RpcClient,RpcCommandError,RpcTransportGoneError,isTransportGoneError}from"./chunk-6CEDL5S2.js";import{SessionManager,assertValidSessionId}from"./chunk-CF5OGBC4.js";import"./chunk-GTJJ73DE.js";import{RpcRequestTimeoutError}from"./chunk-H33A33M4.js";import"./chunk-22YXCY7K.js";import"./chunk-SJI6UB23.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,daemonEnvKeys,daemonEnvOverrides,emit,ensureHost,loadHostLaunchSpec,refusal,resolveHostSocket,writeDaemonEnvKeys}from"./chunk-SB6MXNO5.js";import{HostEnsureRefusedError,STOP_WAIT_BUDGET_MS}from"./chunk-7DRWPZ3N.js";import"./chunk-QMRJYMNH.js";import{endpointKindOfSocket}from"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import{withRpcKeyRoot}from"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import{canonicalSessionPath,createHostDaemonPaths}from"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-SOMFLLPD.js";import"./chunk-TMXRR3N7.js";import"./chunk-GKAYPJ4E.js";import"./chunk-EVTTLPIY.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,getAgentDir}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{readFileSync}from"node:fs";import{resolve}from"node:path";var DETACH_ACK_TIMEOUT_MS=5e3;async function detachBeforeClose(client,report,timeoutMs=DETACH_ACK_TIMEOUT_MS){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),timeoutMs)});try{await Promise.race([client.detachConnection(),late])==="late"&&report(`the host did not confirm the detach within ${timeoutMs} ms; closing the connection anyway`)}catch(error){if(error instanceof RpcTransportGoneError)return;report(`the host refused the detach (${error instanceof Error?error.message:String(error)}); closing the connection anyway`)}finally{clearTimeout(timer)}}var USAGE_CODES=new Set(["missing_session_id","invalid_path","invalid_session_context","invalid_session_kind","invalid_launch_profile","invalid_session_id","invalid_release_reason","empty","unknown_command"]),FAILURE_CODES=new Set(["open_failed","warm_failed","release_failed"]),REASON_FOR_CODE={streaming:"busy",not_found:"unknown_cursor"},BARE_CODE=/^[a-z][a-z0-9_]*$/;function mapError(error,socket){let detail=error instanceof Error?error.message:String(error);if(error instanceof RpcCommandError){let code=error.errorCode??(BARE_CODE.test(detail)?detail:void 0);if(code===void 0)return hostError(detail,socket);let exitCode=USAGE_CODES.has(code)?HOST_EXIT_USAGE:FAILURE_CODES.has(code)?HOST_EXIT_ERROR:HOST_EXIT_REFUSED;return{exitCode,payload:{action:exitCode===HOST_EXIT_REFUSED?"refuse":"error",reason:REASON_FOR_CODE[code]??code,detail,socket,...error.errorData!==void 0&&{data:error.errorData}}}}return isTransportGoneError(error)?{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"transport_gone",detail,socket}}:hostError(detail,socket)}function hostError(detail,socket){return{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"host_error",detail,socket}}}async function openHostSession(client,request,socket,ensured){let opened=await client.openSession({cwd:request.cwd,retain_on_disconnect:!0,...request.model&&{provider:request.model.provider,modelId:request.model.id}});ensured?.release();let{state}=opened,identity={sessionId:opened.sessionId,sessionPath:state.sessionFile,durableSessionId:state.sessionId};try{request.name!==void 0&&await client.setSessionName(request.name);let disposition=request.prompt===void 0?void 0:await client.prompt(request.prompt);return{exitCode:HOST_EXIT_OK,payload:{action:"open",socket,pid:ensured?.pid,reused:ensured?.reused,...identity,cwd:state.cwd,model:state.model?{provider:state.model.provider,id:state.model.id}:null,attached:opened.attached??!1,...disposition!==void 0&&{prompt:{disposition}}}}}catch(error){let outcome=mapError(error,socket),closed=await closeOpened(client,opened.sessionId);return{...outcome,payload:{...outcome.payload,...identity,closed}}}}async function closeOpened(client,sessionId){try{return await client.closeSession(sessionId),!(await client.listSessions()).some(row=>row.sessionId===sessionId)}catch{return!1}}import{existsSync}from"node:fs";import{readdir}from"node:fs/promises";import{dirname,join}from"node:path";async function resolveSessionRef(client,ref,agentDir){let rows=await client.listSessions(),handle=rows.find(row=>row.sessionId===ref);if(handle)return{kind:"live",row:handle};if(isSessionId(ref)){let byId=await resolveDurableId(ref,rows,agentDir);if(byId)return byId}let named=rows.filter(row=>row.name===ref);if(named.length>1)return{kind:"ambiguous",candidates:named.map(row=>row.sessionId)};let live=named[0]??rows.find(row=>row.sessionPath!==void 0&&samePath(row.sessionPath,ref));return live?{kind:"live",row:live}:looksLikePath(ref)?parkedByPath(ref):{kind:"unknown"}}async function resolveDurableId(id,rows,agentDir){let liveRows=rows.filter(row=>row.durableSessionId===id),transcripts=(await transcriptsUnder(agentDir)).filter(session=>session.id===id),files=new Set([...liveRows.map(row=>row.sessionPath===void 0?row.sessionId:canonicalSessionPath(row.sessionPath)),...transcripts.map(session=>canonicalSessionPath(session.path))]);return files.size>1?{kind:"ambiguous",candidates:[...files]}:liveRows[0]?{kind:"live",row:liveRows[0]}:transcripts[0]?parked(transcripts[0]):void 0}function isSessionId(ref){try{return assertValidSessionId(ref),!0}catch{return!1}}function looksLikePath(ref){return ref.includes("/")||ref.includes("\\")||ref.endsWith(".jsonl")}async function parkedByPath(ref){let path=canonicalSessionPath(ref);if(!existsSync(path))return{kind:"unknown"};let info=(await SessionManager.listAll(dirname(path))).find(session=>samePath(session.path,path));return info?parked(info):{kind:"unknown"}}async function transcriptsUnder(agentDir){let root=join(agentDir,"sessions");if(!existsSync(root))return[];let dirs=(await readdir(root,{withFileTypes:!0})).filter(entry=>entry.isDirectory());return(await Promise.all(dirs.map(entry=>SessionManager.listAll(join(root,entry.name))))).flat()}function parked(info){return{kind:"parked",sessionPath:info.path,cwd:info.cwd,durableSessionId:info.id}}function samePath(left,right){return canonicalSessionPath(left)===canonicalSessionPath(right)}function waitForHostSession(client,sessionId,request,onTransportLoss){let started=Date.now();return new Promise((resolveWait,reject)=>{let finished=!1,observed=!1,state,timer,cleanup=()=>{finished=!0,clearTimeout(timer),unsubscribe(),onTransportLoss(void 0)},fail=error=>{finished||(cleanup(),reject(error))},finish=outcome=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_OK,payload:{action:"wait",sessionId,until:request.until,outcome,waited_ms:Date.now()-started,state:{isStreaming:state?.isStreaming??!1,pendingMessageCount:state?.pendingMessageCount??0,lastAbortSource:state?.lastAbortSource??null}}}))},unsubscribe=client.onEvent(record=>{let event=record;if(event.type==="session_closed"||event.type==="session_parked"){finish(event.type);return}if(event.type==="agent_settled"&&"reason"in event&&event.reason==="session_closed"){finish("session_closed");return}event.type!=="agent_idle"&&!(request.until==="done"&&event.type==="agent_settled")||(observed=!0,client.getState().then(snapshot=>{state=snapshot,request.until==="done"?finish("done"):isDrained(snapshot)&&finish("idle")},fail))});onTransportLoss(fail),timer=setTimeout(()=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"wait_timeout",sessionId,until:request.until,timeoutMs:request.timeoutMs}}))},request.timeoutMs),client.getState().then(snapshot=>{state=snapshot,!observed&&(request.until==="done"?!snapshot.isStreaming:isDrained(snapshot))&&finish("already_idle")},fail)})}function isDrained(state){return!state.isStreaming&&state.steering.length===0&&state.followUp.length===0&&state.ordered.length===0&&state.pendingMessageCount===0}async function runHostSessionRequest(request){let deadline=Date.now()+STOP_WAIT_BUDGET_MS;for(;;)try{return await runHostSessionRequestOnce(request,Math.max(0,deadline-Date.now()))}catch(error){if(request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping"&&Date.now()<deadline)continue;return mapError(error,request.target.socket)}}async function runHostSessionRequestOnce(request,stoppingTimeoutMs){let{socket,agentDir}=request.target,client,ensured,disconnected,connectionUnusable=!1;try{if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"});request.action==="open"&&(ensured=await ensureHost({socket,agentDir,hostArgs:request.spec.hostArgs,env:daemonEnvOverrides(process.env,request.spec.env),policy:request.spec.policy,upgrade:"never",stoppingTimeoutMs}),ensured.reused||await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),daemonEnvKeys(process.env,request.spec.env))),client=new RpcClient({socketPath:socket,onDisconnect:error=>{connectionUnusable=!0,disconnected?.(error)}});try{await client.start()}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ECONNREFUSED"))return refusal("refuse",void 0,{reason:"host_unavailable",socket,detail:error.message});throw error}let sessionId,durableSessionId;if("ref"in request){let found=await resolveSessionRef(client,request.ref,agentDir);if(found.kind==="unknown")return refusal("refuse",void 0,{reason:"unknown_session",ref:request.ref,socket});if(found.kind==="ambiguous"){let detail={reason:"ambiguous_session",ref:request.ref,candidates:found.candidates,socket};return refusal("refuse",void 0,detail)}let reopen=found.kind==="parked"?{sessionPath:found.sessionPath,cwd:found.cwd,retain_on_disconnect:!0,attended:!1}:{sessionPath:found.row.sessionPath,cwd:found.row.cwd};durableSessionId=found.kind==="parked"?found.durableSessionId:found.row.durableSessionId,sessionId=(await client.openSession(reopen)).sessionId}switch(request.action){case"open":return await openHostSession(client,request,socket,ensured);case"prompt":return{exitCode:HOST_EXIT_OK,payload:{action:"prompt",sessionId,disposition:await client.prompt(request.text)}};case"steer":{let streaming=(await client.getState()).isStreaming,disposition=await client.steer(request.text);return{exitCode:HOST_EXIT_OK,payload:{action:"steer",sessionId,disposition,streaming}}}case"abort":{let aborted=(await client.getState()).isStreaming;return await client.abortStrict(),{exitCode:HOST_EXIT_OK,payload:{action:"abort",sessionId,acknowledged:!0,aborted}}}case"model":{await client.setModel(request.model.provider,request.model.id);let state=await client.getState();return{exitCode:HOST_EXIT_OK,payload:{action:"model",sessionId,requested:request.model,model:state.model?{provider:state.model.provider,id:state.model.id}:null,pendingModelSwitch:state.pendingModelSwitch??null}}}case"list":return{exitCode:HOST_EXIT_OK,payload:{action:"list",socket,sessions:await client.listSessions({observe:!0})}};case"state":return{exitCode:HOST_EXIT_OK,payload:{action:"state",sessionId,durableSessionId,state:await client.getState()}};case"read":{if(request.messages){let all=await client.getMessages(),messages=request.tail===void 0?all:all.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,messages,count:messages.length}}}let{entries,leafId}=await client.getEntries(request.since),slice=request.tail===void 0?entries:entries.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,entries:slice,count:slice.length,total:entries.length,leafId,nextSince:slice.at(-1)?.id??request.since??null,...request.since!==void 0&&{since:request.since}}}}case"wait":return await waitForHostSession(client,sessionId,request,handler=>{disconnected=handler});case"unload":{let answer=await client.unloadSession({sessionId,interrupt:request.interrupt,force:request.force,clearQueue:request.clearQueue,children:request.children});return{exitCode:answer.outcome==="unloaded"?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{action:"unload",sessionId,...answer}}}case"close":{let reason,unsubscribe=client.onEvent(record=>{let event=record;event.type==="session_closed"&&(reason=event.reason)});try{await client.closeSession(sessionId);let remaining=(await client.listSessions()).find(row=>row.sessionId===sessionId);return{exitCode:HOST_EXIT_OK,payload:remaining?{action:"close",sessionId,closed:!1,attachments:remaining.attachments}:{action:"close",sessionId,closed:!0,reason:reason??"client_close"}}}finally{unsubscribe()}}default:return assertNever(request)}}catch(error){if((error instanceof RpcRequestTimeoutError||isTransportGoneError(error))&&(connectionUnusable=!0),request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping")throw error;return error instanceof HostEnsureRefusedError?refusal("refuse",void 0,{reason:error.reason,socket,detail:error.detail}):mapError(error,socket)}finally{ensured?.release(),client&&!connectionUnusable&&await detachBeforeClose(client,line=>process.stderr.write(`senpi host session: ${line}
2
+ import{RpcClient,RpcCommandError,RpcTransportGoneError,isTransportGoneError}from"./chunk-4UR6UFBH.js";import{SessionManager,assertValidSessionId}from"./chunk-4NYNMAYF.js";import"./chunk-GTJJ73DE.js";import{RpcRequestTimeoutError}from"./chunk-H33A33M4.js";import"./chunk-22YXCY7K.js";import"./chunk-SJI6UB23.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,daemonEnvKeys,daemonEnvOverrides,emit,ensureHost,loadHostLaunchSpec,refusal,resolveHostSocket,writeDaemonEnvKeys}from"./chunk-M7GF73FO.js";import{HostEnsureRefusedError,STOP_WAIT_BUDGET_MS}from"./chunk-622VYTRI.js";import"./chunk-QMRJYMNH.js";import{endpointKindOfSocket}from"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import{withRpcKeyRoot}from"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import{canonicalSessionPath,createHostDaemonPaths}from"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-SOMFLLPD.js";import"./chunk-TMXRR3N7.js";import"./chunk-7PROV6BB.js";import"./chunk-EVTTLPIY.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import{APP_NAME,getAgentDir}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{readFileSync}from"node:fs";import{resolve}from"node:path";var DETACH_ACK_TIMEOUT_MS=5e3;async function detachBeforeClose(client,report,timeoutMs=DETACH_ACK_TIMEOUT_MS){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),timeoutMs)});try{await Promise.race([client.detachConnection(),late])==="late"&&report(`the host did not confirm the detach within ${timeoutMs} ms; closing the connection anyway`)}catch(error){if(error instanceof RpcTransportGoneError)return;report(`the host refused the detach (${error instanceof Error?error.message:String(error)}); closing the connection anyway`)}finally{clearTimeout(timer)}}var USAGE_CODES=new Set(["missing_session_id","invalid_path","invalid_session_context","invalid_session_kind","invalid_launch_profile","invalid_session_id","invalid_release_reason","empty","unknown_command"]),FAILURE_CODES=new Set(["open_failed","warm_failed","release_failed"]),REASON_FOR_CODE={streaming:"busy",not_found:"unknown_cursor"},BARE_CODE=/^[a-z][a-z0-9_]*$/;function mapError(error,socket){let detail=error instanceof Error?error.message:String(error);if(error instanceof RpcCommandError){let code=error.errorCode??(BARE_CODE.test(detail)?detail:void 0);if(code===void 0)return hostError(detail,socket);let exitCode=USAGE_CODES.has(code)?HOST_EXIT_USAGE:FAILURE_CODES.has(code)?HOST_EXIT_ERROR:HOST_EXIT_REFUSED;return{exitCode,payload:{action:exitCode===HOST_EXIT_REFUSED?"refuse":"error",reason:REASON_FOR_CODE[code]??code,detail,socket,...error.errorData!==void 0&&{data:error.errorData}}}}return isTransportGoneError(error)?{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"transport_gone",detail,socket}}:hostError(detail,socket)}function hostError(detail,socket){return{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"host_error",detail,socket}}}async function openHostSession(client,request,socket,ensured){let opened=await client.openSession({cwd:request.cwd,retain_on_disconnect:!0,...request.model&&{provider:request.model.provider,modelId:request.model.id}});ensured?.release();let{state}=opened,identity={sessionId:opened.sessionId,sessionPath:state.sessionFile,durableSessionId:state.sessionId};try{request.name!==void 0&&await client.setSessionName(request.name);let disposition=request.prompt===void 0?void 0:await client.prompt(request.prompt);return{exitCode:HOST_EXIT_OK,payload:{action:"open",socket,pid:ensured?.pid,reused:ensured?.reused,...identity,cwd:state.cwd,model:state.model?{provider:state.model.provider,id:state.model.id}:null,attached:opened.attached??!1,...disposition!==void 0&&{prompt:{disposition}}}}}catch(error){let outcome=mapError(error,socket),closed=await closeOpened(client,opened.sessionId);return{...outcome,payload:{...outcome.payload,...identity,closed}}}}async function closeOpened(client,sessionId){try{return await client.closeSession(sessionId),!(await client.listSessions()).some(row=>row.sessionId===sessionId)}catch{return!1}}import{existsSync}from"node:fs";import{readdir}from"node:fs/promises";import{dirname,join}from"node:path";async function resolveSessionRef(client,ref,agentDir){let rows=await client.listSessions(),handle=rows.find(row=>row.sessionId===ref);if(handle)return{kind:"live",row:handle};if(isSessionId(ref)){let byId=await resolveDurableId(ref,rows,agentDir);if(byId)return byId}let named=rows.filter(row=>row.name===ref);if(named.length>1)return{kind:"ambiguous",candidates:named.map(row=>row.sessionId)};let live=named[0]??rows.find(row=>row.sessionPath!==void 0&&samePath(row.sessionPath,ref));return live?{kind:"live",row:live}:looksLikePath(ref)?parkedByPath(ref):{kind:"unknown"}}async function resolveDurableId(id,rows,agentDir){let liveRows=rows.filter(row=>row.durableSessionId===id),transcripts=(await transcriptsUnder(agentDir)).filter(session=>session.id===id),files=new Set([...liveRows.map(row=>row.sessionPath===void 0?row.sessionId:canonicalSessionPath(row.sessionPath)),...transcripts.map(session=>canonicalSessionPath(session.path))]);return files.size>1?{kind:"ambiguous",candidates:[...files]}:liveRows[0]?{kind:"live",row:liveRows[0]}:transcripts[0]?parked(transcripts[0]):void 0}function isSessionId(ref){try{return assertValidSessionId(ref),!0}catch{return!1}}function looksLikePath(ref){return ref.includes("/")||ref.includes("\\")||ref.endsWith(".jsonl")}async function parkedByPath(ref){let path=canonicalSessionPath(ref);if(!existsSync(path))return{kind:"unknown"};let info=(await SessionManager.listAll(dirname(path))).find(session=>samePath(session.path,path));return info?parked(info):{kind:"unknown"}}async function transcriptsUnder(agentDir){let root=join(agentDir,"sessions");if(!existsSync(root))return[];let dirs=(await readdir(root,{withFileTypes:!0})).filter(entry=>entry.isDirectory());return(await Promise.all(dirs.map(entry=>SessionManager.listAll(join(root,entry.name))))).flat()}function parked(info){return{kind:"parked",sessionPath:info.path,cwd:info.cwd,durableSessionId:info.id}}function samePath(left,right){return canonicalSessionPath(left)===canonicalSessionPath(right)}function waitForHostSession(client,sessionId,request,onTransportLoss){let started=Date.now();return new Promise((resolveWait,reject)=>{let finished=!1,observed=!1,state,timer,cleanup=()=>{finished=!0,clearTimeout(timer),unsubscribe(),onTransportLoss(void 0)},fail=error=>{finished||(cleanup(),reject(error))},finish=outcome=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_OK,payload:{action:"wait",sessionId,until:request.until,outcome,waited_ms:Date.now()-started,state:{isStreaming:state?.isStreaming??!1,pendingMessageCount:state?.pendingMessageCount??0,lastAbortSource:state?.lastAbortSource??null}}}))},unsubscribe=client.onEvent(record=>{let event=record;if(event.type==="session_closed"||event.type==="session_parked"){finish(event.type);return}if(event.type==="agent_settled"&&"reason"in event&&event.reason==="session_closed"){finish("session_closed");return}event.type!=="agent_idle"&&!(request.until==="done"&&event.type==="agent_settled")||(observed=!0,client.getState().then(snapshot=>{state=snapshot,request.until==="done"?finish("done"):isDrained(snapshot)&&finish("idle")},fail))});onTransportLoss(fail),timer=setTimeout(()=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"wait_timeout",sessionId,until:request.until,timeoutMs:request.timeoutMs}}))},request.timeoutMs),client.getState().then(snapshot=>{state=snapshot,!observed&&(request.until==="done"?!snapshot.isStreaming:isDrained(snapshot))&&finish("already_idle")},fail)})}function isDrained(state){return!state.isStreaming&&state.steering.length===0&&state.followUp.length===0&&state.ordered.length===0&&state.pendingMessageCount===0}async function runHostSessionRequest(request){let deadline=Date.now()+STOP_WAIT_BUDGET_MS;for(;;)try{return await runHostSessionRequestOnce(request,Math.max(0,deadline-Date.now()))}catch(error){if(request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping"&&Date.now()<deadline)continue;return mapError(error,request.target.socket)}}async function runHostSessionRequestOnce(request,stoppingTimeoutMs){let{socket,agentDir}=request.target,client,ensured,disconnected,connectionUnusable=!1;try{if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"});request.action==="open"&&(ensured=await ensureHost({socket,agentDir,hostArgs:request.spec.hostArgs,env:daemonEnvOverrides(process.env,request.spec.env),policy:request.spec.policy,upgrade:"never",stoppingTimeoutMs}),ensured.reused||await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),daemonEnvKeys(process.env,request.spec.env))),client=new RpcClient({socketPath:socket,onDisconnect:error=>{connectionUnusable=!0,disconnected?.(error)}});try{await client.start()}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ECONNREFUSED"))return refusal("refuse",void 0,{reason:"host_unavailable",socket,detail:error.message});throw error}let sessionId,durableSessionId;if("ref"in request){let found=await resolveSessionRef(client,request.ref,agentDir);if(found.kind==="unknown")return refusal("refuse",void 0,{reason:"unknown_session",ref:request.ref,socket});if(found.kind==="ambiguous"){let detail={reason:"ambiguous_session",ref:request.ref,candidates:found.candidates,socket};return refusal("refuse",void 0,detail)}let reopen=found.kind==="parked"?{sessionPath:found.sessionPath,cwd:found.cwd,retain_on_disconnect:!0,attended:!1}:{sessionPath:found.row.sessionPath,cwd:found.row.cwd};durableSessionId=found.kind==="parked"?found.durableSessionId:found.row.durableSessionId,sessionId=(await client.openSession(reopen)).sessionId}switch(request.action){case"open":return await openHostSession(client,request,socket,ensured);case"prompt":return{exitCode:HOST_EXIT_OK,payload:{action:"prompt",sessionId,disposition:await client.prompt(request.text)}};case"steer":{let streaming=(await client.getState()).isStreaming,disposition=await client.steer(request.text);return{exitCode:HOST_EXIT_OK,payload:{action:"steer",sessionId,disposition,streaming}}}case"abort":{let aborted=(await client.getState()).isStreaming;return await client.abortStrict(),{exitCode:HOST_EXIT_OK,payload:{action:"abort",sessionId,acknowledged:!0,aborted}}}case"model":{await client.setModel(request.model.provider,request.model.id);let state=await client.getState();return{exitCode:HOST_EXIT_OK,payload:{action:"model",sessionId,requested:request.model,model:state.model?{provider:state.model.provider,id:state.model.id}:null,pendingModelSwitch:state.pendingModelSwitch??null}}}case"list":return{exitCode:HOST_EXIT_OK,payload:{action:"list",socket,sessions:await client.listSessions({observe:!0})}};case"state":return{exitCode:HOST_EXIT_OK,payload:{action:"state",sessionId,durableSessionId,state:await client.getState()}};case"read":{if(request.messages){let all=await client.getMessages(),messages=request.tail===void 0?all:all.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,messages,count:messages.length}}}let{entries,leafId}=await client.getEntries(request.since),slice=request.tail===void 0?entries:entries.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,entries:slice,count:slice.length,total:entries.length,leafId,nextSince:slice.at(-1)?.id??request.since??null,...request.since!==void 0&&{since:request.since}}}}case"wait":return await waitForHostSession(client,sessionId,request,handler=>{disconnected=handler});case"unload":{let answer=await client.unloadSession({sessionId,interrupt:request.interrupt,force:request.force,clearQueue:request.clearQueue,children:request.children});return{exitCode:answer.outcome==="unloaded"?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{action:"unload",sessionId,...answer}}}case"close":{let reason,unsubscribe=client.onEvent(record=>{let event=record;event.type==="session_closed"&&(reason=event.reason)});try{await client.closeSession(sessionId);let remaining=(await client.listSessions()).find(row=>row.sessionId===sessionId);return{exitCode:HOST_EXIT_OK,payload:remaining?{action:"close",sessionId,closed:!1,attachments:remaining.attachments}:{action:"close",sessionId,closed:!0,reason:reason??"client_close"}}}finally{unsubscribe()}}default:return assertNever(request)}}catch(error){if((error instanceof RpcRequestTimeoutError||isTransportGoneError(error))&&(connectionUnusable=!0),request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping")throw error;return error instanceof HostEnsureRefusedError?refusal("refuse",void 0,{reason:error.reason,socket,detail:error.detail}):mapError(error,socket)}finally{ensured?.release(),client&&!connectionUnusable&&await detachBeforeClose(client,line=>process.stderr.write(`senpi host session: ${line}
3
3
  `)),await client?.stop()}}function assertNever(value){throw new Error(`unreachable host session request: ${JSON.stringify(value)}`)}var USAGE=`usage: ${APP_NAME} host session <command> [--socket <path>] [--rpc-key-root <dir>] [--json]
4
4
 
5
5
  open --cwd <dir> [--model <provider/id>] [--name <text>] [--prompt <text|@file>] [--launch-spec <file>]
@@ -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,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,replayStartupSubmission,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-V2QAYGOK.js";import"./chunk-6CEDL5S2.js";import"./chunk-BASS47UD.js";import"./chunk-JMQOLOC2.js";import"./chunk-X53PD4ZC.js";import"./chunk-CF5OGBC4.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import{createInteractiveTui,createInteractiveTuiReference}from"./chunk-4BATXPB7.js";import"./chunk-H33A33M4.js";import"./chunk-5LKB732P.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-L7ZIS3MC.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-UODSYQ2D.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-SB6MXNO5.js";import"./chunk-7DRWPZ3N.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-4E7GDG4H.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-F5JLDCYD.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import"./chunk-DSWDJ7HT.js";import"./chunk-GKAYPJ4E.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-CFEHJ4VU.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,replayStartupSubmission,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
2
+ import{InteractiveMode,OptimisticUserEchoController,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,replayStartupSubmission,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-7CFORZPE.js";import"./chunk-4UR6UFBH.js";import"./chunk-STGOYIXC.js";import"./chunk-Q6NR6644.js";import"./chunk-45MVD7BU.js";import"./chunk-4NYNMAYF.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import{createInteractiveTui,createInteractiveTuiReference}from"./chunk-K3UHGDUQ.js";import"./chunk-H33A33M4.js";import"./chunk-3TZQXZKH.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-4JIBEZZE.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-XZDCMDUH.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-M7GF73FO.js";import"./chunk-622VYTRI.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-7VMEE62L.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-527Q2UYM.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import"./chunk-WQ4RBPMS.js";import"./chunk-7PROV6BB.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-NDSWTAYJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,replayStartupSubmission,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
@@ -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{applyGrokNeoThemeFallback,collectAuthDiagnostics,collectExtensionLoadDiagnostics,createCliRuntimeFactory,createSessionManager,interactiveAuthNotices,main,promptConfirm,resolveAutoTitleSessions}from"./chunk-V2QAYGOK.js";import"./chunk-6CEDL5S2.js";import"./chunk-BASS47UD.js";import"./chunk-JMQOLOC2.js";import"./chunk-X53PD4ZC.js";import"./chunk-CF5OGBC4.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import"./chunk-4BATXPB7.js";import"./chunk-H33A33M4.js";import"./chunk-5LKB732P.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-L7ZIS3MC.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-UODSYQ2D.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-SB6MXNO5.js";import"./chunk-7DRWPZ3N.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-4E7GDG4H.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-F5JLDCYD.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import"./chunk-DSWDJ7HT.js";import"./chunk-GKAYPJ4E.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-CFEHJ4VU.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{applyGrokNeoThemeFallback,collectAuthDiagnostics,collectExtensionLoadDiagnostics,createCliRuntimeFactory,createSessionManager,interactiveAuthNotices,main,promptConfirm,resolveAutoTitleSessions};
2
+ import{applyGrokNeoThemeFallback,collectAuthDiagnostics,collectExtensionLoadDiagnostics,createCliRuntimeFactory,createSessionManager,interactiveAuthNotices,main,promptConfirm,resolveAutoTitleSessions}from"./chunk-7CFORZPE.js";import"./chunk-4UR6UFBH.js";import"./chunk-STGOYIXC.js";import"./chunk-Q6NR6644.js";import"./chunk-45MVD7BU.js";import"./chunk-4NYNMAYF.js";import"./chunk-GTJJ73DE.js";import"./chunk-FEQDJBDL.js";import"./chunk-K3UHGDUQ.js";import"./chunk-H33A33M4.js";import"./chunk-3TZQXZKH.js";import"./chunk-22YXCY7K.js";import"./chunk-3QPE75AR.js";import"./chunk-4GKU755E.js";import"./chunk-4JIBEZZE.js";import"./chunk-SJI6UB23.js";import"./chunk-436DNN4Z.js";import"./chunk-J2I56WLK.js";import"./chunk-TQHNFP77.js";import"./chunk-XZDCMDUH.js";import"./chunk-LM6DOWQH.js";import"./chunk-MOVB6H22.js";import"./chunk-NH7SYIGN.js";import"./chunk-WAOGBBZR.js";import"./chunk-VD7AKTGP.js";import"./chunk-Y3TMJV3J.js";import"./chunk-MTQQ2VQH.js";import"./chunk-M7GF73FO.js";import"./chunk-622VYTRI.js";import"./chunk-QMRJYMNH.js";import"./chunk-Y7Z7XPUF.js";import"./chunk-54YTJCYZ.js";import"./chunk-26UBFF6N.js";import"./chunk-I5ASHSLZ.js";import"./chunk-2CNSCMYC.js";import"./chunk-7WYJAYHH.js";import"./chunk-I3PHVJAS.js";import"./chunk-R2Z7CX77.js";import"./chunk-EAEEM2KN.js";import"./chunk-YI6KRJDC.js";import"./chunk-DBQBJTMF.js";import"./chunk-SF4MQDKZ.js";import"./chunk-VPVD5G32.js";import"./chunk-H4QOEVS5.js";import"./chunk-PPQPV52D.js";import"./chunk-7VMEE62L.js";import"./chunk-UBNUGVW6.js";import"./chunk-ADT36P7E.js";import"./chunk-KLAX467B.js";import"./chunk-J7FW7MED.js";import"./chunk-2EJ4BGBM.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-MSDBBOB2.js";import"./chunk-WHQ2QPP5.js";import"./chunk-YUTUD26F.js";import"./chunk-WB4BUHOH.js";import"./chunk-6VWIMHMH.js";import"./chunk-SOMFLLPD.js";import"./chunk-KDUJCDLM.js";import"./chunk-YU2P3CAR.js";import"./chunk-ADOOQW3O.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-527Q2UYM.js";import"./chunk-TMXRR3N7.js";import"./chunk-LPYBKMPT.js";import"./chunk-WQ4RBPMS.js";import"./chunk-7PROV6BB.js";import"./chunk-EVTTLPIY.js";import"./chunk-BPNSOZ2C.js";import"./chunk-DLAY7CIU.js";import"./chunk-YUVC7SJB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-ZDHAJROE.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-HJDTYAPV.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-WIOV3AXZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-OKMHSVCA.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-NDNQ23SK.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-GLTOBXZY.js";import"./chunk-NDSWTAYJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-YK3ZZCHI.js";import"./chunk-T2SMQPRE.js";import"./chunk-RUGTHELO.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-IHES3JES.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-AOTHPTMU.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{applyGrokNeoThemeFallback,collectAuthDiagnostics,collectExtensionLoadDiagnostics,createCliRuntimeFactory,createSessionManager,interactiveAuthNotices,main,promptConfirm,resolveAutoTitleSessions};