@tencent-ai/agent-harness 0.2.0-beta.2 → 0.2.0-beta.3

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 (149) hide show
  1. package/CHANGELOG.md +26 -2
  2. package/cli/CHANGELOG.md +64 -0
  3. package/cli/dist-server/shared.cjs +379 -315
  4. package/cli/dist-server/types/node/bash-sandbox/bash-sandbox-protocol.d.ts +3 -0
  5. package/cli/dist-server/types/node/cli/cli-protocol.d.ts +3 -0
  6. package/cli/dist-server/types/node/cli/stream-json-protocol.d.ts +8 -1
  7. package/cli/dist-server/types/node/sensitive-content/sensitive-content-protocol.d.ts +7 -0
  8. package/cli/dist-server/types/node/server/boot.d.ts +7 -4
  9. package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-error-model.d.ts +1 -1
  10. package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-protocol.d.ts +2 -3
  11. package/cli/dist-server/types/node/server/formats/acp/index.d.ts +12 -0
  12. package/cli/dist-server/types/node/server/formats/acp/projection.d.ts +10 -0
  13. package/cli/dist-server/types/node/server/index.d.ts +1 -1
  14. package/cli/dist-server/types/node/server/sessions.d.ts +3 -2
  15. package/cli/dist-server/types/node/server/types.d.ts +59 -7
  16. package/cli/dist-server/types/node/tools/tool-protocol.d.ts +16 -2
  17. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-protocol.d.ts +31 -2
  18. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-protocol.d.ts +8 -4
  19. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-scope.d.ts +46 -0
  20. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-service.d.ts +26 -3
  21. package/cli/dist-server/types/vendor/cbc-core/node/agent/index.d.ts +3 -0
  22. package/cli/dist-server/types/vendor/cbc-core/node/agent/model-call-failure.d.ts +9 -0
  23. package/cli/dist-server/types/vendor/cbc-core/node/agent/model-step-sequence.d.ts +11 -0
  24. package/cli/dist-server/types/vendor/cbc-core/node/agent/runner-factory.d.ts +25 -9
  25. package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
  26. package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-pattern.d.ts +9 -8
  27. package/cli/dist-server/types/vendor/cbc-core/node/context/compaction-lineage.d.ts +39 -0
  28. package/cli/dist-server/types/vendor/cbc-core/node/context/context-compact-summarizer.d.ts +2 -0
  29. package/cli/dist-server/types/vendor/cbc-core/node/context/context-protocol.d.ts +17 -0
  30. package/cli/dist-server/types/vendor/cbc-core/node/context/index.d.ts +1 -0
  31. package/cli/dist-server/types/vendor/cbc-core/node/context/pre-message-compact-strategy.d.ts +1 -2
  32. package/cli/dist-server/types/vendor/cbc-core/node/session/index.d.ts +1 -0
  33. package/cli/dist-server/types/vendor/cbc-core/node/session/interruption-service.d.ts +8 -0
  34. package/cli/dist-server/types/vendor/cbc-core/node/session/model-request-retry-phase.d.ts +16 -0
  35. package/cli/dist-server/types/vendor/cbc-core/node/session/model-response-interceptors.d.ts +15 -0
  36. package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager-host-protocol.d.ts +3 -2
  37. package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager.d.ts +7 -3
  38. package/cli/dist-server/types/vendor/cbc-core/node/session/session-protocol.d.ts +47 -5
  39. package/cli/dist-server/types/vendor/cbc-core/node/session/session-run-state-machine-protocol.d.ts +14 -1
  40. package/cli/dist-server/types/vendor/cbc-core/node/session/stream-timeout-retry-budget.d.ts +8 -1
  41. package/cli/dist-server/types/vendor/cbc-core/node/trace/turn-context.d.ts +28 -1
  42. package/cli/dist-server/types/vendor/cbc-core/node/utils/command-message-utils.d.ts +20 -0
  43. package/cli/dist-server/types/vendor/cbc-core/node/utils/history-utils.d.ts +4 -4
  44. package/cli/dist-server/types/vendor/cbc-core/node/utils/input-item-utils.d.ts +8 -0
  45. package/cli/dist-server/types/vendor/cbc-core/node/utils/token-utils.d.ts +3 -1
  46. package/cli/dist-server/types/vendor/cbc-shared/node/agent/openai-agents-types.d.ts +1 -0
  47. package/cli/dist-server/types/vendor/cbc-shared/node/checkpoint/checkpoint-types.d.ts +6 -0
  48. package/cli/dist-server/types/vendor/cbc-shared/node/model/model-errors.d.ts +30 -2
  49. package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/index.d.ts +1 -0
  50. package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/sandbox-rule-context.d.ts +38 -0
  51. package/cli/dist-server/types/workspace/authentication/lib/common/account-scoped-external-link-authentication-provider.d.ts +3 -3
  52. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-manager.d.ts +6 -0
  53. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-observation.d.ts +36 -0
  54. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-protocol.d.ts +21 -0
  55. package/cli/dist-server/types/workspace/authentication/lib/common/external-link-authentication-provider.d.ts +20 -4
  56. package/cli/dist-server/types/workspace/authentication/lib/common/index.d.ts +1 -0
  57. package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-protocol.d.ts +2 -0
  58. package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-service.d.ts +1 -0
  59. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-protocol.d.ts +31 -2
  60. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-protocol.d.ts +8 -4
  61. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-scope.d.ts +46 -0
  62. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-service.d.ts +26 -3
  63. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/index.d.ts +3 -0
  64. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-call-failure.d.ts +9 -0
  65. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-step-sequence.d.ts +11 -0
  66. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/runner-factory.d.ts +25 -9
  67. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
  68. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-pattern.d.ts +9 -8
  69. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/compaction-lineage.d.ts +39 -0
  70. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-compact-summarizer.d.ts +2 -0
  71. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-protocol.d.ts +17 -0
  72. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/index.d.ts +1 -0
  73. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/pre-message-compact-strategy.d.ts +1 -2
  74. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/index.d.ts +1 -0
  75. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/interruption-service.d.ts +8 -0
  76. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-request-retry-phase.d.ts +16 -0
  77. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-response-interceptors.d.ts +15 -0
  78. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager-host-protocol.d.ts +3 -2
  79. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager.d.ts +7 -3
  80. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-protocol.d.ts +47 -5
  81. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-run-state-machine-protocol.d.ts +14 -1
  82. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/stream-timeout-retry-budget.d.ts +8 -1
  83. package/cli/dist-server/types/workspace/cbc-core/lib/node/trace/turn-context.d.ts +28 -1
  84. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/command-message-utils.d.ts +20 -0
  85. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/history-utils.d.ts +4 -4
  86. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/input-item-utils.d.ts +8 -0
  87. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/token-utils.d.ts +3 -1
  88. package/cli/dist-server/types/workspace/cbc-shared/lib/node/agent/openai-agents-types.d.ts +1 -0
  89. package/cli/dist-server/types/workspace/cbc-shared/lib/node/checkpoint/checkpoint-types.d.ts +6 -0
  90. package/cli/dist-server/types/workspace/cbc-shared/lib/node/model/model-errors.d.ts +30 -2
  91. package/cli/dist-server/types/workspace/cbc-worktree/lib/node/worktree/worktree-service.d.ts +5 -0
  92. package/cli/dist-server/types/workspace/core/lib/common/protocol.d.ts +8 -1
  93. package/cli/dist-server/types/workspace/product/lib/common/index.d.ts +1 -0
  94. package/cli/dist-server/types/workspace/product/lib/common/tencent-docs-endpoint.d.ts +37 -0
  95. package/cli/dist-server/types/workspace/product/lib/common/types/config.d.ts +12 -0
  96. package/cli/dist-server/types/workspace/product/lib/common/types/features.d.ts +1 -9
  97. package/cli/dist-server/types/workspace/product/lib/common/types/product.d.ts +15 -0
  98. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/center-protocol.generated.d.ts +5 -0
  99. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/file-policy.d.ts +4 -1
  100. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/http-policy.d.ts +20 -0
  101. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/rule-config.d.ts +10 -0
  102. package/cli/dist-server/types/workspace/sandbox-cli/lib/node/sandbox-center-client.d.ts +3 -0
  103. package/cli/dist-server/types/workspace/telemetry/lib/common/event/types/craft.d.ts +43 -3
  104. package/cli/package.json +1 -1
  105. package/cli/product.cloudhosted.json +4 -4
  106. package/cli/product.internal.json +11 -7
  107. package/cli/product.ioa.json +32 -24
  108. package/cli/product.json +45 -17
  109. package/cli/product.selfhosted.json +2 -2
  110. package/cli/vendor/shim/brokered-bin/7z +675 -0
  111. package/cli/vendor/shim/brokered-bin/7za +675 -0
  112. package/cli/vendor/shim/brokered-bin/7zz +675 -0
  113. package/cli/vendor/shim/brokered-bin/rar +675 -0
  114. package/cli/vendor/shim/brokered-bin/tar +675 -0
  115. package/cli/vendor/shim/brokered-bin/zip +187 -0
  116. package/docs/in-process.md +26 -2
  117. package/docs/protocol.md +7 -1
  118. package/docs/server.md +2 -0
  119. package/lib/agent/v2.js +1 -1
  120. package/lib/application/services.js +1 -1
  121. package/lib/client/client.js +1 -1
  122. package/lib/client/mcp.d.ts +1 -1
  123. package/lib/client/mcp.js +1 -1
  124. package/lib/components/acp-mcp-transport.d.mts +84 -1
  125. package/lib/components/question-elicitation.d.mts +20 -1
  126. package/lib/components/{acp/acp-prompt-input.d.ts → session/prompt-input.d.ts} +1 -1
  127. package/lib/components/session-replay.d.mts +6 -7
  128. package/lib/components/session-replay.mjs +1 -1
  129. package/lib/effect-runtime/mcp-lifecycle.mjs +1 -1
  130. package/lib/harness/create-harness.js +1 -1
  131. package/lib/integration/agent-integration.d.ts +5 -0
  132. package/lib/runtime/private-runtime-role.js +1 -1
  133. package/lib/session/agent-backend.d.ts +3 -0
  134. package/lib/session/agent-backend.js +1 -1
  135. package/lib/session/config-defaults.d.ts +4 -0
  136. package/lib/session/config-defaults.js +1 -0
  137. package/lib/session/config-store.d.ts +1 -1
  138. package/lib/session/config-store.js +1 -1
  139. package/lib/session/replay.d.ts +2 -2
  140. package/lib/session/replay.js +1 -1
  141. package/lib/session/server-config.d.ts +11 -2
  142. package/lib/session/server-config.js +1 -1
  143. package/lib/session/server-events.d.ts +10 -8
  144. package/lib/session/server-events.js +1 -1
  145. package/lib/session/server-mcp.js +1 -1
  146. package/package.json +20 -19
  147. package/lib/components/acp/acp-client-channel.d.ts +0 -36
  148. package/lib/components/acp/acp-mcp-transport.d.ts +0 -84
  149. package/lib/components/acp/acp-question-elicitation.d.ts +0 -20
package/lib/agent/v2.js CHANGED
@@ -1 +1 @@
1
- var Ze=Object.defineProperty;var u=(a,e)=>Ze(a,"name",{value:e,configurable:!0});import{createHash as Qe,randomUUID as xe}from"node:crypto";import oe from"node:path";import{Effect as H,Result as et,Schema as tt}from"effect";import"../auth/session.js";import{AGENT_HARNESS_CHECKPOINT_METHODS as re,CheckpointList as rt,CheckpointRead as it,CheckpointRestore as nt}from"../checkpoint/rpcs.js";import"../checkpoint/schemas.js";import{currentHarnessProcessRuntime as ot}from"../effect-runtime/process-runtime-context.js";import{ClientMcpRouter as st}from"../integration/client-mcp-attachment.js";import{SessionMcpSourceUnavailableError as at,SessionMcpViewRevokedError as ct}from"../integration/session-mcp-view.js";import{EMPTY_USER_MCP_SNAPSHOT as ce}from"../integration/source-compiler.js";import{resolveStdioMcpContainment as dt}from"../integration/stdio-guardian.js";import{abortable as R,abortReason as E,once as de,queueTransition as Ie}from"../internal/async.js";import{normalizeError as le}from"../internal/errors.js";import{isRecord as A}from"../internal/guards.js";import{MCP_SERVER_PROTOCOL_METHODS as ue}from"../mcp-server/module.js";import{MCP_SERVER_MAX_ERROR_CHARS as lt}from"../mcp-server/schemas.js";import{requestHandler as he}from"../module/validation.js";import{ACP_V2_METHODS as q,loadAcpV2CoreMethodAllowlist as ut}from"../protocol/acp-v2.js";import{validateAcpV2CoreSchema as fe,validateAcpV2SchemaWithCodeBuddyCredits as ht}from"../protocol/acp-v2-schema.js";import{AGENT_HARNESS_ERROR_META_KEY as ft,AGENT_HARNESS_ERROR_UPDATE as pe,AGENT_HARNESS_TURN_TERMINAL_META_KEY as Fe,agentHarnessSessionErrorValidationError as Me,agentHarnessTurnTerminalSchema as pt}from"../protocol/error.js";import{AGENT_HARNESS_PROMPT_CAPABILITY as Ee,AGENT_HARNESS_PROMPT_META_KEY as me,AGENT_HARNESS_PROMPT_STEER_MODE as Oe,projectPromptRequestToPrivate as ke,projectPromptResponseToPublic as mt,promptMetadata as qe,promptMetadataValidationError as gt}from"../protocol/prompt.js";import{equalSessionEnabledPlugins as yt,mergeSessionEnabledPluginsConfigOption as je,normalizeSessionPluginSettingsSnapshot as wt,sessionEnabledPluginsFromSetRequest as St}from"../protocol/session-plugin-settings.js";import{isAgentHarnessProcessContainmentEnabled as Ct}from"../runtime/sfe-process-containment.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as p,AgentHarnessInvalidParamsError as P,AgentHarnessJsonRpcError as f,AgentHarnessPeerError as Rt,AgentHarnessTimeoutError as Pt}from"../server/errors.js";import{AGENT_HARNESS_COMPACT_METHOD as ge,AGENT_HARNESS_COMPACTION_TRIGGER_META_KEY as vt,AGENT_HARNESS_COMPACTION_UPDATE as Ne,compactionUpdateValidationError as bt,compactSessionRequestValidationError as At,compactSessionResponseValidationError as It}from"../session/compact.js";import{AGENT_HARNESS_REWIND_METHOD as ye,AGENT_HARNESS_TURN_REPLAY_TYPE as Ft,rewindSessionRequestSchema as Mt,turnBoundaryValidationError as Et,turnPageValidationError as Ot,turnReplayValidationError as kt}from"../session/turn.js";import{mergeSubagentReplay as qt}from"../subagent/history.js";import{PRIVATE_SUBAGENT_META_KEY as z,REQUEST_ID_META_KEY as G,ROOT_REQUEST_ID_META_KEY as we,SubagentAttachmentBufferOverflowError as jt,SubagentJournalOverflowError as Nt,SubagentProjection as _e}from"../subagent/projection.js";import{measure as B,useLog as T}from"../telemetry/index.js";import{ReconnectMessageCoverageCollector as _t}from"./reconnect-message-merge.js";import{AcpSessionProxy as Bt,AcpSessionProxyBufferOverflowError as Tt}from"./session-proxy.js";const Be=32,Te=8*1024*1024,De=2048,Dt=1e4,Ut=1e4,Gt=3e4,Ue=3e4,Ge=Be,We=Te,He=De,L=4096,Le=256,Ke=64,ze="codebuddy.ai/privateSessionInitializationDurations",Wt="codebuddy.ai/timestamp",Ht=null,Se=Object.freeze({code:"internal_error",message:"The agent process terminated unexpectedly."}),Lt=Object.freeze({authReady:"privateSessionAuthReady",configProjection:"privateSessionConfigProjection",endpointResolve:"privateSessionEndpointResolve",sessionMaterialize:"privateSessionMaterialize",modelsProjection:"privateSessionModelsProjection",modesProjection:"privateSessionModesProjection"});function Kt(a){const e=a._meta;if(!A(e))return a;const t=e[ze];if(A(t)){const i=T();for(const[n,o]of Object.entries(Lt)){const s=t[n];typeof s=="number"&&Number.isFinite(s)&&s>=0&&s<=Ue&&i.addDuration(o,s)}}const r={...e};if(delete r[ze],Object.keys(r).length===0){const{_meta:i,...n}=a;return n}return{...a,_meta:r}}u(Kt,"consumePrivateSessionInitializationDurations");function zt(a,e=Ct(),t){return{session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},...dt({platform:a,requested:!0,windowsProcessContainmentEnabled:e,windowsJob:t}).allowStdio?{stdio:{}}:{}},prompt:{embeddedContext:{},image:{},_meta:{[me]:Ee}}}}}u(zt,"defaultAgentCapabilities");function ie(a){return Array.isArray(a)?a.map(ie):A(a)?Object.fromEntries(Object.entries(a).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ie(t)])):a}u(ie,"stableJsonValue");const $t=50,$e=1;function Ve(a){return Qe("sha256").update(JSON.stringify(ie(a))).digest("base64url")}u(Ve,"digestMcpStatusValue");function Vt(a){return Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}u(Vt,"encodeMcpServerStatusCursor");function Yt(a){const e=u(()=>{throw new P("Invalid MCP server status cursor")},"fail");try{if(!/^[A-Za-z0-9_-]+$/.test(a))return e();const t=Buffer.from(a,"base64url");if(t.toString("base64url")!==a)return e();const r=JSON.parse(t.toString("utf8"));return!A(r)||Object.keys(r).length!==6||r.version!==$e||typeof r.attachmentEpoch!="string"||r.attachmentEpoch.length===0||typeof r.fingerprint!="string"||r.fingerprint.length===0||!Number.isSafeInteger(r.index)||r.index<=0||typeof r.previousName!="string"||r.previousName.length===0||typeof r.queryFingerprint!="string"||r.queryFingerprint.length===0?e():r}catch(t){if(t instanceof P)throw t;return e()}}u(Yt,"decodeMcpServerStatusCursor");function Jt(a){return{...a._meta===void 0?{}:{_meta:structuredClone(a._meta)},...a.annotations?.title===void 0?{}:{title:a.annotations.title},...a.description===void 0?{}:{description:a.description},inputSchema:structuredClone(a.inputSchema),name:a.name,...a.outputSchema===void 0?{}:{outputSchema:structuredClone(a.outputSchema)},...a.annotations===void 0?{}:{annotations:structuredClone(a.annotations)}}}u(Jt,"projectMcpServerTool");function Xt(a){const e=a.status==="available"?a.tools:[];return{authStatus:"unknown",name:a.logicalName,resourceTemplates:[],resources:[],serverInfo:null,tools:Object.fromEntries(e.map(t=>[t.name,Jt(t)]))}}u(Xt,"projectMcpServerStatus");function X(a){const e=(a.mcpServers??[]).map(t=>JSON.stringify(ie(t))).sort();return JSON.stringify({cwd:oe.resolve(a.cwd),mcpServers:e})}u(X,"sessionAttachmentKey");function Z(a){return JSON.stringify((a.additionalDirectories??[]).map(e=>oe.resolve(e)).sort())}u(Z,"additionalDirectoriesKey");function Ce(a,e){const t=A(a._meta)?{...a._meta}:a._meta;return A(t)&&(delete t.after,delete t.before),{additionalDirectories:structuredClone(a.additionalDirectories??[]),cwd:a.cwd,mcpServers:structuredClone(a.mcpServers??[]),...t===void 0?{}:{_meta:t},replayFrom:null,sessionId:e}}u(Ce,"resumeParamsForSession");function Zt(a){const e=a.session??{},t=e.prompt??{},r=A(t._meta)?t._meta:{};return{...a,session:{...e,prompt:{...t,_meta:{...r,[me]:Ee}}}}}u(Zt,"advertisePromptSteerCapability");function I(a){return AbortSignal.any([...a])}u(I,"combineSignals");function Re(){return new DOMException("The operation was aborted due to timeout","TimeoutError")}u(Re,"operationTimeoutReason");function Pe(a){return a.filter(e=>{if(!A(e.params))return!0;const t=e.params.update;return!A(t)||t.sessionUpdate!=="state_update"})}u(Pe,"withoutReplayStateUpdates");function $(a,e){if(!Number.isSafeInteger(a)||a<=0)throw new RangeError(`${e} must be a positive integer`)}u($,"assertPositiveInteger");function se(a){if((a.additionalDirectories?.length??0)>Le)throw new P(`additionalDirectories must contain at most ${Le} entries`);if((a.mcpServers?.length??0)>Ke)throw new P(`mcpServers must contain at most ${Ke} entries`)}u(se,"assertSessionSetupLimits");function D(a,e){const t=fe(a,e);if(t)throw new P(t.message);return e}u(D,"validatePublicRequest");function Qt(a){const e=D("ForkSessionRequest",a),t=Et(e._meta,!1);if(t)throw new P(t);return e}u(Qt,"validatePublicForkRequest");function xt(a){const e=D("ResumeSessionRequest",a),t=kt(e.replayFrom);if(t)throw new P(t);return e}u(xt,"validatePublicResumeRequest");function er(a){const e=D("PromptRequest",a),t=gt(e._meta);if(t)throw new P(t);return e}u(er,"validatePublicPromptRequest");function tr(a){const e=At(a);if(e)throw new P(e);return a}u(tr,"validatePublicCompactRequest");function rr(a){const e=It(a);if(e)throw new f(p.internalError,`Invalid private session/compact result: ${e}`.slice(0,L));return structuredClone(a)}u(rr,"validatePrivateCompactResponse");function ir(a){const e=tt.decodeUnknownResult(Mt,{onExcessProperty:"error",reportInput:!1})(a);if(et.isFailure(e))throw new P(`Invalid session/rewind params: ${e.failure.message}`);return e.success}u(ir,"validatePublicRewindRequest");function K(a){return a.replayFrom?.type===Ft}u(K,"isTurnReplay");function V(a,e,t){const r=Ot(a._meta,e);if(r)throw new f(p.internalError,`Invalid ${t} turn replay response: ${r}`.slice(0,L));return a}u(V,"validateTurnPageBoundary");function nr(a){if(!A(a))throw new f(p.internalError,"Invalid Host session/rewind response");if(a._meta!==void 0&&a._meta!==null&&!A(a._meta))throw new f(p.internalError,"Invalid Host session/rewind response _meta");if(Object.keys(a).some(e=>e!=="_meta"))throw new f(p.internalError,"Invalid Host session/rewind response fields");return a._meta===void 0?{}:{_meta:structuredClone(a._meta)}}u(nr,"validateHostRewindResponse");function O(a,e){const t=ht(a,e);if(t)throw new f(p.internalError,`Invalid private ACP v2 ${a}: ${t.message}`.slice(0,L));return e}u(O,"validatePrivateBoundary");function ve(a,e){const t=fe(a,e);if(t)throw new f(p.invalidRequest,`Invalid Host ACP v2 ${a}: ${t.message}`.slice(0,L));return e}u(ve,"validateHostBoundary");function U(a){return new f(p.invalidRequest,`Session ${a} is not active for this connection`)}u(U,"invalidSession");function M(a){return new f(p.invalidRequest,`Session ${a} already has active or pending work`)}u(M,"busySession");class ae extends f{static{u(this,"AttachmentBufferOverflowError")}constructor(e){super(p.overloaded,e)}}function or(a){return new f(p.invalidRequest,`Session ${a} has no active prompt that can accept steer input`)}u(or,"noActivePromptForSteer");function sr(a){return new f(p.invalidRequest,`Session ${a} active prompt request identity does not match expectedRequestId`)}u(sr,"activePromptIdentityMismatch");function Y(a){return a.deliveryMode==="drop"}u(Y,"attachmentDropped");function ar(a){return a instanceof Rt||a instanceof f&&a.code!==p.internalError}u(ar,"recoverablePrivateReplayError");function Ye(a){return!(a instanceof f&&a.code===p.internalError)}u(Ye,"recoverableHostReplayError");function ne(a,e,t="capabilities"){for(const[r,i]of Object.entries(a)){if(r==="_meta"||i===void 0||i===null)continue;const n=e[r],o=`${t}.${r}`;if(A(i)){if(!A(n))return o;const s=ne(i,n,o);if(s)return s;continue}if(n!==i)return o}}u(ne,"capabilityContains");function Q(a,e,t){return e===void 0?a:new AggregateError([a,e],t)}u(Q,"aggregateFailure");function Je(a,e){const t=a??[],r=t.findIndex(d=>d.configId==="model"),i=t.filter(d=>d.configId!=="model");if(!e)return a===void 0?void 0:i;const n=new Set(e.options.map(d=>d.value)),o=r<0?void 0:t[r],s={category:"model",configId:"model",currentValue:o?.type==="select"&&typeof o.currentValue=="string"&&n.has(o.currentValue)?o.currentValue:e.currentValue,name:"Model",options:e.options.map(d=>({...d})),type:"select"},c=[...i];return c.splice(r<0?c.length:Math.min(r,c.length),0,s),c}u(Je,"projectHostConfigOptionsForWorkspace");function cr(a,e){if(!a||!e)return a;const t=a.find(r=>r.configId==="model");return t?.type!=="select"||!Array.isArray(t.options)||t.options.length!==0?a:Je(a,e)}u(cr,"projectWorkspaceModelForEmptyChildCatalog");function dr(a){if(a===void 0)return!0;if(!A(a)||a.category!=="model"||a.configId!=="model"||a.type!=="select"||a.name!=="Model"||typeof a.currentValue!="string"||a.currentValue.length===0||!Array.isArray(a.options)||a.options.length===0)return!1;const e=new Set;for(const t of a.options){if(!A(t)||Object.keys(t).some(r=>r!=="name"&&r!=="value")||typeof t.name!="string"||t.name.length===0||typeof t.value!="string"||t.value.length===0||e.has(t.value))return!1;e.add(t.value)}return e.has(a.currentValue)}u(dr,"validWorkspaceSessionModelConfigOption");function lr(a){return Object.freeze({category:"model",configId:"model",currentValue:a.currentValue,name:"Model",options:Object.freeze(a.options.map(e=>Object.freeze({name:e.name,value:e.value}))),type:"select"})}u(lr,"cloneWorkspaceSessionModelConfigOption");class ur{static{u(this,"SessionManager")}constructor(e){this.activations=new Set,this.facadeController=new AbortController,this.managementOperations=new Set,this.ownerSignals=new WeakSet,this.profiles=new WeakMap,this.requestAdmissions=new WeakMap,this.reservations=new Map,this.sessions=new Map,this.trackedCleanup=new Set,this.workspaceProductGates=new Map,this.authMutationTail=Promise.resolve(),this.authProjection={kind:"clear",params:{generation:0}},this.closing=!1,this.childBackedProductAdmissionCount=0,this.inFlightPrivateRefreshCallbackCount=0,this.pendingProductForegroundCount=0,this.productAdmissionCount=0,this.productGate={tail:Promise.resolve()},this.clientMcp=new st,this.serverInfo=e.serverInfo,this.agentCapabilities=e.agentCapabilities,this.maxActiveSessions=e.maxActiveSessions,this.maxBufferedNotificationBytes=e.maxBufferedNotificationBytes,this.maxBufferedNotifications=e.maxBufferedNotifications,this.closeSessionTimeoutMs=e.closeSessionTimeoutMs,this.configReloadTimeoutMs=e.configReloadTimeoutMs,this.createAttachmentScope=e.createAttachmentScope,this.detachedSessionGraceMs=e.detachedSessionGraceMs,this.sessionActivationTimeoutMs=e.sessionActivationTimeoutMs,this.hostSessionControl=e.hostSessionControl,this.mcpIntegration=e.mcpIntegration,this.sessionRuntime=e.sessionRuntime,this.sessionReplay=e.sessionReplay,this.sessionService=e.sessions,this.checkpointService=e.checkpoints,this.userMcp=e.userMcp,this.pluginMcp=e.pluginMcp,this.strictMcpConfig=e.strictMcpConfig,this.subagentProjection=e.subagentProjection,this.refreshAuthentication=e.refreshAuthentication,this.schedulePostResponse=e.schedulePostResponse,this.onPermanentFailure=e.onPermanentFailure,this.processRuntime=e.processRuntime,this.prepareSessionRuntime=e.prepareSessionRuntime,this.prepareSessionWorkspace=e.prepareSessionWorkspace,this.releaseSessionWorkspace=e.releaseSessionWorkspace,this.methods=e.methods,this.productGeneration=e.initialProductGeneration,this.productGenerationRequested=e.initialProductGeneration}selectProfile(e){const t=e.client,r=t?.capabilities?.agent;if(!t||!A(r))throw new P("capabilities.agent must be an ACP v2 ClientCapabilities object");const i={capabilities:r,info:t.clientInfo,protocolVersion:2};D("InitializeRequest",i);const n=A(r.elicitation)?r.elicitation:void 0,o=A(n?.form),s=A(n?.url);if(this.mcpIntegration&&(!o||!s))throw new P("Executor-backed MCP requires elicitation.form and elicitation.url client capabilities");const d={capabilities:{...o||s?{elicitation:{...o?{form:{}}:{},...s?{url:{}}:{}}}:{}},elicitationForm:o,elicitationUrl:s};return this.profiles.set(e.connectionSignal,d),this.ownerSignals.has(e.connectionSignal)||(this.ownerSignals.add(e.connectionSignal),e.connectionSignal.addEventListener("abort",()=>{this.releaseOwner(e.connectionSignal,e.connectionSignal.reason).catch(()=>{})},{once:!0})),d}async runAdmittedSessionRequest(e,t,r){return this.runProductAdmittedRequest(t,()=>this.runSameBatchSessionRequest(e,t,r))}async runExistingWorkspaceAdmittedSessionRequest(e,t,r){const i=this.resolveAdmissionSessionId(e,t.connectionSignal),n=this.sessions.get(i),o=n!==void 0&&(n.child!==void 0||n.childStartup!==void 0);return this.runProductAdmittedRequest(t,()=>this.runSameBatchSessionRequest(e,t,async()=>{const s=this.sessions.get(i);if(!s)return r();const c=I([t.signal,t.connectionSignal,this.facadeController.signal]),d=await this.acquireExistingWorkspaceAdmission(s,c);try{return await r()}finally{d()}}),o)}async runPreparedAdmittedSessionRequest(e,t,r){const i=this.ownedReadySession(e,t.connectionSignal),n=i.resumeParams?.cwd;if(!n)throw new f(p.internalError,"Session is missing its workspace cwd");return this.runPreparedProductAdmittedRequest(t,n,o=>this.runSameBatchSessionRequest(e,t,async()=>{if(this.ownedReadySession(e,t.connectionSignal)!==i)throw U(e);const s=o?await this.rebindWorkspaceProduct(i,o,t):void 0;try{return await r()}finally{s?.()}}))}async runResumeSessionRequest(e,t){if(this.sessions.has(e.sessionId))return this.runExistingWorkspaceAdmittedSessionRequest(e.sessionId,t,()=>this.resumeSession(e,t));this.assertCanActivate(),this.claim(e.sessionId,"activating",t.connectionSignal);try{return await this.runPreparedProductAdmittedRequest(t,e.cwd,r=>this.runSameBatchSessionRequest(e.sessionId,t,()=>this.resumeSession(e,t,r,!0)),!1)}finally{const r=this.reservations.get(e.sessionId);r?.kind==="activating"&&r.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async runSameBatchSessionRequest(e,t,r){const i=t.responseCommitted;if(!i)return r();const n=this.resolveAdmissionSessionId(e,t.connectionSignal);let o=this.requestAdmissions.get(i);if(o||(o=new Map,this.requestAdmissions.set(i,o)),o.has(n))throw M(e);const s={};o.set(n,s);let c=!1;const d=u(()=>{c||(c=!0,o?.get(n)===s&&o.delete(n))},"release");try{return await r()}finally{const l=t.responseCommitted;l?l.then(d,d).catch(()=>{}):d()}}async runProductAdmittedRequest(e,t,r=!1){const i=await B("productAdmission",()=>this.acquireProductAdmission(e,r));try{return await t()}finally{i()}}async runPreparedProductAdmittedRequest(e,t,r,i=!0){const n=I([e.signal,e.connectionSignal,this.facadeController.signal]),o=this.prepareSessionRuntime;o&&await B("productResolve",()=>R(Promise.resolve().then(()=>o(n,e)),n));const s=this.prepareSessionWorkspace;if(!s)return this.runProductAdmittedRequest(e,()=>r(),i);for(let c=0;c<3;c+=1){const d=Promise.resolve().then(()=>s(t,n));let l;try{l=await B("workspacePrepare",()=>R(d,n))}catch(h){throw this.trackCleanup(d.then(m=>{m.releaseReservation()},()=>{})),h}try{this.validateWorkspaceProductLease(l);const h=this.retainWorkspaceProductPreparation(l);try{const m=await B("productAdmission",()=>this.acquireProductAdmission(e,i));if(l.productGeneration!==this.productGeneration||!l.isCurrent()){m();continue}try{await B("workspaceGenerationSync",()=>this.ensureWorkspaceProductGeneration(l,n));const y=await B("workspaceAdmission",()=>this.acquireWorkspaceProductAdmission(l,n));if(l.productGeneration!==this.productGeneration||this.workspaceProductGates.get(l.scopeKey)?.currentGeneration!==l.workspaceGeneration||!l.isCurrent()){y();continue}h();try{return await r(l)}finally{y()}}finally{m()}}finally{h()}}finally{l.releaseReservation()}}throw new f(p.notReady,"Workspace Product changed during request admission")}validateWorkspaceProductLease(e){if(!e||typeof e.cacheKey!="string"||e.cacheKey.length===0||typeof e.canonicalCwd!="string"||!oe.isAbsolute(e.canonicalCwd)||oe.resolve(e.canonicalCwd)!==e.canonicalCwd||typeof e.scopeKey!="string"||e.scopeKey.length===0||!Number.isSafeInteger(e.workspaceGeneration)||e.workspaceGeneration<1||!Number.isSafeInteger(e.productGeneration)||e.productGeneration<1||e.launch.productGeneration!==e.productGeneration||typeof e.isCurrent!="function"||typeof e.retainReservation!="function"||typeof e.releaseReservation!="function"||!dr(e.sessionModelConfigOption))throw new Error("Workspace Product resolver returned an invalid lease")}bindWorkspaceProduct(e,t){const r=e.workspaceProduct;e.workspaceProduct=Object.freeze({product:t.product,productGeneration:t.productGeneration,canonicalCwd:t.canonicalCwd,launch:t.launch,retainReservation:t.retainReservation,releaseReservation:t.retainReservation(),...t.sessionModelConfigOption===void 0?{}:{sessionModelConfigOption:lr(t.sessionModelConfigOption)},scopeKey:t.scopeKey,workspaceGeneration:t.workspaceGeneration}),r?.releaseReservation()}workspaceProductBindingMatches(e,t){return e.productGeneration===t.productGeneration&&e.canonicalCwd===t.canonicalCwd&&e.workspaceGeneration===t.workspaceGeneration&&e.scopeKey===t.scopeKey&&e.launch.bootstrapFile===t.launch.bootstrapFile&&e.launch.bootstrapSha256===t.launch.bootstrapSha256&&e.launch.productGeneration===t.launch.productGeneration}async rebindWorkspaceProduct(e,t,r){if(e.workspaceProductRebindInFlight)throw M(e.sessionId??"unknown");const i=e.workspaceProduct;if(i&&this.workspaceProductBindingMatches(i,t))return this.bindWorkspaceProduct(e,t),()=>{};const n=I([r.signal,r.connectionSignal,this.facadeController.signal]);await this.awaitBarrier(e,n),this.assertSessionStillReady(e,r);const o=e.workspaceProduct;if(o&&this.workspaceProductBindingMatches(o,t))return this.bindWorkspaceProduct(e,t),()=>{};if(e.workspaceProductRebindInFlight||!this.productChildIsIdle(e))throw M(e.sessionId??"unknown");e.workspaceProductRebindInFlight=!0;const s=de(()=>{e.workspaceProductRebindInFlight=!1}),c=o?.scopeKey;try{const d=e.child;if(d?await this.retireChildForProductGeneration(e,d,new Error("Agent session child retiring for workspace Product rebind")):o&&this.clearWorkspaceProductBinding(e),this.assertSessionStillReady(e,r),await this.rebindWorkspaceMcpAttachment(e,t.canonicalCwd,r,n),n.aborted)throw E(n);return this.assertSessionStillReady(e,r),this.bindWorkspaceProduct(e,t),s}catch(d){throw s(),d}finally{c!==void 0&&this.maybeReleaseWorkspaceScope(c)}}clearWorkspaceProductBinding(e){const t=e.workspaceProduct;e.workspaceProduct=void 0,t?.releaseReservation()}releaseWorkspaceProductBinding(e){const t=e.workspaceProduct?.scopeKey;this.clearWorkspaceProductBinding(e),t!==void 0&&this.maybeReleaseWorkspaceScope(t)}workspaceProductGate(e){const t=this.workspaceProductGates.get(e.scopeKey);if(t)return t;const r=[];for(const o of this.activations){const s=o.workspaceProduct;o.child!==void 0&&s!==void 0&&s.scopeKey===e.scopeKey&&s.productGeneration===e.productGeneration&&r.push(s.workspaceGeneration)}const i=r.length===0?e.workspaceGeneration:Math.min(...r),n={admissionCount:0,currentGeneration:i,preparationCount:0,requestedGeneration:i,tail:Promise.resolve()};return this.workspaceProductGates.set(e.scopeKey,n),n}retainWorkspaceProductPreparation(e){const t=this.workspaceProductGate(e);return t.preparationCount+=1,de(()=>{t.preparationCount-=1,this.maybeReleaseWorkspaceScope(e.scopeKey)})}async ensureWorkspaceProductGeneration(e,t){const r=this.workspaceProductGate(e);if(e.workspaceGeneration<r.currentGeneration)throw new f(p.notReady,"Workspace Product lease is stale");if(e.workspaceGeneration===r.currentGeneration)return;if(r.transition&&r.requestedGeneration>=e.workspaceGeneration)return await R(r.transition,t),this.ensureWorkspaceProductGeneration(e,t);r.requestedGeneration=e.workspaceGeneration;const i=e.retainReservation(),n=Ie(r,()=>this.performWorkspaceProductRotation(e,r)),o=u(()=>{try{this.maybeReleaseWorkspaceScope(e.scopeKey)}finally{i()}},"settleTransition");this.trackCleanup(n.then(o,o)),await R(n,t)}async performWorkspaceProductRotation(e,t){t.admissionCount>0&&(t.drained??=Promise.withResolvers(),await t.drained.promise);const r=[...this.activations].filter(c=>c.workspaceProduct?.scopeKey===e.scopeKey&&c.workspaceProduct?.productGeneration===e.productGeneration&&c.foreground&&c.productForegroundDrain!==void 0).map(c=>c.productForegroundDrain.promise);await Promise.all(r);const i=new Error(`Agent session child retiring for workspace Product generation ${e.workspaceGeneration}`),n=[];for(const c of[...this.activations]){const d=c.child,l=c.workspaceProduct;if(d&&l&&l.scopeKey===e.scopeKey&&l.productGeneration===e.productGeneration&&l.workspaceGeneration!==e.workspaceGeneration){const h=this.retireChildForProductGeneration(c,d,i);h.catch(()=>{}),n.push(h)}}t.currentGeneration=e.workspaceGeneration,await Promise.resolve(this.releaseSessionWorkspace?.(e.scopeKey,e.workspaceGeneration)).catch(()=>{});const s=(await Promise.allSettled(n)).filter(c=>c.status==="rejected");if(s.length===1)throw s[0].reason;if(s.length>1)throw new AggregateError(s.map(c=>c.reason),"Workspace Product child retirement failed")}acquireWorkspaceProductAdmission(e,t){const r=this.workspaceProductGate(e);return this.acquireWorkspaceGateAdmission(e.scopeKey,r,t)}acquireWorkspaceGateAdmission(e,t,r){return t.transition?R(t.transition.then(()=>{},()=>{}),r).then(()=>{const i=this.workspaceProductGates.get(e);return i?this.acquireWorkspaceGateAdmission(e,i,r):()=>{}}):(t.admissionCount+=1,de(()=>{t.admissionCount-=1,t.admissionCount===0&&(t.drained?.resolve(),t.drained=void 0,this.maybeReleaseWorkspaceScope(e))}))}acquireExistingWorkspaceAdmission(e,t){if(e.child===void 0&&e.childStartup===void 0)return()=>{};const r=e.workspaceProduct?.scopeKey,i=r?this.workspaceProductGates.get(r):void 0;return!r||!i?()=>{}:i.transition?R(i.transition.then(()=>{},()=>{}),t).then(()=>this.acquireExistingWorkspaceAdmission(e,t)):this.acquireWorkspaceGateAdmission(r,i,t)}maybeReleaseWorkspaceScope(e){for(const i of this.activations)if(i.workspaceProduct?.scopeKey===e)return;const t=this.workspaceProductGates.get(e);if(t&&(t.admissionCount>0||t.preparationCount>0||t.transition)||(this.workspaceProductGates.delete(e),!this.releaseSessionWorkspace))return;const r=Promise.resolve(this.releaseSessionWorkspace(e)).then(()=>{});this.trackCleanup(r.catch(()=>{}))}rotateProductGeneration(e,t=()=>Promise.resolve(),r={}){if(this.productAdmissionFailure!==void 0)return Promise.reject(new f(p.notReady,"Product generation transition failed; restart Agent Harness"));if(!Number.isSafeInteger(e)||e<=0||e<=this.productGeneration||e<=this.productGenerationRequested)return Promise.reject(new Error("Product generation must increase monotonically from a positive integer"));if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));if(r.busyPolicy==="fail_closed"&&(this.childBackedProductAdmissionCount>0||this.pendingProductForegroundCount>0||this.inFlightPrivateRefreshCallbackCount>0)){const n=new f(p.notReady,"Product state changed while Agent work depended on the prior authentication; restart Agent Harness");return this.failProductAdmissionPermanently(n),Promise.reject(n)}this.productGenerationRequested=e;const i=Ie(this.productGate,()=>this.performProductGenerationRotation(e,t,r.signal));return this.managementOperations.add(i),i.then(()=>this.managementOperations.delete(i),()=>this.managementOperations.delete(i)),i}failProductGeneration(e){this.failProductAdmissionPermanently(e)}failProductAdmissionPermanently(e){if(this.productAdmissionFailure!==void 0)return this.productAdmissionFailure;const t=e==null?new Error("Product generation transition failed"):le(e);this.productAdmissionFailure=t;try{this.onPermanentFailure?.(t)}catch{}return t}acquireProductAdmission(e,t=!1){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));if(this.productAdmissionFailure!==void 0)return Promise.reject(new f(p.notReady,"Product generation transition failed; restart Agent Harness"));const r=this.productGate.transition;if(r){const n=I([e.signal,e.connectionSignal,this.facadeController.signal]),o=r.then(()=>{},()=>{});return R(o,n).then(()=>this.acquireProductAdmission(e,t))}this.productAdmissionCount+=1,t&&(this.childBackedProductAdmissionCount+=1);let i=!1;return()=>{i||(i=!0,this.productAdmissionCount-=1,t&&(this.childBackedProductAdmissionCount-=1),this.productAdmissionCount===0&&(this.productAdmissionsDrained?.resolve(),this.productAdmissionsDrained=void 0))}}async performProductGenerationRotation(e,t,r){if(this.productAdmissionFailure!==void 0)throw new f(p.notReady,"Product generation transition failed; restart Agent Harness");const i=new Error(`Agent session child retiring for Product generation ${e}`),n=new Map,o=u((l,h)=>{if(n.has(h))return;const m=this.retireChildForProductGeneration(l,h,i);m.catch(()=>{}),n.set(h,m)},"retire");if(r===void 0)for(const l of this.activations){const h=l.child;h&&this.productChildIsIdle(l)&&o(l,h)}try{await R(this.awaitProductAdmissionsDrained(),r,"Product generation rotation aborted before commit");const l=[];for(const h of[...this.activations]){const m=h.foreground?h.productForegroundDrain:void 0;m&&l.push(m.promise)}await R(Promise.all(l).then(()=>{}),r,"Product generation rotation aborted before commit")}catch(l){throw this.reopenCancelledProductRotation(e,r),l}const s=this.reopenCancelledProductRotation(e,r);if(s)throw E(s,"Product generation rotation aborted before commit");try{if(this.productAdmissionFailure!==void 0)throw this.productAdmissionFailure;await t()}catch(l){const h=this.failProductAdmissionPermanently(l),y=(await Promise.allSettled(n.values())).filter(C=>C.status==="rejected");throw y.length===0?h:new AggregateError([h,...y.map(C=>C.reason)],"Product generation switch and idle child cleanup failed")}for(const l of[...this.activations]){const h=l.child;h&&o(l,h)}const c=await Promise.allSettled(n.values());this.productGeneration=e,this.workspaceProductGates.clear();const d=c.filter(l=>l.status==="rejected");if(d.length===1)throw d[0].reason;if(d.length>1)throw new AggregateError(d.map(l=>l.reason),"Product generation child retirement failed")}productChildIsIdle(e){const t=e.sessionId;return!e.activeOperationController&&!e.childStartup&&!e.configWriteInFlight&&!e.executorReleaseInFlight&&!e.foreground&&!e.rebinding&&!e.replayInFlight&&!e.workspaceProductRebindInFlight&&!e.closePromise&&!(t&&this.reservations.has(t))}awaitProductAdmissionsDrained(){return this.productAdmissionCount===0?Promise.resolve():(this.productAdmissionsDrained??=Promise.withResolvers(),this.productAdmissionsDrained.promise)}reopenCancelledProductRotation(e,t){if(!(!t?.aborted||this.productAdmissionFailure!==void 0))return this.productGenerationRequested===e&&(this.productGenerationRequested=this.productGeneration),t}async retireChildForProductGeneration(e,t,r){if(e.child!==t)return;await this.retireMcpStatusProjection(e);const i=e.childFailureToken??t;e.executorReleaseInFlight=!0,this.rotateReverseController(e,r),e.child=void 0,e.authReady=!1,e.childFailureToken=void 0,e.privateMcpServers=void 0,this.clearWorkspaceProductBinding(e),await e.mcpAttachment?.disconnectPeer(i);const n=Promise.resolve().then(()=>t.dispose(r));e.executorReleasePromise=n;try{await n}finally{e.executorReleasePromise===n&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async newSession(e,t,r){se(e),this.assertCanActivate(),T().set({mcpIntegrationEnabled:this.mcpIntegration!==void 0,workspaceCanonicalized:r===void 0?!1:r.canonicalCwd!==e.cwd,workspacePrepared:r!==void 0});const i=this.createActivation(t);r&&this.bindWorkspaceProduct(i,r),i.attachmentKey=X(e),this.activations.add(i);const n=this.createSessionActivationDeadline(i,[t.connectionSignal,t.signal,this.facadeController.signal,i.startupController.signal]);try{await i.attachmentScope.ready();const o=n.signal,s=i.workspaceProduct===void 0?e:{...e,cwd:i.workspaceProduct.canonicalCwd},c=await this.prepareMcpAttachment(i,s,null,o);T().set({mcpAttachmentCreated:i.mcpAttachment!==void 0});const d=i.mcpAttachment?await this.materializeNewSessionMcp(i,e,o,c):e;T().setCount("effectiveMcpServerCount",d.mcpServers?.length??0);const l=await this.spawnInitializedChild(i,e.cwd,o),h=i.workspaceProduct===void 0?d:{...d,cwd:i.workspaceProduct.canonicalCwd},m=this.validateChildBoundary(i,"NewSessionResponse",await B("privateSessionNew",()=>R(l.newSession(h,{signal:o}),o))),y=Kt(m);this.assertSessionIdentity(i,y.sessionId);const C=this.mergeSessionConfigOptions(i,y.configOptions);return i.configOptions=structuredClone(C),i.resumeParams=Ce(e,y.sessionId),this.attach(i,y.sessionId),await B("mcpStatusProjection",async()=>{await this.installMcpStatusProjection(i),this.recordSessionNewMcpCounts(i)}),this.releaseBufferedAfterResponse(i,t),{...y,configOptions:C}}catch(o){throw this.dropBuffered(i),await this.failActivation(i,o),o}finally{n.clear()}}preflightNewSession(e){se(e),this.assertCanActivate()}async forkSession(e,t){se(e),this.assertCanActivate();const r=this.sessions.get(e.sessionId);if(r){if(!r.proxy.has(t.connectionSignal))throw U(e.sessionId);if(await this.awaitBarrier(r,t.signal),r.closePromise||r.foreground||r.replayInFlight||r.configWriteInFlight||r.executorReleaseInFlight||r.childStartup||Y(r))throw M(e.sessionId)}this.claim(e.sessionId,"forking",t.connectionSignal);const i=this.createActivation(t);i.attachmentKey=X(e),this.activations.add(i);let n;try{await i.attachmentScope.ready();const o=await this.runHostSessionOperation(t,async c=>{const d=I([c,i.startupController.signal]),l=O("ForkSessionResponse",await(this.sessionService?H.runPromise(this.sessionService.fork(e,{signal:d})):this.requireHostSessionControl().forkSession(e,{signal:d})));if(l.sessionId===e.sessionId)throw new f(p.internalError,"Host session/fork returned the source sessionId");n=l.sessionId,this.claim(l.sessionId,"activating",t.connectionSignal),i.expectedSessionId=l.sessionId,i.resumeParams=Ce(e,l.sessionId),this.assertSessionIdentity(i,l.sessionId);const h=je(l.configOptions,i.pluginSettings.enabledPlugins);return i.configOptions=structuredClone(h),this.attach(i,l.sessionId),{...l,configOptions:h}},!1,this.sessionService!==void 0),s=await this.hydrateDurableProjection(i,t);return this.releaseBufferedAfterResponse(i,t,s),o}catch(o){throw this.dropBuffered(i),await this.failActivation(i,o),o}finally{for(const o of[e.sessionId,...n?[n]:[]])this.reservations.get(o)?.owner===t.connectionSignal&&this.reservations.delete(o)}}async resumeSession(e,t,r,i=!1){se(e);const n=this.sessions.get(e.sessionId);if(n)return n.detached?this.resumeDetachedSession(n,e,t):n.owner!==t.connectionSignal||!n.proxy.has(t.connectionSignal)||n.proxy.list().length>1?this.resumeConcurrentAttachment(n,e,t):this.resumeAttachedSession(n,e,t);this.assertCanActivate(),i||this.claim(e.sessionId,"activating",t.connectionSignal);const o=this.createActivation(t,e.sessionId);o.attachmentKey=X(e),o.resumeParams=Ce(e,e.sessionId),o.attached=!0,o.replayInFlight=e.replayFrom!=null,e.replayFrom!=null&&(o.compactionDeliveryEpoch={}),r&&this.bindWorkspaceProduct(o,r),this.activations.add(o);try{await o.attachmentScope.ready(),this.subagentProjection.beginAttachment(e.sessionId,t.connectionSignal);const s=I([t.connectionSignal,t.signal,this.facadeController.signal,o.startupController.signal]),c=await R(this.resumeStoredSession(o,e,{onUpdate:u(h=>this.deliverHostUpdate(o,h),"onUpdate"),signal:s}),s),d=O("ResumeSessionResponse",c.response);if(V(d,K(e),"Host"),this.assertSessionIdentity(o,e.sessionId),await o.deliveryTail,o.deliveryFailure!==void 0)throw o.deliveryFailure;if(o.replayInFlight=!1,this.sessionRuntime.readCatalog){const h=await o.attachmentScope.runEffect(this.sessionRuntime.readCatalog(e.sessionId,this.sessionOpenOptions(o,e.cwd,s,{})));for(const m of h)await this.deliverBufferedHostUpdate(o,m)}const l=this.mergeHostSessionConfigOptions(o,d.configOptions);return o.configOptions=structuredClone(l),this.attach(o,e.sessionId),this.releaseBufferedAfterResponse(o,t),{...d,configOptions:l}}catch(s){throw o.replayInFlight=!1,this.dropBuffered(o),await this.failActivation(o,s),s}finally{const s=this.reservations.get(e.sessionId);s?.kind==="activating"&&s.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async resumeConcurrentAttachment(e,t,r){const i=e.proxy.has(r.connectionSignal);if(i&&!e.proxy.has(r.connectionSignal,"live")||this.reservations.has(t.sessionId)||e.closePromise||e.rebinding||e.configWriteInFlight||e.replayInFlight||e.attachmentReplayInFlight||e.deliveryMode==="drop"||e.deliveryFailure!==void 0)throw M(t.sessionId);if(e.attachmentKey!==X(t))throw new P("session/resume cannot replace cwd or MCP setup on an active attachment");if(Z(e.resumeParams??{})!==Z(t))throw new P("session/resume cannot replace additionalDirectories while multiple clients are attached");const n=this.profile(r.connectionSignal),o=ne(e.negotiatedClientCapabilities,n.capabilities,"capabilities");if(o)throw new P(`Attached Client is missing negotiated ${o}`);if(t.replayFrom!==null&&t.replayFrom!==void 0&&t.replayFrom.type!=="start")throw new P("A concurrent session attachment must replay from start");if(i&&(t.replayFrom===null||t.replayFrom===void 0)){const m=structuredClone(e.configOptions);return m===void 0?{}:{configOptions:m}}const s=t.replayFrom?.type==="start";if(s&&(e.foreground||e.activeOperationController!==void 0))throw M(t.sessionId);const c=e.proxy.add(r,n,"replaying");if(!c)throw r.connectionSignal.aborted?E(r.connectionSignal):M(t.sessionId);s&&(e.attachmentReplayInFlight=!0);const d=u(()=>{s&&(e.attachmentReplayInFlight=!1)},"releaseReplayLock"),l=u(m=>{this.trackCleanup(this.releaseFailedProxyAttachment(e,r,m))},"fail"),h=u(m=>{if(i&&!r.connectionSignal.aborted){this.activateProxyAttachmentAfterResponse(e,r,l,d);return}d(),this.trackCleanup(this.releaseSessionAttachment(e,r.connectionSignal,m,r.connection.transport))},"restore");try{if(t.replayFrom===null||t.replayFrom===void 0){if(!i){for(const j of this.subagentProjection.snapshotStartedNotifications(t.sessionId,e.owner))if(!await e.proxy.notifyReplay(r.connectionSignal,j.method,j.params))throw E(r.connectionSignal)}const b=structuredClone(e.configOptions);return this.activateProxyAttachmentAfterResponse(e,r,l,d),b===void 0?{}:{configOptions:b}}const m=new _e({maxBufferedNotificationBytes:this.maxBufferedNotificationBytes,maxBufferedNotifications:this.maxBufferedNotifications});m.beginAttachment(t.sessionId,r.connectionSignal);const y=m.beginReplay(t.sessionId,r.connectionSignal,"replace"),C=I([r.signal,r.connectionSignal,c,e.lifecycleController.signal,this.facadeController.signal]),k=await R(this.resumeStoredSession(e,t,{onUpdate:u(async b=>{const j=O("UpdateSessionNotification",b);this.assertCallbackSessionId(e,j.sessionId);const N=this.projectConcurrentReplayUpdate(e,m,y,r.connectionSignal,j);for(const _ of Pe(N))if(!await e.proxy.notifyReplay(r.connectionSignal,_.method,_.params))throw E(r.connectionSignal)},"onUpdate"),signal:C}),C),S=V(O("ResumeSessionResponse",k.response),K(t),"Host");m.commitReplay(y,r.connectionSignal);const F=this.mergeHostSessionConfigOptions(e,S.configOptions);return this.activateProxyAttachmentAfterResponse(e,r,l,d),{...S,configOptions:F}}catch(m){throw h(m),m}}activateProxyAttachmentAfterResponse(e,t,r,i){const n=u(async()=>{try{await e.proxy.activate(t.connectionSignal)}catch{}finally{i?.()}},"activate");if(t.responseCommitted){t.responseCommitted.then(n,o=>{i?.(),r(o)}).catch(()=>{});return}this.schedulePostResponseTask(n,"Agent Harness concurrent resume is missing its response-commit boundary",o=>{i?.(),r(o)})}async releaseFailedProxyAttachment(e,t,r){t.connection.transport==="stdio"&&e.proxy.list().length===0&&(e.deliveryFailure??=r),await this.releaseSessionAttachment(e,t.connectionSignal,r,t.connection.transport);const i=e.sessionId;try{i&&t.closeSessionAttachment?await t.closeSessionAttachment(i,r):await t.closeConnection?.(r)}catch(n){await t.closeConnection?.(n)}}async resumeDetachedSession(e,t,r){const i=e.detached;if(!i||e.owner===r.connectionSignal||e.rebinding||e.closePromise||e.configWriteInFlight||e.replayInFlight||e.attachmentReplayInFlight||e.deliveryMode!=="buffer"||e.deliveryFailure!==void 0)throw M(t.sessionId);const n=this.prepareDetachedResume(e,t,r),o=this.profile(r.connectionSignal),s=e.owner,c=this.subagentProjection.beginRebind(t.sessionId,s,r.connectionSignal);let d;try{d=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,K(t)?"merge_history":"replace")}catch(y){throw e.proxy.remove(r.connectionSignal),this.subagentProjection.abortRebind(c,r.connectionSignal),y}if(!e.proxy.add(r,o))throw this.subagentProjection.abortReplay(d,r.connectionSignal),this.subagentProjection.abortRebind(c,r.connectionSignal),E(r.connectionSignal);const l={compactions:new Map([...e.compactions].map(([y,C])=>[y,{...C}])),detachedExpiresAt:i.expiresAt,detachedOwner:s,detachedOwnerContext:e.ownerContext,detachedReason:i.reason,negotiatedClientCapabilities:e.negotiatedClientCapabilities,projection:c,replay:d};i.timer.cancel(),e.compactionDeliveryEpoch={},e.rebinding=!0,e.rebindProjection=c,e.replayProjection=d,e.replayInFlight=!0,e.replayResponsePending=!1,e.owner=r.connectionSignal,e.ownerContext=r,e.negotiatedClientCapabilities=structuredClone(o.capabilities),e.rebindLiveNotifications=e.bufferedNotifications,e.bufferedNotifications=[],e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=n,e.reconnectRootTerminalMatched=!1,this.rotateDeliveryGeneration(e);const h=e.attachmentScope.makeController();e.replayController=h;const m=I([r.signal,r.connectionSignal,h.signal,e.lifecycleController.signal,this.facadeController.signal]);try{const y=await R(this.resumeStoredSession(e,t,{onUpdate:u(S=>this.deliverHostUpdate(e,S),"onUpdate"),signal:m}),m),C=O("ResumeSessionResponse",y.response);if(V(C,K(t),"Host"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;this.subagentProjection.commitReplay(d,r.connectionSignal),e.replayProjection=void 0;const k=this.mergeHostSessionConfigOptions(e,C.configOptions);return e.configOptions=structuredClone(k),this.releaseDetachedRebindAfterResponse(e,r,l),{...C,configOptions:k}}catch(y){throw this.rollbackDetachedRebind(e,l,y),y}}prepareDetachedResume(e,t,r){if(t.replayFrom==null)throw new P("A detached session must be resumed with an authoritative replay selector");if(t.replayFrom.type!=="start")throw new P("A detached session must be resumed from the authoritative start snapshot");if(e.attachmentKey!==X(t))throw new P("session/resume cannot replace cwd or MCP setup while reconnecting");if(Z(e.resumeParams??{})!==Z(t))throw new P("session/resume cannot replace additionalDirectories while reconnecting");const i=new _t({maxBytes:this.maxBufferedNotificationBytes,maxEntries:this.maxBufferedNotifications});for(const s of e.bufferedNotifications){const c=s.privateLiveUpdate?.notification;if(!c)throw new f(p.internalError,"Reconnect live suffix contained an already-projected notification");i.trackLive(c)}const n=this.profile(r.connectionSignal),o=ne(e.negotiatedClientCapabilities,n.capabilities,"capabilities");if(o)throw new P(`Reconnect Client is missing negotiated ${o}`);return i}async resumeAttachedSession(e,t,r){if(!e.proxy.has(r.connectionSignal)||e.closePromise||this.reservations.has(t.sessionId)||e.deliveryMode==="drop"||e.configWriteInFlight)throw M(t.sessionId);if(e.attachmentKey!==X(t))throw new P("session/resume cannot replace cwd or MCP setup on an active attachment");const i=Z(e.resumeParams??{})!==Z(t);if(t.replayFrom==null){if(i)return this.refreshAttachedSessionSetup(e,t,r);const d=structuredClone(e.configOptions);return d===void 0?{}:{configOptions:d}}if(e.foreground||e.replayInFlight)throw M(t.sessionId);if(!e.child)return this.resumeDormantSession(e,t,r);if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Y(e)||e.foreground||e.replayInFlight||e.configWriteInFlight)throw M(t.sessionId);const n=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,K(t)?"merge_history":"replace");e.compactionDeliveryEpoch={};const o=e.attachmentScope.makeController();e.replayController=o,e.replayInFlight=!0,e.replayProjection=n,e.replayResponsePending=!0;try{this.holdNotifications(e,r.responseCommitted)}catch(d){throw this.subagentProjection.abortReplay(n,r.connectionSignal),this.clearReplayController(e,o),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,d}const s=this.requireChild(e),c=u(()=>{this.clearReplayController(e,o),e.replayInFlight=!1,e.replayResponsePending=!1},"finishAfterResponse");try{const d=await s.resumeSession(this.projectResumeSessionMcp(e,t),{signal:I([r.signal,r.connectionSignal,o.signal])});e.replayResponsePending=!1;const h=this.validateChildBoundary(e,"ResumeSessionResponse",d);if(V(h,K(t),"private ACP v2 child"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;this.subagentProjection.commitReplay(n,r.connectionSignal),e.replayProjection=void 0;const m=this.mergeSessionConfigOptions(e,h.configOptions);return e.configOptions=structuredClone(m),this.commitAdditionalDirectories(e,t),this.releaseBufferedAfterResponse(e,r,c),{...h,configOptions:m}}catch(d){return e.replayResponsePending=!1,e.replayProjection===n&&(this.subagentProjection.abortReplay(n,r.connectionSignal),e.replayProjection=void 0),this.settleFailedReplay(e,d,c,{aggregateMessage:"Replay request and response boundary both failed",recoverable:ar(d),releaseBoundary:u(()=>this.releaseBufferedAfterResponse(e,r,c),"releaseBoundary")})}}async failReplayTerminally(e,t,r){throw r(),e.deliveryMode==="buffer"&&this.dropBuffered(e),e.attached&&await this.failActivation(e,t),t}async settleFailedReplay(e,t,r,i){if(i.recoverable&&e.deliveryFailure===void 0&&e.attached&&this.activations.has(e)&&e.deliveryMode==="buffer"){try{i.releaseBoundary()}catch(o){throw r(),e.attached&&await this.failActivation(e,o),Q(t,o,i.aggregateMessage)}throw t}return this.failReplayTerminally(e,t,r)}async refreshAttachedSessionSetup(e,t,r){if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Y(e)||e.foreground||e.replayInFlight||e.configWriteInFlight||e.childStartup)throw M(t.sessionId);const i=e.attachmentScope.makeController();e.replayController=i,e.replayInFlight=!0;try{this.holdNotifications(e,r.responseCommitted)}catch(l){throw this.clearReplayController(e,i),e.replayInFlight=!1,l}const n=u(()=>{this.clearReplayController(e,i),e.replayInFlight=!1},"finishAfterResponse"),o=I([r.signal,r.connectionSignal,i.signal,this.facadeController.signal]),s=e.child,c=structuredClone(e.configOptions),d=e.resumeParams;try{let l;if(s)l=this.validateChildBoundary(e,"ResumeSessionResponse",await R(s.resumeSession(this.projectResumeSessionMcp(e,{...t,additionalDirectories:[...t.additionalDirectories??[]],replayFrom:null}),{signal:o}),o));else{const m=await R(this.resumeStoredSession(e,{...t,additionalDirectories:[...t.additionalDirectories??[]],replayFrom:null},{onUpdate:u(y=>this.deliverBufferedHostUpdate(e,y),"onUpdate"),signal:o}),o);l=O("ResumeSessionResponse",m.response)}if(V(l,!1,s?"private ACP v2 child":"Host"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;const h=this.mergeHostSessionConfigOptions(e,l.configOptions);return e.configOptions=structuredClone(h),this.commitAdditionalDirectories(e,t),this.releaseBufferedAfterResponse(e,r,n),{...l,configOptions:h}}catch(l){if(e.configOptions=c,e.resumeParams=d,s){try{await this.releaseExecutorForRewind(e,l)}catch(h){const m=Q(l,h,"Session setup refresh and private child cleanup failed");return this.failReplayTerminally(e,m,n)}throw this.discardBufferedAfterResponse(e,r,n),l}return this.settleFailedReplay(e,l,n,{aggregateMessage:"Session setup refresh and response boundary both failed",recoverable:Ye(l),releaseBoundary:u(()=>this.discardBufferedAfterResponse(e,r,n),"releaseBoundary")})}}async resumeDormantSession(e,t,r){if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Y(e)||e.foreground||e.replayInFlight||e.configWriteInFlight||e.child)throw M(t.sessionId);const i=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,K(t)?"merge_history":"replace");e.compactionDeliveryEpoch={};const n=e.attachmentScope.makeController();e.replayController=n,e.replayInFlight=!0,e.replayProjection=i;try{this.holdNotifications(e,r.responseCommitted)}catch(c){throw this.subagentProjection.abortReplay(i,r.connectionSignal),this.clearReplayController(e,n),e.replayInFlight=!1,e.replayProjection=void 0,c}const o=u(()=>{this.clearReplayController(e,n),e.replayInFlight=!1},"finishAfterResponse"),s=I([r.signal,r.connectionSignal,n.signal,this.facadeController.signal]);try{const c=await R(this.resumeStoredSession(e,t,{onUpdate:u(h=>this.deliverHostUpdate(e,h),"onUpdate"),signal:s}),s),d=O("ResumeSessionResponse",c.response);if(V(d,K(t),"Host"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;this.subagentProjection.commitReplay(i,r.connectionSignal),e.replayProjection=void 0;const l=this.mergeHostSessionConfigOptions(e,d.configOptions);return e.configOptions=structuredClone(l),this.commitAdditionalDirectories(e,t),this.releaseBufferedAfterResponse(e,r,o),{...d,configOptions:l}}catch(c){return e.replayProjection===i&&(this.subagentProjection.abortReplay(i,r.connectionSignal),e.replayProjection=void 0),this.settleFailedReplay(e,c,o,{aggregateMessage:"Replay request and response boundary both failed",recoverable:Ye(c),releaseBoundary:u(()=>this.releaseBufferedAfterResponse(e,r,o),"releaseBoundary")})}}async hydrateDurableProjection(e,t){const r=e.sessionId,i=e.resumeParams;if(!r||!i)throw new f(p.internalError,"Active session is missing its durable resume setup");if(e.deliveryMode!=="buffer")throw new f(p.internalError,"Durable projection hydration requires a pending response boundary");const n=this.subagentProjection.beginReplay(r,t.connectionSignal,"replace"),o=e.attachmentScope.makeController();e.replayController=o,e.replayInFlight=!0,e.replayProjection=n,e.replayResponsePending=!0;const s=u(()=>{this.clearReplayController(e,o),e.replayInFlight=!1,e.replayResponsePending=!1},"finishAfterResponse"),c=I([t.signal,t.connectionSignal,o.signal,this.facadeController.signal,e.startupController.signal]);try{const d=await R(this.resumeStoredSession(e,{...i,replayFrom:{type:"start"}},{onUpdate:u(h=>this.projectDurableSnapshotUpdate(e,h),"onUpdate"),signal:c}),c),l=V(O("ResumeSessionResponse",d.response),!1,"Host");if(e.deliveryFailure!==void 0)throw e.deliveryFailure;return this.subagentProjection.commitReplay(n,t.connectionSignal),e.replayProjection=void 0,e.configOptions=structuredClone(this.mergeHostSessionConfigOptions(e,l.configOptions)),s}catch(d){throw e.replayProjection===n&&(this.subagentProjection.abortReplay(n,t.connectionSignal),e.replayProjection=void 0),s(),d}}async listMcpServerStatuses(e,t){const r=this.ownedReadySession(e.threadId,t.connectionSignal),i=this.mcpOperationSignal(r,t);await this.awaitBarrier(r,i),this.assertSessionStillReady(r,t);const{attachment:n,cursorEpoch:o}=this.requireMaterializedMcpAttachment(r),s=n.listServerStatuses(),c=s.map(Xt),d=Ve({detail:e.detail??null,threadId:e.threadId}),l=Ve(s);let h=0;if(e.cursor){const C=Yt(e.cursor);if(C.attachmentEpoch!==o||C.fingerprint!==l||C.queryFingerprint!==d||C.index>c.length||c[C.index-1]?.name!==C.previousName)throw new P("MCP server status cursor no longer matches this attachment snapshot");h=C.index}const m=e.limit??$t,y=Math.min(h+m,c.length);return{data:c.slice(h,y),nextCursor:y<c.length?Vt({attachmentEpoch:o,fingerprint:l,index:y,previousName:c[y-1].name,queryFingerprint:d,version:$e}):null}}async callMcpServerTool(e,t){if(e._meta!==void 0)throw new P("MCP tool-call request _meta is not supported");const r=this.ownedReadySession(e.threadId,t.connectionSignal),i=this.mcpOperationSignal(r,t);await this.awaitBarrier(r,i),this.assertSessionStillReady(r,t);const{attachment:n}=this.requireMaterializedMcpAttachment(r),o=n.listServerStatuses().find(s=>s.logicalName===e.server);if(!o)throw new P(`Unknown MCP server "${e.server}"`);if(o.status!=="available")throw new f(p.notReady,`MCP server "${e.server}" is unavailable`);if(!o.tools.some(s=>s.name===e.tool))throw new P(`Unknown MCP tool "${e.tool}" for server "${e.server}"`);try{const s=await n.callTool(e.server,e.tool,e.arguments===void 0?{}:e.arguments,i);return{...s._meta===void 0?{}:{_meta:structuredClone(s._meta)},content:structuredClone(s.content),...s.isError===void 0?{}:{isError:s.isError},...s.structuredContent===void 0?{}:{structuredContent:structuredClone(s.structuredContent)}}}catch(s){if(s instanceof f)throw s;if(s instanceof at||s instanceof ct)throw new f(p.notReady,`MCP server "${e.server}" is unavailable`);const c=le(s).message;throw c.startsWith("Unknown MCP server ")||c.startsWith("MCP tool ")?new P(`MCP server "${e.server}" does not expose tool "${e.tool}"`):new f(p.internalError,"MCP tool call failed")}}async listSubagents(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);await this.awaitBarrier(r,t.signal),this.assertSessionStillReady(r,t);const i=r.resumeParams&&this.sessionReplay?.subagents?await this.sessionReplay.subagents.list({sessionId:e.sessionId,cwd:r.resumeParams.cwd},this.mcpOperationSignal(r,t)):[];await this.awaitBarrier(r,t.signal),this.assertSessionStillReady(r,t);const n=this.subagentProjection.listSubagents(e.sessionId,r.owner),o=new Map(i.map(s=>[s.sessionId,s]));for(const s of n.subagents)o.set(s.sessionId,s);return{subagents:[...o.values()]}}async readSubagent(e,t){const r=await this.resolveStoredSubagent(e.sessionId,t),{current:i,session:n}=r??await this.resolveSubagentAfterBoundary(e.sessionId,t);if(e.replayFrom==null)return{subagent:i.subagent};const o=r?.stored??(n.resumeParams&&this.sessionReplay?.subagents?await this.sessionReplay.subagents.read({sessionId:i.rootSessionId,cwd:n.resumeParams.cwd,workspace:n.workspaceProduct},e.sessionId,this.mcpOperationSignal(n,t)):void 0);await this.settleSubagentResponseBoundary(n,t);const s=this.subagentProjection.rootSessionIdFor(e.sessionId)===i.rootSessionId?this.subagentProjection.snapshotRead(e.sessionId,n.owner):void 0,c={rootSessionId:i.rootSessionId,subagent:s?.subagent??o?.subagent??i.subagent,journal:o?qt(o.journal,s?.journal??[]):s?.journal??[]},d=this.profile(t.connectionSignal);if(!n.proxy.add(t,d,"replaying"))throw t.connectionSignal.aborted?E(t.connectionSignal):M(c.rootSessionId);try{for(const l of c.journal)if(!await n.proxy.notifyReplay(t.connectionSignal,this.methods.client.session.update,l))throw E(t.connectionSignal);return this.activateProxyAttachmentAfterResponse(n,t,l=>this.trackCleanup(this.releaseFailedProxyAttachment(n,t,l))),{subagent:c.subagent}}catch(l){throw await n.proxy.activate(t.connectionSignal),l}}listSessions(e,t){return this.runHostSessionOperation(t,async r=>O("ListSessionsResponse",await(this.sessionService?H.runPromise(this.sessionService.list(e,{signal:r})):this.requireHostSessionControl().listSessions(e,{signal:r}))))}listCheckpoints(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?H.runPromise(this.checkpointService.list(e,{signal:r})):this.requireHostSessionControl().listCheckpoints(e,{signal:r}))}readCheckpoint(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?H.runPromise(this.checkpointService.read(e,{signal:r})):this.requireHostSessionControl().readCheckpoint(e,{signal:r}))}restoreCheckpoint(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?H.runPromise(this.checkpointService.restore(e,{signal:r})):this.requireHostSessionControl().restoreCheckpoint(e,{signal:r}),!0)}async runCheckpointOperation(e,t,r,i=!1){const n=this.sessions.get(e);if(n){if(!n.proxy.has(t.connectionSignal))throw U(e);if(await this.awaitBarrier(n,t.signal),n.closePromise||n.foreground||n.replayInFlight||n.attachmentReplayInFlight||n.configWriteInFlight||n.executorReleaseInFlight||n.childStartup||Y(n))throw M(e)}this.claim(e,"checkpointing",t.connectionSignal);try{if(!i)return await this.runHostSessionOperation(t,r);if(!n)return await this.runHostSessionOperation(t,r,!0,this.checkpointService!==void 0);this.holdNotifications(n,t.responseCommitted);try{await this.releaseExecutorForRewind(n,new Error("Session checkpoint restoring"))}catch(s){throw this.dropBuffered(n),await this.failActivation(n,s),s}this.discardBufferedNotifications(n);let o;try{o=await this.runHostSessionOperation(t,r,!0,this.checkpointService!==void 0)}catch(s){try{this.discardBufferedAfterResponse(n,t)}catch(c){throw await this.failActivation(n,c),Q(s,c,"Checkpoint restore and response boundary both failed")}throw s}try{this.discardBufferedAfterResponse(n,t)}catch(s){throw await this.failActivation(n,s),s}return o}finally{const o=this.reservations.get(e);o?.kind==="checkpointing"&&o.owner===t.connectionSignal&&this.reservations.delete(e)}}async deleteSession(e,t){const r=this.sessions.get(e.sessionId),i=r?.proxy.list().map(n=>n.context)??[];if(r&&r.attachmentReplayInFlight)throw M(e.sessionId);if(r&&!r.proxy.has(t.connectionSignal)&&(!r.detached||r.rebinding))throw U(e.sessionId);this.claim(e.sessionId,"deleting",t.connectionSignal);try{return r&&await this.closeAttached(r,e,!0),await this.runHostSessionOperation(t,async n=>O("DeleteSessionResponse",await(this.sessionService?H.runPromise(this.sessionService.delete(e,{signal:n})):this.requireHostSessionControl().deleteSession(e,{signal:n}))),!1,this.sessionService!==void 0)}finally{this.scheduleClosedAttachmentRoutes(e.sessionId,i,t);const n=this.reservations.get(e.sessionId);n?.kind==="deleting"&&n.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async rewindSession(e,t){const r=this.ownedSession(e.sessionId,t.connectionSignal);if(await this.awaitBarrier(r,t.signal),r.closePromise||r.foreground||r.replayInFlight||r.attachmentReplayInFlight||r.configWriteInFlight||r.executorReleaseInFlight||r.childStartup||Y(r))throw M(e.sessionId);const i=r.resumeParams;if(!i)throw new f(p.internalError,"Active session is missing its durable resume setup");this.claim(e.sessionId,"rewinding",t.connectionSignal),this.holdNotifications(r,t.responseCommitted);try{try{await this.releaseExecutorForRewind(r,new Error("Session rewinding"))}catch(s){throw this.dropBuffered(r),await this.failActivation(r,s),s}let n;try{const s=this.sessionRuntime.rewind;t.signal.throwIfAborted(),n=await this.runHostSessionOperation(t,async c=>nr(s?await r.attachmentScope.runEffect(s(e,{cwd:i.cwd,signal:c})):await this.requireHostSessionControl().rewindSession(e,{signal:c})),s!==void 0)}catch(s){throw this.releaseBufferedAfterResponse(r,t),s}await this.closeAttachmentDescendantRoutes(r,e.sessionId,t.connectionSignal);let o;try{o=await this.hydrateDurableProjection(r,t)}catch(s){throw r.deliveryFailure??=s,this.handleChildFailure(r,s),s}try{this.releaseBufferedAfterResponse(r,t,o)}catch(s){throw o(),r.deliveryFailure??=s,this.handleChildFailure(r,s),s}return n}finally{const n=this.reservations.get(e.sessionId);n?.kind==="rewinding"&&n.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async runForegroundOperation(e,t,r,i,n){e.foreground=!0,e.acknowledgedRequestId=void 0,r==="compact"&&(e.activeCompactionId=void 0),e.activeForegroundAccepted=!1,e.activeResponseCommitted=t.responseCommitted,e.activeRequestId=void 0;const o=this.beginActiveOperation(e,r),s=u(()=>{this.finishActiveOperation(e,o),this.rotateReverseController(e,new Error(i.failed))},"finishAfterResponse");try{const c=await this.ensureExecutor(e,t,o.signal);if(this.assertSessionStillReady(e,t),e.deliveryFailure!==void 0)throw e.deliveryFailure;this.rotateReverseController(e,new Error(i.start)),this.holdOrContinueActivationBoundary(e,t.responseCommitted);const d=I([t.signal,t.connectionSignal,e.reverseController.current.signal]),l=new AbortController,h=u(()=>l.abort(E(d)),"abortAdmission");d.addEventListener("abort",h,{once:!0}),d.aborted&&h();const m=I([l.signal,o.signal]);let y;try{m.throwIfAborted(),y=await n(c,m)}finally{d.removeEventListener("abort",h)}return e.activeForegroundAccepted=!0,this.releaseBufferedAfterResponse(e,t),y}catch(c){throw this.resolveProductForeground(e),e.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(e,t,s):s(),c}}async compactSession(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);if(r.foreground||r.replayInFlight||r.configWriteInFlight||(await this.awaitBarrier(r,t.signal),r.foreground||r.replayInFlight||r.configWriteInFlight))throw M(e.sessionId);return this.runForegroundOperation(r,t,"compact",{failed:"Manual compaction failed",start:"Starting manual compaction"},async(i,n)=>{const o=await i.compactSession(e,{signal:n});if(r.deliveryFailure!==void 0)throw r.deliveryFailure;const s=this.withPrivateBoundaryContainment(r,()=>rr(o));return this.captureActiveRequestId(r,s._meta,"session/compact result"),s})}async closeSession(e,t){const r=this.ownedSession(e.sessionId,t.connectionSignal),i=r.proxy.list().map(o=>o.context);let n=[];if(r.mcpStatusUnsubscribe&&r.mcpAttachment&&r.privateMcpServers!==void 0)try{n=r.mcpAttachment.listServerStatuses()}catch{}this.claim(e.sessionId,"closing",t.connectionSignal);try{const o=await this.closeAttached(r,e,!0);return this.scheduleClosedMcpStatusNotifications(e.sessionId,n,t),o}finally{this.scheduleClosedAttachmentRoutes(e.sessionId,i,t);const o=this.reservations.get(e.sessionId);o?.kind==="closing"&&o.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}scheduleClosedMcpStatusNotifications(e,t,r){if(t.length===0)return;const i=u(async()=>{r.connectionSignal.aborted||await Promise.all(t.map(n=>r.notify(ue.mcpServer.startupStatus.updated,this.mcpStatusNotification(e,n,"cancelled"))))},"deliver");if(r.responseCommitted){r.responseCommitted.then(i).catch(()=>{});return}try{this.schedulePostResponse?.(i)}catch{}}scheduleClosedAttachmentRoutes(e,t,r){const i=t.filter(o=>o.closeSessionAttachment!==void 0);if(i.length===0)return;const n=u(async()=>{const o=new Error("Session closed");await Promise.all(i.map(async s=>{try{await s.closeSessionAttachment?.(e,o)}catch(c){await s.closeConnection?.(c)}}))},"close");if(r.responseCommitted){r.responseCommitted.then(n,n).catch(()=>{});return}try{this.schedulePostResponse?.(n)}catch{}}async closeAttachmentDescendantRoutes(e,t,r){await Promise.all(e.proxy.list().map(async i=>{const n=i.context;if(n.connectionSignal!==r)try{await n.closeSessionDescendants?.(t)}catch(o){await n.closeConnection?.(o)}}))}async setSessionConfigOption(e,t){let r;try{r=St(e)}catch(s){throw new P(le(s).message)}if(r!==void 0)return this.setSessionEnabledPlugins(e,r,t);const i=this.ownedReadySession(e.sessionId,t.connectionSignal);if(await this.awaitBarrier(i,t.signal),i.foreground||i.replayInFlight||i.configWriteInFlight)throw M(e.sessionId);i.configWriteInFlight=!0;const n=this.beginActiveOperation(i,"config"),o=u(()=>{this.finishActiveOperation(i,n)},"finishAfterResponse");try{const s=await this.ensureExecutor(i,t,n.signal);if(this.assertSessionStillReady(i,t),i.deliveryFailure!==void 0)throw i.deliveryFailure;this.holdOrContinueActivationBoundary(i,t.responseCommitted);const c=I([t.signal,t.connectionSignal,n.signal]);if(c.aborted)throw E(c);const d=await R(s.setSessionConfigOption(e,{signal:c}),c);if(i.deliveryFailure!==void 0)throw i.deliveryFailure;const l=this.validateChildBoundary(i,"SetSessionConfigOptionResponse",d),h=this.mergeSessionConfigOptions(i,l.configOptions);return i.configOptions=structuredClone(h),this.releaseBufferedAfterResponse(i,t,o),{...l,configOptions:h}}catch(s){throw i.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(i,t,o):o(),s}}async setSessionEnabledPlugins(e,t,r){const i=this.ownedReadySession(e.sessionId,r.connectionSignal);if(await this.awaitBarrier(i,r.signal),i.foreground||i.replayInFlight||i.configWriteInFlight||i.executorReleaseInFlight||i.childStartup)throw M(e.sessionId);i.configWriteInFlight=!0;const n=this.beginActiveOperation(i,"config"),o=u(()=>{this.finishActiveOperation(i,n)},"finishAfterResponse");try{this.assertSessionStillReady(i,r),this.holdOrContinueActivationBoundary(i,r.responseCommitted);const s=I([r.signal,r.connectionSignal,n.signal,i.lifecycleController.signal,this.facadeController.signal]);if(s.aborted)throw E(s);const c=!yt(i.pluginSettings.enabledPlugins,t);if(c){const l=i.pluginSettings;if(await this.retireSessionPluginRuntime(i,new Error("Session Plugin settings changed"),{preserveExecutorResources:!0,preserveWorkspaceProduct:!0}),s.aborted)throw E(s);i.pluginSettings=wt({enabledPlugins:t,generation:l.generation+1})}if(c||!i.child)try{if(await this.ensureExecutor(i,r,n.signal,{preserveSessionOnFailure:!0}),this.assertSessionStillReady(i,r),i.deliveryFailure!==void 0)throw i.deliveryFailure}catch(l){if(s.aborted)throw E(s);if(this.assertSessionStillReady(i,r),i.deliveryFailure!==void 0||i.child!==void 0||i.childFailureToken!==void 0||i.mcpAttachment!==void 0)throw l}const d=this.mergeSessionConfigOptions(i,i.configOptions);return i.configOptions=structuredClone(d),c&&await this.deliverNotification(i,{method:this.methods.client.session.update,params:{sessionId:e.sessionId,update:{configOptions:structuredClone(d),sessionUpdate:"config_option_update"}}}),this.releaseBufferedAfterResponse(i,r,o),{configOptions:d}}catch(s){throw i.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(i,r,o):o(),s}}async retireSessionPluginRuntime(e,t,r={}){const i=e.child,n=e.mcpAttachment,o=e.childFailureToken??i,s=[];let c;e.executorReleaseInFlight=!0,e.childFailureToken=void 0,e.child=void 0,e.authReady=!1;try{try{this.rotateReverseController(e,t)}catch(d){s.push(d)}try{await this.retireMcpStatusProjection(e)}catch(d){s.push(d)}if(e.privateMcpServers=void 0,r.preserveExecutorResources||(e.mcpAttachment=void 0,e.mcpAttachmentCwd=void 0),!r.preserveWorkspaceProduct)try{this.clearWorkspaceProductBinding(e)}catch(d){s.push(d)}if(o)try{await n?.disconnectPeer(o)}catch(d){s.push(d)}if(i){c=Promise.resolve().then(()=>i.dispose(t)),e.executorReleasePromise=c;try{await c}catch(d){s.push(d)}}if(!r.preserveExecutorResources)try{await n?.revoke()}catch(d){s.push(d)}if(s.length>0)throw new AggregateError(s,"Session Plugin runtime retirement failed")}finally{e.executorReleasePromise===c&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async prompt(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);await this.awaitBarrier(r,t.signal);const i=qe(e._meta);if(i?.mode===Oe)return this.steerPrompt(r,e,i.expectedRequestId,t);if(r.foreground||r.replayInFlight||r.configWriteInFlight)throw M(e.sessionId);return this.runForegroundOperation(r,t,"prompt",{failed:"Foreground prompt failed",start:"Starting a new prompt"},async(n,o)=>{const s=await n.prompt(ke(e),{signal:o});if(r.deliveryFailure!==void 0)throw r.deliveryFailure;const c=this.validateChildBoundary(r,"PromptResponse",s);return this.withPrivateBoundaryContainment(r,()=>this.capturePromptResponseRequestId(r,c))})}async steerPrompt(e,t,r,i){const n=e.activeOperationController,o=e.child;if(!e.foreground||e.activeOperationKind!=="prompt"||!n||!o||e.replayInFlight||e.configWriteInFlight)throw or(t.sessionId);if(e.activeRequestId===void 0||e.activeRequestId!==r)throw sr(t.sessionId);this.holdOrContinueActivationBoundary(e,i.responseCommitted);const s=I([i.signal,i.connectionSignal,n.signal,e.reverseController.current.signal]);try{if(s.aborted)throw E(s);const c=await o.prompt(ke(t),{signal:s});if(e.deliveryFailure!==void 0)throw e.deliveryFailure;const d=this.validateChildBoundary(e,"PromptResponse",c),l=this.withPrivateBoundaryContainment(e,()=>this.capturePromptResponseRequestId(e,d));return this.releaseBufferedAfterResponse(e,i),l}catch(c){throw e.deliveryMode==="buffer"&&this.releaseBufferedAfterResponse(e,i),c}}async cancel(e,t){const r=this.sessions.get(e.sessionId);if(!r||!r.proxy.has(t.connectionSignal)||this.reservations.has(e.sessionId))return;const i=new Error("Session cancelled");(r.activeOperationKind==="prompt"||r.activeOperationKind==="compact")&&r.activeOperationController?.abort(i),this.rotateReverseController(r,i);const n=r.child;n&&!r.replayInFlight&&await n.cancelSession(e)}close(e){return this.closePromise??=this.closeAll(e),this.closePromise}async reloadUserConfig(e="config/batchWrite"){this.closing||await Promise.allSettled([...this.sessions.values()].map(async t=>{const r=t.child;if(!r)return;const i=this.processRuntime.createPolicyDeadline(this.configReloadTimeoutMs,{signals:[t.lifecycleController.signal,this.facadeController.signal],timeoutReason:Re()});try{await R(r.refreshUserConfig(e,{signal:i.signal}),i.signal)}finally{i.close()}}))}setAuthentication(e,t={}){return this.enqueueAuthenticationMutation(async()=>{this.assertNewAuthenticationGeneration(e.generation);const r=structuredClone(e);this.authProjection={kind:"set",params:r},await this.applyAuthenticationToExistingChildren(t.fenceExisting===!0)})}clearAuthentication(e,t={}){return this.enqueueAuthenticationMutation(async()=>{this.assertNewAuthenticationGeneration(e.generation);const r=structuredClone(e);this.authProjection={kind:"clear",params:r},await this.applyAuthenticationToExistingChildren(!0)})}enqueueAuthenticationMutation(e){const t=this.authMutationTail.then(e,e);return this.authMutationTail=t.catch(()=>{}),t}assertNewAuthenticationGeneration(e){if(!Number.isSafeInteger(e)||e<0||e<=this.authProjection.params.generation)throw new Error("Authentication generation must increase monotonically")}async applyAuthenticationToExistingChildren(e){const t=[...this.activations].filter(r=>r.child!==void 0&&r.authReady);await Promise.all(t.map(async r=>{const i=r.child;if(!i)return;let n;const o=this.processRuntime.createPolicyDeadline(this.configReloadTimeoutMs,{signals:[r.lifecycleController.signal,this.facadeController.signal],timeoutReason:Re()});try{const c=e?i.clearAuthentication?.({generation:this.authProjection.params.generation},{signal:o.signal}):this.authProjection.kind==="set"?i.setAuthentication?.(this.authProjection.params,{signal:o.signal}):i.clearAuthentication?.(this.authProjection.params,{signal:o.signal});if(!(await R(Promise.resolve(c),o.signal))?.applied)throw new Error("Private Agent child rejected authentication generation")}catch(c){n=c}finally{o.close()}if(!e&&n===void 0)return;const s=n??new Error("Agent session fenced by authentication state change");try{await this.failActivation(r,s)}catch(c){r.deliveryFailure??=c}}))}createActivation(e,t){const r=this.profile(e.connectionSignal),i=structuredClone(r.capabilities),n=this.createAttachmentScope(this.processRuntime),o=new Bt({maxBufferedBytes:this.maxBufferedNotificationBytes,maxBufferedNotifications:this.maxBufferedNotifications,onAttachmentFailure:u((c,d)=>this.releaseFailedProxyAttachment(s,c.context,d),"onAttachmentFailure")}),s={attachmentScope:n,attached:!1,attachmentReplayInFlight:!1,activeForegroundAccepted:!1,authReady:!1,barrier:Promise.withResolvers(),...e.responseCommitted===void 0?{}:{barrierResponseCommitted:e.responseCommitted},bufferedNotificationBytes:0,bufferedNotificationCount:0,bufferedNotifications:[],compactionDeliveryEpoch:{},compactions:new Map,configWriteInFlight:!1,deliveryGeneration:0,deliveryMode:"buffer",deliveryTail:Promise.resolve(),executorReleaseInFlight:!1,expectedSessionId:t,foreground:!1,lifecycleController:n.makeController(),negotiatedClientCapabilities:i,owner:e.connectionSignal,ownerContext:e,productForegroundPending:!1,pluginSettings:Object.freeze({enabledPlugins:Object.freeze({}),generation:0}),proxy:o,replayInFlight:!1,replayResponsePending:!1,rebinding:!1,reconnectRootTerminalMatched:!1,reverseController:{current:n.makeController()},startupController:n.makeController(),workspaceProductRebindInFlight:!1};if(!o.add(e,r))throw E(e.connectionSignal);try{n.bindFinalizer(c=>this.disposeAttachmentResources(s,c))}catch(c){throw n.close(c).catch(()=>{}),c}return s}mergeSessionConfigOptions(e,t){const r=t??e.configOptions;return je(cr(r,e.workspaceProduct?.sessionModelConfigOption),e.pluginSettings.enabledPlugins)}mergeHostSessionConfigOptions(e,t){const r=e.workspaceProduct;return this.mergeSessionConfigOptions(e,r===void 0?t:Je(t,r.sessionModelConfigOption))}commitAdditionalDirectories(e,t){if(!e.resumeParams)throw new f(p.internalError,"Active session is missing its durable resume setup");e.resumeParams={...e.resumeParams,additionalDirectories:structuredClone(t.additionalDirectories??[])}}createMcpAttachment(e,t,r,i){if(!this.mcpIntegration)return;const n=this.profile(e.owner);if((t.mcpServers?.some(h=>h.type!=="acp")||r.servers.length||i.servers.length)&&(!n.elicitationForm||!n.elicitationUrl))throw new P("Executor-backed MCP requires elicitation.form and elicitation.url client capabilities");const o=t.mcpServers??[],s=new Set;for(const h of o){if(typeof h.name!="string"||!h.name.trim()||h.name.length>128||h.name.startsWith("_")||h.name.startsWith("plugin:")||s.has(h.name))throw new P("MCP server names must be unique, nonempty, non-reserved and at most 128 characters");s.add(h.name)}const c=o.filter(h=>h.type==="acp"),d=c.length?e.proxy.list().find(h=>h.context.connectionSignal===e.owner)?.context:void 0;if(c.length&&!d)throw new P("Client MCP owner is disconnected");return this.mcpIntegration.createAttachment({interaction:u((h,m)=>this.requestMcpElicitation(e,h,m.signal),"interaction"),setup:{cwd:t.cwd,mcpServers:t.mcpServers?.filter(h=>h.type!=="acp"),...d?{clientMcp:{servers:c,owner:d,router:this.clientMcp}}:{},pluginMcpSnapshot:r,userMcpSnapshot:{...i,servers:i.servers.filter(h=>!c.some(m=>m.name===h.logicalName))}}})}mcpStatusNotification(e,t,r){const i=r??(t.status==="available"?"ready":"failed");return{error:i==="failed"?(t.error?.message??"MCP server unavailable").slice(0,lt):null,failureReason:null,name:t.logicalName,status:i,threadId:e}}publishMcpServerStatus(e,t,r){const i=e.sessionId;return!i||!e.attached||this.sessions.get(i)!==e?Promise.resolve():this.deliverNotification(e,{method:ue.mcpServer.startupStatus.updated,params:this.mcpStatusNotification(i,t,r)})}suspendMcpStatusProjection(e){e.mcpStatusUnsubscribe?.(),e.mcpStatusUnsubscribe=void 0,e.mcpAttachmentCursorEpoch=void 0}async retireMcpStatusProjection(e){let t=[];if(e.mcpStatusUnsubscribe&&e.mcpAttachment&&e.privateMcpServers!==void 0)try{t=e.mcpAttachment.listServerStatuses()}catch{}this.suspendMcpStatusProjection(e),await Promise.allSettled(t.map(r=>this.publishMcpServerStatus(e,r,"cancelled")))}async installMcpStatusProjection(e){const t=e.mcpAttachment;if(!t||e.privateMcpServers===void 0||!e.sessionId){this.suspendMcpStatusProjection(e);return}this.suspendMcpStatusProjection(e);const r=xe();e.mcpAttachmentCursorEpoch=r;try{e.mcpStatusUnsubscribe=t.subscribeServerStatus(i=>{e.mcpAttachment!==t||e.mcpAttachmentCursorEpoch!==r||this.publishMcpServerStatus(e,i).catch(n=>{e.mcpAttachment===t&&this.activations.has(e)&&!e.closePromise&&(e.deliveryFailure??=n,this.handleChildFailure(e,n))})});for(const i of t.listServerStatuses())await this.deliverNotification(e,{method:ue.mcpServer.startupStatus.updated,params:{error:null,failureReason:null,name:i.logicalName,status:"starting",threadId:e.sessionId}}),await this.publishMcpServerStatus(e,i)}catch(i){throw e.mcpAttachmentCursorEpoch===r&&this.suspendMcpStatusProjection(e),i}}async resolvePluginMcpSnapshot(e,t,r){return this.strictMcpConfig?{errors:[],generation:"strict-mcp-config",servers:[],version:1}:B("pluginMcpResolve",async()=>{const i=this.pluginMcp?.resolve??((...o)=>this.requireHostSessionControl().resolvePluginMcp(...o)),n=await R(i(t,e.pluginSettings,{signal:r}),r);if(n.pluginSettingsGeneration!==e.pluginSettings.generation)throw new f(p.internalError,"Resource resolved Plugin MCP from a different settings generation");return structuredClone(n.pluginMcpSnapshot)})}async resolveUserMcpSnapshot(e,t){if(this.strictMcpConfig)return ce;const r=this.userMcp?.resolve??this.hostSessionControl?.resolveUserMcp?.bind(this.hostSessionControl);if(!r)return ce;try{const i=structuredClone(await R(r(e,{signal:t}),t)),n=T();return n.setCount("invalidUserMcpServerCount",i.errors.filter(o=>o.code==="invalid_config").length),n.setCount("unsupportedUserMcpAuthCount",i.errors.filter(o=>o.code==="unsupported_auth").length),n.setCount("unsupportedUserMcpTransportCount",i.errors.filter(o=>o.code==="unsupported_transport").length),i}catch{if(t.aborted)throw E(t);if(this.facadeController.signal.aborted)throw E(this.facadeController.signal);return T().setCount("userMcpSnapshotResolveFailureCount",1),ce}}async prepareMcpAttachment(e,t,r,i){const[n,o]=await Promise.all([this.resolvePluginMcpSnapshot(e,t.cwd,i),this.resolveUserMcpSnapshot(t.cwd,i)]),s=e.mcpAttachment;if(!this.mcpIntegration){if((t.mcpServers?.length??0)>0||n.servers.length>0||o.servers.length>0)throw new f(p.notReady,"Session MCP integration is unavailable");s&&(await this.retireMcpStatusProjection(e),await R(s.revoke(),i),e.mcpAttachment===s&&(e.mcpAttachment=void 0,e.mcpAttachmentCwd=void 0,e.privateMcpServers=void 0));return}const c=await B("mcpCompile",()=>this.createMcpAttachment(e,t,n,o));let d;try{r!==null&&c?.bindSessionId(r),c&&(d=await B("mcpMaterialize",()=>R(c.materialize(),i)))}catch(l){throw await c?.revoke().catch(()=>{}),l}return s&&await this.retireMcpStatusProjection(e),e.mcpAttachment=c,e.mcpAttachmentCwd=c?t.cwd:void 0,e.privateMcpServers=void 0,s&&s!==c&&await s.revoke(),d}async rebindWorkspaceMcpAttachment(e,t,r,i){if(!this.mcpIntegration||e.mcpAttachment!==void 0&&e.mcpAttachmentCwd===t)return;const n=e.resumeParams,o=e.sessionId;if(!n||!o)throw new f(p.internalError,"Active session is missing its durable MCP setup");const s=e.mcpAttachment;if(i.aborted)throw E(i);if(this.assertSessionStillReady(e,r),s&&(await this.retireMcpStatusProjection(e),await s.revoke()),e.mcpAttachment===s&&(e.mcpAttachment=void 0,e.mcpAttachmentCwd=void 0,e.privateMcpServers=void 0),i.aborted)throw E(i);if(this.assertSessionStillReady(e,r),!e.child)return;const[c,d]=await Promise.all([this.resolvePluginMcpSnapshot(e,t,i),this.resolveUserMcpSnapshot(t,i)]),l=this.createMcpAttachment(e,{cwd:t,mcpServers:n.mcpServers},c,d);try{l?.bindSessionId(o)}catch(h){throw await l?.revoke().catch(()=>{}),h}e.mcpAttachment=l,e.mcpAttachmentCwd=l?t:void 0}async materializeNewSessionMcp(e,t,r,i){if(!e.mcpAttachment)return t;const n=i??await R(e.mcpAttachment.materialize(),r);return this.recordMcpMaterializationDiagnostics(n.diagnostics),e.privateMcpServers=structuredClone(n.mcpServers),{...t,mcpServers:[...e.privateMcpServers]}}recordMcpMaterializationDiagnostics(e){const t=T();t.setCount("droppedPluginMcpServerCount",e?.droppedPluginServerCount??0),t.setCount("droppedUserMcpServerCount",e?.droppedUserServerCount??0)}recordSessionNewMcpCounts(e){const t=e.mcpAttachment;if(t)try{const r=t.listServerStatuses(),i=T();i.setCount("availableMcpServerCount",r.filter(n=>n.status==="available").length),i.setCount("unavailableMcpServerCount",r.filter(n=>n.status==="unavailable").length),i.setCount("mcpToolCount",r.reduce((n,o)=>n+o.tools.length,0))}catch{}}async materializeResumeSessionMcp(e,t,r,i){if(!e.mcpAttachment)return{...t,replayFrom:null};const n=i??await R(e.mcpAttachment.materialize(),r);return this.recordMcpMaterializationDiagnostics(n.diagnostics),e.privateMcpServers=structuredClone(n.mcpServers),await this.installMcpStatusProjection(e),{...t,mcpServers:[...e.privateMcpServers],replayFrom:null}}projectResumeSessionMcp(e,t){const r=e.workspaceProduct===void 0?t:{...t,cwd:e.workspaceProduct.canonicalCwd};if(!e.mcpAttachment)return r;if(!e.privateMcpServers)throw new f(p.internalError,"Active MCP attachment is not materialized");return{...r,mcpServers:[...e.privateMcpServers]}}async requestMcpElicitation(e,t,r){const i=e.sessionId;if(!e.attached||!i||e.proxy.list("live").length===0||e.detached!==void 0||e.rebinding||this.facadeController.signal.aborted||r.aborted)return{action:"cancel"};await this.awaitBarrier(e,r);const n=t.mode==="form"?{message:t.message,mode:"form",requestedSchema:t.requestedSchema??{type:"object"},sessionId:i}:{elicitationId:t.elicitationId,message:t.message,mode:"url",sessionId:i,url:t.url},o=O("CreateElicitationRequest",n),s=await this.requestAttachedClients(e,t.mode,this.methods.client.elicitation.create,o,c=>ve("CreateElicitationResponse",c),r);return s.action!=="accept"&&s.action!=="decline"&&s.action!=="cancel"?{action:"cancel"}:{action:s.action,...s.action==="accept"&&A(s.content)?{content:s.content}:{}}}assertCanActivate(){if(this.closing)throw new f(p.notReady,"Agent Harness is shutting down");if(this.activations.size>=this.maxActiveSessions)throw new f(p.overloaded,"Maximum active Agent sessions reached")}claim(e,t,r){if(this.reservations.has(e)||t==="activating"&&this.sessions.has(e))throw M(e);this.reservations.set(e,{kind:t,owner:r})}attach(e,t){if(this.sessions.has(t)||this.reservations.has(t)&&this.reservations.get(t)?.kind!=="activating")throw M(t);e.attached=!0,e.sessionId=t,e.mcpAttachment?.bindSessionId(t),this.sessions.set(t,e),this.subagentProjection.attachSession(t,e.owner);const r=this.reservations.get(t);r?.kind==="activating"&&r.owner===e.owner&&this.reservations.delete(t)}ownedSession(e,t){const r=this.sessions.get(e);if(!r||!r.proxy.has(t))throw U(e);return r}ownedReadySession(e,t){const r=this.ownedSession(e,t);if(!r.proxy.has(t,"live")||r.attachmentReplayInFlight||r.closePromise||this.reservations.has(e))throw U(e);return r}mcpOperationSignal(e,t){return I([t.signal,t.connectionSignal,e.lifecycleController.signal,this.facadeController.signal])}requireMaterializedMcpAttachment(e){const t=e.mcpAttachment,r=e.mcpAttachmentCursorEpoch;if(!t||e.privateMcpServers===void 0||r===void 0)throw new f(p.notReady,"Session MCP attachment is not materialized");return{attachment:t,cursorEpoch:r}}resolveAdmissionSessionId(e,t){if(this.sessions.get(e)?.proxy.has(t))return e;const i=this.subagentProjection.rootSessionIdFor(e);return i!==void 0&&this.sessions.get(i)?.proxy.has(t)?i:e}requireChild(e){if(!e.child)throw new f(p.internalError,"Private ACP v2 child is unavailable");return e.child}requireHostSessionControl(){if(!this.hostSessionControl)throw new Error("Legacy session control is not configured");return this.hostSessionControl}async resumeStoredSession(e,t,r){return this.sessionReplay?{response:await H.runPromise(this.sessionReplay.resume(t,{...r,workspace:e.workspaceProduct,clientCapabilities:this.profile(e.owner).capabilities}))}:this.requireHostSessionControl().resumeSession(t,r)}assertSessionStillReady(e,t){const r=e.sessionId;if(!r||!e.proxy.has(t.connectionSignal,"live")||e.attachmentReplayInFlight||this.sessions.get(r)!==e||e.closePromise||this.reservations.has(r)||Y(e))throw U(r??"unknown")}ensureExecutor(e,t,r,i={}){if(r.aborted)return Promise.reject(E(r));if(e.child&&!e.childStartup)return Promise.resolve(e.child);if(e.childStartup)return R(e.childStartup,I([t.signal,r]));if(!e.resumeParams)return Promise.reject(new f(p.internalError,"Dormant session is missing its durable resume setup"));const n=this.activateDormantExecutor(e,t,r,i);return e.childStartup=n,n.then(()=>{e.childStartup===n&&(e.childStartup=void 0)},()=>{e.childStartup===n&&(e.childStartup=void 0)}),n}createSessionActivationDeadline(e,t){const r=I(t),i=new Pt(p.notReady,`Agent session activation timed out after ${this.sessionActivationTimeoutMs}ms`);return e.attachmentScope.deadline(r,this.sessionActivationTimeoutMs,i)}async releaseExecutorForRewind(e,t){const r=e.child;if(!r){this.releaseWorkspaceProductBinding(e);return}e.executorReleaseInFlight=!0,this.rotateReverseController(e,t);const i=Promise.resolve().then(()=>r.dispose(t));e.executorReleasePromise=i;try{await i,e.child===r&&(e.child=void 0,e.authReady=!1,e.privateMcpServers=void 0,this.clearWorkspaceProductBinding(e))}finally{e.executorReleasePromise===i&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async activateDormantExecutor(e,t,r,i){const n=e.bufferedNotifications.length,o=e.deliveryFailure,s=e.configOptions,c=e.foreground,d=e.agentInitiatedForegroundToken,l=e.publicForegroundDeliveryToken,h=e.productForegroundPending,m=e.productForegroundDrain,y=i.preserveSessionOnFailure?{committed:!1}:void 0;y&&(e.recoverableActivation=y);const C=e.attachmentScope.makeController();e.replayController=C,e.replayInFlight=!0,this.holdOrContinueActivationBoundary(e,t.responseCommitted);const k=this.createSessionActivationDeadline(e,[t.signal,t.connectionSignal,this.facadeController.signal,e.startupController.signal,C.signal,r]),S=k.signal;try{const F=e.resumeParams;if(!F)throw new f(p.internalError,"Dormant session is missing its durable resume setup");const b=e.workspaceProduct===void 0?F:{...F,cwd:e.workspaceProduct.canonicalCwd},j=await this.prepareMcpAttachment(e,b,F.sessionId,S),N=await this.materializeResumeSessionMcp(e,F,S,j),_=await this.spawnInitializedChild(e,F.cwd,S),W=e.workspaceProduct===void 0?N:{...N,cwd:e.workspaceProduct.canonicalCwd},x=this.validateChildBoundary(e,"ResumeSessionResponse",await R(_.resumeSession(W,{signal:S}),S));if(this.assertSessionIdentity(e,F.sessionId),await R(e.deliveryTail,S),y?.failure!==void 0)throw y.failure;if(e.deliveryFailure!==void 0)throw e.deliveryFailure;return y&&(y.committed=!0,e.recoverableActivation===y&&(e.recoverableActivation=void 0),this.withPrivateBoundaryContainment(e,()=>this.finalizeBufferedPrivateLiveUpdatesFrom(e,n))),e.configOptions=structuredClone(this.mergeSessionConfigOptions(e,x.configOptions)),this.clearReplayController(e,C),e.replayInFlight=!1,_}catch(F){if(C.signal.aborted||C.abort(F),this.clearReplayController(e,C),e.replayInFlight=!1,y&&!y.committed&&this.activations.has(e)&&!e.lifecycleController.signal.aborted){let b;try{await this.retireSessionPluginRuntime(e,F,{preserveWorkspaceProduct:!0})}catch(j){b=j}finally{this.discardBufferedNotificationsFrom(e,n)}throw!h&&e.productForegroundPending&&this.resolveProductForeground(e),e.foreground=c,e.agentInitiatedForegroundToken=d,e.publicForegroundDeliveryToken=l,e.productForegroundPending=h,e.productForegroundDrain=m,e.configOptions=s,e.deliveryFailure=o,b!==void 0?Q(F,b,"Replacement Plugin runtime activation and cleanup failed"):F}throw this.activations.has(e)&&(this.dropBuffered(e),await this.failActivation(e,F)),F}finally{y&&e.recoverableActivation===y&&(e.recoverableActivation=void 0),k.clear()}}sessionOpenOptions(e,t,r,i){return{callbacks:this.createCallbacks(e,i),clientCapabilities:this.profile(e.owner).capabilities,clientInfo:this.serverInfo,cwd:e.workspaceProduct?.canonicalCwd??t,onFailure:u(n=>this.handlePrivateChildExit(e,n,i),"onFailure"),pluginSettings:e.pluginSettings,workspace:e.workspaceProduct,signal:r}}async spawnInitializedChild(e,t,r){const i={};e.childFailureToken=i;const n=e.attachmentScope.runEffect(this.sessionRuntime.open(this.sessionOpenOptions(e,t,r,i)));let o;try{o=await R(n,r)}catch(s){throw e.childFailureToken===i&&(e.childFailureToken=void 0),r.aborted&&this.trackCleanup(n.then(c=>c.dispose(E(r)),()=>{})),s}return e.child=o,this.validateInitializedChild(e,o),await B("authProjection",()=>this.applyAuthenticationToChild(e,o,r)),o}async applyAuthenticationToChild(e,t,r){for(;;){await R(this.authMutationTail,r);const i=this.authProjection;if(!(await R(Promise.resolve(i.kind==="set"?t.setAuthentication?.(i.params,{signal:r}):t.clearAuthentication?.(i.params,{signal:r})),r))?.applied)throw new f(p.internalError,"Private Agent child rejected authentication state");if(await R(this.authMutationTail,r),this.authProjection.params.generation===i.params.generation){e.authReady=!0;return}}}validateInitializedChild(e,t){this.withPrivateBoundaryContainment(e,()=>{const r=ne(this.agentCapabilities,t.capabilities,"capabilities");if(r)throw new f(p.internalError,`Session runtime is missing advertised ${r}`.slice(0,L));const i=this.sessionRuntime.profile?.supports;if((i?.configReload??!0)&&!t.supports.configReload)throw new f(p.internalError,'Session runtime is missing advertised capabilities._meta["codebuddy.ai"].config.reload');if((i?.compact??!0)&&!t.supports.compact)throw new f(p.internalError,'Session runtime is missing advertised capabilities._meta["codebuddy.ai"].session.compact');if((i?.promptSteer??!0)&&!t.supports.promptSteer)throw new f(p.internalError,`Session runtime is missing advertised capabilities.session.prompt._meta["${me}"].modes`);if(e.privateMcpServers?.some(n=>n.type==="acp")&&t.capabilities.session?.mcp?.acp==null)throw new f(p.internalError,"Session runtime is missing advertised capabilities.session.mcp.acp")})}validateChildBoundary(e,t,r){return this.withPrivateBoundaryContainment(e,()=>O(t,r))}withPrivateBoundaryContainment(e,t){try{return t()}catch(r){if(e.attached)if(e.deliveryFailure??=r,e.closePromise)for(const i of e.proxy.list())i.context.closeConnection?.(r).catch(()=>{});else this.handleChildFailure(e,r);throw r}}async deliverHostUpdate(e,t){const r=O("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId);const i=this.projectPrivateUpdate(e,r);e.rebinding&&(e.reconnectMessageCoverage?.observeSnapshot(r),this.captureReconnectRootTerminal(e,r)),await this.enqueueProjectedNotifications(e,Pe(i))}async deliverBufferedHostUpdate(e,t){const r=O("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId),await this.deliverProjectedNotifications(e,this.projectPrivateUpdate(e,r))}async projectDurableSnapshotUpdate(e,t){const r=O("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId),this.projectPrivateUpdate(e,r,!1)}projectPrivateUpdate(e,t,r=!0){const i=Me(t.update);if(i)throw new f(p.internalError,`Invalid private error update: ${i}`.slice(0,L));if(!this.validateCompactionUpdate(e,t,r))return[];!e.replayInFlight&&e.replayProjection===void 0&&t.update.sessionUpdate==="state_update"&&t.update.state==="idle"&&this.assertCompactionsTerminalBeforeIdle(e,t);let n=t;if(t.update.sessionUpdate==="config_option_update"){const o=this.mergeSessionConfigOptions(e,t.update.configOptions);n={...t,update:{...t.update,configOptions:o}},e.replayProjection||(e.configOptions=structuredClone(o))}return e.replayProjection?this.subagentProjection.projectReplay(e.replayProjection,e.owner,n):this.subagentProjection.project(n.sessionId,e.owner,n)}projectConcurrentReplayUpdate(e,t,r,i,n){const o=Me(n.update);if(o)throw new f(p.internalError,`Invalid private error update: ${o}`.slice(0,L));if(!this.validateCompactionUpdate(e,n,!1,!0))return[];const s=n.update.sessionUpdate==="config_option_update"?{...n,update:{...n.update,configOptions:this.mergeSessionConfigOptions(e,n.update.configOptions)}}:n;return t.projectReplay(r,i,s)}validateCompactionUpdate(e,t,r,i){if(t.update.sessionUpdate!==Ne)return!0;const n=bt(t.update);if(n)throw new f(p.internalError,`Invalid private compaction update: ${n}`.slice(0,L));const o=t.update,s=i??(e.replayInFlight||e.replayProjection!==void 0),c=o._meta,d=e.sessionId??e.expectedSessionId,l=c[z];let h,m;if(l===void 0)m=t.sessionId===d,h=`root:${t.sessionId}`;else{if(!A(l)||l.version!==1||typeof l.sessionId!="string"||l.sessionId.trim().length===0)throw new f(p.internalError,"Private compaction update returned an invalid Subagent route");m=!1,h=`subagent:${l.sessionId}`}const y=c[vt],C=c[G],k=c[we],S=typeof C=="string"&&C.trim().length>0;if(y==="manual"&&!m)throw new f(p.internalError,"Private manual compaction update is not a root lifecycle");if(s&&o.status==="in_progress")throw new f(p.internalError,"Private compaction replay returned transient in_progress state");const F=JSON.stringify([h,o.compactionId]),b=e.compactions.get(F),j=b!==void 0&&(b.status==="in_progress"||b.status==="completed"||b.status==="failed"||b.status==="cancelled"),N=o.status==="in_progress"||o.status==="completed"||o.status==="failed"||o.status==="cancelled",_=o.status==="completed"||o.status==="failed"||o.status==="cancelled";if(b){if(b.trigger!==y||b.route!==h)throw new f(p.internalError,"Private compaction lifecycle changed route or trigger identity");if(b.status!==o.status&&j&&N&&!(b.status==="in_progress"&&_))throw new f(p.internalError,"Private compaction lifecycle changed terminal status or regressed")}const W=JSON.stringify([h,ie(o)]);if(r&&b?.lastDeliveredEpoch===e.compactionDeliveryEpoch&&b.lastDeliveredFingerprint===W)return!1;const x=b!==void 0&&o.status!=="in_progress"&&(b.status===o.status||!j||!N);if(y==="manual"&&!s&&!x){if(!m||e.activeOperationKind!=="compact"&&e.activeOperationKind!=="prompt"||!e.foreground)throw new f(p.internalError,"Private manual compaction update is outside its foreground lifecycle");if(!b&&o.status!=="in_progress")throw new f(p.internalError,"Private manual compaction completed before it started");if(e.activeCompactionId!==void 0&&e.activeCompactionId!==o.compactionId)throw new f(p.internalError,"Private manual compaction changed its lifecycle id");e.activeCompactionId=o.compactionId,this.captureActiveRequestId(e,c,"compaction update",!1)}else!x&&!s&&m&&S&&e.activeOperationKind==="prompt"&&e.foreground&&this.captureActiveRequestId(e,c,"compaction update",!1);const g=b??{lastObservedFingerprint:W,route:h,status:o.status,trigger:y};return S&&g.requestId===void 0&&(g.requestId=C,g.rootRequestId=typeof k=="string"?k:void 0),g.status=o.status,g.lastObservedFingerprint=W,e.compactions.set(F,g),r&&(g.lastDeliveredEpoch=e.compactionDeliveryEpoch,g.lastDeliveredFingerprint=W),!0}assertCompactionsTerminalBeforeIdle(e,t){const r=t.update._meta,i=A(r)?r[G]:void 0,n=A(r)?r[z]:void 0,o=A(n)&&typeof n.sessionId=="string"?`subagent:${n.sessionId}`:`root:${t.sessionId}`;for(const d of e.compactions.values())if(d.route===o&&d.requestId===i&&d.status==="in_progress")throw new f(p.internalError,"Private compaction reached idle before a terminal status");if(e.activeOperationKind!=="compact")return;const s=e.activeCompactionId,c=s===void 0?void 0:e.compactions.get(JSON.stringify([`root:${t.sessionId}`,s]));if(c===void 0||!(c.status==="completed"||c.status==="failed"||c.status==="cancelled"))throw new f(p.internalError,"Private manual compaction omitted its terminal lifecycle update")}capturePromptResponseRequestId(e,t){const r=mt(t);if(!r)throw new f(p.internalError,`Private ACP v2 PromptResponse omitted ${G} or returned it empty`);return this.captureActiveRequestId(e,r._meta,"PromptResponse"),r}captureRootUpdateRequestId(e,t){if(e.replayInFlight||e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground)return;const r=t.update._meta;if(A(r)&&Object.hasOwn(r,z))return;const i=t.update;i.sessionUpdate!==Ne&&(i.sessionUpdate==="terminal_update"||i.sessionUpdate==="terminal_output_chunk"||i.sessionUpdate!=="usage_update"&&this.captureActiveRequestId(e,A(r)?r:void 0,`session/update.params.update.${i.sessionUpdate}`,!1))}captureActiveRequestId(e,t,r,i=!0){if(e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground||!A(t)||!Object.hasOwn(t,G))return;const n=t[G];if(typeof n!="string"||n.trim().length===0){if(!i)return;throw new f(p.internalError,`Private ACP v2 ${r} returned an invalid ${G}`)}if(e.activeRequestId!==void 0&&e.activeRequestId!==n){if(!i)return;throw new f(p.internalError,"Private ACP v2 child changed the active prompt request identity")}e.activeRequestId=n}deferPrivateLiveUpdate(e,t,r,i){if(e.deliveryMode!=="buffer")return Promise.reject(new f(p.notReady,"Private live update arrived outside the replay response boundary"));e.rebinding&&e.reconnectMessageCoverage?.trackLive(t);const n=this.reserveBufferedNotification(e,{...r===void 0?{}:{afterDelivery:r},method:this.methods.client.session.update,params:t,privateLiveUpdate:{notification:t,...i===void 0?{}:{projected:i}}});if(!n){const s=new ae("ACP v2 response-boundary notification buffer limit exceeded");return e.deliveryFailure??=s,this.handleChildFailure(e,s),Promise.reject(s)}return(e.rebindLiveNotifications??e.bufferedNotifications).push(n),Promise.resolve()}async enqueueProjectedNotifications(e,t,r){const i=t.map(s=>{const c=s.params;return this.enqueueNotification(e,{...r&&c.sessionId===e.sessionId?{afterDelivery:r}:{},...this.toBufferedNotification(s)})}),o=(await Promise.allSettled(i)).find(s=>s.status==="rejected");if(o)throw o.reason}async deliverProjectedNotifications(e,t,r){const i=t.map(s=>{const c=s.params;return this.deliverNotification(e,{...r&&c.sessionId===e.sessionId?{afterDelivery:r}:{},...this.toBufferedNotification(s)})}),o=(await Promise.allSettled(i)).find(s=>s.status==="rejected");if(o)throw o.reason}createCallbacks(e,t){return{refreshAuthentication:u(async(r,i)=>{if(this.assertCurrentPrivateChildCallback(e,t),!this.refreshAuthentication)throw new f(-32e3,"Authentication required");const n=I([e.lifecycleController.signal,this.facadeController.signal,...i?.signal?[i.signal]:[]]);this.inFlightPrivateRefreshCallbackCount+=1;try{return await this.refreshAuthentication(r,{signal:n})}finally{this.inFlightPrivateRefreshCallbackCount-=1}},"refreshAuthentication"),completeElicitation:u(async r=>{this.assertCurrentPrivateChildCallback(e,t);const i=this.withPrivateBoundaryContainment(e,()=>{const n=O("CompleteElicitationNotification",r);return this.assertReverseSessionExists(e),n});await this.awaitBarrier(e),this.assertCurrentPrivateChildCallback(e,t),this.assertReverseReady(e,"url"),await this.deliverNotification(e,{method:this.methods.client.elicitation.complete,params:i})},"completeElicitation"),createElicitation:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=this.withPrivateBoundaryContainment(e,()=>{const s=O("CreateElicitationRequest",r);if(!("sessionId"in s)||typeof s.sessionId!="string")throw new f(p.invalidRequest,"Request-scoped elicitation cannot cross isolated ACP connections");const c=s;return this.assertCallbackSessionId(e,c.sessionId),this.assertReverseSessionExists(e),c});await this.awaitBarrier(e,i?.signal),this.assertCurrentPrivateChildCallback(e,t);const o=this.withPrivateBoundaryContainment(e,()=>this.subagentProjection.projectSessionScopedRequest(n.sessionId,e.owner,n));return this.requestAttachedClients(e,o.mode,this.methods.client.elicitation.create,o,s=>ve("CreateElicitationResponse",s),i?.signal)},"createElicitation"),mcpConnect:u(async(r,i,n)=>{this.assertCurrentPrivateChildCallback(e,t);const o=e.mcpAttachment;if(!o)throw new P("Private Agent requested MCP without an active session scope");return o.connect(r,{peerToken:t,peer:i,signal:I([e.lifecycleController.signal,this.facadeController.signal,...n?.signal?[n.signal]:[]])})},"mcpConnect"),mcpDisconnect:u(async r=>{this.assertCurrentPrivateChildCallback(e,t),await e.mcpAttachment?.disconnect(r,{peerToken:t})},"mcpDisconnect"),mcpMessage:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=e.mcpAttachment;if(!n)throw new P("Private Agent requested MCP without an active session scope");return n.message(r,{peerToken:t,signal:I([e.lifecycleController.signal,this.facadeController.signal,...i?.signal?[i.signal]:[]])})},"mcpMessage"),mcpNotification:u(async r=>{this.assertCurrentPrivateChildCallback(e,t);const i=e.mcpAttachment;if(!i)throw new P("Private Agent notified MCP without an active session scope");i.notify(r,{peerToken:t})},"mcpNotification"),mcpPeerClosed:u(async()=>{await e.mcpAttachment?.disconnectPeer(t)},"mcpPeerClosed"),requestPermission:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=this.withPrivateBoundaryContainment(e,()=>{const s=O("RequestPermissionRequest",r);return this.assertCallbackSessionId(e,s.sessionId),this.assertReverseSessionExists(e),s});await this.awaitBarrier(e,i?.signal),this.assertCurrentPrivateChildCallback(e,t);const o=this.withPrivateBoundaryContainment(e,()=>this.subagentProjection.projectSessionScopedRequest(n.sessionId,e.owner,n));return this.requestAttachedClients(e,!1,this.methods.client.session.requestPermission,o,s=>ve("RequestPermissionResponse",s),i?.signal)},"requestPermission"),sessionUpdate:u(async r=>{if(!(e.closePromise||e.executorReleaseInFlight||e.childFailurePromise||e.childFailureToken!==t||!this.activations.has(e)))try{const i=O("UpdateSessionNotification",r);this.assertCallbackSessionId(e,i.sessionId);const n=i.update._meta,o=A(n)?n[G]:void 0;if(!e.replayInFlight&&i.update.sessionUpdate==="state_update"&&i.update.state==="idle"&&!Object.hasOwn(n??{},z)&&e.activeRequestId!==void 0&&typeof o=="string"&&o.trim().length>0&&o!==e.activeRequestId)return;this.captureRootUpdateRequestId(e,i);const s=e.replayResponsePending,c=i.update,d=c._meta,l=c.sessionUpdate==="state_update"&&!(A(d)&&Object.hasOwn(d,z)),h=e.activeOperationKind==="prompt"||e.activeOperationKind==="compact";!s&&l&&c.state==="running"&&!h&&(e.publicForegroundDeliveryToken=void 0,e.agentInitiatedForegroundToken={},e.foreground=!0,this.beginProductForeground(e));const m=!s&&l&&c.state==="idle",y=m&&h?e.activeOperationController:void 0,C=y?{}:void 0,k=m?e.agentInitiatedForegroundToken:void 0;m&&(this.assertCompactionsTerminalBeforeIdle(e,i),y&&(e.publicForegroundDeliveryToken=C,this.finishPublicForegroundAtTerminalReceipt(e,y)));const S=C?()=>{e.publicForegroundDeliveryToken===C&&(e.publicForegroundDeliveryToken=void 0,e.foreground=!1,this.rotateReverseController(e,new Error("Foreground turn completed")))}:k?()=>{e.agentInitiatedForegroundToken===k&&(e.agentInitiatedForegroundToken=void 0,e.foreground=!1,e.activeRequestId=void 0,this.resolveProductForeground(e),e.productForegroundDrain=void 0,this.rotateReverseController(e,new Error("Foreground turn completed")))}:void 0;if(e.deliveryMode==="buffer"&&!(e.replayInFlight&&e.replayResponsePending)){const b=e.rebinding||e.recoverableActivation!==void 0?void 0:this.projectPrivateUpdate(e,i);await this.deferPrivateLiveUpdate(e,i,S,b);return}const F=this.projectPrivateUpdate(e,i);if(e.replayResponsePending){await this.enqueueProjectedNotifications(e,Pe(F));return}await this.deliverProjectedNotifications(e,F,S)}catch(i){if(e.closePromise||!this.activations.has(e))return;throw e.deliveryFailure??=i,this.handleChildFailure(e,i),i}},"sessionUpdate")}}assertCurrentPrivateChildCallback(e,t){if(e.childFailureToken!==t||e.childFailurePromise||!this.activations.has(e))throw new f(p.notReady,"Private ACP v2 child is no longer active")}assertCallbackSessionId(e,t){if(e.expectedSessionId!==void 0&&e.expectedSessionId!==t)throw new f(p.internalError,"Private ACP v2 child emitted a different sessionId");if(e.observedSessionId!==void 0&&e.observedSessionId!==t)throw new f(p.internalError,"Private ACP v2 child emitted multiple session identities");e.observedSessionId=t}assertSessionIdentity(e,t){if(this.assertCallbackSessionId(e,t),e.expectedSessionId!==void 0&&e.expectedSessionId!==t)throw new f(p.internalError,"Private ACP v2 response changed the requested session identity")}async requestAttachedClients(e,t,r,i,n,o){this.assertReverseReady(e,t);const s=this.reverseSignal(e,o);return e.proxy.requestFirst(r,i,c=>n(c),{select:u(c=>this.supportsReverseRequest(c.profile,t),"select"),signal:s,timeoutMs:Ht})}supportsReverseRequest(e,t){return t===!1||t==="form"&&e.elicitationForm||t==="url"&&e.elicitationUrl}assertReverseReady(e,t){if(!e.attached||e.sessionId===void 0||e.deliveryMode!=="forward")throw new f(p.notReady,"Private ACP v2 reverse request arrived before the session response boundary committed");if(!e.proxy.list("live").some(i=>this.supportsReverseRequest(i.profile,t)))throw new f(p.methodNotFound,"The public ACP v2 Client did not advertise elicitation")}assertReverseSessionExists(e){if(!e.attached||e.sessionId===void 0||e.deliveryMode==="drop")throw new f(p.notReady,"Private ACP v2 reverse request arrived before the session response boundary committed")}reverseSignal(e,t){return I([e.lifecycleController.signal,this.facadeController.signal,e.reverseController.current.signal,...e.activeOperationController?[e.activeOperationController.signal]:[],...t?[t]:[]])}profile(e){const t=this.profiles.get(e);if(!t)throw new f(p.notReady,"ACP v2 Agent profile is not initialized");return t}holdNotifications(e,t){if(e.deliveryMode!=="forward")throw new f(p.notReady,"Session response boundary is still pending");e.deliveryMode="buffer",e.bufferedNotifications=[],e.barrier=Promise.withResolvers(),e.barrierResponseCommitted=t}holdOrContinueActivationBoundary(e,t){if(e.deliveryMode==="forward"){this.holdNotifications(e,t);return}if(e.deliveryMode!=="buffer")throw new f(p.notReady,"Session attachment is closed")}schedulePostResponseTask(e,t,r){if(!this.schedulePostResponse){const i=new f(p.internalError,t);throw r(i),i}try{this.schedulePostResponse(e)}catch(i){throw r(i),i}}releaseBufferedAfterResponse(e,t,r){const i=u(async()=>{if(e.detached&&e.activeForegroundAccepted){e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId),e.activeResponseCommitted=void 0;return}try{(e.activeOperationKind==="prompt"||e.activeOperationKind==="compact")&&e.activeForegroundAccepted&&e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId),await this.flushBuffered(e)}catch(o){e.deliveryFailure??=o,this.handleChildFailure(e,o)}finally{e.barrier.resolve(),r?.()}},"release"),n=t.responseCommitted;if(n){n.then(i,o=>{if(this.canSurviveResponseFailure(e,t))return i();if(e.detached&&e.activeForegroundAccepted){e.activeResponseCommitted=void 0;return}e.deliveryFailure??=o,this.handleChildFailure(e,o),r?.()}).catch(o=>{e.deliveryFailure??=o,this.handleChildFailure(e,o)});return}this.schedulePostResponseTask(i,"Agent Harness request is missing its response-commit boundary",()=>{this.dropBuffered(e),r?.()})}releaseDetachedRebindAfterResponse(e,t,r){const i=u(async()=>{try{this.subagentProjection.commitRebind(r.projection,t.connectionSignal),e.rebindProjection=void 0,e.detached=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayResponsePending=!1,e.activeForegroundAccepted&&e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId,e.activeResponseCommitted=void 0),this.installReconnectLiveSuffix(e),await this.flushBuffered(e),await this.installMcpStatusProjection(e),this.finishForegroundFromReconnectSnapshot(e)}catch(o){e.deliveryFailure??=o,this.handleChildFailure(e,o)}finally{e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.barrier.resolve()}},"commit"),n=u(o=>{this.rollbackDetachedRebind(e,r,o)},"fail");if(t.responseCommitted){t.responseCommitted.then(i,n).catch(o=>{e.deliveryFailure??=o,this.handleChildFailure(e,o)});return}this.schedulePostResponseTask(i,"Agent Harness reconnect is missing its response-commit boundary",o=>this.rollbackDetachedRebind(e,r,o))}installReconnectLiveSuffix(e){const t=e.rebindLiveNotifications??[],r=[],i=new Map;for(const s of t){const c=s.privateLiveUpdate?.notification;if(!c)throw new f(p.internalError,"Reconnect live suffix contained an already-projected notification");r.push(c),i.set(c,s)}const n=e.reconnectMessageCoverage;if(!n)throw new f(p.internalError,"Reconnect message coverage was not initialized");const o=n.mergeLive(r);e.reconnectMessageCoverage=void 0;for(const s of o)this.captureReconnectLiveRootState(e,s);for(const s of t)this.releaseBufferedNotification(e,s);e.rebindLiveNotifications=void 0,e.bufferedNotifications=[];for(const s of o){const c=i.get(s),d=this.reserveBufferedNotification(e,{...c?.afterDelivery===void 0?{}:{afterDelivery:c.afterDelivery},method:this.methods.client.session.update,params:s,privateLiveUpdate:{notification:s}});if(!d)throw new ae("Reconnect live suffix exceeds the notification buffer limit");e.bufferedNotifications.push(d)}}captureReconnectLiveRootState(e,t){const r=t.update,i=r._meta;if(t.sessionId!==e.sessionId||r.sessionUpdate!=="state_update"||A(i)&&Object.hasOwn(i,z)||r.state!=="idle"&&r.state!=="running")return;const n=e.activeRequestId;n===void 0||!A(i)||i[G]!==n||i[we]!==n||(e.reconnectLastRootState=r.state)}captureReconnectRootTerminal(e,t){const r=t.update,i=r._meta;if(t.sessionId!==e.sessionId||r.sessionUpdate!=="session_info_update"||!A(i)||Object.hasOwn(i,z)||!Object.hasOwn(i,Fe))return;const n=pt.safeParse(i[Fe]);if(!n.success)throw new f(p.internalError,"Private ACP v2 replay returned an invalid root turn terminal");const o=e.activeRequestId;o!==void 0&&n.data.requestId===o&&n.data.rootRequestId===o&&(e.reconnectRootTerminalMatched=!0)}finishForegroundFromReconnectSnapshot(e){if(!e.reconnectRootTerminalMatched&&e.reconnectLastRootState!=="idle")return;const t=e.activeOperationController;t&&this.finishActiveOperation(e,t),this.rotateReverseController(e,new Error("Foreground turn completed while detached"))}rollbackDetachedRebind(e,t,r){const i=e.owner;e.proxy.remove(i),e.replayController?.abort(r),e.replayProjection===t.replay&&this.subagentProjection.abortReplay(t.replay,e.owner),this.subagentProjection.abortRebind(t.projection,e.owner),this.discardBufferedNotifications(e);const n=i.aborted,o=this.activations.has(e)&&e.attached;if(!o||n){for(const s of e.rebindLiveNotifications??[])this.releaseBufferedNotification(e,s);e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.rebindProjection=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,o?this.trackCleanup(this.closeActivationsImmediately([e],i,r)):(e.deliveryMode="drop",e.barrier.resolve());return}e.owner=t.detachedOwner,e.ownerContext=t.detachedOwnerContext,e.negotiatedClientCapabilities=t.negotiatedClientCapabilities,e.compactions=new Map([...t.compactions].map(([s,c])=>[s,{...c}])),e.bufferedNotifications=e.rebindLiveNotifications??[],e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.rebindProjection=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,e.deliveryMode="buffer",this.rotateDeliveryGeneration(e),this.armDetachedSession(e,t.detachedOwner,t.detachedReason,t.detachedExpiresAt)}discardBufferedAfterResponse(e,t,r){const i=u(()=>{this.discardBufferedNotifications(e),e.deliveryMode="forward",e.barrier.resolve(),r?.()},"discard"),n=u(s=>{if(this.canSurviveResponseFailure(e,t)){i();return}e.deliveryFailure??=s,this.handleChildFailure(e,s),r?.()},"fail"),o=t.responseCommitted;if(o){o.then(i,n).catch(n);return}this.schedulePostResponseTask(async()=>i(),"Agent Harness request is missing its response-commit boundary",()=>{this.dropBuffered(e),r?.()})}canSurviveResponseFailure(e,t){return t.connectionSignal.aborted&&e.proxy.list().some(r=>r.context.connectionSignal!==t.connectionSignal&&!r.context.connectionSignal.aborted)}toBufferedNotification(e){return{method:e.method,params:e.params}}async flushBuffered(e){if(e.deliveryMode!=="buffer")return;const t=e.bufferedNotifications;e.bufferedNotifications=[];const r=[];let i=!1,n,o=0;for(;o<t.length;o+=1){const d=t[o];try{const l=d.privateLiveUpdate?this.enqueueProjectedNotifications(e,d.privateLiveUpdate.projected??this.projectPrivateUpdate(e,d.privateLiveUpdate.notification),d.afterDelivery):this.enqueueNotification(e,d);r.push(l.finally(()=>this.releaseBufferedNotification(e,d)))}catch(l){this.releaseBufferedNotification(e,d),i=!0,n=l,o+=1;break}}if(i){for(;o<t.length;o+=1)this.releaseBufferedNotification(e,t[o]);throw await Promise.allSettled(r),n}e.deliveryMode="forward";const c=(await Promise.allSettled(r)).find(d=>d.status==="rejected");if(c)throw c.reason}async resolveStoredSubagent(e,t){const r=this.sessionReplay?.subagents;if(!r||this.subagentProjection.rootSessionIdFor(e)!==void 0||(await this.awaitOwnedResponseBoundaryWave(t),this.subagentProjection.rootSessionIdFor(e)!==void 0))return;let i;for(const n of this.sessions.values()){if(!n.proxy.has(t.connectionSignal,"live")||!n.sessionId||!n.resumeParams)continue;await this.settleSubagentResponseBoundary(n,t);const o=await r.read({sessionId:n.sessionId,cwd:n.resumeParams.cwd,workspace:n.workspaceProduct},e,this.mcpOperationSignal(n,t));if(this.assertSessionStillReady(n,t),!!o){if(i)throw new P("Subagent identity is ambiguous across attached roots");i={current:{rootSessionId:n.sessionId,subagent:o.subagent},session:n,stored:o}}}if(!(i&&(await this.settleSubagentResponseBoundary(i.session,t),this.subagentProjection.rootSessionIdFor(e)!==void 0)))return i}async resolveSubagentAfterBoundary(e,t){let r=this.subagentProjection.rootSessionIdFor(e);if(r===void 0){if(!await this.awaitOwnedResponseBoundaryWave(t))return this.throwUnknownSubagent(e,t);if(r=this.subagentProjection.rootSessionIdFor(e),r===void 0)return this.throwUnknownSubagent(e,t)}const i=this.ownedSession(r,t.connectionSignal);if(t.responseCommitted!==void 0&&i.barrierResponseCommitted===t.responseCommitted&&i.deliveryMode==="buffer")throw U(e);await this.settleSubagentResponseBoundary(i,t);const n=this.subagentProjection.readSubagent(e,i.owner);if(n.rootSessionId!==r)throw new f(p.internalError,"Subagent root identity changed across a response boundary");return{current:n,session:i}}throwUnknownSubagent(e,t){const r=[...this.sessions.values()].find(i=>i.proxy.has(t.connectionSignal));throw r&&this.subagentProjection.readSubagent(e,r.owner),U(e)}async awaitOwnedResponseBoundaryWave(e){const t=e.responseCommitted,r=[...this.sessions.values()].flatMap(i=>i.proxy.has(e.connectionSignal)&&i.deliveryMode==="buffer"&&i.detached===void 0&&i.closePromise===void 0&&(t===void 0||i.barrierResponseCommitted!==t)?[{boundary:i.barrier,session:i}]:[]);return r.length===0?!1:(await Promise.all(r.map(({boundary:i,session:n})=>this.awaitSubagentResponseBoundary(n,i,e))),!0)}async settleSubagentResponseBoundary(e,t){const r=e.barrier;if(await this.awaitSubagentResponseBoundary(e,r,t),this.assertSessionStillReady(e,t),e.barrier===r&&e.deliveryMode==="forward")return;if(e.detached!==void 0||e.deliveryMode==="drop"||e.barrier===r)throw U(e.sessionId??"unknown");const i=e.barrier;if(await this.awaitSubagentResponseBoundary(e,i,t),this.assertSessionStillReady(e,t),e.barrier!==i||e.deliveryMode!=="forward")throw new f(p.notReady,"Subagent response boundary changed before it could be read")}async awaitSubagentResponseBoundary(e,t,r){const i=I([r.signal,r.connectionSignal,e.lifecycleController.signal,this.facadeController.signal]);if(await R(t.promise,i),await R(e.deliveryTail,i),e.deliveryFailure!==void 0)throw e.deliveryFailure}dropBuffered(e){this.discardBufferedNotifications(e),e.deliveryMode="drop",e.barrier.resolve()}discardBufferedNotifications(e){for(const t of e.bufferedNotifications)this.releaseBufferedNotification(e,t);e.bufferedNotifications=[]}discardBufferedNotificationsFrom(e,t){const r=e.bufferedNotifications.splice(t);for(const i of r)this.releaseBufferedNotification(e,i)}finalizeBufferedPrivateLiveUpdatesFrom(e,t){for(let r=t;r<e.bufferedNotifications.length;r+=1){const i=e.bufferedNotifications[r],n=i?.privateLiveUpdate;i===void 0||n===void 0||n.projected!==void 0||(e.bufferedNotifications[r]={...i,privateLiveUpdate:{...n,projected:this.projectPrivateUpdate(e,n.notification)}})}}deliverNotification(e,t){if(e.deliveryMode==="drop")return Promise.reject(new f(p.notReady,"Session attachment is closed"));if(e.deliveryMode==="buffer"){const r=this.reserveBufferedNotification(e,t);if(!r){const i=new ae("ACP v2 response-boundary notification buffer limit exceeded");return e.deliveryFailure??=i,this.handleChildFailure(e,i),Promise.reject(i)}return e.bufferedNotifications.push(r),Promise.resolve()}return this.enqueueNotification(e,t)}reserveBufferedNotification(e,t){const r=Buffer.byteLength(JSON.stringify({jsonrpc:"2.0",method:t.method,params:t.params}),"utf8");if(!(e.bufferedNotificationCount>=this.maxBufferedNotifications||e.bufferedNotificationBytes+r>this.maxBufferedNotificationBytes))return e.bufferedNotificationCount+=1,e.bufferedNotificationBytes+=r,{...t,reservedBytes:r}}releaseBufferedNotification(e,t){t.reservedBytes!==void 0&&(e.bufferedNotificationCount-=1,e.bufferedNotificationBytes-=t.reservedBytes,t.reservedBytes=void 0)}rotateDeliveryGeneration(e){e.deliveryGeneration+=1,e.deliveryFailure=void 0,e.deliveryTail=Promise.resolve()}enqueueNotification(e,t){if(e.deliveryMode==="drop")return Promise.reject(new f(p.notReady,"Session attachment is closed"));const r=e.deliveryGeneration,i=e.deliveryTail.then(async()=>{if(e.deliveryMode==="drop"||e.deliveryGeneration!==r)throw new f(p.notReady,"Session delivery generation changed");await e.proxy.notify(t.method,t.params),t.afterDelivery?.()});return e.deliveryTail=i.catch(n=>{e.deliveryGeneration===r&&(e.deliveryFailure??=n)}),i}async awaitBarrier(e,t){if(t?(await R(e.barrier.promise,t),await R(e.deliveryTail,t)):(await e.barrier.promise,await e.deliveryTail),e.deliveryFailure!==void 0)throw e.deliveryFailure}rotateReverseController(e,t){const r=e.reverseController.current;e.reverseController.current=e.attachmentScope.replaceController(r,t)}clearReplayController(e,t){const r=e.replayController;!r||t!==void 0&&r!==t||(e.replayController=void 0,e.attachmentScope.releaseController(r))}beginActiveOperation(e,t){if(e.activeOperationController)throw M(e.sessionId??"unknown");const r=e.attachmentScope.makeController();return e.activeOperationController=r,e.activeOperationKind=t,(t==="prompt"||t==="compact")&&this.beginProductForeground(e),r}beginProductForeground(e){e.productForegroundPending||(e.productForegroundDrain=Promise.withResolvers(),e.productForegroundPending=!0,this.pendingProductForegroundCount+=1)}resolveProductForeground(e){e.productForegroundPending&&(e.productForegroundPending=!1,this.pendingProductForegroundCount-=1,e.productForegroundDrain?.resolve())}finishPublicForegroundAtTerminalReceipt(e,t){e.activeOperationController!==t||e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||(this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.activeCompactionId=void 0,e.activeOperationController=void 0,e.activeOperationKind=void 0,e.attachmentScope.releaseController(t))}finishActiveOperation(e,t){e.activeOperationController===t&&(e.activeOperationKind==="prompt"||e.activeOperationKind==="compact"?(this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.foreground=!1,e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.activeCompactionId=void 0):e.activeOperationKind==="config"&&(e.configWriteInFlight=!1),e.activeOperationController=void 0,e.activeOperationKind=void 0,e.attachmentScope.releaseController(t))}abortActiveOperation(e,t){const r=e.activeOperationController;r&&!r.signal.aborted&&r.abort(t)}handlePrivateChildExit(e,t,r){if(e.childFailureToken!==r||!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight||e.childFailurePromise)return;const i=e.recoverableActivation;if(i){i.failure??=t,e.replayController?.abort(t);return}const n=e.activeRequestId,o=e.sessionId,s=e.resumeParams?.cwd,c=e.acknowledgedRequestId===n||e.activeResponseCommitted!==void 0;if(e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground||!e.activeForegroundAccepted||typeof n!="string"||n.trim().length===0||typeof o!="string"||o.trim().length===0||typeof s!="string"||s.trim().length===0||!c){this.handleChildFailure(e,t);return}const d=this.recoverAcknowledgedChildExit(e,t,r,{cwd:s,requestId:n,sessionId:o});e.childFailurePromise=d,d.finally(()=>{e.childFailurePromise===d&&(e.childFailurePromise=void 0)}).catch(()=>{}),this.trackCleanup(d)}async recoverAcknowledgedChildExit(e,t,r,i){try{e.acknowledgedRequestId!==i.requestId&&(await e.activeResponseCommitted,e.acknowledgedRequestId=i.requestId)}catch(C){this.handleChildFailure(e,C);return}if(e.childFailureToken!==r||!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight||e.activeRequestId!==i.requestId)return;const n=e.activeOperationController,o=e.child,s=this.processRuntime.policyNow(),c=new Date(s).toISOString(),d={[G]:i.requestId,[we]:i.requestId,[Wt]:c};this.abortActiveOperation(e,t),this.rotateReverseController(e,t),e.child=void 0,e.authReady=!1,e.childFailureToken=void 0,e.privateMcpServers=void 0,this.releaseWorkspaceProductBinding(e);const l=[];try{await this.enqueueNotification(e,{method:this.methods.client.session.update,params:{sessionId:i.sessionId,update:{sessionUpdate:pe,error:Se,willRetry:!1,_meta:d}}})}catch(C){l.push(C)}const[h,m]=await Promise.allSettled([o?.dispose(t)??Promise.resolve(),this.runAttachedHostSessionOperation(e,C=>{const k={cwd:i.cwd,error:Se,requestId:i.requestId,rootRequestId:i.requestId,sessionId:i.sessionId,stopReason:pe,timestamp:s};return this.sessionService?H.runPromise(this.sessionService.commitTerminal(k,{signal:C})):this.requireHostSessionControl().commitTerminalState(k,{signal:C})})]);h.status==="rejected"&&l.push(h.reason);let y=!1;m.status==="fulfilled"?y=!0:l.push(m.reason);try{y&&await this.enqueueNotification(e,{method:this.methods.client.session.update,params:{sessionId:i.sessionId,update:{sessionUpdate:"state_update",state:"idle",stopReason:pe,_meta:{[ft]:Se,...d}}}})}catch(C){l.push(C)}finally{n&&this.finishActiveOperation(e,n)}if(l.length>0){const C=l.length===1?l[0]:new AggregateError(l,"Private Agent child terminal recovery failed");e.deliveryFailure??=C,this.handleChildFailure(e,C)}}runAttachedHostSessionOperation(e,t){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));const r=I([e.lifecycleController.signal,this.facadeController.signal]),i=R(Promise.resolve().then(()=>t(r)),r);return this.managementOperations.add(i),i.then(()=>this.managementOperations.delete(i),()=>this.managementOperations.delete(i)),i}handleChildFailure(e,t){this.handleActivationFailure(e,t,t instanceof ae||t instanceof Tt||t instanceof jt||t instanceof Nt?"attachment":"connection")}handleActivationFailure(e,t,r){if(!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight)return;e.activeRequestId=void 0;const i=e.attached,n=e.sessionId,o=e.proxy.list().map(s=>s.context);if(e.startupController.signal.aborted||e.startupController.abort(t),this.rotateReverseController(e,t),this.dropBuffered(e),this.detach(e),this.trackCleanup(this.disposeChild(e,t)),i){if(r==="connection"){for(const s of o)s.closeConnection?.(t).catch(()=>{});return}if(n===void 0){for(const s of o)s.closeConnection?.(t).catch(()=>{});return}for(const s of o){const c=s.closeSessionAttachment;c?.(n,t).catch(d=>{s.closeConnection?.(d).catch(()=>{})})}}}runHostSessionOperation(e,t,r=!1,i=!1){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));const n=I([...r?[]:[e.connectionSignal,e.signal],this.facadeController.signal]),o=Promise.resolve().then(()=>t(n)),s=i?o:R(o,n);return this.managementOperations.add(s),s.then(()=>this.managementOperations.delete(s),()=>this.managementOperations.delete(s)),s}closeAttached(e,t,r){return e.closePromise??=this.performCloseAttached(e,t,r),e.closePromise}async performCloseAttached(e,t,r){if(e.replayInFlight)return this.forceCloseReplay(e);const i=new Error("Session closing");this.abortActiveOperation(e,i),this.rotateReverseController(e,i);const n=this.processRuntime.createPolicyDeadline(this.closeSessionTimeoutMs,{signals:[e.lifecycleController.signal,this.facadeController.signal],timeoutReason:Re()}),o=n.signal;let s,c;try{if(e.deliveryMode==="buffer"?this.dropBuffered(e):r&&await R(e.deliveryTail,o),e.deliveryFailure!==void 0)throw e.deliveryFailure;const l=e.child;if(l?s=this.validateChildBoundary(e,"CloseSessionResponse",await R(l.closeSession(t,{signal:o}),o)):s={},await R(e.deliveryTail,o),e.deliveryFailure!==void 0)throw e.deliveryFailure}catch(l){c=l}finally{n.close()}let d;try{await this.disposeChild(e,c)}catch(l){d=l}finally{this.dropBuffered(e),this.detach(e)}if(c!==void 0)throw Q(c,d,"Private ACP v2 session close and cleanup failed");if(d!==void 0)throw d;return s??{}}async forceCloseReplay(e){const t=new Error("Session closed during replay");this.abortActiveOperation(e,t),e.replayController?.abort(t),this.clearReplayController(e),e.replayInFlight=!1,e.replayResponsePending=!1,this.rotateReverseController(e,t),this.dropBuffered(e);try{await this.disposeChild(e,t)}finally{this.detach(e)}return{}}async failActivation(e,t){e.startupController.signal.aborted||e.startupController.abort(t),this.rotateReverseController(e,t),this.detach(e);try{await this.disposeChild(e,t)}catch(r){throw Q(t,r,"Private ACP v2 activation and cleanup failed")}}disposeChild(e,t){return this.suspendMcpStatusProjection(e),e.disposePromise??=e.attachmentScope.close(t),e.disposePromise}async disposeAttachmentResources(e,t){this.suspendMcpStatusProjection(e);const r=e.executorReleasePromise??e.child?.dispose(t)??Promise.resolve(),n=(await Promise.allSettled([r,e.mcpAttachment?.revoke()??Promise.resolve()])).filter(o=>o.status==="rejected");if(n.length===1)throw n[0].reason;if(n.length>1)throw new AggregateError(n.map(o=>o.reason),"Private Agent child and MCP attachment cleanup failed")}detach(e){for(const n of e.proxy.list())e.proxy.remove(n.context.connectionSignal);this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.agentInitiatedForegroundToken=void 0,e.publicForegroundDeliveryToken=void 0;const t=e.rebindProjection&&e.detached?e.detached.owner:e.owner;e.rebindProjection&&(this.subagentProjection.abortRebind(e.rebindProjection,e.owner),e.rebindProjection=void 0),e.detached&&(e.detached.timer.cancel(),e.detached=void 0);for(const n of e.rebindLiveNotifications??[])this.releaseBufferedNotification(e,n);e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.lifecycleController.signal.aborted||e.lifecycleController.abort(new Error("Agent session runtime detached")),e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.childFailureToken=void 0;const r=e.sessionId;r&&this.sessions.get(r)===e&&this.sessions.delete(r);const i=r??e.expectedSessionId;i&&this.subagentProjection.detachSession(i,t),this.activations.delete(e),this.releaseWorkspaceProductBinding(e)}trackCleanup(e){this.trackedCleanup.add(e),e.then(()=>this.trackedCleanup.delete(e),()=>this.trackedCleanup.delete(e))}async releaseOwner(e,t){const r=[...this.activations].filter(i=>i.proxy.has(e)||!i.attached&&i.owner===e);await Promise.all(r.map(i=>this.releaseSessionAttachment(i,e,t)))}async releaseSessionAttachment(e,t,r,i){const n=e.proxy.list().find(s=>s.context.connectionSignal===t)?.context.connection.transport??i;if(e.proxy.remove(t),e.proxy.list().length>0||e.detached||!this.activations.has(e))return;const o=e.sessionId;if(!(o&&this.reservations.get(o)?.kind==="checkpointing"&&e.deliveryMode==="buffer"&&(await e.barrier.promise,e.proxy.list().length>0||e.detached||!this.activations.has(e)))){if(n!=="stdio"&&this.canDetachSubscriber(e)){this.detachSubscriber(e,t,r);return}await this.closeActivationsImmediately([e],t,r)}}canDetachSubscriber(e){return!!(e.attached&&e.sessionId&&!e.closePromise&&!e.executorReleaseInFlight&&!e.childStartup&&!e.rebinding&&!e.replayInFlight&&!e.configWriteInFlight&&e.deliveryFailure===void 0&&(e.deliveryMode==="forward"||e.deliveryMode==="buffer"&&e.activeForegroundAccepted))}detachSubscriber(e,t,r){this.suspendMcpStatusProjection(e),e.deliveryMode==="forward"&&this.holdNotifications(e),this.rotateDeliveryGeneration(e),this.rotateReverseController(e,r),this.armDetachedSession(e,t,r)}armDetachedSession(e,t,r,i=this.processRuntime.policyNow()+this.detachedSessionGraceMs){e.detached&&e.detached.timer.cancel();const n=e.attachmentScope.schedule(Math.max(0,i-this.processRuntime.policyNow()),async()=>{if(e.detached?.owner!==t||e.rebinding||!this.activations.has(e))return;const o=this.expireDetachedSession(e,t);this.trackCleanup(o),await o});e.detached={expiresAt:i,owner:t,reason:r,timer:n}}async expireDetachedSession(e,t){const r=e.sessionId;if(!(!r||e.detached?.owner!==t||e.rebinding||!this.activations.has(e))){this.reservations.has(r)||this.reservations.set(r,{kind:"closing",owner:t});try{await this.closeAttached(e,{sessionId:r},!1)}finally{this.reservations.get(r)?.owner===t&&this.reservations.delete(r)}}}async closeOwnedImmediately(e,t){const r=[...this.activations].filter(i=>i.owner===e);await this.closeActivationsImmediately(r,e,t)}async closeActivationsImmediately(e,t,r){for(const i of e){if(i.detached&&i.detached.timer.cancel(),i.startupController.signal.aborted||i.startupController.abort(r),this.abortActiveOperation(i,r),this.rotateReverseController(i,r),!i.attached||!i.sessionId){this.dropBuffered(i);continue}i.deliveryMode==="buffer"&&this.dropBuffered(i);const n=i.sessionId;n&&!this.reservations.has(n)&&this.reservations.set(n,{kind:"closing",owner:t})}await Promise.allSettled(e.map(async i=>{i.attached&&i.sessionId?await this.closeAttached(i,{sessionId:i.sessionId},!1):(await this.disposeChild(i,r),this.detach(i))}));for(const[i,n]of this.reservations)n.owner===t&&this.reservations.delete(i)}async closeAll(e){this.closing=!0,this.facadeController.signal.aborted||this.facadeController.abort(e);const t=new Set([...this.activations].map(r=>r.owner));for(await Promise.allSettled([...t].map(r=>this.closeOwnedImmediately(r,e))),await Promise.allSettled([...this.managementOperations]);this.trackedCleanup.size>0;)await Promise.allSettled([...this.trackedCleanup])}}function Xe(a,e){const t=fe(a,e);if(t)throw new P(t.message);return e}u(Xe,"validatePublicNotification");function be(a){if(typeof a!="object"||a===null||Object.isFrozen(a))return a;Object.freeze(a);for(const e of Object.values(a))be(e);return a}u(be,"deepFreeze");function Ae(a,e){const t=[...a];return t.length===e.length&&t.every((r,i)=>r===e[i])}u(Ae,"sameMethods");export async function createAgentV2Facade(a){if(!a.hostSessionControl&&(!a.sessions||!a.checkpoints||!a.sessionReplay||!a.sessionRuntime.rewind||!a.pluginMcp||!a.userMcp))throw new TypeError("Session storage, replay, rewind and MCP services are required without legacy session control");const e=a.processRuntime??ot(),t=a.maxActiveSessions??Be,r=a.maxBufferedNotificationBytes??Te,i=a.maxBufferedNotifications??De,n=a.closeSessionTimeoutMs??Dt,o=a.configReloadTimeoutMs??Ut,s=a.detachedSessionGraceMs??Gt,c=a.sessionActivationTimeoutMs??Ue,d=a.initialProductGeneration??0;if($(t,"maxActiveSessions"),$(r,"maxBufferedNotificationBytes"),$(i,"maxBufferedNotifications"),$(n,"closeSessionTimeoutMs"),$(o,"configReloadTimeoutMs"),$(s,"detachedSessionGraceMs"),$(c,"sessionActivationTimeoutMs"),!Number.isSafeInteger(d)||d<0)throw new RangeError("initialProductGeneration must be a non-negative safe integer");if(t>Ge)throw new RangeError(`maxActiveSessions must not exceed ${Ge}`);if(r>We)throw new RangeError(`maxBufferedNotificationBytes must not exceed ${We}`);if(i>He)throw new RangeError(`maxBufferedNotifications must not exceed ${He}`);const[l,h]=await Promise.all([ut(),import("../effect-runtime/session-attachment-scope.mjs")]),m=a.sessionRuntime.profile,y=structuredClone(a.agentCapabilities??m?.capabilities??zt(a.platform??process.platform,a.windowsProcessContainmentEnabled,a.windowsJob)),C=be(m?.supports.promptSteer===!1?y:Zt(y)),k=ne({session:{delete:{},fork:{}}},C,"capabilities");if(k)throw new Error(`Agent v2 facade requires ${k}`);O("InitializeResponse",{authMethods:[],capabilities:C,info:a.serverInfo,protocolVersion:2});const S=new ur({agentCapabilities:C,closeSessionTimeoutMs:n,configReloadTimeoutMs:o,createAttachmentScope:h.openSessionAttachmentScope,detachedSessionGraceMs:s,hostSessionControl:a.hostSessionControl,initialProductGeneration:d,maxActiveSessions:t,maxBufferedNotificationBytes:r,maxBufferedNotifications:i,mcpIntegration:a.mcpIntegration,strictMcpConfig:a.strictMcpConfig??!1,methods:q,onPermanentFailure:a.onPermanentFailure,processRuntime:e,prepareSessionRuntime:a.prepareSessionRuntime,prepareSessionWorkspace:a.prepareSessionWorkspace,releaseSessionWorkspace:a.releaseSessionWorkspace,refreshAuthentication:a.refreshAuthentication,schedulePostResponse:a.schedulePostResponse,sessionActivationTimeoutMs:c,serverInfo:a.serverInfo,sessionRuntime:a.sessionRuntime,sessionReplay:a.sessionReplay,sessions:a.sessions,checkpoints:a.checkpoints,userMcp:a.userMcp,pluginMcp:a.pluginMcp,subagentProjection:new _e({maxBufferedNotificationBytes:r,maxBufferedNotifications:i})}),F=be({agent:C}),b=new Map([[q.agent.mcp.message,(g,w)=>S.clientMcp.message(D("MessageMcpRequest",g),w)],[q.agent.session.new,async(g,w)=>{T().set({path:"cold"});const v=D("NewSessionRequest",g),ee=v.mcpServers??[],te=T();return te.setCount("requestedMcpServerCount",ee.length),te.setCount("requestedStdioMcpCount",ee.filter(J=>J.type==="stdio").length),te.setCount("requestedRemoteMcpCount",ee.filter(J=>J.type==="http"||J.type==="sse").length),S.preflightNewSession(v),S.runPreparedProductAdmittedRequest(w,v.cwd,J=>S.newSession(v,w,J))}],[q.agent.session.list,(g,w)=>S.listSessions(D("ListSessionsRequest",g),w)],[q.agent.session.delete,(g,w)=>{const v=D("DeleteSessionRequest",g);return S.runExistingWorkspaceAdmittedSessionRequest(v.sessionId,w,()=>S.deleteSession(v,w))}],[q.agent.session.fork,(g,w)=>{const v=Qt(g);return S.runAdmittedSessionRequest(v.sessionId,w,()=>S.forkSession(v,w))}],[q.agent.session.resume,(g,w)=>{const v=xt(g);return S.runResumeSessionRequest(v,w)}],[q.agent.session.close,(g,w)=>{const v=D("CloseSessionRequest",g);return S.runExistingWorkspaceAdmittedSessionRequest(v.sessionId,w,()=>S.closeSession(v,w))}],[q.agent.session.setConfigOption,(g,w)=>{const v=D("SetSessionConfigOptionRequest",g);return S.runPreparedAdmittedSessionRequest(v.sessionId,w,()=>S.setSessionConfigOption(v,w))}],[q.agent.session.prompt,(g,w)=>{const v=er(g);if(m?.supports.promptSteer===!1&&qe(v._meta)?.mode===Oe)throw new f(p.methodNotFound,"Session backend does not support steer");return S.runPreparedAdmittedSessionRequest(v.sessionId,w,()=>S.prompt(v,w))}]]),j=new Map([[re.list,he(rt,(g,w)=>S.listCheckpoints(g,w))],[re.read,he(it,(g,w)=>S.readCheckpoint(g,w))],[re.restore,he(nt,(g,w)=>S.restoreCheckpoint(g,w))],[ge,(g,w)=>{const v=tr(g);return S.runPreparedAdmittedSessionRequest(v.sessionId,w,()=>S.compactSession(v,w))}],[ye,(g,w)=>{const v=ir(g);return S.runExistingWorkspaceAdmittedSessionRequest(v.sessionId,w,()=>S.rewindSession(v,w))}]]),N=new Map([...b,...j]);if(m?.supports.compact===!1&&N.delete(ge),m?.checkpoints===!1)for(const g of Object.values(re))N.delete(g);m?.checkpoints===!1&&!a.sessionRuntime.rewind&&N.delete(ye);const _=new Map([[q.agent.mcp.message,(g,w)=>S.clientMcp.notify(Xe("MessageMcpNotification",g),w)],[q.agent.session.cancel,(g,w)=>S.cancel(Xe("CancelSessionNotification",g),w)]]),W=Object.freeze({inboundNotificationHandlers:_,inboundRequestHandlers:N,outboundNotificationMethods:l.outboundNotifications,outboundRequestMethods:l.outboundRequests});if(!Ae(b.keys(),l.inboundRequests)||!Ae(_.keys(),l.inboundNotifications)||!Ae(j.keys(),[...Object.values(re),ge,ye]))throw new Error("Agent v2 facade registries do not match their exact method allowlists");return{capabilities:F,clearAuthentication:u((g,w)=>S.clearAuthentication(g,w),"clearAuthentication"),failProductGeneration:u(g=>S.failProductGeneration(g),"failProductGeneration"),initialize:u((g,w)=>{const v=S.selectProfile(w),ee=Object.freeze([q.client.session.requestPermission,...Object.values(q.client.mcp),...v.elicitationForm||v.elicitationUrl?[q.client.elicitation.create]:[]]),te=Object.freeze([q.client.session.update,q.client.mcp.message,...v.elicitationUrl?[q.client.elicitation.complete]:[]]);return{capabilities:F,registry:Object.freeze({inboundNotificationHandlers:_,inboundRequestHandlers:N,outboundNotificationMethods:te,outboundRequestMethods:ee})}},"initialize"),notificationHandlers:_,registry:W,requestHandlers:N,close:u(g=>S.close(g),"close"),callMcpServerTool:u((g,w)=>S.runAdmittedSessionRequest(g.threadId,w,()=>S.callMcpServerTool(g,w)),"callMcpServerTool"),listMcpServerStatuses:u((g,w)=>S.runAdmittedSessionRequest(g.threadId,w,()=>S.listMcpServerStatuses(g,w)),"listMcpServerStatuses"),listSubagents:u((g,w)=>S.runAdmittedSessionRequest(g.sessionId,w,()=>S.listSubagents(g,w)),"listSubagents"),readSubagent:u((g,w)=>S.runAdmittedSessionRequest(g.sessionId,w,()=>S.readSubagent(g,w)),"readSubagent"),reloadUserConfig:u(g=>S.reloadUserConfig(g),"reloadUserConfig"),rotateProductGeneration:u((g,w,v)=>S.rotateProductGeneration(g,w,v),"rotateProductGeneration"),setAuthentication:u((g,w)=>S.setAuthentication(g,w),"setAuthentication")}}u(createAgentV2Facade,"createAgentV2Facade");
1
+ var Ze=Object.defineProperty;var u=(a,e)=>Ze(a,"name",{value:e,configurable:!0});import{createHash as Qe,randomUUID as xe}from"node:crypto";import T from"node:path";import{Effect as z,Result as et,Schema as tt}from"effect";import"../auth/session.js";import{AGENT_HARNESS_CHECKPOINT_METHODS as ie,CheckpointList as rt,CheckpointRead as it,CheckpointRestore as nt}from"../checkpoint/rpcs.js";import"../checkpoint/schemas.js";import{currentHarnessProcessRuntime as ot}from"../effect-runtime/process-runtime-context.js";import{ClientMcpRouter as st}from"../integration/client-mcp-attachment.js";import{SessionMcpSourceUnavailableError as at,SessionMcpViewRevokedError as ct}from"../integration/session-mcp-view.js";import{EMPTY_USER_MCP_SNAPSHOT as de}from"../integration/source-compiler.js";import{resolveStdioMcpContainment as dt}from"../integration/stdio-guardian.js";import{abortable as R,abortReason as k,once as le,queueTransition as Ie}from"../internal/async.js";import{normalizeError as ue}from"../internal/errors.js";import{isRecord as I}from"../internal/guards.js";import{MCP_SERVER_PROTOCOL_METHODS as he}from"../mcp-server/module.js";import{MCP_SERVER_MAX_ERROR_CHARS as lt}from"../mcp-server/schemas.js";import{requestHandler as fe}from"../module/validation.js";import{ACP_V2_METHODS as N,loadAcpV2CoreMethodAllowlist as ut}from"../protocol/acp-v2.js";import{validateAcpV2CoreSchema as pe,validateAcpV2SchemaWithCodeBuddyCredits as ht}from"../protocol/acp-v2-schema.js";import{AGENT_HARNESS_ERROR_META_KEY as ft,AGENT_HARNESS_ERROR_UPDATE as me,AGENT_HARNESS_TURN_TERMINAL_META_KEY as Fe,agentHarnessSessionErrorValidationError as Me,agentHarnessTurnTerminalSchema as pt}from"../protocol/error.js";import{AGENT_HARNESS_PROMPT_CAPABILITY as Ee,AGENT_HARNESS_PROMPT_META_KEY as ge,AGENT_HARNESS_PROMPT_STEER_MODE as Oe,projectPromptRequestToPrivate as ke,projectPromptResponseToPublic as mt,promptMetadata as qe,promptMetadataValidationError as gt}from"../protocol/prompt.js";import{equalSessionEnabledPlugins as yt,mergeSessionEnabledPluginsConfigOption as je,normalizeSessionPluginSettingsSnapshot as wt,sessionEnabledPluginsFromSetRequest as St}from"../protocol/session-plugin-settings.js";import{isAgentHarnessProcessContainmentEnabled as Ct}from"../runtime/sfe-process-containment.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as p,AgentHarnessInvalidParamsError as b,AgentHarnessJsonRpcError as f,AgentHarnessPeerError as Pt,AgentHarnessTimeoutError as Rt}from"../server/errors.js";import{AGENT_HARNESS_COMPACT_METHOD as ye,AGENT_HARNESS_COMPACTION_TRIGGER_META_KEY as vt,AGENT_HARNESS_COMPACTION_UPDATE as Ne,compactionUpdateValidationError as bt,compactSessionRequestValidationError as At,compactSessionResponseValidationError as It}from"../session/compact.js";import{AGENT_HARNESS_REWIND_METHOD as we,AGENT_HARNESS_TURN_REPLAY_TYPE as Ft,rewindSessionRequestSchema as Mt,turnBoundaryValidationError as Et,turnPageValidationError as Ot,turnReplayValidationError as kt}from"../session/turn.js";import{mergeSubagentReplay as qt}from"../subagent/history.js";import{PRIVATE_SUBAGENT_META_KEY as Y,REQUEST_ID_META_KEY as L,ROOT_REQUEST_ID_META_KEY as Se,SubagentAttachmentBufferOverflowError as jt,SubagentJournalOverflowError as Nt,SubagentProjection as _e}from"../subagent/projection.js";import{measure as B,useLog as D}from"../telemetry/index.js";import{ReconnectMessageCoverageCollector as _t}from"./reconnect-message-merge.js";import{AcpSessionProxy as Bt,AcpSessionProxyBufferOverflowError as Tt}from"./session-proxy.js";const Be=32,Te=8*1024*1024,De=2048,Dt=1e4,Ut=1e4,Gt=3e4,Ue=3e4,Ge=Be,We=Te,He=De,$=4096,Le=256,Ke=64,ze="codebuddy.ai/privateSessionInitializationDurations",Wt="codebuddy.ai/timestamp",Ht=null,Ce=Object.freeze({code:"internal_error",message:"The agent process terminated unexpectedly."}),Lt=Object.freeze({authReady:"privateSessionAuthReady",configProjection:"privateSessionConfigProjection",endpointResolve:"privateSessionEndpointResolve",sessionMaterialize:"privateSessionMaterialize",modelsProjection:"privateSessionModelsProjection",modesProjection:"privateSessionModesProjection"});function Kt(a){const e=a._meta;if(!I(e))return a;const t=e[ze];if(I(t)){const i=D();for(const[n,o]of Object.entries(Lt)){const s=t[n];typeof s=="number"&&Number.isFinite(s)&&s>=0&&s<=Ue&&i.addDuration(o,s)}}const r={...e};if(delete r[ze],Object.keys(r).length===0){const{_meta:i,...n}=a;return n}return{...a,_meta:r}}u(Kt,"consumePrivateSessionInitializationDurations");function zt(a,e=Ct(),t){return{session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},...dt({platform:a,requested:!0,windowsProcessContainmentEnabled:e,windowsJob:t}).allowStdio?{stdio:{}}:{}},prompt:{embeddedContext:{},image:{},_meta:{[ge]:Ee}}}}}u(zt,"defaultAgentCapabilities");function ne(a){return Array.isArray(a)?a.map(ne):I(a)?Object.fromEntries(Object.entries(a).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ne(t)])):a}u(ne,"stableJsonValue");const $t=50,$e=1;function Ve(a){return Qe("sha256").update(JSON.stringify(ne(a))).digest("base64url")}u(Ve,"digestMcpStatusValue");function Vt(a){return Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}u(Vt,"encodeMcpServerStatusCursor");function Yt(a){const e=u(()=>{throw new b("Invalid MCP server status cursor")},"fail");try{if(!/^[A-Za-z0-9_-]+$/.test(a))return e();const t=Buffer.from(a,"base64url");if(t.toString("base64url")!==a)return e();const r=JSON.parse(t.toString("utf8"));return!I(r)||Object.keys(r).length!==6||r.version!==$e||typeof r.attachmentEpoch!="string"||r.attachmentEpoch.length===0||typeof r.fingerprint!="string"||r.fingerprint.length===0||!Number.isSafeInteger(r.index)||r.index<=0||typeof r.previousName!="string"||r.previousName.length===0||typeof r.queryFingerprint!="string"||r.queryFingerprint.length===0?e():r}catch(t){if(t instanceof b)throw t;return e()}}u(Yt,"decodeMcpServerStatusCursor");function Jt(a){return{...a._meta===void 0?{}:{_meta:structuredClone(a._meta)},...a.annotations?.title===void 0?{}:{title:a.annotations.title},...a.description===void 0?{}:{description:a.description},inputSchema:structuredClone(a.inputSchema),name:a.name,...a.outputSchema===void 0?{}:{outputSchema:structuredClone(a.outputSchema)},...a.annotations===void 0?{}:{annotations:structuredClone(a.annotations)}}}u(Jt,"projectMcpServerTool");function Xt(a){const e=a.status==="available"?a.tools:[];return{authStatus:"unknown",name:a.logicalName,resourceTemplates:[],resources:[],serverInfo:null,tools:Object.fromEntries(e.map(t=>[t.name,Jt(t)]))}}u(Xt,"projectMcpServerStatus");function U(a){const e=(a.mcpServers??[]).map(t=>JSON.stringify(ne(t))).sort();return JSON.stringify({cwd:T.resolve(a.cwd),mcpServers:e})}u(U,"sessionAttachmentKey");function x(a){return JSON.stringify((a.additionalDirectories??[]).map(e=>T.resolve(e)).sort())}u(x,"additionalDirectoriesKey");function se(a,e){const t=I(a._meta)?{...a._meta}:a._meta;return I(t)&&(delete t.after,delete t.before),{additionalDirectories:structuredClone(a.additionalDirectories??[]),cwd:a.cwd,mcpServers:structuredClone(a.mcpServers??[]),...t===void 0?{}:{_meta:t},replayFrom:null,sessionId:e}}u(se,"resumeParamsForSession");function Zt(a){const e=a.session??{},t=e.prompt??{},r=I(t._meta)?t._meta:{};return{...a,session:{...e,prompt:{...t,_meta:{...r,[ge]:Ee}}}}}u(Zt,"advertisePromptSteerCapability");function E(a){return AbortSignal.any([...a])}u(E,"combineSignals");function Pe(){return new DOMException("The operation was aborted due to timeout","TimeoutError")}u(Pe,"operationTimeoutReason");function Re(a){return a.filter(e=>{if(!I(e.params))return!0;const t=e.params.update;return!I(t)||t.sessionUpdate!=="state_update"})}u(Re,"withoutReplayStateUpdates");function J(a,e){if(!Number.isSafeInteger(a)||a<=0)throw new RangeError(`${e} must be a positive integer`)}u(J,"assertPositiveInteger");function ae(a){if((a.additionalDirectories?.length??0)>Le)throw new b(`additionalDirectories must contain at most ${Le} entries`);if((a.mcpServers?.length??0)>Ke)throw new b(`mcpServers must contain at most ${Ke} entries`)}u(ae,"assertSessionSetupLimits");function G(a,e){const t=pe(a,e);if(t)throw new b(t.message);return e}u(G,"validatePublicRequest");function Qt(a){const e=G("ForkSessionRequest",a),t=Et(e._meta,!1);if(t)throw new b(t);return e}u(Qt,"validatePublicForkRequest");function xt(a){const e=G("ResumeSessionRequest",a),t=kt(e.replayFrom);if(t)throw new b(t);return e}u(xt,"validatePublicResumeRequest");function er(a){const e=G("PromptRequest",a),t=gt(e._meta);if(t)throw new b(t);return e}u(er,"validatePublicPromptRequest");function tr(a){const e=At(a);if(e)throw new b(e);return a}u(tr,"validatePublicCompactRequest");function rr(a){const e=It(a);if(e)throw new f(p.internalError,`Invalid private session/compact result: ${e}`.slice(0,$));return structuredClone(a)}u(rr,"validatePrivateCompactResponse");function ir(a){const e=tt.decodeUnknownResult(Mt,{onExcessProperty:"error",reportInput:!1})(a);if(et.isFailure(e))throw new b(`Invalid session/rewind params: ${e.failure.message}`);return e.success}u(ir,"validatePublicRewindRequest");function W(a){return a.replayFrom?.type===Ft}u(W,"isTurnReplay");function X(a,e,t){const r=Ot(a._meta,e);if(r)throw new f(p.internalError,`Invalid ${t} turn replay response: ${r}`.slice(0,$));return a}u(X,"validateTurnPageBoundary");function nr(a){if(!I(a))throw new f(p.internalError,"Invalid Host session/rewind response");if(a._meta!==void 0&&a._meta!==null&&!I(a._meta))throw new f(p.internalError,"Invalid Host session/rewind response _meta");if(Object.keys(a).some(e=>e!=="_meta"))throw new f(p.internalError,"Invalid Host session/rewind response fields");return a._meta===void 0?{}:{_meta:structuredClone(a._meta)}}u(nr,"validateHostRewindResponse");function j(a,e){const t=ht(a,e);if(t)throw new f(p.internalError,`Invalid private ACP v2 ${a}: ${t.message}`.slice(0,$));return e}u(j,"validatePrivateBoundary");function ve(a,e){const t=pe(a,e);if(t)throw new f(p.invalidRequest,`Invalid Host ACP v2 ${a}: ${t.message}`.slice(0,$));return e}u(ve,"validateHostBoundary");function H(a){return new f(p.invalidRequest,`Session ${a} is not active for this connection`)}u(H,"invalidSession");function M(a){return new f(p.invalidRequest,`Session ${a} already has active or pending work`)}u(M,"busySession");class ce extends f{static{u(this,"AttachmentBufferOverflowError")}constructor(e){super(p.overloaded,e)}}function or(a){return new f(p.invalidRequest,`Session ${a} has no active prompt that can accept steer input`)}u(or,"noActivePromptForSteer");function sr(a){return new f(p.invalidRequest,`Session ${a} active prompt request identity does not match expectedRequestId`)}u(sr,"activePromptIdentityMismatch");function Z(a){return a.deliveryMode==="drop"}u(Z,"attachmentDropped");function ar(a){return a instanceof Pt||a instanceof f&&a.code!==p.internalError}u(ar,"recoverablePrivateReplayError");function Ye(a){return!(a instanceof f&&a.code===p.internalError)}u(Ye,"recoverableHostReplayError");function oe(a,e,t="capabilities"){for(const[r,i]of Object.entries(a)){if(r==="_meta"||i===void 0||i===null)continue;const n=e[r],o=`${t}.${r}`;if(I(i)){if(!I(n))return o;const s=oe(i,n,o);if(s)return s;continue}if(n!==i)return o}}u(oe,"capabilityContains");function V(a,e,t){return e===void 0?a:new AggregateError([a,e],t)}u(V,"aggregateFailure");function Je(a,e){const t=a??[],r=t.findIndex(d=>d.configId==="model"),i=t.filter(d=>d.configId!=="model");if(!e)return a===void 0?void 0:i;const n=new Set(e.options.map(d=>d.value)),o=r<0?void 0:t[r],s={category:"model",configId:"model",currentValue:o?.type==="select"&&typeof o.currentValue=="string"&&n.has(o.currentValue)?o.currentValue:e.currentValue,name:"Model",options:e.options.map(d=>({...d})),type:"select"},c=[...i];return c.splice(r<0?c.length:Math.min(r,c.length),0,s),c}u(Je,"projectHostConfigOptionsForWorkspace");function cr(a,e){if(!a||!e)return a;const t=a.find(r=>r.configId==="model");return t?.type!=="select"||!Array.isArray(t.options)||t.options.length!==0?a:Je(a,e)}u(cr,"projectWorkspaceModelForEmptyChildCatalog");function dr(a){if(a===void 0)return!0;if(!I(a)||a.category!=="model"||a.configId!=="model"||a.type!=="select"||a.name!=="Model"||typeof a.currentValue!="string"||a.currentValue.length===0||!Array.isArray(a.options)||a.options.length===0)return!1;const e=new Set;for(const t of a.options){if(!I(t)||Object.keys(t).some(r=>r!=="name"&&r!=="value")||typeof t.name!="string"||t.name.length===0||typeof t.value!="string"||t.value.length===0||e.has(t.value))return!1;e.add(t.value)}return e.has(a.currentValue)}u(dr,"validWorkspaceSessionModelConfigOption");function lr(a){return Object.freeze({category:"model",configId:"model",currentValue:a.currentValue,name:"Model",options:Object.freeze(a.options.map(e=>Object.freeze({name:e.name,value:e.value}))),type:"select"})}u(lr,"cloneWorkspaceSessionModelConfigOption");class ur{static{u(this,"SessionManager")}constructor(e){this.activations=new Set,this.facadeController=new AbortController,this.managementOperations=new Set,this.ownerSignals=new WeakSet,this.profiles=new WeakMap,this.requestAdmissions=new WeakMap,this.reservations=new Map,this.sessions=new Map,this.trackedCleanup=new Set,this.workspaceProductGates=new Map,this.authMutationTail=Promise.resolve(),this.authProjection={kind:"clear",params:{generation:0}},this.closing=!1,this.childBackedProductAdmissionCount=0,this.inFlightPrivateRefreshCallbackCount=0,this.pendingProductForegroundCount=0,this.productAdmissionCount=0,this.productGate={tail:Promise.resolve()},this.clientMcp=new st,this.serverInfo=e.serverInfo,this.agentCapabilities=e.agentCapabilities,this.maxActiveSessions=e.maxActiveSessions,this.maxBufferedNotificationBytes=e.maxBufferedNotificationBytes,this.maxBufferedNotifications=e.maxBufferedNotifications,this.closeSessionTimeoutMs=e.closeSessionTimeoutMs,this.configReloadTimeoutMs=e.configReloadTimeoutMs,this.createAttachmentScope=e.createAttachmentScope,this.detachedSessionGraceMs=e.detachedSessionGraceMs,this.sessionActivationTimeoutMs=e.sessionActivationTimeoutMs,this.hostSessionControl=e.hostSessionControl,this.mcpIntegration=e.mcpIntegration,this.sessionRuntime=e.sessionRuntime,this.sessionReplay=e.sessionReplay,this.sessionService=e.sessions,this.checkpointService=e.checkpoints,this.userMcp=e.userMcp,this.pluginMcp=e.pluginMcp,this.strictMcpConfig=e.strictMcpConfig,this.subagentProjection=e.subagentProjection,this.refreshAuthentication=e.refreshAuthentication,this.schedulePostResponse=e.schedulePostResponse,this.onPermanentFailure=e.onPermanentFailure,this.processRuntime=e.processRuntime,this.prepareSessionRuntime=e.prepareSessionRuntime,this.prepareSessionWorkspace=e.prepareSessionWorkspace,this.releaseSessionWorkspace=e.releaseSessionWorkspace,this.methods=e.methods,this.productGeneration=e.initialProductGeneration,this.productGenerationRequested=e.initialProductGeneration}selectProfile(e){const t=e.client,r=t?.capabilities?.agent;if(!t||!I(r))throw new b("capabilities.agent must be an ACP v2 ClientCapabilities object");const i={capabilities:r,info:t.clientInfo,protocolVersion:2};G("InitializeRequest",i);const n=I(r.elicitation)?r.elicitation:void 0,o=I(n?.form),s=I(n?.url);if(this.mcpIntegration&&(!o||!s))throw new b("Executor-backed MCP requires elicitation.form and elicitation.url client capabilities");const d={capabilities:{...o||s?{elicitation:{...o?{form:{}}:{},...s?{url:{}}:{}}}:{}},elicitationForm:o,elicitationUrl:s};return this.profiles.set(e.connectionSignal,d),this.ownerSignals.has(e.connectionSignal)||(this.ownerSignals.add(e.connectionSignal),e.connectionSignal.addEventListener("abort",()=>{this.releaseOwner(e.connectionSignal,e.connectionSignal.reason).catch(()=>{})},{once:!0})),d}async runAdmittedSessionRequest(e,t,r){return this.runProductAdmittedRequest(t,()=>this.runSameBatchSessionRequest(e,t,r))}async runExistingWorkspaceAdmittedSessionRequest(e,t,r){const i=this.resolveAdmissionSessionId(e,t.connectionSignal),n=this.sessions.get(i),o=n!==void 0&&(n.child!==void 0||n.childStartup!==void 0);return this.runProductAdmittedRequest(t,()=>this.runSameBatchSessionRequest(e,t,async()=>{const s=this.sessions.get(i);if(!s)return r();const c=E([t.signal,t.connectionSignal,this.facadeController.signal]),d=await this.acquireExistingWorkspaceAdmission(s,c);try{return await r()}finally{d()}}),o)}async runPreparedAdmittedSessionRequest(e,t,r){const i=this.ownedReadySession(e,t.connectionSignal),n=i.resumeParams?.cwd;if(!n)throw new f(p.internalError,"Session is missing its workspace cwd");return this.runPreparedProductAdmittedRequest(t,n,o=>this.runSameBatchSessionRequest(e,t,async()=>{if(this.ownedReadySession(e,t.connectionSignal)!==i)throw H(e);const s=o?await this.rebindWorkspaceProduct(i,o,t):void 0;try{return await r()}finally{s?.()}}))}async runResumeSessionRequest(e,t){if(this.sessions.has(e.sessionId))return this.runExistingWorkspaceAdmittedSessionRequest(e.sessionId,t,()=>this.resumeSession(e,t));this.assertCanActivate(),this.claim(e.sessionId,"activating",t.connectionSignal);try{return await this.runPreparedProductAdmittedRequest(t,e.cwd,r=>this.runSameBatchSessionRequest(e.sessionId,t,()=>this.resumeSession(e,t,r,!0)),!1)}finally{const r=this.reservations.get(e.sessionId);r?.kind==="activating"&&r.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async runSameBatchSessionRequest(e,t,r){const i=t.responseCommitted;if(!i)return r();const n=this.resolveAdmissionSessionId(e,t.connectionSignal);let o=this.requestAdmissions.get(i);if(o||(o=new Map,this.requestAdmissions.set(i,o)),o.has(n))throw M(e);const s={};o.set(n,s);let c=!1;const d=u(()=>{c||(c=!0,o?.get(n)===s&&o.delete(n))},"release");try{return await r()}finally{const l=t.responseCommitted;l?l.then(d,d).catch(()=>{}):d()}}async runProductAdmittedRequest(e,t,r=!1){const i=await B("productAdmission",()=>this.acquireProductAdmission(e,r));try{return await t()}finally{i()}}async runPreparedProductAdmittedRequest(e,t,r,i=!0){const n=E([e.signal,e.connectionSignal,this.facadeController.signal]),o=this.prepareSessionRuntime;o&&await B("productResolve",()=>R(Promise.resolve().then(()=>o(n,e)),n));const s=this.prepareSessionWorkspace;if(!s)return this.runProductAdmittedRequest(e,()=>r(),i);for(let c=0;c<3;c+=1){const d=Promise.resolve().then(()=>s(t,n));let l;try{l=await B("workspacePrepare",()=>R(d,n))}catch(h){throw this.trackCleanup(d.then(g=>{g.releaseReservation()},()=>{})),h}try{this.validateWorkspaceProductLease(l);const h=this.retainWorkspaceProductPreparation(l);try{const g=await B("productAdmission",()=>this.acquireProductAdmission(e,i));if(l.productGeneration!==this.productGeneration||!l.isCurrent()){g();continue}try{await B("workspaceGenerationSync",()=>this.ensureWorkspaceProductGeneration(l,n));const y=await B("workspaceAdmission",()=>this.acquireWorkspaceProductAdmission(l,n));if(l.productGeneration!==this.productGeneration||this.workspaceProductGates.get(l.scopeKey)?.currentGeneration!==l.workspaceGeneration||!l.isCurrent()){y();continue}h();try{return await r(l)}finally{y()}}finally{g()}}finally{h()}}finally{l.releaseReservation()}}throw new f(p.notReady,"Workspace Product changed during request admission")}validateWorkspaceProductLease(e){if(!e||typeof e.cacheKey!="string"||e.cacheKey.length===0||typeof e.canonicalCwd!="string"||!T.isAbsolute(e.canonicalCwd)||T.resolve(e.canonicalCwd)!==e.canonicalCwd||typeof e.scopeKey!="string"||e.scopeKey.length===0||!Number.isSafeInteger(e.workspaceGeneration)||e.workspaceGeneration<1||!Number.isSafeInteger(e.productGeneration)||e.productGeneration<1||e.launch.productGeneration!==e.productGeneration||typeof e.isCurrent!="function"||typeof e.retainReservation!="function"||typeof e.releaseReservation!="function"||!dr(e.sessionModelConfigOption))throw new Error("Workspace Product resolver returned an invalid lease")}bindWorkspaceProduct(e,t){const r=e.workspaceProduct;e.workspaceProduct=Object.freeze({product:t.product,productGeneration:t.productGeneration,canonicalCwd:t.canonicalCwd,launch:t.launch,retainReservation:t.retainReservation,releaseReservation:t.retainReservation(),...t.sessionModelConfigOption===void 0?{}:{sessionModelConfigOption:lr(t.sessionModelConfigOption)},scopeKey:t.scopeKey,workspaceGeneration:t.workspaceGeneration}),r?.releaseReservation()}workspaceProductBindingMatches(e,t){return e.productGeneration===t.productGeneration&&e.canonicalCwd===t.canonicalCwd&&e.workspaceGeneration===t.workspaceGeneration&&e.scopeKey===t.scopeKey&&e.launch.bootstrapFile===t.launch.bootstrapFile&&e.launch.bootstrapSha256===t.launch.bootstrapSha256&&e.launch.productGeneration===t.launch.productGeneration}async rebindWorkspaceProduct(e,t,r){if(e.workspaceProductRebindInFlight)throw M(e.sessionId??"unknown");const i=e.workspaceProduct;if(i&&this.workspaceProductBindingMatches(i,t))return this.bindWorkspaceProduct(e,t),()=>{};const n=E([r.signal,r.connectionSignal,this.facadeController.signal]);await this.awaitBarrier(e,n),this.assertSessionStillReady(e,r);const o=e.workspaceProduct;if(o&&this.workspaceProductBindingMatches(o,t))return this.bindWorkspaceProduct(e,t),()=>{};if(e.workspaceProductRebindInFlight||!this.productChildIsIdle(e))throw M(e.sessionId??"unknown");e.workspaceProductRebindInFlight=!0;const s=le(()=>{e.workspaceProductRebindInFlight=!1}),c=o?.scopeKey;try{const d=e.child;if(d?await this.retireChildForProductGeneration(e,d,new Error("Agent session child retiring for workspace Product rebind")):o&&this.clearWorkspaceProductBinding(e),this.assertSessionStillReady(e,r),await this.rebindWorkspaceMcpAttachment(e,t.canonicalCwd,r,n),n.aborted)throw k(n);return this.assertSessionStillReady(e,r),this.bindWorkspaceProduct(e,t),s}catch(d){throw s(),d}finally{c!==void 0&&this.maybeReleaseWorkspaceScope(c)}}clearWorkspaceProductBinding(e){const t=e.workspaceProduct;e.workspaceProduct=void 0,t?.releaseReservation()}releaseWorkspaceProductBinding(e){const t=e.workspaceProduct?.scopeKey;this.clearWorkspaceProductBinding(e),t!==void 0&&this.maybeReleaseWorkspaceScope(t)}workspaceProductGate(e){const t=this.workspaceProductGates.get(e.scopeKey);if(t)return t;const r=[];for(const o of this.activations){const s=o.workspaceProduct;o.child!==void 0&&s!==void 0&&s.scopeKey===e.scopeKey&&s.productGeneration===e.productGeneration&&r.push(s.workspaceGeneration)}const i=r.length===0?e.workspaceGeneration:Math.min(...r),n={admissionCount:0,currentGeneration:i,preparationCount:0,requestedGeneration:i,tail:Promise.resolve()};return this.workspaceProductGates.set(e.scopeKey,n),n}retainWorkspaceProductPreparation(e){const t=this.workspaceProductGate(e);return t.preparationCount+=1,le(()=>{t.preparationCount-=1,this.maybeReleaseWorkspaceScope(e.scopeKey)})}async ensureWorkspaceProductGeneration(e,t){const r=this.workspaceProductGate(e);if(e.workspaceGeneration<r.currentGeneration)throw new f(p.notReady,"Workspace Product lease is stale");if(e.workspaceGeneration===r.currentGeneration)return;if(r.transition&&r.requestedGeneration>=e.workspaceGeneration)return await R(r.transition,t),this.ensureWorkspaceProductGeneration(e,t);r.requestedGeneration=e.workspaceGeneration;const i=e.retainReservation(),n=Ie(r,()=>this.performWorkspaceProductRotation(e,r)),o=u(()=>{try{this.maybeReleaseWorkspaceScope(e.scopeKey)}finally{i()}},"settleTransition");this.trackCleanup(n.then(o,o)),await R(n,t)}async performWorkspaceProductRotation(e,t){t.admissionCount>0&&(t.drained??=Promise.withResolvers(),await t.drained.promise);const r=[...this.activations].filter(c=>c.workspaceProduct?.scopeKey===e.scopeKey&&c.workspaceProduct?.productGeneration===e.productGeneration&&c.foreground&&c.productForegroundDrain!==void 0).map(c=>c.productForegroundDrain.promise);await Promise.all(r);const i=new Error(`Agent session child retiring for workspace Product generation ${e.workspaceGeneration}`),n=[];for(const c of[...this.activations]){const d=c.child,l=c.workspaceProduct;if(d&&l&&l.scopeKey===e.scopeKey&&l.productGeneration===e.productGeneration&&l.workspaceGeneration!==e.workspaceGeneration){const h=this.retireChildForProductGeneration(c,d,i);h.catch(()=>{}),n.push(h)}}t.currentGeneration=e.workspaceGeneration,await Promise.resolve(this.releaseSessionWorkspace?.(e.scopeKey,e.workspaceGeneration)).catch(()=>{});const s=(await Promise.allSettled(n)).filter(c=>c.status==="rejected");if(s.length===1)throw s[0].reason;if(s.length>1)throw new AggregateError(s.map(c=>c.reason),"Workspace Product child retirement failed")}acquireWorkspaceProductAdmission(e,t){const r=this.workspaceProductGate(e);return this.acquireWorkspaceGateAdmission(e.scopeKey,r,t)}acquireWorkspaceGateAdmission(e,t,r){return t.transition?R(t.transition.then(()=>{},()=>{}),r).then(()=>{const i=this.workspaceProductGates.get(e);return i?this.acquireWorkspaceGateAdmission(e,i,r):()=>{}}):(t.admissionCount+=1,le(()=>{t.admissionCount-=1,t.admissionCount===0&&(t.drained?.resolve(),t.drained=void 0,this.maybeReleaseWorkspaceScope(e))}))}acquireExistingWorkspaceAdmission(e,t){if(e.child===void 0&&e.childStartup===void 0)return()=>{};const r=e.workspaceProduct?.scopeKey,i=r?this.workspaceProductGates.get(r):void 0;return!r||!i?()=>{}:i.transition?R(i.transition.then(()=>{},()=>{}),t).then(()=>this.acquireExistingWorkspaceAdmission(e,t)):this.acquireWorkspaceGateAdmission(r,i,t)}maybeReleaseWorkspaceScope(e){for(const i of this.activations)if(i.workspaceProduct?.scopeKey===e)return;const t=this.workspaceProductGates.get(e);if(t&&(t.admissionCount>0||t.preparationCount>0||t.transition)||(this.workspaceProductGates.delete(e),!this.releaseSessionWorkspace))return;const r=Promise.resolve(this.releaseSessionWorkspace(e)).then(()=>{});this.trackCleanup(r.catch(()=>{}))}rotateProductGeneration(e,t=()=>Promise.resolve(),r={}){if(this.productAdmissionFailure!==void 0)return Promise.reject(new f(p.notReady,"Product generation transition failed; restart Agent Harness"));if(!Number.isSafeInteger(e)||e<=0||e<=this.productGeneration||e<=this.productGenerationRequested)return Promise.reject(new Error("Product generation must increase monotonically from a positive integer"));if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));if(r.busyPolicy==="fail_closed"&&(this.childBackedProductAdmissionCount>0||this.pendingProductForegroundCount>0||this.inFlightPrivateRefreshCallbackCount>0)){const n=new f(p.notReady,"Product state changed while Agent work depended on the prior authentication; restart Agent Harness");return this.failProductAdmissionPermanently(n),Promise.reject(n)}this.productGenerationRequested=e;const i=Ie(this.productGate,()=>this.performProductGenerationRotation(e,t,r.signal));return this.managementOperations.add(i),i.then(()=>this.managementOperations.delete(i),()=>this.managementOperations.delete(i)),i}failProductGeneration(e){this.failProductAdmissionPermanently(e)}failProductAdmissionPermanently(e){if(this.productAdmissionFailure!==void 0)return this.productAdmissionFailure;const t=e==null?new Error("Product generation transition failed"):ue(e);this.productAdmissionFailure=t;try{this.onPermanentFailure?.(t)}catch{}return t}acquireProductAdmission(e,t=!1){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));if(this.productAdmissionFailure!==void 0)return Promise.reject(new f(p.notReady,"Product generation transition failed; restart Agent Harness"));const r=this.productGate.transition;if(r){const n=E([e.signal,e.connectionSignal,this.facadeController.signal]),o=r.then(()=>{},()=>{});return R(o,n).then(()=>this.acquireProductAdmission(e,t))}this.productAdmissionCount+=1,t&&(this.childBackedProductAdmissionCount+=1);let i=!1;return()=>{i||(i=!0,this.productAdmissionCount-=1,t&&(this.childBackedProductAdmissionCount-=1),this.productAdmissionCount===0&&(this.productAdmissionsDrained?.resolve(),this.productAdmissionsDrained=void 0))}}async performProductGenerationRotation(e,t,r){if(this.productAdmissionFailure!==void 0)throw new f(p.notReady,"Product generation transition failed; restart Agent Harness");const i=new Error(`Agent session child retiring for Product generation ${e}`),n=new Map,o=u((l,h)=>{if(n.has(h))return;const g=this.retireChildForProductGeneration(l,h,i);g.catch(()=>{}),n.set(h,g)},"retire");if(r===void 0)for(const l of this.activations){const h=l.child;h&&this.productChildIsIdle(l)&&o(l,h)}try{await R(this.awaitProductAdmissionsDrained(),r,"Product generation rotation aborted before commit");const l=[];for(const h of[...this.activations]){const g=h.foreground?h.productForegroundDrain:void 0;g&&l.push(g.promise)}await R(Promise.all(l).then(()=>{}),r,"Product generation rotation aborted before commit")}catch(l){throw this.reopenCancelledProductRotation(e,r),l}const s=this.reopenCancelledProductRotation(e,r);if(s)throw k(s,"Product generation rotation aborted before commit");try{if(this.productAdmissionFailure!==void 0)throw this.productAdmissionFailure;await t()}catch(l){const h=this.failProductAdmissionPermanently(l),y=(await Promise.allSettled(n.values())).filter(C=>C.status==="rejected");throw y.length===0?h:new AggregateError([h,...y.map(C=>C.reason)],"Product generation switch and idle child cleanup failed")}for(const l of[...this.activations]){const h=l.child;h&&o(l,h)}const c=await Promise.allSettled(n.values());this.productGeneration=e,this.workspaceProductGates.clear();const d=c.filter(l=>l.status==="rejected");if(d.length===1)throw d[0].reason;if(d.length>1)throw new AggregateError(d.map(l=>l.reason),"Product generation child retirement failed")}productChildIsIdle(e){const t=e.sessionId;return!e.activeOperationController&&!e.childStartup&&!e.configWriteInFlight&&!e.executorReleaseInFlight&&!e.foreground&&!e.rebinding&&!e.replayInFlight&&!e.workspaceProductRebindInFlight&&!e.closePromise&&!(t&&this.reservations.has(t))}awaitProductAdmissionsDrained(){return this.productAdmissionCount===0?Promise.resolve():(this.productAdmissionsDrained??=Promise.withResolvers(),this.productAdmissionsDrained.promise)}reopenCancelledProductRotation(e,t){if(!(!t?.aborted||this.productAdmissionFailure!==void 0))return this.productGenerationRequested===e&&(this.productGenerationRequested=this.productGeneration),t}async retireChildForProductGeneration(e,t,r){if(e.child!==t)return;await this.retireMcpStatusProjection(e);const i=e.childFailureToken??t;e.executorReleaseInFlight=!0,this.rotateReverseController(e,r),e.child=void 0,e.authReady=!1,e.childFailureToken=void 0,e.privateMcpServers=void 0,this.clearWorkspaceProductBinding(e),await e.mcpAttachment?.disconnectPeer(i);const n=Promise.resolve().then(()=>t.dispose(r));e.executorReleasePromise=n;try{await n}finally{e.executorReleasePromise===n&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async newSession(e,t,r){ae(e),this.assertCanActivate(),D().set({mcpIntegrationEnabled:this.mcpIntegration!==void 0,workspaceCanonicalized:r===void 0?!1:r.canonicalCwd!==e.cwd,workspacePrepared:r!==void 0});const i=this.createActivation(t);r&&this.bindWorkspaceProduct(i,r),i.attachmentKey=U(e),this.activations.add(i);const n=this.createSessionActivationDeadline(i,[t.connectionSignal,t.signal,this.facadeController.signal,i.startupController.signal]);try{await i.attachmentScope.ready();const o=n.signal,s=i.workspaceProduct===void 0?e:{...e,cwd:i.workspaceProduct.canonicalCwd},c=await this.prepareMcpAttachment(i,s,null,o);D().set({mcpAttachmentCreated:i.mcpAttachment!==void 0});const d=i.mcpAttachment?await this.materializeNewSessionMcp(i,e,o,c):e;D().setCount("effectiveMcpServerCount",d.mcpServers?.length??0);const l=await this.spawnInitializedChild(i,e.cwd,o),h=i.workspaceProduct===void 0?d:{...d,cwd:i.workspaceProduct.canonicalCwd},g=this.validateChildBoundary(i,"NewSessionResponse",await B("privateSessionNew",()=>R(l.newSession(h,{signal:o}),o))),y=Kt(g);this.assertSessionIdentity(i,y.sessionId);const C=this.mergeSessionConfigOptions(i,y.configOptions);return i.configOptions=structuredClone(C),i.resumeParams=se(e,y.sessionId),this.attach(i,y.sessionId),await B("mcpStatusProjection",async()=>{await this.installMcpStatusProjection(i),this.recordSessionNewMcpCounts(i)}),this.releaseBufferedAfterResponse(i,t),{...y,configOptions:C}}catch(o){throw this.dropBuffered(i),await this.failActivation(i,o),o}finally{n.clear()}}preflightNewSession(e){ae(e),this.assertCanActivate()}async forkSession(e,t){ae(e),this.assertCanActivate();const r=this.sessions.get(e.sessionId);if(r){if(!r.proxy.has(t.connectionSignal))throw H(e.sessionId);if(await this.awaitBarrier(r,t.signal),r.closePromise||r.foreground||r.replayInFlight||r.configWriteInFlight||r.executorReleaseInFlight||r.childStartup||Z(r))throw M(e.sessionId)}this.claim(e.sessionId,"forking",t.connectionSignal);const i=this.createActivation(t);i.attachmentKey=U(e),this.activations.add(i);let n;try{await i.attachmentScope.ready();const o=await this.runHostSessionOperation(t,async c=>{const d=E([c,i.startupController.signal]),l=j("ForkSessionResponse",await(this.sessionService?z.runPromise(this.sessionService.fork(e,{signal:d})):this.requireHostSessionControl().forkSession(e,{signal:d})));if(l.sessionId===e.sessionId)throw new f(p.internalError,"Host session/fork returned the source sessionId");n=l.sessionId,this.claim(l.sessionId,"activating",t.connectionSignal),i.expectedSessionId=l.sessionId,i.resumeParams=se(e,l.sessionId),this.assertSessionIdentity(i,l.sessionId);const h=je(l.configOptions,i.pluginSettings.enabledPlugins);return i.configOptions=structuredClone(h),this.attach(i,l.sessionId),{...l,configOptions:h}},!1,this.sessionService!==void 0),s=await this.hydrateDurableProjection(i,t);return this.releaseBufferedAfterResponse(i,t,s),o}catch(o){throw this.dropBuffered(i),await this.failActivation(i,o),o}finally{for(const o of[e.sessionId,...n?[n]:[]])this.reservations.get(o)?.owner===t.connectionSignal&&this.reservations.delete(o)}}async resumeSession(e,t,r,i=!1){ae(e);const n=this.sessions.get(e.sessionId);if(n)return n.detached?this.resumeDetachedSession(n,e,t):n.owner===t.connectionSignal&&n.proxy.has(t.connectionSignal)&&n.attachmentKey!==U(e)?this.resumeAttachedSession(n,e,t):n.owner!==t.connectionSignal||!n.proxy.has(t.connectionSignal)||n.proxy.list().length>1?this.resumeConcurrentAttachment(n,e,t):this.resumeAttachedSession(n,e,t);this.assertCanActivate(),i||this.claim(e.sessionId,"activating",t.connectionSignal);const o=this.createActivation(t,e.sessionId);o.attachmentKey=U(e),o.resumeParams=se(e,e.sessionId),o.attached=!0,o.replayInFlight=e.replayFrom!=null,e.replayFrom!=null&&(o.compactionDeliveryEpoch={}),r&&this.bindWorkspaceProduct(o,r),this.activations.add(o);try{await o.attachmentScope.ready(),this.subagentProjection.beginAttachment(e.sessionId,t.connectionSignal);const s=E([t.connectionSignal,t.signal,this.facadeController.signal,o.startupController.signal]),c=await R(this.resumeStoredSession(o,e,{onUpdate:u(h=>this.deliverHostUpdate(o,h),"onUpdate"),signal:s}),s),d=j("ResumeSessionResponse",c.response);if(X(d,W(e),"Host"),this.assertSessionIdentity(o,e.sessionId),await o.deliveryTail,o.deliveryFailure!==void 0)throw o.deliveryFailure;if(o.replayInFlight=!1,this.sessionRuntime.readCatalog){const h=await o.attachmentScope.runEffect(this.sessionRuntime.readCatalog(e.sessionId,this.sessionOpenOptions(o,e.cwd,s,{})));for(const g of h)await this.deliverBufferedHostUpdate(o,g)}const l=this.mergeHostSessionConfigOptions(o,d.configOptions);return o.configOptions=structuredClone(l),this.attach(o,e.sessionId),this.releaseBufferedAfterResponse(o,t),{...d,configOptions:l}}catch(s){throw o.replayInFlight=!1,this.dropBuffered(o),await this.failActivation(o,s),s}finally{const s=this.reservations.get(e.sessionId);s?.kind==="activating"&&s.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async resumeConcurrentAttachment(e,t,r){const i=e.proxy.has(r.connectionSignal);if(i&&!e.proxy.has(r.connectionSignal,"live")||this.reservations.has(t.sessionId)||e.closePromise||e.rebinding||e.configWriteInFlight||e.replayInFlight||e.attachmentReplayInFlight||e.deliveryMode==="drop"||e.deliveryFailure!==void 0)throw M(t.sessionId);if(T.resolve(e.resumeParams.cwd)!==T.resolve(t.cwd))throw new b("session/resume cannot replace cwd on an active attachment");if(e.attachmentKey!==U(t))throw M(t.sessionId);if(x(e.resumeParams??{})!==x(t))throw new b("session/resume cannot replace additionalDirectories while multiple clients are attached");const n=this.profile(r.connectionSignal),o=oe(e.negotiatedClientCapabilities,n.capabilities,"capabilities");if(o)throw new b(`Attached Client is missing negotiated ${o}`);if(t.replayFrom!==null&&t.replayFrom!==void 0&&t.replayFrom.type!=="start")throw new b("A concurrent session attachment must replay from start");if(i&&(t.replayFrom===null||t.replayFrom===void 0)){const g=structuredClone(e.configOptions);return g===void 0?{}:{configOptions:g}}const s=t.replayFrom?.type==="start";if(s&&(e.foreground||e.activeOperationController!==void 0))throw M(t.sessionId);const c=e.proxy.add(r,n,"replaying");if(!c)throw r.connectionSignal.aborted?k(r.connectionSignal):M(t.sessionId);s&&(e.attachmentReplayInFlight=!0);const d=u(()=>{s&&(e.attachmentReplayInFlight=!1)},"releaseReplayLock"),l=u(g=>{this.trackCleanup(this.releaseFailedProxyAttachment(e,r,g))},"fail"),h=u(g=>{if(i&&!r.connectionSignal.aborted){this.activateProxyAttachmentAfterResponse(e,r,l,d);return}d(),this.trackCleanup(this.releaseSessionAttachment(e,r.connectionSignal,g,r.connection.transport))},"restore");try{if(t.replayFrom===null||t.replayFrom===void 0){if(!i){for(const O of this.subagentProjection.snapshotStartedNotifications(t.sessionId,e.owner))if(!await e.proxy.notifyReplay(r.connectionSignal,O.method,O.params))throw k(r.connectionSignal)}const P=structuredClone(e.configOptions);return this.activateProxyAttachmentAfterResponse(e,r,l,d),P===void 0?{}:{configOptions:P}}const g=new _e({maxBufferedNotificationBytes:this.maxBufferedNotificationBytes,maxBufferedNotifications:this.maxBufferedNotifications});g.beginAttachment(t.sessionId,r.connectionSignal);const y=g.beginReplay(t.sessionId,r.connectionSignal,"replace"),C=E([r.signal,r.connectionSignal,c,e.lifecycleController.signal,this.facadeController.signal]),F=await R(this.resumeStoredSession(e,t,{onUpdate:u(async P=>{const O=j("UpdateSessionNotification",P);this.assertCallbackSessionId(e,O.sessionId);const q=this.projectConcurrentReplayUpdate(e,g,y,r.connectionSignal,O);for(const _ of Re(q))if(!await e.proxy.notifyReplay(r.connectionSignal,_.method,_.params))throw k(r.connectionSignal)},"onUpdate"),signal:C}),C),m=X(j("ResumeSessionResponse",F.response),W(t),"Host");g.commitReplay(y,r.connectionSignal);const v=this.mergeHostSessionConfigOptions(e,m.configOptions);return this.activateProxyAttachmentAfterResponse(e,r,l,d),{...m,configOptions:v}}catch(g){throw h(g),g}}activateProxyAttachmentAfterResponse(e,t,r,i){const n=u(async()=>{try{await e.proxy.activate(t.connectionSignal)}catch{}finally{i?.()}},"activate");if(t.responseCommitted){t.responseCommitted.then(n,o=>{i?.(),r(o)}).catch(()=>{});return}this.schedulePostResponseTask(n,"Agent Harness concurrent resume is missing its response-commit boundary",o=>{i?.(),r(o)})}async releaseFailedProxyAttachment(e,t,r){t.connection.transport==="stdio"&&e.proxy.list().length===0&&(e.deliveryFailure??=r),await this.releaseSessionAttachment(e,t.connectionSignal,r,t.connection.transport);const i=e.sessionId;try{i&&t.closeSessionAttachment?await t.closeSessionAttachment(i,r):await t.closeConnection?.(r)}catch(n){await t.closeConnection?.(n)}}async resumeDetachedSession(e,t,r){const i=e.detached;if(!i||e.owner===r.connectionSignal||e.rebinding||e.closePromise||e.configWriteInFlight||e.replayInFlight||e.attachmentReplayInFlight||e.deliveryMode!=="buffer"||e.deliveryFailure!==void 0)throw M(t.sessionId);const n=this.prepareDetachedResume(e,t,r),o=e.attachmentKey!==U(t);o&&this.assertMcpSetupIdle(e,t.sessionId);const s=this.profile(r.connectionSignal),c=e.owner,d=this.subagentProjection.beginRebind(t.sessionId,c,r.connectionSignal);let l;try{l=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,W(t)?"merge_history":"replace")}catch(P){throw e.proxy.remove(r.connectionSignal),this.subagentProjection.abortRebind(d,r.connectionSignal),P}if(!e.proxy.add(r,s))throw this.subagentProjection.abortReplay(l,r.connectionSignal),this.subagentProjection.abortRebind(d,r.connectionSignal),k(r.connectionSignal);const h={compactions:new Map([...e.compactions].map(([P,O])=>[P,{...O}])),detachedExpiresAt:i.expiresAt,detachedOwner:c,detachedOwnerContext:e.ownerContext,detachedReason:i.reason,negotiatedClientCapabilities:e.negotiatedClientCapabilities,projection:d,replay:l};i.timer.cancel(),e.compactionDeliveryEpoch={},e.rebinding=!0,e.rebindProjection=d,e.replayProjection=l,e.replayInFlight=!0,e.replayResponsePending=!1,e.owner=r.connectionSignal,e.ownerContext=r,e.negotiatedClientCapabilities=structuredClone(s.capabilities),e.rebindLiveNotifications=e.bufferedNotifications,e.bufferedNotifications=[],e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=n,e.reconnectRootTerminalMatched=!1,this.rotateDeliveryGeneration(e);const g=e.attachmentScope.makeController();e.replayController=g;const y=E([r.signal,r.connectionSignal,g.signal,e.lifecycleController.signal,this.facadeController.signal]),C=e.mcpAttachment;let F,m=!1,v=!1;try{o&&(F=await this.stageMcpAttachment(e,{...t,cwd:e.workspaceProduct?.canonicalCwd??t.cwd},t.sessionId,y),y.throwIfAborted());const P=await R(this.resumeStoredSession(e,t,{onUpdate:u(_=>this.deliverHostUpdate(e,_),"onUpdate"),signal:y}),y),O=j("ResumeSessionResponse",P.response);if(X(O,W(t),"Host"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;if(F){if(e.foreground||e.childStartup)throw M(t.sessionId);e.child&&(m=!0,this.validateChildBoundary(e,"ResumeSessionResponse",await R(e.child.resumeSession({...this.projectResumeSessionMcp(e,t),mcpServers:[...F.materialized?.mcpServers??[]],replayFrom:null},{signal:y}),y))),y.throwIfAborted(),await this.retireMcpStatusProjection(e),e.mcpAttachment=F.attachment,e.mcpAttachmentCwd=F.attachment?e.workspaceProduct?.canonicalCwd??t.cwd:void 0,e.privateMcpServers=F.materialized?.mcpServers,v=!0,this.recordMcpMaterializationDiagnostics(F.materialized?.diagnostics),C&&C!==F.attachment&&await C.revoke(),e.resumeParams=se(t,t.sessionId),e.attachmentKey=U(t)}this.subagentProjection.commitReplay(l,r.connectionSignal),e.replayProjection=void 0;const q=this.mergeHostSessionConfigOptions(e,O.configOptions);return e.configOptions=structuredClone(q),this.releaseDetachedRebindAfterResponse(e,r,h,v),{...O,configOptions:q}}catch(P){if(v)throw await this.failActivation(e,P),P;try{F?.attachment!==C&&await F?.attachment?.revoke(),m&&await this.releaseExecutorForRewind(e,P)}catch(O){const q=V(P,O,"Reconnect setup and cleanup failed");throw await this.failActivation(e,q),q}throw this.rollbackDetachedRebind(e,h,P),P}}prepareDetachedResume(e,t,r){if(t.replayFrom==null)throw new b("A detached session must be resumed with an authoritative replay selector");if(t.replayFrom.type!=="start")throw new b("A detached session must be resumed from the authoritative start snapshot");if(T.resolve(e.resumeParams.cwd)!==T.resolve(t.cwd))throw new b("session/resume cannot replace cwd while reconnecting");if(x(e.resumeParams??{})!==x(t))throw new b("session/resume cannot replace additionalDirectories while reconnecting");const i=new _t({maxBytes:this.maxBufferedNotificationBytes,maxEntries:this.maxBufferedNotifications});for(const s of e.bufferedNotifications){const c=s.privateLiveUpdate?.notification;if(!c)throw new f(p.internalError,"Reconnect live suffix contained an already-projected notification");i.trackLive(c)}const n=this.profile(r.connectionSignal),o=oe(e.negotiatedClientCapabilities,n.capabilities,"capabilities");if(o)throw new b(`Reconnect Client is missing negotiated ${o}`);return i}async resumeAttachedSession(e,t,r){if(!e.proxy.has(r.connectionSignal)||e.closePromise||this.reservations.has(t.sessionId)||e.deliveryMode==="drop"||e.configWriteInFlight)throw M(t.sessionId);if(T.resolve(e.resumeParams.cwd)!==T.resolve(t.cwd))throw new b("session/resume cannot replace cwd on an active attachment");if(e.attachmentKey!==U(t))return this.refreshAttachedSessionSetup(e,t,r);const n=x(e.resumeParams??{})!==x(t);if(t.replayFrom==null){if(n)return this.refreshAttachedSessionSetup(e,t,r);const l=structuredClone(e.configOptions);return l===void 0?{}:{configOptions:l}}if(e.foreground||e.replayInFlight)throw M(t.sessionId);if(!e.child)return this.resumeDormantSession(e,t,r);if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Z(e)||e.foreground||e.replayInFlight||e.configWriteInFlight)throw M(t.sessionId);const o=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,W(t)?"merge_history":"replace");e.compactionDeliveryEpoch={};const s=e.attachmentScope.makeController();e.replayController=s,e.replayInFlight=!0,e.replayProjection=o,e.replayResponsePending=!0;try{this.holdNotifications(e,r.responseCommitted)}catch(l){throw this.subagentProjection.abortReplay(o,r.connectionSignal),this.clearReplayController(e,s),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,l}const c=this.requireChild(e),d=u(()=>{this.clearReplayController(e,s),e.replayInFlight=!1,e.replayResponsePending=!1},"finishAfterResponse");try{const l=await c.resumeSession(this.projectResumeSessionMcp(e,t),{signal:E([r.signal,r.connectionSignal,s.signal])});e.replayResponsePending=!1;const g=this.validateChildBoundary(e,"ResumeSessionResponse",l);if(X(g,W(t),"private ACP v2 child"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;this.subagentProjection.commitReplay(o,r.connectionSignal),e.replayProjection=void 0;const y=this.mergeSessionConfigOptions(e,g.configOptions);return e.configOptions=structuredClone(y),this.commitAdditionalDirectories(e,t),this.releaseBufferedAfterResponse(e,r,d),{...g,configOptions:y}}catch(l){return e.replayResponsePending=!1,e.replayProjection===o&&(this.subagentProjection.abortReplay(o,r.connectionSignal),e.replayProjection=void 0),this.settleFailedReplay(e,l,d,{aggregateMessage:"Replay request and response boundary both failed",recoverable:ar(l),releaseBoundary:u(()=>this.releaseBufferedAfterResponse(e,r,d),"releaseBoundary")})}}async failReplayTerminally(e,t,r){throw r(),e.deliveryMode==="buffer"&&this.dropBuffered(e),e.attached&&await this.failActivation(e,t),t}async settleFailedReplay(e,t,r,i){if(i.recoverable&&e.deliveryFailure===void 0&&e.attached&&this.activations.has(e)&&e.deliveryMode==="buffer"){try{i.releaseBoundary()}catch(o){throw r(),e.attached&&await this.failActivation(e,o),V(t,o,i.aggregateMessage)}throw t}return this.failReplayTerminally(e,t,r)}async refreshAttachedSessionSetup(e,t,r){if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Z(e)||e.foreground||e.replayInFlight||e.attachmentReplayInFlight||e.rebinding||e.configWriteInFlight||e.childStartup)throw M(t.sessionId);const i=e.attachmentKey!==U(t);i&&this.assertMcpSetupIdle(e,t.sessionId);const n=t.replayFrom==null?void 0:this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,W(t)?"merge_history":"replace"),o=e.attachmentScope.makeController();e.replayController=o,e.replayInFlight=!0,e.replayProjection=n,e.replayResponsePending=n!==void 0&&e.child!==void 0,n&&(e.compactionDeliveryEpoch={});try{this.holdNotifications(e,r.responseCommitted)}catch(m){throw n&&this.subagentProjection.abortReplay(n,r.connectionSignal),e.replayProjection=void 0,e.replayResponsePending=!1,this.clearReplayController(e,o),e.replayInFlight=!1,m}const s=u(()=>{this.clearReplayController(e,o),e.replayInFlight=!1,e.replayResponsePending=!1},"finishAfterResponse"),c=E([r.signal,r.connectionSignal,o.signal,this.facadeController.signal]),d=e.child,l=structuredClone(e.configOptions),h=e.resumeParams,g=e.mcpAttachment;let y,C=!1,F=!1;try{i&&(y=await this.stageMcpAttachment(e,{...t,cwd:e.workspaceProduct?.canonicalCwd??t.cwd},t.sessionId,c),c.throwIfAborted(),this.assertMcpSetupIdle(e,t.sessionId));let m;if(d)F=!0,m=this.validateChildBoundary(e,"ResumeSessionResponse",await R(d.resumeSession({...this.projectResumeSessionMcp(e,{...t,additionalDirectories:[...t.additionalDirectories??[]],replayFrom:t.replayFrom??null}),...y?{mcpServers:[...y.materialized?.mcpServers??[]]}:{}},{signal:c}),c));else{const P=await R(this.resumeStoredSession(e,{...t,additionalDirectories:[...t.additionalDirectories??[]],replayFrom:t.replayFrom??null},{onUpdate:u(O=>n?this.deliverHostUpdate(e,O):this.deliverBufferedHostUpdate(e,O),"onUpdate"),signal:c}),c);m=j("ResumeSessionResponse",P.response)}if(X(m,W(t),d?"private ACP v2 child":"Host"),e.replayResponsePending=!1,await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;const v=this.mergeHostSessionConfigOptions(e,m.configOptions);return c.throwIfAborted(),y&&(await this.retireMcpStatusProjection(e),e.mcpAttachment=y.attachment,e.mcpAttachmentCwd=y.attachment?e.workspaceProduct?.canonicalCwd??t.cwd:void 0,e.privateMcpServers=y.materialized?.mcpServers,C=!0,this.recordMcpMaterializationDiagnostics(y.materialized?.diagnostics),await this.installMcpStatusProjection(e),g&&g!==y.attachment&&await g.revoke()),n&&(this.subagentProjection.commitReplay(n,r.connectionSignal),e.replayProjection=void 0),e.configOptions=structuredClone(v),this.commitAdditionalDirectories(e,t),e.resumeParams={...e.resumeParams,mcpServers:structuredClone(t.mcpServers??[])},e.attachmentKey=U(t),this.releaseBufferedAfterResponse(e,r,s),{...m,configOptions:v}}catch(m){if(e.replayResponsePending=!1,e.replayProjection===n&&n&&(this.subagentProjection.abortReplay(n,r.connectionSignal),e.replayProjection=void 0),C)return this.failReplayTerminally(e,m,s);try{y?.attachment!==g&&await y?.attachment?.revoke()}catch(v){return this.failReplayTerminally(e,V(m,v,"Session setup refresh and MCP cleanup failed"),s)}if(e.configOptions=l,e.resumeParams=h,d&&F){try{await this.releaseExecutorForRewind(e,m)}catch(v){const P=V(m,v,"Session setup refresh and private child cleanup failed");return this.failReplayTerminally(e,P,s)}throw this.discardBufferedAfterResponse(e,r,s),m}if(i)throw this.discardBufferedAfterResponse(e,r,s),m;return this.settleFailedReplay(e,m,s,{aggregateMessage:"Session setup refresh and response boundary both failed",recoverable:Ye(m),releaseBoundary:u(()=>this.discardBufferedAfterResponse(e,r,s),"releaseBoundary")})}}assertMcpSetupIdle(e,t){if(e.foreground||e.childStartup||this.subagentProjection.listSubagents(t,e.owner).subagents.some(r=>r.state?.state==="running"))throw M(t)}async resumeDormantSession(e,t,r){if(await this.awaitBarrier(e,r.signal),e.closePromise||this.reservations.has(t.sessionId)||Z(e)||e.foreground||e.replayInFlight||e.configWriteInFlight||e.child)throw M(t.sessionId);const i=this.subagentProjection.beginReplay(t.sessionId,r.connectionSignal,W(t)?"merge_history":"replace");e.compactionDeliveryEpoch={};const n=e.attachmentScope.makeController();e.replayController=n,e.replayInFlight=!0,e.replayProjection=i;try{this.holdNotifications(e,r.responseCommitted)}catch(c){throw this.subagentProjection.abortReplay(i,r.connectionSignal),this.clearReplayController(e,n),e.replayInFlight=!1,e.replayProjection=void 0,c}const o=u(()=>{this.clearReplayController(e,n),e.replayInFlight=!1},"finishAfterResponse"),s=E([r.signal,r.connectionSignal,n.signal,this.facadeController.signal]);try{const c=await R(this.resumeStoredSession(e,t,{onUpdate:u(h=>this.deliverHostUpdate(e,h),"onUpdate"),signal:s}),s),d=j("ResumeSessionResponse",c.response);if(X(d,W(t),"Host"),await e.deliveryTail,e.deliveryFailure!==void 0)throw e.deliveryFailure;this.subagentProjection.commitReplay(i,r.connectionSignal),e.replayProjection=void 0;const l=this.mergeHostSessionConfigOptions(e,d.configOptions);return e.configOptions=structuredClone(l),this.commitAdditionalDirectories(e,t),this.releaseBufferedAfterResponse(e,r,o),{...d,configOptions:l}}catch(c){return e.replayProjection===i&&(this.subagentProjection.abortReplay(i,r.connectionSignal),e.replayProjection=void 0),this.settleFailedReplay(e,c,o,{aggregateMessage:"Replay request and response boundary both failed",recoverable:Ye(c),releaseBoundary:u(()=>this.releaseBufferedAfterResponse(e,r,o),"releaseBoundary")})}}async hydrateDurableProjection(e,t){const r=e.sessionId,i=e.resumeParams;if(!r||!i)throw new f(p.internalError,"Active session is missing its durable resume setup");if(e.deliveryMode!=="buffer")throw new f(p.internalError,"Durable projection hydration requires a pending response boundary");const n=this.subagentProjection.beginReplay(r,t.connectionSignal,"replace"),o=e.attachmentScope.makeController();e.replayController=o,e.replayInFlight=!0,e.replayProjection=n,e.replayResponsePending=!0;const s=u(()=>{this.clearReplayController(e,o),e.replayInFlight=!1,e.replayResponsePending=!1},"finishAfterResponse"),c=E([t.signal,t.connectionSignal,o.signal,this.facadeController.signal,e.startupController.signal]);try{const d=await R(this.resumeStoredSession(e,{...i,replayFrom:{type:"start"}},{onUpdate:u(h=>this.projectDurableSnapshotUpdate(e,h),"onUpdate"),signal:c}),c),l=X(j("ResumeSessionResponse",d.response),!1,"Host");if(e.deliveryFailure!==void 0)throw e.deliveryFailure;return this.subagentProjection.commitReplay(n,t.connectionSignal),e.replayProjection=void 0,e.configOptions=structuredClone(this.mergeHostSessionConfigOptions(e,l.configOptions)),s}catch(d){throw e.replayProjection===n&&(this.subagentProjection.abortReplay(n,t.connectionSignal),e.replayProjection=void 0),s(),d}}async listMcpServerStatuses(e,t){const r=this.ownedReadySession(e.threadId,t.connectionSignal),i=this.mcpOperationSignal(r,t);await this.awaitBarrier(r,i),this.assertSessionStillReady(r,t);const{attachment:n,cursorEpoch:o}=this.requireMaterializedMcpAttachment(r),s=n.listServerStatuses(),c=s.map(Xt),d=Ve({detail:e.detail??null,threadId:e.threadId}),l=Ve(s);let h=0;if(e.cursor){const C=Yt(e.cursor);if(C.attachmentEpoch!==o||C.fingerprint!==l||C.queryFingerprint!==d||C.index>c.length||c[C.index-1]?.name!==C.previousName)throw new b("MCP server status cursor no longer matches this attachment snapshot");h=C.index}const g=e.limit??$t,y=Math.min(h+g,c.length);return{data:c.slice(h,y),nextCursor:y<c.length?Vt({attachmentEpoch:o,fingerprint:l,index:y,previousName:c[y-1].name,queryFingerprint:d,version:$e}):null}}async callMcpServerTool(e,t){if(e._meta!==void 0)throw new b("MCP tool-call request _meta is not supported");const r=this.ownedReadySession(e.threadId,t.connectionSignal),i=this.mcpOperationSignal(r,t);await this.awaitBarrier(r,i),this.assertSessionStillReady(r,t);const{attachment:n}=this.requireMaterializedMcpAttachment(r),o=n.listServerStatuses().find(s=>s.logicalName===e.server);if(!o)throw new b(`Unknown MCP server "${e.server}"`);if(o.status!=="available")throw new f(p.notReady,`MCP server "${e.server}" is unavailable`);if(!o.tools.some(s=>s.name===e.tool))throw new b(`Unknown MCP tool "${e.tool}" for server "${e.server}"`);try{const s=await n.callTool(e.server,e.tool,e.arguments===void 0?{}:e.arguments,i);return{...s._meta===void 0?{}:{_meta:structuredClone(s._meta)},content:structuredClone(s.content),...s.isError===void 0?{}:{isError:s.isError},...s.structuredContent===void 0?{}:{structuredContent:structuredClone(s.structuredContent)}}}catch(s){if(s instanceof f)throw s;if(s instanceof at||s instanceof ct)throw new f(p.notReady,`MCP server "${e.server}" is unavailable`);const c=ue(s).message;throw c.startsWith("Unknown MCP server ")||c.startsWith("MCP tool ")?new b(`MCP server "${e.server}" does not expose tool "${e.tool}"`):new f(p.internalError,"MCP tool call failed")}}async listSubagents(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);await this.awaitBarrier(r,t.signal),this.assertSessionStillReady(r,t);const i=r.resumeParams&&this.sessionReplay?.subagents?await this.sessionReplay.subagents.list({sessionId:e.sessionId,cwd:r.resumeParams.cwd},this.mcpOperationSignal(r,t)):[];await this.awaitBarrier(r,t.signal),this.assertSessionStillReady(r,t);const n=this.subagentProjection.listSubagents(e.sessionId,r.owner),o=new Map(i.map(s=>[s.sessionId,s]));for(const s of n.subagents)o.set(s.sessionId,s);return{subagents:[...o.values()]}}async readSubagent(e,t){const r=await this.resolveStoredSubagent(e.sessionId,t),{current:i,session:n}=r??await this.resolveSubagentAfterBoundary(e.sessionId,t);if(e.replayFrom==null)return{subagent:i.subagent};const o=r?.stored??(n.resumeParams&&this.sessionReplay?.subagents?await this.sessionReplay.subagents.read({sessionId:i.rootSessionId,cwd:n.resumeParams.cwd,workspace:n.workspaceProduct},e.sessionId,this.mcpOperationSignal(n,t)):void 0);await this.settleSubagentResponseBoundary(n,t);const s=this.subagentProjection.rootSessionIdFor(e.sessionId)===i.rootSessionId?this.subagentProjection.snapshotRead(e.sessionId,n.owner):void 0,c={rootSessionId:i.rootSessionId,subagent:s?.subagent??o?.subagent??i.subagent,journal:o?qt(o.journal,s?.journal??[]):s?.journal??[]},d=this.profile(t.connectionSignal);if(!n.proxy.add(t,d,"replaying"))throw t.connectionSignal.aborted?k(t.connectionSignal):M(c.rootSessionId);try{for(const l of c.journal)if(!await n.proxy.notifyReplay(t.connectionSignal,this.methods.client.session.update,l))throw k(t.connectionSignal);return this.activateProxyAttachmentAfterResponse(n,t,l=>this.trackCleanup(this.releaseFailedProxyAttachment(n,t,l))),{subagent:c.subagent}}catch(l){throw await n.proxy.activate(t.connectionSignal),l}}listSessions(e,t){return this.runHostSessionOperation(t,async r=>j("ListSessionsResponse",await(this.sessionService?z.runPromise(this.sessionService.list(e,{signal:r})):this.requireHostSessionControl().listSessions(e,{signal:r}))))}listCheckpoints(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?z.runPromise(this.checkpointService.list(e,{signal:r})):this.requireHostSessionControl().listCheckpoints(e,{signal:r}))}readCheckpoint(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?z.runPromise(this.checkpointService.read(e,{signal:r})):this.requireHostSessionControl().readCheckpoint(e,{signal:r}))}restoreCheckpoint(e,t){return this.runCheckpointOperation(e.sessionId,t,r=>this.checkpointService?z.runPromise(this.checkpointService.restore(e,{signal:r})):this.requireHostSessionControl().restoreCheckpoint(e,{signal:r}),!0)}async runCheckpointOperation(e,t,r,i=!1){const n=this.sessions.get(e);if(n){if(!n.proxy.has(t.connectionSignal))throw H(e);if(await this.awaitBarrier(n,t.signal),n.closePromise||n.foreground||n.replayInFlight||n.attachmentReplayInFlight||n.configWriteInFlight||n.executorReleaseInFlight||n.childStartup||Z(n))throw M(e)}this.claim(e,"checkpointing",t.connectionSignal);try{if(!i)return await this.runHostSessionOperation(t,r);if(!n)return await this.runHostSessionOperation(t,r,!0,this.checkpointService!==void 0);this.holdNotifications(n,t.responseCommitted);try{await this.releaseExecutorForRewind(n,new Error("Session checkpoint restoring"))}catch(s){throw this.dropBuffered(n),await this.failActivation(n,s),s}this.discardBufferedNotifications(n);let o;try{o=await this.runHostSessionOperation(t,r,!0,this.checkpointService!==void 0)}catch(s){try{this.discardBufferedAfterResponse(n,t)}catch(c){throw await this.failActivation(n,c),V(s,c,"Checkpoint restore and response boundary both failed")}throw s}try{this.discardBufferedAfterResponse(n,t)}catch(s){throw await this.failActivation(n,s),s}return o}finally{const o=this.reservations.get(e);o?.kind==="checkpointing"&&o.owner===t.connectionSignal&&this.reservations.delete(e)}}async deleteSession(e,t){const r=this.sessions.get(e.sessionId),i=r?.proxy.list().map(n=>n.context)??[];if(r&&r.attachmentReplayInFlight)throw M(e.sessionId);if(r&&!r.proxy.has(t.connectionSignal)&&(!r.detached||r.rebinding))throw H(e.sessionId);this.claim(e.sessionId,"deleting",t.connectionSignal);try{return r&&await this.closeAttached(r,e,!0),await this.runHostSessionOperation(t,async n=>j("DeleteSessionResponse",await(this.sessionService?z.runPromise(this.sessionService.delete(e,{signal:n})):this.requireHostSessionControl().deleteSession(e,{signal:n}))),!1,this.sessionService!==void 0)}finally{this.scheduleClosedAttachmentRoutes(e.sessionId,i,t);const n=this.reservations.get(e.sessionId);n?.kind==="deleting"&&n.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async rewindSession(e,t){const r=this.ownedSession(e.sessionId,t.connectionSignal);if(await this.awaitBarrier(r,t.signal),r.closePromise||r.foreground||r.replayInFlight||r.attachmentReplayInFlight||r.configWriteInFlight||r.executorReleaseInFlight||r.childStartup||Z(r))throw M(e.sessionId);const i=r.resumeParams;if(!i)throw new f(p.internalError,"Active session is missing its durable resume setup");this.claim(e.sessionId,"rewinding",t.connectionSignal),this.holdNotifications(r,t.responseCommitted);try{try{await this.releaseExecutorForRewind(r,new Error("Session rewinding"))}catch(s){throw this.dropBuffered(r),await this.failActivation(r,s),s}let n;try{const s=this.sessionRuntime.rewind;t.signal.throwIfAborted(),n=await this.runHostSessionOperation(t,async c=>nr(s?await r.attachmentScope.runEffect(s(e,{cwd:i.cwd,signal:c})):await this.requireHostSessionControl().rewindSession(e,{signal:c})),s!==void 0)}catch(s){throw this.releaseBufferedAfterResponse(r,t),s}await this.closeAttachmentDescendantRoutes(r,e.sessionId,t.connectionSignal);let o;try{o=await this.hydrateDurableProjection(r,t)}catch(s){throw r.deliveryFailure??=s,this.handleChildFailure(r,s),s}try{this.releaseBufferedAfterResponse(r,t,o)}catch(s){throw o(),r.deliveryFailure??=s,this.handleChildFailure(r,s),s}return n}finally{const n=this.reservations.get(e.sessionId);n?.kind==="rewinding"&&n.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}async runForegroundOperation(e,t,r,i,n){e.foreground=!0,e.acknowledgedRequestId=void 0,r==="compact"&&(e.activeCompactionId=void 0),e.activeForegroundAccepted=!1,e.activeResponseCommitted=t.responseCommitted,e.activeRequestId=void 0;const o=this.beginActiveOperation(e,r),s=u(()=>{this.finishActiveOperation(e,o),this.rotateReverseController(e,new Error(i.failed))},"finishAfterResponse");try{const c=await this.ensureExecutor(e,t,o.signal);if(this.assertSessionStillReady(e,t),e.deliveryFailure!==void 0)throw e.deliveryFailure;this.rotateReverseController(e,new Error(i.start)),this.holdOrContinueActivationBoundary(e,t.responseCommitted);const d=E([t.signal,t.connectionSignal,e.reverseController.current.signal]),l=new AbortController,h=u(()=>l.abort(k(d)),"abortAdmission");d.addEventListener("abort",h,{once:!0}),d.aborted&&h();const g=E([l.signal,o.signal]);let y;try{g.throwIfAborted(),y=await n(c,g)}finally{d.removeEventListener("abort",h)}return e.activeForegroundAccepted=!0,this.releaseBufferedAfterResponse(e,t),y}catch(c){throw this.resolveProductForeground(e),e.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(e,t,s):s(),c}}async compactSession(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);if(r.foreground||r.replayInFlight||r.configWriteInFlight||(await this.awaitBarrier(r,t.signal),r.foreground||r.replayInFlight||r.configWriteInFlight))throw M(e.sessionId);return this.runForegroundOperation(r,t,"compact",{failed:"Manual compaction failed",start:"Starting manual compaction"},async(i,n)=>{const o=await i.compactSession(e,{signal:n});if(r.deliveryFailure!==void 0)throw r.deliveryFailure;const s=this.withPrivateBoundaryContainment(r,()=>rr(o));return this.captureActiveRequestId(r,s._meta,"session/compact result"),s})}async closeSession(e,t){const r=this.ownedSession(e.sessionId,t.connectionSignal),i=r.proxy.list().map(o=>o.context);let n=[];if(r.mcpStatusUnsubscribe&&r.mcpAttachment&&r.privateMcpServers!==void 0)try{n=r.mcpAttachment.listServerStatuses()}catch{}this.claim(e.sessionId,"closing",t.connectionSignal);try{const o=await this.closeAttached(r,e,!0);return this.scheduleClosedMcpStatusNotifications(e.sessionId,n,t),o}finally{this.scheduleClosedAttachmentRoutes(e.sessionId,i,t);const o=this.reservations.get(e.sessionId);o?.kind==="closing"&&o.owner===t.connectionSignal&&this.reservations.delete(e.sessionId)}}scheduleClosedMcpStatusNotifications(e,t,r){if(t.length===0)return;const i=u(async()=>{r.connectionSignal.aborted||await Promise.all(t.map(n=>r.notify(he.mcpServer.startupStatus.updated,this.mcpStatusNotification(e,n,"cancelled"))))},"deliver");if(r.responseCommitted){r.responseCommitted.then(i).catch(()=>{});return}try{this.schedulePostResponse?.(i)}catch{}}scheduleClosedAttachmentRoutes(e,t,r){const i=t.filter(o=>o.closeSessionAttachment!==void 0);if(i.length===0)return;const n=u(async()=>{const o=new Error("Session closed");await Promise.all(i.map(async s=>{try{await s.closeSessionAttachment?.(e,o)}catch(c){await s.closeConnection?.(c)}}))},"close");if(r.responseCommitted){r.responseCommitted.then(n,n).catch(()=>{});return}try{this.schedulePostResponse?.(n)}catch{}}async closeAttachmentDescendantRoutes(e,t,r){await Promise.all(e.proxy.list().map(async i=>{const n=i.context;if(n.connectionSignal!==r)try{await n.closeSessionDescendants?.(t)}catch(o){await n.closeConnection?.(o)}}))}async setSessionConfigOption(e,t){let r;try{r=St(e)}catch(s){throw new b(ue(s).message)}if(r!==void 0)return this.setSessionEnabledPlugins(e,r,t);const i=this.ownedReadySession(e.sessionId,t.connectionSignal);if(await this.awaitBarrier(i,t.signal),i.foreground||i.replayInFlight||i.configWriteInFlight)throw M(e.sessionId);i.configWriteInFlight=!0;const n=this.beginActiveOperation(i,"config"),o=u(()=>{this.finishActiveOperation(i,n)},"finishAfterResponse");try{const s=await this.ensureExecutor(i,t,n.signal);if(this.assertSessionStillReady(i,t),i.deliveryFailure!==void 0)throw i.deliveryFailure;this.holdOrContinueActivationBoundary(i,t.responseCommitted);const c=E([t.signal,t.connectionSignal,n.signal]);if(c.aborted)throw k(c);const d=await R(s.setSessionConfigOption(e,{signal:c}),c);if(i.deliveryFailure!==void 0)throw i.deliveryFailure;const l=this.validateChildBoundary(i,"SetSessionConfigOptionResponse",d),h=this.mergeSessionConfigOptions(i,l.configOptions);return i.configOptions=structuredClone(h),this.releaseBufferedAfterResponse(i,t,o),{...l,configOptions:h}}catch(s){throw i.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(i,t,o):o(),s}}async setSessionEnabledPlugins(e,t,r){const i=this.ownedReadySession(e.sessionId,r.connectionSignal);if(await this.awaitBarrier(i,r.signal),i.foreground||i.replayInFlight||i.configWriteInFlight||i.executorReleaseInFlight||i.childStartup)throw M(e.sessionId);i.configWriteInFlight=!0;const n=this.beginActiveOperation(i,"config"),o=u(()=>{this.finishActiveOperation(i,n)},"finishAfterResponse");try{this.assertSessionStillReady(i,r),this.holdOrContinueActivationBoundary(i,r.responseCommitted);const s=E([r.signal,r.connectionSignal,n.signal,i.lifecycleController.signal,this.facadeController.signal]);if(s.aborted)throw k(s);const c=!yt(i.pluginSettings.enabledPlugins,t);if(c){const l=i.pluginSettings;if(await this.retireSessionPluginRuntime(i,new Error("Session Plugin settings changed"),{preserveExecutorResources:!0,preserveWorkspaceProduct:!0}),s.aborted)throw k(s);i.pluginSettings=wt({enabledPlugins:t,generation:l.generation+1})}if(c||!i.child)try{if(await this.ensureExecutor(i,r,n.signal,{preserveSessionOnFailure:!0}),this.assertSessionStillReady(i,r),i.deliveryFailure!==void 0)throw i.deliveryFailure}catch(l){if(s.aborted)throw k(s);if(this.assertSessionStillReady(i,r),i.deliveryFailure!==void 0||i.child!==void 0||i.childFailureToken!==void 0||i.mcpAttachment!==void 0)throw l}const d=this.mergeSessionConfigOptions(i,i.configOptions);return i.configOptions=structuredClone(d),c&&await this.deliverNotification(i,{method:this.methods.client.session.update,params:{sessionId:e.sessionId,update:{configOptions:structuredClone(d),sessionUpdate:"config_option_update"}}}),this.releaseBufferedAfterResponse(i,r,o),{configOptions:d}}catch(s){throw i.deliveryMode==="buffer"?this.releaseBufferedAfterResponse(i,r,o):o(),s}}async retireSessionPluginRuntime(e,t,r={}){const i=e.child,n=e.mcpAttachment,o=e.childFailureToken??i,s=[];let c;e.executorReleaseInFlight=!0,e.childFailureToken=void 0,e.child=void 0,e.authReady=!1;try{try{this.rotateReverseController(e,t)}catch(d){s.push(d)}try{await this.retireMcpStatusProjection(e)}catch(d){s.push(d)}if(e.privateMcpServers=void 0,r.preserveExecutorResources||(e.mcpAttachment=void 0,e.mcpAttachmentCwd=void 0),!r.preserveWorkspaceProduct)try{this.clearWorkspaceProductBinding(e)}catch(d){s.push(d)}if(o)try{await n?.disconnectPeer(o)}catch(d){s.push(d)}if(i){c=Promise.resolve().then(()=>i.dispose(t)),e.executorReleasePromise=c;try{await c}catch(d){s.push(d)}}if(!r.preserveExecutorResources)try{await n?.revoke()}catch(d){s.push(d)}if(s.length>0)throw new AggregateError(s,"Session Plugin runtime retirement failed")}finally{e.executorReleasePromise===c&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async prompt(e,t){const r=this.ownedReadySession(e.sessionId,t.connectionSignal);await this.awaitBarrier(r,t.signal);const i=qe(e._meta);if(i?.mode===Oe)return this.steerPrompt(r,e,i.expectedRequestId,t);if(r.foreground||r.replayInFlight||r.configWriteInFlight)throw M(e.sessionId);return this.runForegroundOperation(r,t,"prompt",{failed:"Foreground prompt failed",start:"Starting a new prompt"},async(n,o)=>{const s=await n.prompt(ke(e),{signal:o});if(r.deliveryFailure!==void 0)throw r.deliveryFailure;const c=this.validateChildBoundary(r,"PromptResponse",s);return this.withPrivateBoundaryContainment(r,()=>this.capturePromptResponseRequestId(r,c))})}async steerPrompt(e,t,r,i){const n=e.activeOperationController,o=e.child;if(!e.foreground||e.activeOperationKind!=="prompt"||!n||!o||e.replayInFlight||e.configWriteInFlight)throw or(t.sessionId);if(e.activeRequestId===void 0||e.activeRequestId!==r)throw sr(t.sessionId);this.holdOrContinueActivationBoundary(e,i.responseCommitted);const s=E([i.signal,i.connectionSignal,n.signal,e.reverseController.current.signal]);try{if(s.aborted)throw k(s);const c=await o.prompt(ke(t),{signal:s});if(e.deliveryFailure!==void 0)throw e.deliveryFailure;const d=this.validateChildBoundary(e,"PromptResponse",c),l=this.withPrivateBoundaryContainment(e,()=>this.capturePromptResponseRequestId(e,d));return this.releaseBufferedAfterResponse(e,i),l}catch(c){throw e.deliveryMode==="buffer"&&this.releaseBufferedAfterResponse(e,i),c}}async cancel(e,t){const r=this.sessions.get(e.sessionId);if(!r||!r.proxy.has(t.connectionSignal)||this.reservations.has(e.sessionId))return;const i=new Error("Session cancelled");(r.activeOperationKind==="prompt"||r.activeOperationKind==="compact")&&r.activeOperationController?.abort(i),this.rotateReverseController(r,i);const n=r.child;n&&!r.replayInFlight&&await n.cancelSession(e)}close(e){return this.closePromise??=this.closeAll(e),this.closePromise}async reloadUserConfig(e="config/batchWrite"){this.closing||await Promise.allSettled([...this.sessions.values()].map(async t=>{const r=t.child;if(!r)return;const i=this.processRuntime.createPolicyDeadline(this.configReloadTimeoutMs,{signals:[t.lifecycleController.signal,this.facadeController.signal],timeoutReason:Pe()});try{await R(r.refreshUserConfig(e,{signal:i.signal}),i.signal)}finally{i.close()}}))}setAuthentication(e,t={}){return this.enqueueAuthenticationMutation(async()=>{this.assertNewAuthenticationGeneration(e.generation);const r=structuredClone(e);this.authProjection={kind:"set",params:r},await this.applyAuthenticationToExistingChildren(t.fenceExisting===!0)})}clearAuthentication(e,t={}){return this.enqueueAuthenticationMutation(async()=>{this.assertNewAuthenticationGeneration(e.generation);const r=structuredClone(e);this.authProjection={kind:"clear",params:r},await this.applyAuthenticationToExistingChildren(!0)})}enqueueAuthenticationMutation(e){const t=this.authMutationTail.then(e,e);return this.authMutationTail=t.catch(()=>{}),t}assertNewAuthenticationGeneration(e){if(!Number.isSafeInteger(e)||e<0||e<=this.authProjection.params.generation)throw new Error("Authentication generation must increase monotonically")}async applyAuthenticationToExistingChildren(e){const t=[...this.activations].filter(r=>r.child!==void 0&&r.authReady);await Promise.all(t.map(async r=>{const i=r.child;if(!i)return;let n;const o=this.processRuntime.createPolicyDeadline(this.configReloadTimeoutMs,{signals:[r.lifecycleController.signal,this.facadeController.signal],timeoutReason:Pe()});try{const c=e?i.clearAuthentication?.({generation:this.authProjection.params.generation},{signal:o.signal}):this.authProjection.kind==="set"?i.setAuthentication?.(this.authProjection.params,{signal:o.signal}):i.clearAuthentication?.(this.authProjection.params,{signal:o.signal});if(!(await R(Promise.resolve(c),o.signal))?.applied)throw new Error("Private Agent child rejected authentication generation")}catch(c){n=c}finally{o.close()}if(!e&&n===void 0)return;const s=n??new Error("Agent session fenced by authentication state change");try{await this.failActivation(r,s)}catch(c){r.deliveryFailure??=c}}))}createActivation(e,t){const r=this.profile(e.connectionSignal),i=structuredClone(r.capabilities),n=this.createAttachmentScope(this.processRuntime),o=new Bt({maxBufferedBytes:this.maxBufferedNotificationBytes,maxBufferedNotifications:this.maxBufferedNotifications,onAttachmentFailure:u((c,d)=>this.releaseFailedProxyAttachment(s,c.context,d),"onAttachmentFailure")}),s={attachmentScope:n,attached:!1,attachmentReplayInFlight:!1,activeForegroundAccepted:!1,authReady:!1,barrier:Promise.withResolvers(),...e.responseCommitted===void 0?{}:{barrierResponseCommitted:e.responseCommitted},bufferedNotificationBytes:0,bufferedNotificationCount:0,bufferedNotifications:[],compactionDeliveryEpoch:{},compactions:new Map,configWriteInFlight:!1,deliveryGeneration:0,deliveryMode:"buffer",deliveryTail:Promise.resolve(),executorReleaseInFlight:!1,expectedSessionId:t,foreground:!1,lifecycleController:n.makeController(),negotiatedClientCapabilities:i,owner:e.connectionSignal,ownerContext:e,productForegroundPending:!1,pluginSettings:Object.freeze({enabledPlugins:Object.freeze({}),generation:0}),proxy:o,replayInFlight:!1,replayResponsePending:!1,rebinding:!1,reconnectRootTerminalMatched:!1,reverseController:{current:n.makeController()},startupController:n.makeController(),workspaceProductRebindInFlight:!1};if(!o.add(e,r))throw k(e.connectionSignal);try{n.bindFinalizer(c=>this.disposeAttachmentResources(s,c))}catch(c){throw n.close(c).catch(()=>{}),c}return s}mergeSessionConfigOptions(e,t){const r=t??e.configOptions;return je(cr(r,e.workspaceProduct?.sessionModelConfigOption),e.pluginSettings.enabledPlugins)}mergeHostSessionConfigOptions(e,t){const r=e.workspaceProduct;return this.mergeSessionConfigOptions(e,r===void 0?t:Je(t,r.sessionModelConfigOption))}commitAdditionalDirectories(e,t){if(!e.resumeParams)throw new f(p.internalError,"Active session is missing its durable resume setup");e.resumeParams={...e.resumeParams,additionalDirectories:structuredClone(t.additionalDirectories??[])}}createMcpAttachment(e,t,r,i){if(!this.mcpIntegration)return;const n=this.profile(e.owner);if((t.mcpServers?.some(h=>h.type!=="acp")||r.servers.length||i.servers.length)&&(!n.elicitationForm||!n.elicitationUrl))throw new b("Executor-backed MCP requires elicitation.form and elicitation.url client capabilities");const o=t.mcpServers??[],s=new Set;for(const h of o){if(typeof h.name!="string"||!h.name.trim()||h.name.length>128||h.name.startsWith("_")||h.name.startsWith("plugin:")||s.has(h.name))throw new b("MCP server names must be unique, nonempty, non-reserved and at most 128 characters");s.add(h.name)}const c=o.filter(h=>h.type==="acp"),d=c.length?e.proxy.list().find(h=>h.context.connectionSignal===e.owner)?.context:void 0;if(c.length&&!d)throw new b("Client MCP owner is disconnected");return this.mcpIntegration.createAttachment({interaction:u((h,g)=>this.requestMcpElicitation(e,h,g.signal),"interaction"),setup:{cwd:t.cwd,mcpServers:t.mcpServers?.filter(h=>h.type!=="acp"),...d?{clientMcp:{servers:c,owner:d,router:this.clientMcp}}:{},pluginMcpSnapshot:r,userMcpSnapshot:{...i,servers:i.servers.filter(h=>!c.some(g=>g.name===h.logicalName))}}})}mcpStatusNotification(e,t,r){const i=r??(t.status==="available"?"ready":"failed");return{error:i==="failed"?(t.error?.message??"MCP server unavailable").slice(0,lt):null,failureReason:null,name:t.logicalName,status:i,threadId:e}}publishMcpServerStatus(e,t,r){const i=e.sessionId;return!i||!e.attached||this.sessions.get(i)!==e?Promise.resolve():this.deliverNotification(e,{method:he.mcpServer.startupStatus.updated,params:this.mcpStatusNotification(i,t,r)})}suspendMcpStatusProjection(e){e.mcpStatusUnsubscribe?.(),e.mcpStatusUnsubscribe=void 0,e.mcpAttachmentCursorEpoch=void 0}async retireMcpStatusProjection(e){let t=[];if(e.mcpStatusUnsubscribe&&e.mcpAttachment&&e.privateMcpServers!==void 0)try{t=e.mcpAttachment.listServerStatuses()}catch{}this.suspendMcpStatusProjection(e),await Promise.allSettled(t.map(r=>this.publishMcpServerStatus(e,r,"cancelled")))}async installMcpStatusProjection(e){const t=e.mcpAttachment;if(!t||e.privateMcpServers===void 0||!e.sessionId){this.suspendMcpStatusProjection(e);return}this.suspendMcpStatusProjection(e);const r=xe();e.mcpAttachmentCursorEpoch=r;try{e.mcpStatusUnsubscribe=t.subscribeServerStatus(i=>{e.mcpAttachment!==t||e.mcpAttachmentCursorEpoch!==r||this.publishMcpServerStatus(e,i).catch(n=>{e.mcpAttachment===t&&this.activations.has(e)&&!e.closePromise&&(e.deliveryFailure??=n,this.handleChildFailure(e,n))})});for(const i of t.listServerStatuses())await this.deliverNotification(e,{method:he.mcpServer.startupStatus.updated,params:{error:null,failureReason:null,name:i.logicalName,status:"starting",threadId:e.sessionId}}),await this.publishMcpServerStatus(e,i)}catch(i){throw e.mcpAttachmentCursorEpoch===r&&this.suspendMcpStatusProjection(e),i}}async resolvePluginMcpSnapshot(e,t,r){return this.strictMcpConfig?{errors:[],generation:"strict-mcp-config",servers:[],version:1}:B("pluginMcpResolve",async()=>{const i=this.pluginMcp?.resolve??((...o)=>this.requireHostSessionControl().resolvePluginMcp(...o)),n=await R(i(t,e.pluginSettings,{signal:r}),r);if(n.pluginSettingsGeneration!==e.pluginSettings.generation)throw new f(p.internalError,"Resource resolved Plugin MCP from a different settings generation");return structuredClone(n.pluginMcpSnapshot)})}async resolveUserMcpSnapshot(e,t){if(this.strictMcpConfig)return de;const r=this.userMcp?.resolve??this.hostSessionControl?.resolveUserMcp?.bind(this.hostSessionControl);if(!r)return de;try{const i=structuredClone(await R(r(e,{signal:t}),t)),n=D();return n.setCount("invalidUserMcpServerCount",i.errors.filter(o=>o.code==="invalid_config").length),n.setCount("unsupportedUserMcpAuthCount",i.errors.filter(o=>o.code==="unsupported_auth").length),n.setCount("unsupportedUserMcpTransportCount",i.errors.filter(o=>o.code==="unsupported_transport").length),i}catch{if(t.aborted)throw k(t);if(this.facadeController.signal.aborted)throw k(this.facadeController.signal);return D().setCount("userMcpSnapshotResolveFailureCount",1),de}}async prepareMcpAttachment(e,t,r,i){const n=await this.stageMcpAttachment(e,t,r,i),o=e.mcpAttachment;return o&&await this.retireMcpStatusProjection(e),e.mcpAttachment=n.attachment,e.mcpAttachmentCwd=n.attachment?t.cwd:void 0,e.privateMcpServers=void 0,o&&o!==n.attachment&&await o.revoke(),n.materialized}async stageMcpAttachment(e,t,r,i){const[n,o]=await Promise.all([this.resolvePluginMcpSnapshot(e,t.cwd,i),this.resolveUserMcpSnapshot(t.cwd,i)]);if(!this.mcpIntegration){if((t.mcpServers?.length??0)>0||n.servers.length>0||o.servers.length>0)throw new f(p.notReady,"Session MCP integration is unavailable");return{}}const s=await B("mcpCompile",()=>this.createMcpAttachment(e,t,n,o));let c;try{r!==null&&s?.bindSessionId(r),s&&(c=await B("mcpMaterialize",()=>R(s.materialize(),i)))}catch(d){throw await s?.revoke().catch(()=>{}),d}return{attachment:s,materialized:c}}async rebindWorkspaceMcpAttachment(e,t,r,i){if(!this.mcpIntegration||e.mcpAttachment!==void 0&&e.mcpAttachmentCwd===t)return;const n=e.resumeParams,o=e.sessionId;if(!n||!o)throw new f(p.internalError,"Active session is missing its durable MCP setup");const s=e.mcpAttachment;if(i.aborted)throw k(i);if(this.assertSessionStillReady(e,r),s&&(await this.retireMcpStatusProjection(e),await s.revoke()),e.mcpAttachment===s&&(e.mcpAttachment=void 0,e.mcpAttachmentCwd=void 0,e.privateMcpServers=void 0),i.aborted)throw k(i);if(this.assertSessionStillReady(e,r),!e.child)return;const[c,d]=await Promise.all([this.resolvePluginMcpSnapshot(e,t,i),this.resolveUserMcpSnapshot(t,i)]),l=this.createMcpAttachment(e,{cwd:t,mcpServers:n.mcpServers},c,d);try{l?.bindSessionId(o)}catch(h){throw await l?.revoke().catch(()=>{}),h}e.mcpAttachment=l,e.mcpAttachmentCwd=l?t:void 0}async materializeNewSessionMcp(e,t,r,i){if(!e.mcpAttachment)return t;const n=i??await R(e.mcpAttachment.materialize(),r);return this.recordMcpMaterializationDiagnostics(n.diagnostics),e.privateMcpServers=structuredClone(n.mcpServers),{...t,mcpServers:[...e.privateMcpServers]}}recordMcpMaterializationDiagnostics(e){const t=D();t.setCount("droppedPluginMcpServerCount",e?.droppedPluginServerCount??0),t.setCount("droppedUserMcpServerCount",e?.droppedUserServerCount??0)}recordSessionNewMcpCounts(e){const t=e.mcpAttachment;if(t)try{const r=t.listServerStatuses(),i=D();i.setCount("availableMcpServerCount",r.filter(n=>n.status==="available").length),i.setCount("unavailableMcpServerCount",r.filter(n=>n.status==="unavailable").length),i.setCount("mcpToolCount",r.reduce((n,o)=>n+o.tools.length,0))}catch{}}async materializeResumeSessionMcp(e,t,r,i){if(!e.mcpAttachment)return{...t,replayFrom:null};const n=i??await R(e.mcpAttachment.materialize(),r);return this.recordMcpMaterializationDiagnostics(n.diagnostics),e.privateMcpServers=structuredClone(n.mcpServers),await this.installMcpStatusProjection(e),{...t,mcpServers:[...e.privateMcpServers],replayFrom:null}}projectResumeSessionMcp(e,t){const r=e.workspaceProduct===void 0?t:{...t,cwd:e.workspaceProduct.canonicalCwd};if(!e.mcpAttachment)return r;if(!e.privateMcpServers)throw new f(p.internalError,"Active MCP attachment is not materialized");return{...r,mcpServers:[...e.privateMcpServers]}}async requestMcpElicitation(e,t,r){const i=e.sessionId;if(!e.attached||!i||e.proxy.list("live").length===0||e.detached!==void 0||e.rebinding||this.facadeController.signal.aborted||r.aborted)return{action:"cancel"};await this.awaitBarrier(e,r);const n=t.mode==="form"?{message:t.message,mode:"form",requestedSchema:t.requestedSchema??{type:"object"},sessionId:i}:{elicitationId:t.elicitationId,message:t.message,mode:"url",sessionId:i,url:t.url},o=j("CreateElicitationRequest",n),s=await this.requestAttachedClients(e,t.mode,this.methods.client.elicitation.create,o,c=>ve("CreateElicitationResponse",c),r);return s.action!=="accept"&&s.action!=="decline"&&s.action!=="cancel"?{action:"cancel"}:{action:s.action,...s.action==="accept"&&I(s.content)?{content:s.content}:{}}}assertCanActivate(){if(this.closing)throw new f(p.notReady,"Agent Harness is shutting down");if(this.activations.size>=this.maxActiveSessions)throw new f(p.overloaded,"Maximum active Agent sessions reached")}claim(e,t,r){if(this.reservations.has(e)||t==="activating"&&this.sessions.has(e))throw M(e);this.reservations.set(e,{kind:t,owner:r})}attach(e,t){if(this.sessions.has(t)||this.reservations.has(t)&&this.reservations.get(t)?.kind!=="activating")throw M(t);e.attached=!0,e.sessionId=t,e.mcpAttachment?.bindSessionId(t),this.sessions.set(t,e),this.subagentProjection.attachSession(t,e.owner);const r=this.reservations.get(t);r?.kind==="activating"&&r.owner===e.owner&&this.reservations.delete(t)}ownedSession(e,t){const r=this.sessions.get(e);if(!r||!r.proxy.has(t))throw H(e);return r}ownedReadySession(e,t){const r=this.ownedSession(e,t);if(!r.proxy.has(t,"live")||r.attachmentReplayInFlight||r.closePromise||this.reservations.has(e))throw H(e);return r}mcpOperationSignal(e,t){return E([t.signal,t.connectionSignal,e.lifecycleController.signal,this.facadeController.signal])}requireMaterializedMcpAttachment(e){const t=e.mcpAttachment,r=e.mcpAttachmentCursorEpoch;if(!t||e.privateMcpServers===void 0||r===void 0)throw new f(p.notReady,"Session MCP attachment is not materialized");return{attachment:t,cursorEpoch:r}}resolveAdmissionSessionId(e,t){if(this.sessions.get(e)?.proxy.has(t))return e;const i=this.subagentProjection.rootSessionIdFor(e);return i!==void 0&&this.sessions.get(i)?.proxy.has(t)?i:e}requireChild(e){if(!e.child)throw new f(p.internalError,"Private ACP v2 child is unavailable");return e.child}requireHostSessionControl(){if(!this.hostSessionControl)throw new Error("Legacy session control is not configured");return this.hostSessionControl}async resumeStoredSession(e,t,r){return this.sessionReplay?{response:await z.runPromise(this.sessionReplay.resume(t,{...r,workspace:e.workspaceProduct,clientCapabilities:this.profile(e.owner).capabilities}))}:this.requireHostSessionControl().resumeSession(t,r)}assertSessionStillReady(e,t){const r=e.sessionId;if(!r||!e.proxy.has(t.connectionSignal,"live")||e.attachmentReplayInFlight||this.sessions.get(r)!==e||e.closePromise||this.reservations.has(r)||Z(e))throw H(r??"unknown")}ensureExecutor(e,t,r,i={}){if(r.aborted)return Promise.reject(k(r));if(e.child&&!e.childStartup)return Promise.resolve(e.child);if(e.childStartup)return R(e.childStartup,E([t.signal,r]));if(!e.resumeParams)return Promise.reject(new f(p.internalError,"Dormant session is missing its durable resume setup"));const n=this.activateDormantExecutor(e,t,r,i);return e.childStartup=n,n.then(()=>{e.childStartup===n&&(e.childStartup=void 0)},()=>{e.childStartup===n&&(e.childStartup=void 0)}),n}createSessionActivationDeadline(e,t){const r=E(t),i=new Rt(p.notReady,`Agent session activation timed out after ${this.sessionActivationTimeoutMs}ms`);return e.attachmentScope.deadline(r,this.sessionActivationTimeoutMs,i)}async releaseExecutorForRewind(e,t){const r=e.child;if(!r){this.releaseWorkspaceProductBinding(e);return}e.executorReleaseInFlight=!0,this.rotateReverseController(e,t);const i=Promise.resolve().then(()=>r.dispose(t));e.executorReleasePromise=i;try{await i,e.child===r&&(e.child=void 0,e.authReady=!1,e.privateMcpServers=void 0,this.clearWorkspaceProductBinding(e))}finally{e.executorReleasePromise===i&&(e.executorReleasePromise=void 0),e.executorReleaseInFlight=!1}}async activateDormantExecutor(e,t,r,i){const n=e.bufferedNotifications.length,o=e.deliveryFailure,s=e.configOptions,c=e.foreground,d=e.agentInitiatedForegroundToken,l=e.publicForegroundDeliveryToken,h=e.productForegroundPending,g=e.productForegroundDrain,y=i.preserveSessionOnFailure?{committed:!1}:void 0;y&&(e.recoverableActivation=y);const C=e.attachmentScope.makeController();e.replayController=C,e.replayInFlight=!0,this.holdOrContinueActivationBoundary(e,t.responseCommitted);const F=this.createSessionActivationDeadline(e,[t.signal,t.connectionSignal,this.facadeController.signal,e.startupController.signal,C.signal,r]),m=F.signal;try{const v=e.resumeParams;if(!v)throw new f(p.internalError,"Dormant session is missing its durable resume setup");const P=e.workspaceProduct===void 0?v:{...v,cwd:e.workspaceProduct.canonicalCwd},O=await this.prepareMcpAttachment(e,P,v.sessionId,m),q=await this.materializeResumeSessionMcp(e,v,m,O),_=await this.spawnInitializedChild(e,v.cwd,m),K=e.workspaceProduct===void 0?q:{...q,cwd:e.workspaceProduct.canonicalCwd},ee=this.validateChildBoundary(e,"ResumeSessionResponse",await R(_.resumeSession(K,{signal:m}),m));if(this.assertSessionIdentity(e,v.sessionId),await R(e.deliveryTail,m),y?.failure!==void 0)throw y.failure;if(e.deliveryFailure!==void 0)throw e.deliveryFailure;return y&&(y.committed=!0,e.recoverableActivation===y&&(e.recoverableActivation=void 0),this.withPrivateBoundaryContainment(e,()=>this.finalizeBufferedPrivateLiveUpdatesFrom(e,n))),e.configOptions=structuredClone(this.mergeSessionConfigOptions(e,ee.configOptions)),this.clearReplayController(e,C),e.replayInFlight=!1,_}catch(v){if(C.signal.aborted||C.abort(v),this.clearReplayController(e,C),e.replayInFlight=!1,y&&!y.committed&&this.activations.has(e)&&!e.lifecycleController.signal.aborted){let P;try{await this.retireSessionPluginRuntime(e,v,{preserveWorkspaceProduct:!0})}catch(O){P=O}finally{this.discardBufferedNotificationsFrom(e,n)}throw!h&&e.productForegroundPending&&this.resolveProductForeground(e),e.foreground=c,e.agentInitiatedForegroundToken=d,e.publicForegroundDeliveryToken=l,e.productForegroundPending=h,e.productForegroundDrain=g,e.configOptions=s,e.deliveryFailure=o,P!==void 0?V(v,P,"Replacement Plugin runtime activation and cleanup failed"):v}throw this.activations.has(e)&&(this.dropBuffered(e),await this.failActivation(e,v)),v}finally{y&&e.recoverableActivation===y&&(e.recoverableActivation=void 0),F.clear()}}sessionOpenOptions(e,t,r,i){return{callbacks:this.createCallbacks(e,i),clientCapabilities:this.profile(e.owner).capabilities,clientInfo:this.serverInfo,cwd:e.workspaceProduct?.canonicalCwd??t,onFailure:u(n=>this.handlePrivateChildExit(e,n,i),"onFailure"),pluginSettings:e.pluginSettings,workspace:e.workspaceProduct,signal:r}}async spawnInitializedChild(e,t,r){const i={};e.childFailureToken=i;const n=e.attachmentScope.runEffect(this.sessionRuntime.open(this.sessionOpenOptions(e,t,r,i)));let o;try{o=await R(n,r)}catch(s){throw e.childFailureToken===i&&(e.childFailureToken=void 0),r.aborted&&this.trackCleanup(n.then(c=>c.dispose(k(r)),()=>{})),s}return e.child=o,this.validateInitializedChild(e,o),await B("authProjection",()=>this.applyAuthenticationToChild(e,o,r)),o}async applyAuthenticationToChild(e,t,r){for(;;){await R(this.authMutationTail,r);const i=this.authProjection;if(!(await R(Promise.resolve(i.kind==="set"?t.setAuthentication?.(i.params,{signal:r}):t.clearAuthentication?.(i.params,{signal:r})),r))?.applied)throw new f(p.internalError,"Private Agent child rejected authentication state");if(await R(this.authMutationTail,r),this.authProjection.params.generation===i.params.generation){e.authReady=!0;return}}}validateInitializedChild(e,t){this.withPrivateBoundaryContainment(e,()=>{const r=oe(this.agentCapabilities,t.capabilities,"capabilities");if(r)throw new f(p.internalError,`Session runtime is missing advertised ${r}`.slice(0,$));const i=this.sessionRuntime.profile?.supports;if((i?.configReload??!0)&&!t.supports.configReload)throw new f(p.internalError,'Session runtime is missing advertised capabilities._meta["codebuddy.ai"].config.reload');if((i?.compact??!0)&&!t.supports.compact)throw new f(p.internalError,'Session runtime is missing advertised capabilities._meta["codebuddy.ai"].session.compact');if((i?.promptSteer??!0)&&!t.supports.promptSteer)throw new f(p.internalError,`Session runtime is missing advertised capabilities.session.prompt._meta["${ge}"].modes`);if(e.privateMcpServers?.some(n=>n.type==="acp")&&t.capabilities.session?.mcp?.acp==null)throw new f(p.internalError,"Session runtime is missing advertised capabilities.session.mcp.acp")})}validateChildBoundary(e,t,r){return this.withPrivateBoundaryContainment(e,()=>j(t,r))}withPrivateBoundaryContainment(e,t){try{return t()}catch(r){if(e.attached)if(e.deliveryFailure??=r,e.closePromise)for(const i of e.proxy.list())i.context.closeConnection?.(r).catch(()=>{});else this.handleChildFailure(e,r);throw r}}async deliverHostUpdate(e,t){const r=j("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId);const i=this.projectPrivateUpdate(e,r);e.rebinding&&(e.reconnectMessageCoverage?.observeSnapshot(r),this.captureReconnectRootTerminal(e,r)),await this.enqueueProjectedNotifications(e,Re(i))}async deliverBufferedHostUpdate(e,t){const r=j("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId),await this.deliverProjectedNotifications(e,this.projectPrivateUpdate(e,r))}async projectDurableSnapshotUpdate(e,t){const r=j("UpdateSessionNotification",t);this.assertCallbackSessionId(e,r.sessionId),this.projectPrivateUpdate(e,r,!1)}projectPrivateUpdate(e,t,r=!0){const i=Me(t.update);if(i)throw new f(p.internalError,`Invalid private error update: ${i}`.slice(0,$));if(!this.validateCompactionUpdate(e,t,r))return[];!e.replayInFlight&&e.replayProjection===void 0&&t.update.sessionUpdate==="state_update"&&t.update.state==="idle"&&this.assertCompactionsTerminalBeforeIdle(e,t);let n=t;if(t.update.sessionUpdate==="config_option_update"){const o=this.mergeSessionConfigOptions(e,t.update.configOptions);n={...t,update:{...t.update,configOptions:o}},e.replayProjection||(e.configOptions=structuredClone(o))}return e.replayProjection?this.subagentProjection.projectReplay(e.replayProjection,e.owner,n):this.subagentProjection.project(n.sessionId,e.owner,n)}projectConcurrentReplayUpdate(e,t,r,i,n){const o=Me(n.update);if(o)throw new f(p.internalError,`Invalid private error update: ${o}`.slice(0,$));if(!this.validateCompactionUpdate(e,n,!1,!0))return[];const s=n.update.sessionUpdate==="config_option_update"?{...n,update:{...n.update,configOptions:this.mergeSessionConfigOptions(e,n.update.configOptions)}}:n;return t.projectReplay(r,i,s)}validateCompactionUpdate(e,t,r,i){if(t.update.sessionUpdate!==Ne)return!0;const n=bt(t.update);if(n)throw new f(p.internalError,`Invalid private compaction update: ${n}`.slice(0,$));const o=t.update,s=i??(e.replayInFlight||e.replayProjection!==void 0),c=o._meta,d=e.sessionId??e.expectedSessionId,l=c[Y];let h,g;if(l===void 0)g=t.sessionId===d,h=`root:${t.sessionId}`;else{if(!I(l)||l.version!==1||typeof l.sessionId!="string"||l.sessionId.trim().length===0)throw new f(p.internalError,"Private compaction update returned an invalid Subagent route");g=!1,h=`subagent:${l.sessionId}`}const y=c[vt],C=c[L],F=c[Se],m=typeof C=="string"&&C.trim().length>0;if(y==="manual"&&!g)throw new f(p.internalError,"Private manual compaction update is not a root lifecycle");if(s&&o.status==="in_progress")throw new f(p.internalError,"Private compaction replay returned transient in_progress state");const v=JSON.stringify([h,o.compactionId]),P=e.compactions.get(v),O=P!==void 0&&(P.status==="in_progress"||P.status==="completed"||P.status==="failed"||P.status==="cancelled"),q=o.status==="in_progress"||o.status==="completed"||o.status==="failed"||o.status==="cancelled",_=o.status==="completed"||o.status==="failed"||o.status==="cancelled";if(P){if(P.trigger!==y||P.route!==h)throw new f(p.internalError,"Private compaction lifecycle changed route or trigger identity");if(P.status!==o.status&&O&&q&&!(P.status==="in_progress"&&_))throw new f(p.internalError,"Private compaction lifecycle changed terminal status or regressed")}const K=JSON.stringify([h,ne(o)]);if(r&&P?.lastDeliveredEpoch===e.compactionDeliveryEpoch&&P.lastDeliveredFingerprint===K)return!1;const ee=P!==void 0&&o.status!=="in_progress"&&(P.status===o.status||!O||!q);if(y==="manual"&&!s&&!ee){if(!g||e.activeOperationKind!=="compact"&&e.activeOperationKind!=="prompt"||!e.foreground)throw new f(p.internalError,"Private manual compaction update is outside its foreground lifecycle");if(!P&&o.status!=="in_progress")throw new f(p.internalError,"Private manual compaction completed before it started");if(e.activeCompactionId!==void 0&&e.activeCompactionId!==o.compactionId)throw new f(p.internalError,"Private manual compaction changed its lifecycle id");e.activeCompactionId=o.compactionId,this.captureActiveRequestId(e,c,"compaction update",!1)}else!ee&&!s&&g&&m&&e.activeOperationKind==="prompt"&&e.foreground&&this.captureActiveRequestId(e,c,"compaction update",!1);const w=P??{lastObservedFingerprint:K,route:h,status:o.status,trigger:y};return m&&w.requestId===void 0&&(w.requestId=C,w.rootRequestId=typeof F=="string"?F:void 0),w.status=o.status,w.lastObservedFingerprint=K,e.compactions.set(v,w),r&&(w.lastDeliveredEpoch=e.compactionDeliveryEpoch,w.lastDeliveredFingerprint=K),!0}assertCompactionsTerminalBeforeIdle(e,t){const r=t.update._meta,i=I(r)?r[L]:void 0,n=I(r)?r[Y]:void 0,o=I(n)&&typeof n.sessionId=="string"?`subagent:${n.sessionId}`:`root:${t.sessionId}`;for(const d of e.compactions.values())if(d.route===o&&d.requestId===i&&d.status==="in_progress")throw new f(p.internalError,"Private compaction reached idle before a terminal status");if(e.activeOperationKind!=="compact")return;const s=e.activeCompactionId,c=s===void 0?void 0:e.compactions.get(JSON.stringify([`root:${t.sessionId}`,s]));if(c===void 0||!(c.status==="completed"||c.status==="failed"||c.status==="cancelled"))throw new f(p.internalError,"Private manual compaction omitted its terminal lifecycle update")}capturePromptResponseRequestId(e,t){const r=mt(t);if(!r)throw new f(p.internalError,`Private ACP v2 PromptResponse omitted ${L} or returned it empty`);return this.captureActiveRequestId(e,r._meta,"PromptResponse"),r}captureRootUpdateRequestId(e,t){if(e.replayInFlight||e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground)return;const r=t.update._meta;if(I(r)&&Object.hasOwn(r,Y))return;const i=t.update;i.sessionUpdate!==Ne&&(i.sessionUpdate==="terminal_update"||i.sessionUpdate==="terminal_output_chunk"||i.sessionUpdate!=="usage_update"&&this.captureActiveRequestId(e,I(r)?r:void 0,`session/update.params.update.${i.sessionUpdate}`,!1))}captureActiveRequestId(e,t,r,i=!0){if(e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground||!I(t)||!Object.hasOwn(t,L))return;const n=t[L];if(typeof n!="string"||n.trim().length===0){if(!i)return;throw new f(p.internalError,`Private ACP v2 ${r} returned an invalid ${L}`)}if(e.activeRequestId!==void 0&&e.activeRequestId!==n){if(!i)return;throw new f(p.internalError,"Private ACP v2 child changed the active prompt request identity")}e.activeRequestId=n}deferPrivateLiveUpdate(e,t,r,i){if(e.deliveryMode!=="buffer")return Promise.reject(new f(p.notReady,"Private live update arrived outside the replay response boundary"));e.rebinding&&e.reconnectMessageCoverage?.trackLive(t);const n=this.reserveBufferedNotification(e,{...r===void 0?{}:{afterDelivery:r},method:this.methods.client.session.update,params:t,privateLiveUpdate:{notification:t,...i===void 0?{}:{projected:i}}});if(!n){const s=new ce("ACP v2 response-boundary notification buffer limit exceeded");return e.deliveryFailure??=s,this.handleChildFailure(e,s),Promise.reject(s)}return(e.rebindLiveNotifications??e.bufferedNotifications).push(n),Promise.resolve()}async enqueueProjectedNotifications(e,t,r){const i=t.map(s=>{const c=s.params;return this.enqueueNotification(e,{...r&&c.sessionId===e.sessionId?{afterDelivery:r}:{},...this.toBufferedNotification(s)})}),o=(await Promise.allSettled(i)).find(s=>s.status==="rejected");if(o)throw o.reason}async deliverProjectedNotifications(e,t,r){const i=t.map(s=>{const c=s.params;return this.deliverNotification(e,{...r&&c.sessionId===e.sessionId?{afterDelivery:r}:{},...this.toBufferedNotification(s)})}),o=(await Promise.allSettled(i)).find(s=>s.status==="rejected");if(o)throw o.reason}createCallbacks(e,t){return{refreshAuthentication:u(async(r,i)=>{if(this.assertCurrentPrivateChildCallback(e,t),!this.refreshAuthentication)throw new f(-32e3,"Authentication required");const n=E([e.lifecycleController.signal,this.facadeController.signal,...i?.signal?[i.signal]:[]]);this.inFlightPrivateRefreshCallbackCount+=1;try{return await this.refreshAuthentication(r,{signal:n})}finally{this.inFlightPrivateRefreshCallbackCount-=1}},"refreshAuthentication"),completeElicitation:u(async r=>{this.assertCurrentPrivateChildCallback(e,t);const i=this.withPrivateBoundaryContainment(e,()=>{const n=j("CompleteElicitationNotification",r);return this.assertReverseSessionExists(e),n});await this.awaitBarrier(e),this.assertCurrentPrivateChildCallback(e,t),this.assertReverseReady(e,"url"),await this.deliverNotification(e,{method:this.methods.client.elicitation.complete,params:i})},"completeElicitation"),createElicitation:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=this.withPrivateBoundaryContainment(e,()=>{const s=j("CreateElicitationRequest",r);if(!("sessionId"in s)||typeof s.sessionId!="string")throw new f(p.invalidRequest,"Request-scoped elicitation cannot cross isolated ACP connections");const c=s;return this.assertCallbackSessionId(e,c.sessionId),this.assertReverseSessionExists(e),c});await this.awaitBarrier(e,i?.signal),this.assertCurrentPrivateChildCallback(e,t);const o=this.withPrivateBoundaryContainment(e,()=>this.subagentProjection.projectSessionScopedRequest(n.sessionId,e.owner,n));return this.requestAttachedClients(e,o.mode,this.methods.client.elicitation.create,o,s=>ve("CreateElicitationResponse",s),i?.signal)},"createElicitation"),mcpConnect:u(async(r,i,n)=>{this.assertCurrentPrivateChildCallback(e,t);const o=e.mcpAttachment;if(!o)throw new b("Private Agent requested MCP without an active session scope");return o.connect(r,{peerToken:t,peer:i,signal:E([e.lifecycleController.signal,this.facadeController.signal,...n?.signal?[n.signal]:[]])})},"mcpConnect"),mcpDisconnect:u(async r=>{this.assertCurrentPrivateChildCallback(e,t),await e.mcpAttachment?.disconnect(r,{peerToken:t})},"mcpDisconnect"),mcpMessage:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=e.mcpAttachment;if(!n)throw new b("Private Agent requested MCP without an active session scope");return n.message(r,{peerToken:t,signal:E([e.lifecycleController.signal,this.facadeController.signal,...i?.signal?[i.signal]:[]])})},"mcpMessage"),mcpNotification:u(async r=>{this.assertCurrentPrivateChildCallback(e,t);const i=e.mcpAttachment;if(!i)throw new b("Private Agent notified MCP without an active session scope");i.notify(r,{peerToken:t})},"mcpNotification"),mcpPeerClosed:u(async()=>{await e.mcpAttachment?.disconnectPeer(t)},"mcpPeerClosed"),requestPermission:u(async(r,i)=>{this.assertCurrentPrivateChildCallback(e,t);const n=this.withPrivateBoundaryContainment(e,()=>{const s=j("RequestPermissionRequest",r);return this.assertCallbackSessionId(e,s.sessionId),this.assertReverseSessionExists(e),s});await this.awaitBarrier(e,i?.signal),this.assertCurrentPrivateChildCallback(e,t);const o=this.withPrivateBoundaryContainment(e,()=>this.subagentProjection.projectSessionScopedRequest(n.sessionId,e.owner,n));return this.requestAttachedClients(e,!1,this.methods.client.session.requestPermission,o,s=>ve("RequestPermissionResponse",s),i?.signal)},"requestPermission"),sessionUpdate:u(async r=>{if(!(e.closePromise||e.executorReleaseInFlight||e.childFailurePromise||e.childFailureToken!==t||!this.activations.has(e)))try{const i=j("UpdateSessionNotification",r);this.assertCallbackSessionId(e,i.sessionId);const n=i.update._meta,o=I(n)?n[L]:void 0;if(!e.replayInFlight&&i.update.sessionUpdate==="state_update"&&i.update.state==="idle"&&!Object.hasOwn(n??{},Y)&&e.activeRequestId!==void 0&&typeof o=="string"&&o.trim().length>0&&o!==e.activeRequestId)return;this.captureRootUpdateRequestId(e,i);const s=e.replayResponsePending,c=i.update,d=c._meta,l=c.sessionUpdate==="state_update"&&!(I(d)&&Object.hasOwn(d,Y)),h=e.activeOperationKind==="prompt"||e.activeOperationKind==="compact";!s&&l&&c.state==="running"&&!h&&(e.publicForegroundDeliveryToken=void 0,e.agentInitiatedForegroundToken={},e.foreground=!0,this.beginProductForeground(e));const g=!s&&l&&c.state==="idle",y=g&&h?e.activeOperationController:void 0,C=y?{}:void 0,F=g?e.agentInitiatedForegroundToken:void 0;g&&(this.assertCompactionsTerminalBeforeIdle(e,i),y&&(e.publicForegroundDeliveryToken=C,this.finishPublicForegroundAtTerminalReceipt(e,y)));const m=C?()=>{e.publicForegroundDeliveryToken===C&&(e.publicForegroundDeliveryToken=void 0,e.foreground=!1,this.rotateReverseController(e,new Error("Foreground turn completed")))}:F?()=>{e.agentInitiatedForegroundToken===F&&(e.agentInitiatedForegroundToken=void 0,e.foreground=!1,e.activeRequestId=void 0,this.resolveProductForeground(e),e.productForegroundDrain=void 0,this.rotateReverseController(e,new Error("Foreground turn completed")))}:void 0;if(e.deliveryMode==="buffer"&&!(e.replayInFlight&&e.replayResponsePending)){const P=e.rebinding||e.recoverableActivation!==void 0?void 0:this.projectPrivateUpdate(e,i);await this.deferPrivateLiveUpdate(e,i,m,P);return}const v=this.projectPrivateUpdate(e,i);if(e.replayResponsePending){await this.enqueueProjectedNotifications(e,Re(v));return}await this.deliverProjectedNotifications(e,v,m)}catch(i){if(e.closePromise||!this.activations.has(e))return;throw e.deliveryFailure??=i,this.handleChildFailure(e,i),i}},"sessionUpdate")}}assertCurrentPrivateChildCallback(e,t){if(e.childFailureToken!==t||e.childFailurePromise||!this.activations.has(e))throw new f(p.notReady,"Private ACP v2 child is no longer active")}assertCallbackSessionId(e,t){if(e.expectedSessionId!==void 0&&e.expectedSessionId!==t)throw new f(p.internalError,"Private ACP v2 child emitted a different sessionId");if(e.observedSessionId!==void 0&&e.observedSessionId!==t)throw new f(p.internalError,"Private ACP v2 child emitted multiple session identities");e.observedSessionId=t}assertSessionIdentity(e,t){if(this.assertCallbackSessionId(e,t),e.expectedSessionId!==void 0&&e.expectedSessionId!==t)throw new f(p.internalError,"Private ACP v2 response changed the requested session identity")}async requestAttachedClients(e,t,r,i,n,o){this.assertReverseReady(e,t);const s=this.reverseSignal(e,o);return e.proxy.requestFirst(r,i,c=>n(c),{select:u(c=>this.supportsReverseRequest(c.profile,t),"select"),signal:s,timeoutMs:Ht})}supportsReverseRequest(e,t){return t===!1||t==="form"&&e.elicitationForm||t==="url"&&e.elicitationUrl}assertReverseReady(e,t){if(!e.attached||e.sessionId===void 0||e.deliveryMode!=="forward")throw new f(p.notReady,"Private ACP v2 reverse request arrived before the session response boundary committed");if(!e.proxy.list("live").some(i=>this.supportsReverseRequest(i.profile,t)))throw new f(p.methodNotFound,"The public ACP v2 Client did not advertise elicitation")}assertReverseSessionExists(e){if(!e.attached||e.sessionId===void 0||e.deliveryMode==="drop")throw new f(p.notReady,"Private ACP v2 reverse request arrived before the session response boundary committed")}reverseSignal(e,t){return E([e.lifecycleController.signal,this.facadeController.signal,e.reverseController.current.signal,...e.activeOperationController?[e.activeOperationController.signal]:[],...t?[t]:[]])}profile(e){const t=this.profiles.get(e);if(!t)throw new f(p.notReady,"ACP v2 Agent profile is not initialized");return t}holdNotifications(e,t){if(e.deliveryMode!=="forward")throw new f(p.notReady,"Session response boundary is still pending");e.deliveryMode="buffer",e.bufferedNotifications=[],e.barrier=Promise.withResolvers(),e.barrierResponseCommitted=t}holdOrContinueActivationBoundary(e,t){if(e.deliveryMode==="forward"){this.holdNotifications(e,t);return}if(e.deliveryMode!=="buffer")throw new f(p.notReady,"Session attachment is closed")}schedulePostResponseTask(e,t,r){if(!this.schedulePostResponse){const i=new f(p.internalError,t);throw r(i),i}try{this.schedulePostResponse(e)}catch(i){throw r(i),i}}releaseBufferedAfterResponse(e,t,r){const i=u(async()=>{if(e.detached&&e.activeForegroundAccepted){e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId),e.activeResponseCommitted=void 0;return}try{(e.activeOperationKind==="prompt"||e.activeOperationKind==="compact")&&e.activeForegroundAccepted&&e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId),await this.flushBuffered(e)}catch(o){e.deliveryFailure??=o,this.handleChildFailure(e,o)}finally{e.barrier.resolve(),r?.()}},"release"),n=t.responseCommitted;if(n){n.then(i,o=>{if(this.canSurviveResponseFailure(e,t))return i();if(e.detached&&e.activeForegroundAccepted){e.activeResponseCommitted=void 0;return}e.deliveryFailure??=o,this.handleChildFailure(e,o),r?.()}).catch(o=>{e.deliveryFailure??=o,this.handleChildFailure(e,o)});return}this.schedulePostResponseTask(i,"Agent Harness request is missing its response-commit boundary",()=>{this.dropBuffered(e),r?.()})}releaseDetachedRebindAfterResponse(e,t,r,i=!1){const n=u(async()=>{try{this.subagentProjection.commitRebind(r.projection,t.connectionSignal),e.rebindProjection=void 0,e.detached=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayResponsePending=!1,e.activeForegroundAccepted&&e.activeRequestId!==void 0&&(e.acknowledgedRequestId=e.activeRequestId,e.activeResponseCommitted=void 0),this.installReconnectLiveSuffix(e),await this.flushBuffered(e),await this.installMcpStatusProjection(e),this.finishForegroundFromReconnectSnapshot(e)}catch(s){e.deliveryFailure??=s,this.handleChildFailure(e,s)}finally{e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.barrier.resolve()}},"commit"),o=u(s=>{if(i){this.handleChildFailure(e,s);return}this.rollbackDetachedRebind(e,r,s)},"fail");if(t.responseCommitted){t.responseCommitted.then(n,o).catch(s=>{e.deliveryFailure??=s,this.handleChildFailure(e,s)});return}this.schedulePostResponseTask(n,"Agent Harness reconnect is missing its response-commit boundary",o)}installReconnectLiveSuffix(e){const t=e.rebindLiveNotifications??[],r=[],i=new Map;for(const s of t){const c=s.privateLiveUpdate?.notification;if(!c)throw new f(p.internalError,"Reconnect live suffix contained an already-projected notification");r.push(c),i.set(c,s)}const n=e.reconnectMessageCoverage;if(!n)throw new f(p.internalError,"Reconnect message coverage was not initialized");const o=n.mergeLive(r);e.reconnectMessageCoverage=void 0;for(const s of o)this.captureReconnectLiveRootState(e,s);for(const s of t)this.releaseBufferedNotification(e,s);e.rebindLiveNotifications=void 0,e.bufferedNotifications=[];for(const s of o){const c=i.get(s),d=this.reserveBufferedNotification(e,{...c?.afterDelivery===void 0?{}:{afterDelivery:c.afterDelivery},method:this.methods.client.session.update,params:s,privateLiveUpdate:{notification:s}});if(!d)throw new ce("Reconnect live suffix exceeds the notification buffer limit");e.bufferedNotifications.push(d)}}captureReconnectLiveRootState(e,t){const r=t.update,i=r._meta;if(t.sessionId!==e.sessionId||r.sessionUpdate!=="state_update"||I(i)&&Object.hasOwn(i,Y)||r.state!=="idle"&&r.state!=="running")return;const n=e.activeRequestId;n===void 0||!I(i)||i[L]!==n||i[Se]!==n||(e.reconnectLastRootState=r.state)}captureReconnectRootTerminal(e,t){const r=t.update,i=r._meta;if(t.sessionId!==e.sessionId||r.sessionUpdate!=="session_info_update"||!I(i)||Object.hasOwn(i,Y)||!Object.hasOwn(i,Fe))return;const n=pt.safeParse(i[Fe]);if(!n.success)throw new f(p.internalError,"Private ACP v2 replay returned an invalid root turn terminal");const o=e.activeRequestId;o!==void 0&&n.data.requestId===o&&n.data.rootRequestId===o&&(e.reconnectRootTerminalMatched=!0)}finishForegroundFromReconnectSnapshot(e){if(!e.reconnectRootTerminalMatched&&e.reconnectLastRootState!=="idle")return;const t=e.activeOperationController;t&&this.finishActiveOperation(e,t),this.rotateReverseController(e,new Error("Foreground turn completed while detached"))}rollbackDetachedRebind(e,t,r){const i=e.owner;e.proxy.remove(i),e.replayController?.abort(r),e.replayProjection===t.replay&&this.subagentProjection.abortReplay(t.replay,e.owner),this.subagentProjection.abortRebind(t.projection,e.owner),this.discardBufferedNotifications(e);const n=i.aborted,o=this.activations.has(e)&&e.attached;if(!o||n){for(const s of e.rebindLiveNotifications??[])this.releaseBufferedNotification(e,s);e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.rebindProjection=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,o?this.trackCleanup(this.closeActivationsImmediately([e],i,r)):(e.deliveryMode="drop",e.barrier.resolve());return}e.owner=t.detachedOwner,e.ownerContext=t.detachedOwnerContext,e.negotiatedClientCapabilities=t.negotiatedClientCapabilities,e.compactions=new Map([...t.compactions].map(([s,c])=>[s,{...c}])),e.bufferedNotifications=e.rebindLiveNotifications??[],e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.reconnectRootTerminalMatched=!1,e.rebindProjection=void 0,e.rebinding=!1,this.clearReplayController(e),e.replayInFlight=!1,e.replayProjection=void 0,e.replayResponsePending=!1,e.deliveryMode="buffer",this.rotateDeliveryGeneration(e),this.armDetachedSession(e,t.detachedOwner,t.detachedReason,t.detachedExpiresAt)}discardBufferedAfterResponse(e,t,r){const i=u(()=>{this.discardBufferedNotifications(e),e.deliveryMode="forward",e.barrier.resolve(),r?.()},"discard"),n=u(s=>{if(this.canSurviveResponseFailure(e,t)){i();return}e.deliveryFailure??=s,this.handleChildFailure(e,s),r?.()},"fail"),o=t.responseCommitted;if(o){o.then(i,n).catch(n);return}this.schedulePostResponseTask(async()=>i(),"Agent Harness request is missing its response-commit boundary",()=>{this.dropBuffered(e),r?.()})}canSurviveResponseFailure(e,t){return t.connectionSignal.aborted&&e.proxy.list().some(r=>r.context.connectionSignal!==t.connectionSignal&&!r.context.connectionSignal.aborted)}toBufferedNotification(e){return{method:e.method,params:e.params}}async flushBuffered(e){if(e.deliveryMode!=="buffer")return;const t=e.bufferedNotifications;e.bufferedNotifications=[];const r=[];let i=!1,n,o=0;for(;o<t.length;o+=1){const d=t[o];try{const l=d.privateLiveUpdate?this.enqueueProjectedNotifications(e,d.privateLiveUpdate.projected??this.projectPrivateUpdate(e,d.privateLiveUpdate.notification),d.afterDelivery):this.enqueueNotification(e,d);r.push(l.finally(()=>this.releaseBufferedNotification(e,d)))}catch(l){this.releaseBufferedNotification(e,d),i=!0,n=l,o+=1;break}}if(i){for(;o<t.length;o+=1)this.releaseBufferedNotification(e,t[o]);throw await Promise.allSettled(r),n}e.deliveryMode="forward";const c=(await Promise.allSettled(r)).find(d=>d.status==="rejected");if(c)throw c.reason}async resolveStoredSubagent(e,t){const r=this.sessionReplay?.subagents;if(!r||this.subagentProjection.rootSessionIdFor(e)!==void 0||(await this.awaitOwnedResponseBoundaryWave(t),this.subagentProjection.rootSessionIdFor(e)!==void 0))return;let i;for(const n of this.sessions.values()){if(!n.proxy.has(t.connectionSignal,"live")||!n.sessionId||!n.resumeParams)continue;await this.settleSubagentResponseBoundary(n,t);const o=await r.read({sessionId:n.sessionId,cwd:n.resumeParams.cwd,workspace:n.workspaceProduct},e,this.mcpOperationSignal(n,t));if(this.assertSessionStillReady(n,t),!!o){if(i)throw new b("Subagent identity is ambiguous across attached roots");i={current:{rootSessionId:n.sessionId,subagent:o.subagent},session:n,stored:o}}}if(!(i&&(await this.settleSubagentResponseBoundary(i.session,t),this.subagentProjection.rootSessionIdFor(e)!==void 0)))return i}async resolveSubagentAfterBoundary(e,t){let r=this.subagentProjection.rootSessionIdFor(e);if(r===void 0){if(!await this.awaitOwnedResponseBoundaryWave(t))return this.throwUnknownSubagent(e,t);if(r=this.subagentProjection.rootSessionIdFor(e),r===void 0)return this.throwUnknownSubagent(e,t)}const i=this.ownedSession(r,t.connectionSignal);if(t.responseCommitted!==void 0&&i.barrierResponseCommitted===t.responseCommitted&&i.deliveryMode==="buffer")throw H(e);await this.settleSubagentResponseBoundary(i,t);const n=this.subagentProjection.readSubagent(e,i.owner);if(n.rootSessionId!==r)throw new f(p.internalError,"Subagent root identity changed across a response boundary");return{current:n,session:i}}throwUnknownSubagent(e,t){const r=[...this.sessions.values()].find(i=>i.proxy.has(t.connectionSignal));throw r&&this.subagentProjection.readSubagent(e,r.owner),H(e)}async awaitOwnedResponseBoundaryWave(e){const t=e.responseCommitted,r=[...this.sessions.values()].flatMap(i=>i.proxy.has(e.connectionSignal)&&i.deliveryMode==="buffer"&&i.detached===void 0&&i.closePromise===void 0&&(t===void 0||i.barrierResponseCommitted!==t)?[{boundary:i.barrier,session:i}]:[]);return r.length===0?!1:(await Promise.all(r.map(({boundary:i,session:n})=>this.awaitSubagentResponseBoundary(n,i,e))),!0)}async settleSubagentResponseBoundary(e,t){const r=e.barrier;if(await this.awaitSubagentResponseBoundary(e,r,t),this.assertSessionStillReady(e,t),e.barrier===r&&e.deliveryMode==="forward")return;if(e.detached!==void 0||e.deliveryMode==="drop"||e.barrier===r)throw H(e.sessionId??"unknown");const i=e.barrier;if(await this.awaitSubagentResponseBoundary(e,i,t),this.assertSessionStillReady(e,t),e.barrier!==i||e.deliveryMode!=="forward")throw new f(p.notReady,"Subagent response boundary changed before it could be read")}async awaitSubagentResponseBoundary(e,t,r){const i=E([r.signal,r.connectionSignal,e.lifecycleController.signal,this.facadeController.signal]);if(await R(t.promise,i),await R(e.deliveryTail,i),e.deliveryFailure!==void 0)throw e.deliveryFailure}dropBuffered(e){this.discardBufferedNotifications(e),e.deliveryMode="drop",e.barrier.resolve()}discardBufferedNotifications(e){for(const t of e.bufferedNotifications)this.releaseBufferedNotification(e,t);e.bufferedNotifications=[]}discardBufferedNotificationsFrom(e,t){const r=e.bufferedNotifications.splice(t);for(const i of r)this.releaseBufferedNotification(e,i)}finalizeBufferedPrivateLiveUpdatesFrom(e,t){for(let r=t;r<e.bufferedNotifications.length;r+=1){const i=e.bufferedNotifications[r],n=i?.privateLiveUpdate;i===void 0||n===void 0||n.projected!==void 0||(e.bufferedNotifications[r]={...i,privateLiveUpdate:{...n,projected:this.projectPrivateUpdate(e,n.notification)}})}}deliverNotification(e,t){if(e.deliveryMode==="drop")return Promise.reject(new f(p.notReady,"Session attachment is closed"));if(e.deliveryMode==="buffer"){const r=this.reserveBufferedNotification(e,t);if(!r){const i=new ce("ACP v2 response-boundary notification buffer limit exceeded");return e.deliveryFailure??=i,this.handleChildFailure(e,i),Promise.reject(i)}return e.bufferedNotifications.push(r),Promise.resolve()}return this.enqueueNotification(e,t)}reserveBufferedNotification(e,t){const r=Buffer.byteLength(JSON.stringify({jsonrpc:"2.0",method:t.method,params:t.params}),"utf8");if(!(e.bufferedNotificationCount>=this.maxBufferedNotifications||e.bufferedNotificationBytes+r>this.maxBufferedNotificationBytes))return e.bufferedNotificationCount+=1,e.bufferedNotificationBytes+=r,{...t,reservedBytes:r}}releaseBufferedNotification(e,t){t.reservedBytes!==void 0&&(e.bufferedNotificationCount-=1,e.bufferedNotificationBytes-=t.reservedBytes,t.reservedBytes=void 0)}rotateDeliveryGeneration(e){e.deliveryGeneration+=1,e.deliveryFailure=void 0,e.deliveryTail=Promise.resolve()}enqueueNotification(e,t){if(e.deliveryMode==="drop")return Promise.reject(new f(p.notReady,"Session attachment is closed"));const r=e.deliveryGeneration,i=e.deliveryTail.then(async()=>{if(e.deliveryMode==="drop"||e.deliveryGeneration!==r)throw new f(p.notReady,"Session delivery generation changed");await e.proxy.notify(t.method,t.params),t.afterDelivery?.()});return e.deliveryTail=i.catch(n=>{e.deliveryGeneration===r&&(e.deliveryFailure??=n)}),i}async awaitBarrier(e,t){if(t?(await R(e.barrier.promise,t),await R(e.deliveryTail,t)):(await e.barrier.promise,await e.deliveryTail),e.deliveryFailure!==void 0)throw e.deliveryFailure}rotateReverseController(e,t){const r=e.reverseController.current;e.reverseController.current=e.attachmentScope.replaceController(r,t)}clearReplayController(e,t){const r=e.replayController;!r||t!==void 0&&r!==t||(e.replayController=void 0,e.attachmentScope.releaseController(r))}beginActiveOperation(e,t){if(e.activeOperationController)throw M(e.sessionId??"unknown");const r=e.attachmentScope.makeController();return e.activeOperationController=r,e.activeOperationKind=t,(t==="prompt"||t==="compact")&&this.beginProductForeground(e),r}beginProductForeground(e){e.productForegroundPending||(e.productForegroundDrain=Promise.withResolvers(),e.productForegroundPending=!0,this.pendingProductForegroundCount+=1)}resolveProductForeground(e){e.productForegroundPending&&(e.productForegroundPending=!1,this.pendingProductForegroundCount-=1,e.productForegroundDrain?.resolve())}finishPublicForegroundAtTerminalReceipt(e,t){e.activeOperationController!==t||e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||(this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.activeCompactionId=void 0,e.activeOperationController=void 0,e.activeOperationKind=void 0,e.attachmentScope.releaseController(t))}finishActiveOperation(e,t){e.activeOperationController===t&&(e.activeOperationKind==="prompt"||e.activeOperationKind==="compact"?(this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.foreground=!1,e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.activeCompactionId=void 0):e.activeOperationKind==="config"&&(e.configWriteInFlight=!1),e.activeOperationController=void 0,e.activeOperationKind=void 0,e.attachmentScope.releaseController(t))}abortActiveOperation(e,t){const r=e.activeOperationController;r&&!r.signal.aborted&&r.abort(t)}handlePrivateChildExit(e,t,r){if(e.childFailureToken!==r||!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight||e.childFailurePromise)return;const i=e.recoverableActivation;if(i){i.failure??=t,e.replayController?.abort(t);return}const n=e.activeRequestId,o=e.sessionId,s=e.resumeParams?.cwd,c=e.acknowledgedRequestId===n||e.activeResponseCommitted!==void 0;if(e.activeOperationKind!=="prompt"&&e.activeOperationKind!=="compact"||!e.foreground||!e.activeForegroundAccepted||typeof n!="string"||n.trim().length===0||typeof o!="string"||o.trim().length===0||typeof s!="string"||s.trim().length===0||!c){this.handleChildFailure(e,t);return}const d=this.recoverAcknowledgedChildExit(e,t,r,{cwd:s,requestId:n,sessionId:o});e.childFailurePromise=d,d.finally(()=>{e.childFailurePromise===d&&(e.childFailurePromise=void 0)}).catch(()=>{}),this.trackCleanup(d)}async recoverAcknowledgedChildExit(e,t,r,i){try{e.acknowledgedRequestId!==i.requestId&&(await e.activeResponseCommitted,e.acknowledgedRequestId=i.requestId)}catch(C){this.handleChildFailure(e,C);return}if(e.childFailureToken!==r||!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight||e.activeRequestId!==i.requestId)return;const n=e.activeOperationController,o=e.child,s=this.processRuntime.policyNow(),c=new Date(s).toISOString(),d={[L]:i.requestId,[Se]:i.requestId,[Wt]:c};this.abortActiveOperation(e,t),this.rotateReverseController(e,t),e.child=void 0,e.authReady=!1,e.childFailureToken=void 0,e.privateMcpServers=void 0,this.releaseWorkspaceProductBinding(e);const l=[];try{await this.enqueueNotification(e,{method:this.methods.client.session.update,params:{sessionId:i.sessionId,update:{sessionUpdate:me,error:Ce,willRetry:!1,_meta:d}}})}catch(C){l.push(C)}const[h,g]=await Promise.allSettled([o?.dispose(t)??Promise.resolve(),this.runAttachedHostSessionOperation(e,C=>{const F={cwd:i.cwd,error:Ce,requestId:i.requestId,rootRequestId:i.requestId,sessionId:i.sessionId,stopReason:me,timestamp:s};return this.sessionService?z.runPromise(this.sessionService.commitTerminal(F,{signal:C})):this.requireHostSessionControl().commitTerminalState(F,{signal:C})})]);h.status==="rejected"&&l.push(h.reason);let y=!1;g.status==="fulfilled"?y=!0:l.push(g.reason);try{y&&await this.enqueueNotification(e,{method:this.methods.client.session.update,params:{sessionId:i.sessionId,update:{sessionUpdate:"state_update",state:"idle",stopReason:me,_meta:{[ft]:Ce,...d}}}})}catch(C){l.push(C)}finally{n&&this.finishActiveOperation(e,n)}if(l.length>0){const C=l.length===1?l[0]:new AggregateError(l,"Private Agent child terminal recovery failed");e.deliveryFailure??=C,this.handleChildFailure(e,C)}}runAttachedHostSessionOperation(e,t){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));const r=E([e.lifecycleController.signal,this.facadeController.signal]),i=R(Promise.resolve().then(()=>t(r)),r);return this.managementOperations.add(i),i.then(()=>this.managementOperations.delete(i),()=>this.managementOperations.delete(i)),i}handleChildFailure(e,t){this.handleActivationFailure(e,t,t instanceof ce||t instanceof Tt||t instanceof jt||t instanceof Nt?"attachment":"connection")}handleActivationFailure(e,t,r){if(!this.activations.has(e)||e.closePromise||e.executorReleaseInFlight)return;e.activeRequestId=void 0;const i=e.attached,n=e.sessionId,o=e.proxy.list().map(s=>s.context);if(e.startupController.signal.aborted||e.startupController.abort(t),this.rotateReverseController(e,t),this.dropBuffered(e),this.detach(e),this.trackCleanup(this.disposeChild(e,t)),i){if(r==="connection"){for(const s of o)s.closeConnection?.(t).catch(()=>{});return}if(n===void 0){for(const s of o)s.closeConnection?.(t).catch(()=>{});return}for(const s of o){const c=s.closeSessionAttachment;c?.(n,t).catch(d=>{s.closeConnection?.(d).catch(()=>{})})}}}runHostSessionOperation(e,t,r=!1,i=!1){if(this.closing)return Promise.reject(new f(p.notReady,"Agent Harness is shutting down"));const n=E([...r?[]:[e.connectionSignal,e.signal],this.facadeController.signal]),o=Promise.resolve().then(()=>t(n)),s=i?o:R(o,n);return this.managementOperations.add(s),s.then(()=>this.managementOperations.delete(s),()=>this.managementOperations.delete(s)),s}closeAttached(e,t,r){return e.closePromise??=this.performCloseAttached(e,t,r),e.closePromise}async performCloseAttached(e,t,r){if(e.replayInFlight)return this.forceCloseReplay(e);const i=new Error("Session closing");this.abortActiveOperation(e,i),this.rotateReverseController(e,i);const n=this.processRuntime.createPolicyDeadline(this.closeSessionTimeoutMs,{signals:[e.lifecycleController.signal,this.facadeController.signal],timeoutReason:Pe()}),o=n.signal;let s,c;try{if(e.deliveryMode==="buffer"?this.dropBuffered(e):r&&await R(e.deliveryTail,o),e.deliveryFailure!==void 0)throw e.deliveryFailure;const l=e.child;if(l?s=this.validateChildBoundary(e,"CloseSessionResponse",await R(l.closeSession(t,{signal:o}),o)):s={},await R(e.deliveryTail,o),e.deliveryFailure!==void 0)throw e.deliveryFailure}catch(l){c=l}finally{n.close()}let d;try{await this.disposeChild(e,c)}catch(l){d=l}finally{this.dropBuffered(e),this.detach(e)}if(c!==void 0)throw V(c,d,"Private ACP v2 session close and cleanup failed");if(d!==void 0)throw d;return s??{}}async forceCloseReplay(e){const t=new Error("Session closed during replay");this.abortActiveOperation(e,t),e.replayController?.abort(t),this.clearReplayController(e),e.replayInFlight=!1,e.replayResponsePending=!1,this.rotateReverseController(e,t),this.dropBuffered(e);try{await this.disposeChild(e,t)}finally{this.detach(e)}return{}}async failActivation(e,t){e.startupController.signal.aborted||e.startupController.abort(t),this.rotateReverseController(e,t),this.detach(e);try{await this.disposeChild(e,t)}catch(r){throw V(t,r,"Private ACP v2 activation and cleanup failed")}}disposeChild(e,t){return this.suspendMcpStatusProjection(e),e.disposePromise??=e.attachmentScope.close(t),e.disposePromise}async disposeAttachmentResources(e,t){this.suspendMcpStatusProjection(e);const r=e.executorReleasePromise??e.child?.dispose(t)??Promise.resolve(),n=(await Promise.allSettled([r,e.mcpAttachment?.revoke()??Promise.resolve()])).filter(o=>o.status==="rejected");if(n.length===1)throw n[0].reason;if(n.length>1)throw new AggregateError(n.map(o=>o.reason),"Private Agent child and MCP attachment cleanup failed")}detach(e){for(const n of e.proxy.list())e.proxy.remove(n.context.connectionSignal);this.resolveProductForeground(e),e.productForegroundDrain=void 0,e.agentInitiatedForegroundToken=void 0,e.publicForegroundDeliveryToken=void 0;const t=e.rebindProjection&&e.detached?e.detached.owner:e.owner;e.rebindProjection&&(this.subagentProjection.abortRebind(e.rebindProjection,e.owner),e.rebindProjection=void 0),e.detached&&(e.detached.timer.cancel(),e.detached=void 0);for(const n of e.rebindLiveNotifications??[])this.releaseBufferedNotification(e,n);e.rebindLiveNotifications=void 0,e.reconnectLastRootState=void 0,e.reconnectMessageCoverage=void 0,e.lifecycleController.signal.aborted||e.lifecycleController.abort(new Error("Agent session runtime detached")),e.acknowledgedRequestId=void 0,e.activeForegroundAccepted=!1,e.activeResponseCommitted=void 0,e.activeRequestId=void 0,e.childFailureToken=void 0;const r=e.sessionId;r&&this.sessions.get(r)===e&&this.sessions.delete(r);const i=r??e.expectedSessionId;i&&this.subagentProjection.detachSession(i,t),this.activations.delete(e),this.releaseWorkspaceProductBinding(e)}trackCleanup(e){this.trackedCleanup.add(e),e.then(()=>this.trackedCleanup.delete(e),()=>this.trackedCleanup.delete(e))}async releaseOwner(e,t){const r=[...this.activations].filter(i=>i.proxy.has(e)||!i.attached&&i.owner===e);await Promise.all(r.map(i=>this.releaseSessionAttachment(i,e,t)))}async releaseSessionAttachment(e,t,r,i){const n=e.proxy.list().find(s=>s.context.connectionSignal===t)?.context.connection.transport??i;if(e.proxy.remove(t),e.proxy.list().length>0||e.detached||!this.activations.has(e))return;const o=e.sessionId;if(!(o&&this.reservations.get(o)?.kind==="checkpointing"&&e.deliveryMode==="buffer"&&(await e.barrier.promise,e.proxy.list().length>0||e.detached||!this.activations.has(e)))){if(n!=="stdio"&&this.canDetachSubscriber(e)){this.detachSubscriber(e,t,r);return}await this.closeActivationsImmediately([e],t,r)}}canDetachSubscriber(e){return!!(e.attached&&e.sessionId&&!e.closePromise&&!e.executorReleaseInFlight&&!e.childStartup&&!e.rebinding&&!e.replayInFlight&&!e.configWriteInFlight&&e.deliveryFailure===void 0&&(e.deliveryMode==="forward"||e.deliveryMode==="buffer"&&e.activeForegroundAccepted))}detachSubscriber(e,t,r){this.suspendMcpStatusProjection(e),e.deliveryMode==="forward"&&this.holdNotifications(e),this.rotateDeliveryGeneration(e),this.rotateReverseController(e,r),this.armDetachedSession(e,t,r)}armDetachedSession(e,t,r,i=this.processRuntime.policyNow()+this.detachedSessionGraceMs){e.detached&&e.detached.timer.cancel();const n=e.attachmentScope.schedule(Math.max(0,i-this.processRuntime.policyNow()),async()=>{if(e.detached?.owner!==t||e.rebinding||!this.activations.has(e))return;const o=this.expireDetachedSession(e,t);this.trackCleanup(o),await o});e.detached={expiresAt:i,owner:t,reason:r,timer:n}}async expireDetachedSession(e,t){const r=e.sessionId;if(!(!r||e.detached?.owner!==t||e.rebinding||!this.activations.has(e))){this.reservations.has(r)||this.reservations.set(r,{kind:"closing",owner:t});try{await this.closeAttached(e,{sessionId:r},!1)}finally{this.reservations.get(r)?.owner===t&&this.reservations.delete(r)}}}async closeOwnedImmediately(e,t){const r=[...this.activations].filter(i=>i.owner===e);await this.closeActivationsImmediately(r,e,t)}async closeActivationsImmediately(e,t,r){for(const i of e){if(i.detached&&i.detached.timer.cancel(),i.startupController.signal.aborted||i.startupController.abort(r),this.abortActiveOperation(i,r),this.rotateReverseController(i,r),!i.attached||!i.sessionId){this.dropBuffered(i);continue}i.deliveryMode==="buffer"&&this.dropBuffered(i);const n=i.sessionId;n&&!this.reservations.has(n)&&this.reservations.set(n,{kind:"closing",owner:t})}await Promise.allSettled(e.map(async i=>{i.attached&&i.sessionId?await this.closeAttached(i,{sessionId:i.sessionId},!1):(await this.disposeChild(i,r),this.detach(i))}));for(const[i,n]of this.reservations)n.owner===t&&this.reservations.delete(i)}async closeAll(e){this.closing=!0,this.facadeController.signal.aborted||this.facadeController.abort(e);const t=new Set([...this.activations].map(r=>r.owner));for(await Promise.allSettled([...t].map(r=>this.closeOwnedImmediately(r,e))),await Promise.allSettled([...this.managementOperations]);this.trackedCleanup.size>0;)await Promise.allSettled([...this.trackedCleanup])}}function Xe(a,e){const t=pe(a,e);if(t)throw new b(t.message);return e}u(Xe,"validatePublicNotification");function be(a){if(typeof a!="object"||a===null||Object.isFrozen(a))return a;Object.freeze(a);for(const e of Object.values(a))be(e);return a}u(be,"deepFreeze");function Ae(a,e){const t=[...a];return t.length===e.length&&t.every((r,i)=>r===e[i])}u(Ae,"sameMethods");export async function createAgentV2Facade(a){if(!a.hostSessionControl&&(!a.sessions||!a.checkpoints||!a.sessionReplay||!a.sessionRuntime.rewind||!a.pluginMcp||!a.userMcp))throw new TypeError("Session storage, replay, rewind and MCP services are required without legacy session control");const e=a.processRuntime??ot(),t=a.maxActiveSessions??Be,r=a.maxBufferedNotificationBytes??Te,i=a.maxBufferedNotifications??De,n=a.closeSessionTimeoutMs??Dt,o=a.configReloadTimeoutMs??Ut,s=a.detachedSessionGraceMs??Gt,c=a.sessionActivationTimeoutMs??Ue,d=a.initialProductGeneration??0;if(J(t,"maxActiveSessions"),J(r,"maxBufferedNotificationBytes"),J(i,"maxBufferedNotifications"),J(n,"closeSessionTimeoutMs"),J(o,"configReloadTimeoutMs"),J(s,"detachedSessionGraceMs"),J(c,"sessionActivationTimeoutMs"),!Number.isSafeInteger(d)||d<0)throw new RangeError("initialProductGeneration must be a non-negative safe integer");if(t>Ge)throw new RangeError(`maxActiveSessions must not exceed ${Ge}`);if(r>We)throw new RangeError(`maxBufferedNotificationBytes must not exceed ${We}`);if(i>He)throw new RangeError(`maxBufferedNotifications must not exceed ${He}`);const[l,h]=await Promise.all([ut(),import("../effect-runtime/session-attachment-scope.mjs")]),g=a.sessionRuntime.profile,y=structuredClone(a.agentCapabilities??g?.capabilities??zt(a.platform??process.platform,a.windowsProcessContainmentEnabled,a.windowsJob)),C=be(g?.supports.promptSteer===!1?y:Zt(y)),F=oe({session:{delete:{},fork:{}}},C,"capabilities");if(F)throw new Error(`Agent v2 facade requires ${F}`);j("InitializeResponse",{authMethods:[],capabilities:C,info:a.serverInfo,protocolVersion:2});const m=new ur({agentCapabilities:C,closeSessionTimeoutMs:n,configReloadTimeoutMs:o,createAttachmentScope:h.openSessionAttachmentScope,detachedSessionGraceMs:s,hostSessionControl:a.hostSessionControl,initialProductGeneration:d,maxActiveSessions:t,maxBufferedNotificationBytes:r,maxBufferedNotifications:i,mcpIntegration:a.mcpIntegration,strictMcpConfig:a.strictMcpConfig??!1,methods:N,onPermanentFailure:a.onPermanentFailure,processRuntime:e,prepareSessionRuntime:a.prepareSessionRuntime,prepareSessionWorkspace:a.prepareSessionWorkspace,releaseSessionWorkspace:a.releaseSessionWorkspace,refreshAuthentication:a.refreshAuthentication,schedulePostResponse:a.schedulePostResponse,sessionActivationTimeoutMs:c,serverInfo:a.serverInfo,sessionRuntime:a.sessionRuntime,sessionReplay:a.sessionReplay,sessions:a.sessions,checkpoints:a.checkpoints,userMcp:a.userMcp,pluginMcp:a.pluginMcp,subagentProjection:new _e({maxBufferedNotificationBytes:r,maxBufferedNotifications:i})}),v=be({agent:C}),P=new Map([[N.agent.mcp.message,(w,S)=>m.clientMcp.message(G("MessageMcpRequest",w),S)],[N.agent.session.new,async(w,S)=>{D().set({path:"cold"});const A=G("NewSessionRequest",w),te=A.mcpServers??[],re=D();return re.setCount("requestedMcpServerCount",te.length),re.setCount("requestedStdioMcpCount",te.filter(Q=>Q.type==="stdio").length),re.setCount("requestedRemoteMcpCount",te.filter(Q=>Q.type==="http"||Q.type==="sse").length),m.preflightNewSession(A),m.runPreparedProductAdmittedRequest(S,A.cwd,Q=>m.newSession(A,S,Q))}],[N.agent.session.list,(w,S)=>m.listSessions(G("ListSessionsRequest",w),S)],[N.agent.session.delete,(w,S)=>{const A=G("DeleteSessionRequest",w);return m.runExistingWorkspaceAdmittedSessionRequest(A.sessionId,S,()=>m.deleteSession(A,S))}],[N.agent.session.fork,(w,S)=>{const A=Qt(w);return m.runAdmittedSessionRequest(A.sessionId,S,()=>m.forkSession(A,S))}],[N.agent.session.resume,(w,S)=>{const A=xt(w);return m.runResumeSessionRequest(A,S)}],[N.agent.session.close,(w,S)=>{const A=G("CloseSessionRequest",w);return m.runExistingWorkspaceAdmittedSessionRequest(A.sessionId,S,()=>m.closeSession(A,S))}],[N.agent.session.setConfigOption,(w,S)=>{const A=G("SetSessionConfigOptionRequest",w);return m.runPreparedAdmittedSessionRequest(A.sessionId,S,()=>m.setSessionConfigOption(A,S))}],[N.agent.session.prompt,(w,S)=>{const A=er(w);if(g?.supports.promptSteer===!1&&qe(A._meta)?.mode===Oe)throw new f(p.methodNotFound,"Session backend does not support steer");return m.runPreparedAdmittedSessionRequest(A.sessionId,S,()=>m.prompt(A,S))}]]),O=new Map([[ie.list,fe(rt,(w,S)=>m.listCheckpoints(w,S))],[ie.read,fe(it,(w,S)=>m.readCheckpoint(w,S))],[ie.restore,fe(nt,(w,S)=>m.restoreCheckpoint(w,S))],[ye,(w,S)=>{const A=tr(w);return m.runPreparedAdmittedSessionRequest(A.sessionId,S,()=>m.compactSession(A,S))}],[we,(w,S)=>{const A=ir(w);return m.runExistingWorkspaceAdmittedSessionRequest(A.sessionId,S,()=>m.rewindSession(A,S))}]]),q=new Map([...P,...O]);if(g?.supports.compact===!1&&q.delete(ye),g?.checkpoints===!1)for(const w of Object.values(ie))q.delete(w);g?.checkpoints===!1&&!a.sessionRuntime.rewind&&q.delete(we);const _=new Map([[N.agent.mcp.message,(w,S)=>m.clientMcp.notify(Xe("MessageMcpNotification",w),S)],[N.agent.session.cancel,(w,S)=>m.cancel(Xe("CancelSessionNotification",w),S)]]),K=Object.freeze({inboundNotificationHandlers:_,inboundRequestHandlers:q,outboundNotificationMethods:l.outboundNotifications,outboundRequestMethods:l.outboundRequests});if(!Ae(P.keys(),l.inboundRequests)||!Ae(_.keys(),l.inboundNotifications)||!Ae(O.keys(),[...Object.values(ie),ye,we]))throw new Error("Agent v2 facade registries do not match their exact method allowlists");return{capabilities:v,clearAuthentication:u((w,S)=>m.clearAuthentication(w,S),"clearAuthentication"),failProductGeneration:u(w=>m.failProductGeneration(w),"failProductGeneration"),initialize:u((w,S)=>{const A=m.selectProfile(S),te=Object.freeze([N.client.session.requestPermission,...Object.values(N.client.mcp),...A.elicitationForm||A.elicitationUrl?[N.client.elicitation.create]:[]]),re=Object.freeze([N.client.session.update,N.client.mcp.message,...A.elicitationUrl?[N.client.elicitation.complete]:[]]);return{capabilities:v,registry:Object.freeze({inboundNotificationHandlers:_,inboundRequestHandlers:q,outboundNotificationMethods:re,outboundRequestMethods:te})}},"initialize"),notificationHandlers:_,registry:K,requestHandlers:q,close:u(w=>m.close(w),"close"),callMcpServerTool:u((w,S)=>m.runAdmittedSessionRequest(w.threadId,S,()=>m.callMcpServerTool(w,S)),"callMcpServerTool"),listMcpServerStatuses:u((w,S)=>m.runAdmittedSessionRequest(w.threadId,S,()=>m.listMcpServerStatuses(w,S)),"listMcpServerStatuses"),listSubagents:u((w,S)=>m.runAdmittedSessionRequest(w.sessionId,S,()=>m.listSubagents(w,S)),"listSubagents"),readSubagent:u((w,S)=>m.runAdmittedSessionRequest(w.sessionId,S,()=>m.readSubagent(w,S)),"readSubagent"),reloadUserConfig:u(w=>m.reloadUserConfig(w),"reloadUserConfig"),rotateProductGeneration:u((w,S,A)=>m.rotateProductGeneration(w,S,A),"rotateProductGeneration"),setAuthentication:u((w,S)=>m.setAuthentication(w,S),"setAuthentication")}}u(createAgentV2Facade,"createAgentV2Facade");