agentroam-runtime-darwin-arm64 0.2.0-preview.75 → 0.2.0-preview.77
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.
- package/manifest.json +2 -2
- package/package.json +1 -1
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-build-manifest.json +9 -9
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +5 -5
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/required-server-files.json +1 -1
- package/runtime/.next/routes-manifest.json +1 -1
- package/runtime/.next/server/app/_not-found/page.js +1 -1
- package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/_not-found.html +1 -1
- package/runtime/.next/server/app/_not-found.rsc +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/codex-sharing/route.js +1 -1
- package/runtime/.next/server/app/api/agent/codex-sharing/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/harness/status/route.js +1 -1
- package/runtime/.next/server/app/api/agent/harness/status/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/models/route.js +1 -1
- package/runtime/.next/server/app/api/agent/models/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/stream/route.js +4 -4
- package/runtime/.next/server/app/api/agent/stream/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
- package/runtime/.next/server/app/api/business/route.js +1 -1
- package/runtime/.next/server/app/api/business/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/calendar/route.js +2 -3
- package/runtime/.next/server/app/api/calendar/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/client-logs/route.js +1 -1
- package/runtime/.next/server/app/api/collaboration/route.js +9 -9
- package/runtime/.next/server/app/api/collaboration/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/engine-threads/route.js +1 -1
- package/runtime/.next/server/app/api/engine-threads/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/engine-threads.body +1 -1
- package/runtime/.next/server/app/api/flow/v1/catalog/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/catalog/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/cancel/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/cancel/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/events/route.js +2 -2
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/events/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/flow-studio/config/route.js +1 -1
- package/runtime/.next/server/app/api/internal/todo-bootstrap/route.js +1 -0
- package/runtime/.next/server/app/api/internal/todo-bootstrap/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/internal/todo-mcp/route.js +1 -0
- package/runtime/.next/server/app/api/internal/todo-mcp/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers.body +1 -1
- package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
- package/runtime/.next/server/app/api/memory/route.js +1 -1
- package/runtime/.next/server/app/api/messaging/route.js +1 -1
- package/runtime/.next/server/app/api/notifications/[id]/ack/route.js +1 -0
- package/runtime/.next/server/app/api/notifications/[id]/ack/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/notifications/[id]/route.js +1 -0
- package/runtime/.next/server/app/api/notifications/[id]/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/notifications/route.js +1 -0
- package/runtime/.next/server/app/api/notifications/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/notifications/stream/route.js +4 -0
- package/runtime/.next/server/app/api/notifications/stream/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
- package/runtime/.next/server/app/api/plugins/load/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/projects/check/route.js +1 -1
- package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
- package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
- package/runtime/.next/server/app/api/projects/route.js +1 -1
- package/runtime/.next/server/app/api/push/subscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/subscribe/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/push/unsubscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/vapid/route.js +3 -3
- package/runtime/.next/server/app/api/push/vapid/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/push/vapid.body +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/session-images/[id]/route.js +1 -0
- package/runtime/.next/server/app/api/session-images/[id]/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/stop/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/stop/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +3 -3
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/engine-switches/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/engine-switches/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork-at/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork-at/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/native-goal/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/native-goal/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/release/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/release/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/switch-engine/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/switch-engine/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-goal/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-goal/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-history/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-history/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/parallel/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/parallel/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/settings/route.js +1 -1
- package/runtime/.next/server/app/api/skills/route.js +1 -1
- package/runtime/.next/server/app/api/todos/[id]/commands/route.js +1 -0
- package/runtime/.next/server/app/api/todos/[id]/commands/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/todos/[id]/executions/route.js +1 -0
- package/runtime/.next/server/app/api/todos/[id]/executions/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/todos/[id]/route.js +1 -0
- package/runtime/.next/server/app/api/todos/[id]/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/todos/route.js +1 -0
- package/runtime/.next/server/app/api/todos/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/tool-policies/[policyId]/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/[policyId]/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/tool-policies/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/tools/route.js +1 -1
- package/runtime/.next/server/app/api/tools/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/update/check/route.js +1 -1
- package/runtime/.next/server/app/api/update/install/route.js +1 -1
- package/runtime/.next/server/app/api/update/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/computer-settings/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/computers/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
- package/runtime/.next/server/app/api/workspace-changes/route.js +1 -0
- package/runtime/.next/server/app/api/workspace-changes/route.js.nft.json +1 -0
- package/runtime/.next/server/app/web/page.js +4 -4
- package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app-paths-manifest.json +45 -33
- package/runtime/.next/server/chunks/1298.js +1 -0
- package/runtime/.next/server/chunks/1973.js +1 -0
- package/runtime/.next/server/chunks/4621.js +1 -1
- package/runtime/.next/server/chunks/5303.js +1 -1
- package/runtime/.next/server/chunks/535.js +1 -0
- package/runtime/.next/server/chunks/5762.js +3 -3
- package/runtime/.next/server/chunks/5801.js +1 -0
- package/runtime/.next/server/chunks/5812.js +1 -0
- package/runtime/.next/server/chunks/685.js +1 -0
- package/runtime/.next/server/chunks/6977.js +1 -1
- package/runtime/.next/server/chunks/9119.js +15 -0
- package/runtime/.next/server/chunks/9457.js +1 -0
- package/runtime/.next/server/middleware-build-manifest.js +1 -1
- package/runtime/.next/server/pages/404.html +1 -1
- package/runtime/.next/server/pages/500.html +1 -1
- package/runtime/.next/server/server-reference-manifest.json +1 -1
- package/runtime/.next/static/chunks/753-90c7dd1ba08be9be.js +1 -0
- package/runtime/.next/static/chunks/app/web/{error-3cae58f0f14f0b4f.js → error-828d278147a0619d.js} +1 -1
- package/runtime/.next/static/chunks/app/web/layout-a8b7565989c1c063.js +1 -0
- package/runtime/.next/static/chunks/app/web/page-8ff95d45a0160843.js +1 -0
- package/runtime/.next/static/chunks/{main-d8ef9def37924b01.js → main-7240085c0ba42e9a.js} +1 -1
- package/runtime/.next/static/chunks/main-app-07d67f2d4e96ecb8.js +1 -0
- package/runtime/lib/desktop-discovery.mjs +12 -3
- package/runtime/lib/service-identity.mjs +17 -0
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/MacOS/agentroam-remote-desktop +0 -0
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/Resources/agentroam-component.json +1 -1
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/_CodeSignature/CodeResources +2 -2
- package/runtime/node_modules/.package-lock.json +17 -17
- package/runtime/node_modules/@agent/core/dist/index.js +865 -7
- package/runtime/node_modules/@agent/native-runtime/dist/index.js +28979 -9946
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +82 -90
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +65 -64
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-0vfvgmex.mjs +39 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-x4kwpwv9.mjs → core-3h0s3zzg.mjs} +2 -2
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-ba5rrckm.mjs → core-6w7w19rc.mjs} +2 -2
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-8fprsbvz.mjs +42 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-avz7wgsg.mjs +23 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-b9ebje8h.mjs +20 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-tf03rfab.mjs → core-e1h3fbg3.mjs} +3 -3
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-2h2qc9qv.mjs → core-ge6en8c9.mjs} +4 -4
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-h6r54bwv.mjs → core-htcq9qj1.mjs} +2 -2
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-sstebd83.mjs → core-nv0a4kre.mjs} +4 -4
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-y4qk5bdp.mjs +17 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-qj4dtgyt.mjs → core-yrdmz7je.mjs} +3 -3
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-z276fcqp.mjs +28 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core.mjs +12 -11
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +22 -22
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +26 -26
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/package.json +23 -25
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +86 -90
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.cjs +72 -45
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.cjs +13 -13
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.mjs +13 -13
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.mjs +72 -45
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs +72 -45
- package/runtime/node_modules/mediabunny/dist/modules/src/input.js +6 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/media-sink.js +52 -35
- package/runtime/node_modules/mediabunny/dist/modules/src/media-source.js +2 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js +7 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/source.js +7 -4
- package/runtime/node_modules/mediabunny/dist/modules/src/tsconfig.tsbuildinfo +1 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/version.js +1 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/wave/wave-demuxer.js +6 -6
- package/runtime/node_modules/mediabunny/package.json +1 -1
- package/runtime/node_modules/mediabunny/src/input.ts +7 -0
- package/runtime/node_modules/mediabunny/src/media-sink.ts +56 -37
- package/runtime/node_modules/mediabunny/src/media-source.ts +3 -0
- package/runtime/node_modules/mediabunny/src/mpeg-ts/mpeg-ts-demuxer.ts +6 -1
- package/runtime/node_modules/mediabunny/src/source.ts +7 -4
- package/runtime/node_modules/mediabunny/src/version.ts +1 -1
- package/runtime/node_modules/mediabunny/src/wave/wave-demuxer.ts +6 -6
- package/runtime/node_modules/source-map-js/lib/quick-sort.js +92 -22
- package/runtime/node_modules/source-map-js/package.json +1 -1
- package/runtime/package-lock.json +41 -65
- package/runtime/server.js +1 -1
- package/runtime/webapp/dist/assets/AIHubView-CrtJMKfW.js +1 -0
- package/runtime/webapp/dist/assets/{AgentManager-CrN2B-tH.js → AgentManager-C2O-Dacy.js} +2 -2
- package/runtime/webapp/dist/assets/{AiHubPane-Du6ajSsx.js → AiHubPane-D2XWxc9R.js} +1 -1
- package/runtime/webapp/dist/assets/App-Bum2L4_E.js +63 -0
- package/runtime/webapp/dist/assets/App-CtLZIOFu.css +1 -0
- package/runtime/webapp/dist/assets/BrowserLivePanel-DkBugqrH.js +61 -0
- package/runtime/webapp/dist/assets/CalendarPage-DzYWlqoZ.js +1 -0
- package/runtime/webapp/dist/assets/CalendarView-BjjC_t12.css +1 -0
- package/runtime/webapp/dist/assets/CalendarView-HQls5G-1.js +31 -0
- package/runtime/webapp/dist/assets/CollaborationCreateDialog-BwiSJbjb.js +1 -0
- package/runtime/webapp/dist/assets/CollaborationDashboard-CNHt31kl.js +1 -0
- package/runtime/webapp/dist/assets/CollaborationPage-C4l-tTvn.js +6 -0
- package/runtime/webapp/dist/assets/{FilePreview-CevPpP6E.js → FilePreview-EGUAbGpH.js} +5 -5
- package/runtime/webapp/dist/assets/FileTree-aJGl1V0W.js +6 -0
- package/runtime/webapp/dist/assets/FileWorkspaceDrawer-zpD91eB6.js +1 -0
- package/runtime/webapp/dist/assets/FlowStudioPane-K1o4pSkZ.js +5 -0
- package/runtime/webapp/dist/assets/HostProjectPicker-BvboCQ0a.js +1 -0
- package/runtime/webapp/dist/assets/{LSPServerList-BMY6dFfG.js → LSPServerList-BSLzGLtW.js} +1 -1
- package/runtime/webapp/dist/assets/{MCPServerList-c91QNM-g.js → MCPServerList-CeWTI1-m.js} +1 -1
- package/runtime/webapp/dist/assets/{MemoryViewer-C9IfWwzW.js → MemoryViewer-YcceFawC.js} +1 -1
- package/runtime/webapp/dist/assets/NewSessionWindow-C_HCQQnW.js +1 -0
- package/runtime/webapp/dist/assets/NewSessionWindow-DOLG1XEp.css +1 -0
- package/runtime/webapp/dist/assets/{RemoteDesktopPage-w8aL061W.js → RemoteDesktopPage-Cpzv8zH0.js} +1 -1
- package/runtime/webapp/dist/assets/{RunningSessionsIcon-B8Cr2-hp.js → RunningSessionsIcon-DmCYwIYD.js} +5 -5
- package/runtime/webapp/dist/assets/SessionDashboard-C58Mke8a.js +16 -0
- package/runtime/webapp/dist/assets/{SessionDashboardBridge-Bx4EXtos.js → SessionDashboardBridge-BPsNDY5Y.js} +1 -1
- package/runtime/webapp/dist/assets/{SettingsPanel-CS4XL2sd.js → SettingsPanel-CPBIPT-Z.js} +2 -2
- package/runtime/webapp/dist/assets/{SkillManager-5FZnR9My.js → SkillManager-_qaGEuOE.js} +1 -1
- package/runtime/webapp/dist/assets/{TerminalPane-CRrbd0i4.js → TerminalPane-mYe76Pgb.js} +2 -2
- package/runtime/webapp/dist/assets/TodoPage-DdF5_SkL.js +1 -0
- package/runtime/webapp/dist/assets/{abnfDiagram-VCTEODGH-DBioGYiE.js → abnfDiagram-VCTEODGH-DLd8EeCY.js} +1 -1
- package/runtime/webapp/dist/assets/{arc-BRj_RXHL.js → arc-D4smlqs5.js} +1 -1
- package/runtime/webapp/dist/assets/{architectureDiagram-5GKGNRK7-CoCdq67U.js → architectureDiagram-5GKGNRK7-ByE3DRU4.js} +1 -1
- package/runtime/webapp/dist/assets/{arrow-right-Cqqb1zqH.js → arrow-right-BtIv2jiq.js} +1 -1
- package/runtime/webapp/dist/assets/artifact-links-4m1A00GO.js +2 -0
- package/runtime/webapp/dist/assets/{blockDiagram-I7D4REHJ-CLisIPjq.js → blockDiagram-I7D4REHJ-BvTUm5vA.js} +3 -3
- package/runtime/webapp/dist/assets/{c4Diagram-7LVT6UL2-BoLCIVW8.js → c4Diagram-7LVT6UL2-XKwj5RmQ.js} +1 -1
- package/runtime/webapp/dist/assets/calendar-days-BeI09qof.js +6 -0
- package/runtime/webapp/dist/assets/channel-wxCRUEc2.js +1 -0
- package/runtime/webapp/dist/assets/check-BdadwkYj.js +6 -0
- package/runtime/webapp/dist/assets/{chevron-down-DhZV290h.js → chevron-down-DwzPFeq8.js} +1 -1
- package/runtime/webapp/dist/assets/chevron-right-kcIXzCMb.js +6 -0
- package/runtime/webapp/dist/assets/{chunk-2Q5K7J3B-CIQxwzU0.js → chunk-2Q5K7J3B-7A6CDWIw.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-5VM5RSS4-Buiv0MCN.js → chunk-5VM5RSS4-mkNEWbY6.js} +1 -1
- package/runtime/webapp/dist/assets/chunk-F27PBJKO-DKG-1HL0.js +1 -0
- package/runtime/webapp/dist/assets/{chunk-IMKFNOWR-C0NrkJOc.js → chunk-IMKFNOWR-kiJDyKM7.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-JWPE2WC7-CGON_UvB.js → chunk-JWPE2WC7-DS7C5_M7.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-POPQ4Y6H-BXvOsc9g.js → chunk-POPQ4Y6H-DvgeK_lX.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-SVP7TREG-ZD_qn-NK.js → chunk-SVP7TREG-BLo_2ua-.js} +3 -3
- package/runtime/webapp/dist/assets/{chunk-TICWLB2K-DrB8f6RG.js → chunk-TICWLB2K-CJT6Qkz4.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-XXDRQBXY-CYgLMn5t.js → chunk-XXDRQBXY-D1OLqjNu.js} +1 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-Ct3Cgqrl.js +1 -0
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-Ct3Cgqrl.js +1 -0
- package/runtime/webapp/dist/assets/{codeSyntax-DfQ5rLir.js → codeSyntax-Dd0hAazb.js} +3 -3
- package/runtime/webapp/dist/assets/collaboration-CAgt9AiV.js +6 -0
- package/runtime/webapp/dist/assets/composer-file-routing-DSC2Eojr.js +6 -0
- package/runtime/webapp/dist/assets/{cose-bilkent-JH36ORCC-CDPnTlcy.js → cose-bilkent-JH36ORCC-CI6EKHP8.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefin-OW5HDTMX-DDCxhkA5.js → cynefin-OW5HDTMX-CJTXYieX.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefinDiagram-5FMLGOSQ-CIJ1KBPA.js → cynefinDiagram-5FMLGOSQ-CPl1UVhy.js} +2 -2
- package/runtime/webapp/dist/assets/{dagre-GXQ25YYZ-CFX8O3IJ.js → dagre-GXQ25YYZ-Dq3ZQGTN.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-S7CK7UJ4-B8UX2IBH.js → diagram-S7CK7UJ4-DJyU-2Di.js} +3 -3
- package/runtime/webapp/dist/assets/{diagram-UQ7AKVKN-Ce34DNrv.js → diagram-UQ7AKVKN-Csg8hC8m.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VSXAHHWV-CVL_erWD.js → diagram-VSXAHHWV-B14uLH_N.js} +3 -3
- package/runtime/webapp/dist/assets/{diagram-VX7I27RA-DBFHI7Dk.js → diagram-VX7I27RA-D2Ww2nHe.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-Z3DM3KII-Bw_QcSQY.js → diagram-Z3DM3KII-D_YC6AVP.js} +2 -2
- package/runtime/webapp/dist/assets/{download-D3xZPWnZ.js → download-COWHIKec.js} +1 -1
- package/runtime/webapp/dist/assets/{ebnfDiagram-PWID7BFC-DRly04dj.js → ebnfDiagram-PWID7BFC-s66xVEGY.js} +1 -1
- package/runtime/webapp/dist/assets/{erDiagram-RLTQ6QDP-DTm817hG.js → erDiagram-RLTQ6QDP-CgZh5cEn.js} +1 -1
- package/runtime/webapp/dist/assets/{external-link-Cwu5rEgp.js → external-link-T3kil1jt.js} +1 -1
- package/runtime/webapp/dist/assets/{file-types-DKkhMnUV.js → file-types-0e-tNIVd.js} +2 -2
- package/runtime/webapp/dist/assets/{flowDiagram-HODETNUW-tc8ygZtG.js → flowDiagram-HODETNUW-BISMKynN.js} +1 -1
- package/runtime/webapp/dist/assets/{ganttDiagram-EL5Y4UJY-CsQFf1IN.js → ganttDiagram-EL5Y4UJY-Cbyu0NcF.js} +1 -1
- package/runtime/webapp/dist/assets/{gitGraphDiagram-WWUBYQGX-DAIxbmPX.js → gitGraphDiagram-WWUBYQGX-Cs6IQGBz.js} +7 -7
- package/runtime/webapp/dist/assets/history-Df4LXw6L.js +6 -0
- package/runtime/webapp/dist/assets/{image-plus-nplydLA5.js → image-plus-COHCHOpI.js} +1 -1
- package/runtime/webapp/dist/assets/index-CQTDnt74.css +1 -0
- package/runtime/webapp/dist/assets/index-CTJNAMck.js +489 -0
- package/runtime/webapp/dist/assets/{infoDiagram-27XIBGKW-CVcMW4UM.js → infoDiagram-27XIBGKW-4f3bFqNV.js} +1 -1
- package/runtime/webapp/dist/assets/{ishikawaDiagram-5VMMS53U-zzlEtZ1l.js → ishikawaDiagram-5VMMS53U-D-cJ9vio.js} +4 -4
- package/runtime/webapp/dist/assets/{journeyDiagram-3NMN7TZE-q7NuIMSl.js → journeyDiagram-3NMN7TZE-CeToS0Qx.js} +1 -1
- package/runtime/webapp/dist/assets/{kanban-definition-UXKFOSKX-DLYFZlKO.js → kanban-definition-UXKFOSKX-DStbIUk1.js} +7 -7
- package/runtime/webapp/dist/assets/{layout-PFWssIkE.js → layout-i2D4wlYd.js} +1 -1
- package/runtime/webapp/dist/assets/{linear-ZRVcojb1.js → linear-BcJhiCv3.js} +1 -1
- package/runtime/webapp/dist/assets/list-todo-7yETOqQe.js +6 -0
- package/runtime/webapp/dist/assets/{loader-circle-DIW9tlEz.js → loader-circle-CZdAfU-D.js} +1 -1
- package/runtime/webapp/dist/assets/locate-fixed-ByJuEKxC.js +6 -0
- package/runtime/webapp/dist/assets/{mermaid.core-C8Dl0Nah.js → mermaid.core-BjNFAB9I.js} +6 -6
- package/runtime/webapp/dist/assets/{mindmap-definition-YA3MSWOX-BcbqtwVk.js → mindmap-definition-YA3MSWOX-BUIHHUVG.js} +1 -1
- package/runtime/webapp/dist/assets/new-session-window-C7R76XMp.css +1 -0
- package/runtime/webapp/dist/assets/new-session-window-DwtkwFBQ.js +190 -0
- package/runtime/webapp/dist/assets/page-9-9EC7QM.js +86 -0
- package/runtime/webapp/dist/assets/pause-DXyBDZlg.js +6 -0
- package/runtime/webapp/dist/assets/{pegDiagram-XKGWAZYB-BQN3zQuy.js → pegDiagram-XKGWAZYB-BY5Bio5e.js} +1 -1
- package/runtime/webapp/dist/assets/{pieDiagram-E7YTZNPT-pOgxh3os.js → pieDiagram-E7YTZNPT-CF8DVW3F.js} +3 -3
- package/runtime/webapp/dist/assets/pin-2YlrlSJv.js +6 -0
- package/runtime/webapp/dist/assets/play-BxEpdvoI.js +6 -0
- package/runtime/webapp/dist/assets/{quadrantDiagram-AXDQQJYC-BOg7ujzG.js → quadrantDiagram-AXDQQJYC-CXWHO3a-.js} +1 -1
- package/runtime/webapp/dist/assets/{railroadDiagram-O6MQD6OU-CWsN3juJ.js → railroadDiagram-O6MQD6OU-C20JeJZ-.js} +1 -1
- package/runtime/webapp/dist/assets/{requirementDiagram-BXWQKSXE-B0yrO7Oy.js → requirementDiagram-BXWQKSXE-IYd9UrO9.js} +3 -3
- package/runtime/webapp/dist/assets/{rotate-ccw-O4wnfQP7.js → rotate-ccw-CFIRtbUD.js} +1 -1
- package/runtime/webapp/dist/assets/{rotate-cw-CCJtlAtB.js → rotate-cw-B_vFqNsz.js} +1 -1
- package/runtime/webapp/dist/assets/{sankeyDiagram-P5KCCOFB-5MS_e-3E.js → sankeyDiagram-P5KCCOFB-ysBhpblA.js} +2 -2
- package/runtime/webapp/dist/assets/{send-Cdg4ZVlp.js → send-DUE2vBoK.js} +1 -1
- package/runtime/webapp/dist/assets/{sequenceDiagram-WJ2MYXX4-C1w8qYSu.js → sequenceDiagram-WJ2MYXX4-CQMmk6cu.js} +4 -4
- package/runtime/webapp/dist/assets/session-dashboard-DnFhQhBN.js +1 -0
- package/runtime/webapp/dist/assets/{shield-check-CrjI2wPR.js → shield-check-Btyos6Iv.js} +1 -1
- package/runtime/webapp/dist/assets/{sizeCapture-INFHLROL-BonKTynC.js → sizeCapture-INFHLROL-DekvKUn1.js} +1 -1
- package/runtime/webapp/dist/assets/{stateDiagram-D77RDMKH-D3mn6ZK5.js → stateDiagram-D77RDMKH-Ds_FEmbr.js} +1 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-DxJ1ks_8.js +1 -0
- package/runtime/webapp/dist/assets/{swimlanes-42K2YHIH-Bn9KWChU.js → swimlanes-42K2YHIH-cjPcEO_T.js} +1 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-JGHIAQXy.js +8 -0
- package/runtime/webapp/dist/assets/{timeline-definition-24CTP7MA-BfuhI7EF.js → timeline-definition-24CTP7MA-CEOprVt5.js} +1 -1
- package/runtime/webapp/dist/assets/{trash-2-BrfgMjfL.js → trash-2-DLDxY6J7.js} +4 -9
- package/runtime/webapp/dist/assets/{types-VnQ_cKrp.js → types-CFAnlTif.js} +1 -1
- package/runtime/webapp/dist/assets/{vennDiagram-4TSXK5OY-CUFs5JyR.js → vennDiagram-4TSXK5OY-D82uxYY9.js} +5 -5
- package/runtime/webapp/dist/assets/{wardleyDiagram-VM6X3IG4-C27HHz1A.js → wardleyDiagram-VM6X3IG4-JFt7Izt0.js} +1 -1
- package/runtime/webapp/dist/assets/{web-CeCHmdwO.js → web-BMqaP0jw.js} +1 -1
- package/runtime/webapp/dist/assets/{web-BOzkL-0Z.js → web-Q9VPRftY.js} +1 -1
- package/runtime/webapp/dist/assets/{x-DP1nC4qG.js → x-CeSbythI.js} +1 -1
- package/runtime/webapp/dist/assets/{xychartDiagram-S5SC5T6Z-CQwRrSTf.js → xychartDiagram-S5SC5T6Z-1WCa4SfL.js} +3 -3
- package/runtime/webapp/dist/assets/zoom-out-CRr_o1NV.js +16 -0
- package/runtime/webapp/dist/index.html +2 -2
- package/runtime/ws-server.mjs +23 -4
- package/runtime/.next/server/chunks/1614.js +0 -1
- package/runtime/.next/server/chunks/732.js +0 -1
- package/runtime/.next/server/chunks/7519.js +0 -15
- package/runtime/.next/server/chunks/7788.js +0 -1
- package/runtime/.next/static/chunks/333-9881c3d2c558a28d.js +0 -1
- package/runtime/.next/static/chunks/app/web/layout-d5d7d1c5c74eef3c.js +0 -1
- package/runtime/.next/static/chunks/app/web/page-7afa4cb0119e90b7.js +0 -1
- package/runtime/.next/static/chunks/main-app-7a6902a607752446.js +0 -1
- package/runtime/lib/voice-tts-gateway.mjs +0 -96
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-9sxfsmzx.mjs +0 -18
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-dnsvg8nc.mjs +0 -53
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-k67vj6j9.mjs +0 -20
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-qbjntcdf.mjs +0 -18
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-rn7tc54w.mjs +0 -17
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-td7rt8zt.mjs +0 -17
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-y6bhrwmk.mjs +0 -47
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-ya1m7gzj.mjs +0 -18
- package/runtime/webapp/dist/assets/AIHubView-BMeOfqfm.js +0 -1
- package/runtime/webapp/dist/assets/App-CrZstnCH.css +0 -1
- package/runtime/webapp/dist/assets/App-zihaYk1L.js +0 -179
- package/runtime/webapp/dist/assets/BrowserLivePanel-CU_X6OU2.js +0 -56
- package/runtime/webapp/dist/assets/CollaborationCreateDialog-BmgYdwe7.js +0 -1
- package/runtime/webapp/dist/assets/CollaborationDashboard-mHU8iJYg.js +0 -1
- package/runtime/webapp/dist/assets/CollaborationPage-Br5fhNce.js +0 -6
- package/runtime/webapp/dist/assets/FileTree-CagcHV1N.js +0 -11
- package/runtime/webapp/dist/assets/FileWorkspaceDrawer-CWVndCXp.js +0 -1
- package/runtime/webapp/dist/assets/FlowStudioPane-BZA-qvBj.js +0 -5
- package/runtime/webapp/dist/assets/SessionDashboard-CFXXTm_4.js +0 -21
- package/runtime/webapp/dist/assets/artifact-links-73OZyi5W.js +0 -7
- package/runtime/webapp/dist/assets/channel-JGVZzkSo.js +0 -1
- package/runtime/webapp/dist/assets/chunk-F27PBJKO-XBMwIl6X.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-BnctJ00R.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-BnctJ00R.js +0 -1
- package/runtime/webapp/dist/assets/collaboration-CQhzjwS_.js +0 -6
- package/runtime/webapp/dist/assets/composer-file-routing-D9orqwzY.js +0 -11
- package/runtime/webapp/dist/assets/index-B-d1Vs9E.css +0 -1
- package/runtime/webapp/dist/assets/index-DKm9ESDq.js +0 -489
- package/runtime/webapp/dist/assets/page-BG97oPXr.js +0 -91
- package/runtime/webapp/dist/assets/session-dashboard-BigU92sz.js +0 -6
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-WEfEW-mH.js +0 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-D26_Nmko.js +0 -8
- package/runtime/webapp/dist/assets/zoom-out-Dg7YyzcP.js +0 -21
- package/runtime/webapp/dist/pcm-audio-worklet.js +0 -126
- /package/runtime/.next/static/{xuZ1UJWVNJ-rxb5YgETmd → alt-ud1W2PlWW6FLlkBcB}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{xuZ1UJWVNJ-rxb5YgETmd → alt-ud1W2PlWW6FLlkBcB}/_ssgManifest.js +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
|
|
2
2
|
|
|
3
|
-
// Version: 0.3.
|
|
3
|
+
// Version: 0.3.328
|
|
4
4
|
|
|
5
5
|
//! symbol-dispose-prelude: defines Symbol.dispose and Symbol.asyncDispose if missing, for this bundle's `using`.
|
|
6
6
|
if (typeof Symbol.dispose !== 'symbol') {
|
|
@@ -13,13 +13,14 @@ if (typeof Symbol.asyncDispose !== 'symbol') {
|
|
|
13
13
|
Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose')
|
|
14
14
|
} catch {}
|
|
15
15
|
}
|
|
16
|
-
import{
|
|
17
|
-
`),e.initPromise=import("./core-
|
|
18
|
-
`;Vo(l).then(()=>{if(i!==void 0){let m=ir(l);if(m!==null)i.append(m,[{data:p}]).catch(()=>{});return}if(l.debugFilePath){let m=l.debugFilePath;import("./core-x4kwpwv9.mjs").then(({getStorageBackend:y})=>y().append(m,p)).catch(()=>{})}})}function ar(e){let i=e.trim();return i.startsWith("{")&&i.endsWith("}")}var lr=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),ur=new Set(["ripgrep","network.tlsTerminate"]),dr=new Set(["__proto__","constructor","prototype"]),cr=["httpProxyPort","socksProxyPort"];function Xo(e,i,l=""){let c=M(e)?{...e}:{};for(let[p,m]of Object.entries(i)){if(dr.has(p)||m===void 0)continue;let y=l?`${l}.${p}`:p,g=Object.hasOwn(c,p)?c[p]:void 0;if(lr.has(y)&&Array.isArray(g)&&Array.isArray(m))c[p]=f([...g,...m]);else if(M(g)&&M(m)&&!ur.has(y))c[p]=Xo(g,m,y);else c[p]=m}return c}function Jo(e,i){let l={...e};if(!i)return l;let c=l.settings;if(c&&!ar(c))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let p={};if(c)try{p=S(c)}catch{}let m=Xo(p.sandbox,i),y=i.credentials?.files,g=i.filesystem!==void 0||Array.isArray(y)&&y.some((P)=>M(P)&&P.mode==="deny"),C=m.filesystem;if(g&&i.filesystem?.disabled===void 0&&M(C)&&C.disabled===!0)delete C.disabled;let v=i.network,b=v?.allowedDomains!==void 0||(v?.deniedDomains?.length??0)>0||v?.strictAllowlist===!0,_=m.network;if(b&&M(_)){for(let P of cr)if(v?.[P]===void 0&&_[P]!==void 0)delete _[P]}if(i.enabled===!0&&m.failIfUnavailable===void 0)m.failIfUnavailable=!0;return l.settings=o({...p,sandbox:m}),l}function H(e,i){return`${e}=${i}`}function _t(e,i){let l=String(i);if(l.length>1&&l.startsWith("-"))return[H(e,l)];return[e,l]}function en(e,i,l){e.push(..._t(`--${i}`,l))}var hr=2000,eo=2048,rn="sdk-exit-after-stderr-drained",Sr=200;function to(e){return e==="exit"?rn:e}class an{#e=new Set;#t=!1;#o=()=>this.killAll();track(e){if(this.#e.add(e),!this.#t)this.#t=!0,process.on("exit",this.#o)}untrack(e){this.#e.delete(e)}isTracking(e){return this.#e.has(e)}get size(){return this.#e.size}killAll(){for(let e of this.#e)if(!e.killed)if(process.platform==="win32")try{e.stdin.end()}catch{}else e.kill("SIGTERM")}reset(){process.off("exit",this.#o),this.#t=!1,this.#e.clear()}}var Rt=new an,yr=/[(),\u0000-\u001f\u007f-\u009f]/;function Cr(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!Oe(e))throw new u(`Invalid skill name ${o(e)}: the name contains an unpaired surrogate, which cannot survive the UTF-8 encoding of the CLI invocation; no skill discovered from the filesystem can have such a name.`,"skill name with unpaired surrogate rejected");if(e!==e.trim())throw new u(`Invalid skill name ${o(e)}: leading or trailing whitespace is not allowed — the Skill tool trims the invoked name, so a padded rule can never match. Remove the padding.`,"skill name with surrounding whitespace rejected");if(yr.test(e))throw new u(`Invalid skill name ${o(e)}: parentheses, commas, and control characters are not allowed in skill names. Skill names match the skill's directory name (or 'plugin:skill' for plugin-qualified skills); rename the skill if its directory name contains these characters.`,"invalid skill name rejected");if(e==="*")throw Error("Invalid skill name '*': use skills: 'all' to enable every skill.");if(e.endsWith(":*")||e.endsWith(" *"))throw new u(`Invalid skill name ${o(e)}: wildcard-suffix names are not allowed; list each skill by its exact name.`,"wildcard-suffix skill name rejected");if(e.startsWith("/"))throw new u(`Invalid skill name ${o(e)}: skill names may not start with '/'. Skills are invoked as slash commands, but the skills option takes the skill's canonical name — the directory name, or 'plugin:skill'.`,"skill name with leading slash rejected");if(e.includes("\\\\"))throw new u(`Invalid skill name ${o(e)}: consecutive backslashes are not allowed — the permission-rule parser collapses escaped backslashes, so the rule would name a different skill. Rename the skill.`,"skill name with consecutive backslashes rejected");if(e.endsWith("\\"))throw new u(`Invalid skill name ${o(e)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return e}class no{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";abortHandler;forwardedAbort=lt();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||lt(),e.deferSpawn)this.spawnPromise=new Promise((i,l)=>{this.spawnResolve=i,this.spawnReject=l}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(i){throw this.spawnAbort(U(i)),i}let e=this.pendingWrites;if(this.pendingWrites=[],this.spawnResolve)this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0;for(let i of e)this.write(i);if(this.pendingEndInput)this.pendingEndInput=!1,this.processStdin?.end()}spawnAbort(e){if(this.spawnReject)this.spawnReject(e),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[]}updateEnv(e){if(this.options.env)Object.assign(this.options.env,e);else this.options.env={...e}}updateResume(e){this.options.resume=e}getDefaultExecutable(){return ie()?"bun":"node"}spawnLocalProcess(e){let{command:i,args:l,cwd:c,env:p,signal:m}=e,y=performance.now(),g=pr(i,l,{cwd:c,stdio:["pipe","pipe","pipe"],signal:m,env:p,windowsHide:!0}),C=performance.now()-y;if(g.pid!==void 0&&this.options.onProcessSpawned)try{this.options.onProcessSpawned(g.pid,{spawnSyncMs:C})}catch(K){ue(`onProcessSpawned threw: ${E(K)}`)}let v=new fr("utf8"),b=!1,_=!1,P=!1,O,k=d(p.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;g.stderr.on("data",(K)=>{if(P)return;let j=v.write(K);if(this.stderrTail+=j,this.stderrTail.length>2*eo)this.stderrTail=Wt(dt(this.stderrTail),eo);if(k)ue(j),this.options.stderr?.(j)}),g.stderr.on("error",(K)=>{ue(`[ProcessTransport] stderr read failed: ${K.code??K.message}`)});let z=()=>{if(P)return;if(P=!0,O)clearTimeout(O);g.emit(rn,g.exitCode,g.signalCode);let K=g.stderr;if(vr(K))K.unref();else K.destroy()};return g.stderr.once("close",()=>{if(this.stderrTail+=v.end(),b=!0,_)z()}),g.once("exit",()=>{if(_=!0,this.ready=!1,b)z();else O=setTimeout(z,Sr)}),{stdin:g.stdin,stdout:g.stdout,get killed(){return g.killed},get exitCode(){return g.exitCode},get signalCode(){return g.signalCode},kill:g.kill.bind(g),on:(K,j)=>g.on(to(K),j),once:(K,j)=>g.once(to(K),j),off:(K,j)=>g.off(to(K),j)}}initialize(){try{let{additionalDirectories:e=[],projectConfigRoot:i,agent:l,betas:c,cwd:p,executable:m=this.getDefaultExecutable(),executableArgs:y=[],extraArgs:g={},pathToClaudeCodeExecutable:C,env:v={...process.env},thinkingConfig:b,maxTurns:_,maxBudgetUsd:P,taskBudget:O,model:k,fallbackModel:z,jsonSchema:W,permissionMode:K,allowDangerouslySkipPermissions:j,permissionPromptToolName:Ce,permissionPrompts:V,continueConversation:q,resume:ke,settingSources:me,skills:de,disallowedTools:ce=[],tools:Ee,mcpServers:Le,strictMcpConfig:Xe,canUseTool:Je,includePartialMessages:ge,plugins:Fe,pluginsViaInitialize:qe,sandbox:xe}=this.options,{allowedTools:_e=[]}=this.options;if(de!==void 0){let L=de==="all"?["Skill"]:de.map((ee)=>`Skill(${Cr(ee)})`),ne=new Set(_e);_e=[..._e,...L.filter((ee)=>!ne.has(ee))]}let I=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(b){switch(b.type){case"enabled":if(b.budgetTokens===void 0)I.push("--thinking=adaptive");else I.push(H("--max-thinking-tokens",b.budgetTokens));break;case"disabled":I.push("--thinking=disabled");break;case"adaptive":I.push("--thinking=adaptive");break}if(b.type!=="disabled"&&b.display)I.push(H("--thinking-display",b.display))}if(this.options.effort)I.push(H("--effort",this.options.effort));if(_)I.push(H("--max-turns",_));if(P!==void 0)I.push(H("--max-budget-usd",P));if(O)I.push(H("--task-budget",O.total));if(k)I.push(H("--model",k));if(l)I.push(H("--agent",l));if(c&&c.length>0)I.push(H("--betas",c.join(",")));if(W)I.push(H("--json-schema",o(W)));if(this.options.debugFile)I.push(H("--debug-file",this.options.debugFile));else if(this.options.debug)I.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let L=Yo();if(L)I.push(H("--debug-file",L))}if(Je){if(Ce)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");I.push("--permission-prompt-tool=stdio")}else if(Ce)I.push(H("--permission-prompt-tool",Ce));if(V)I.push(H("--permission-prompts",V));if(q)I.push("--continue");if(ke)I.push(H("--resume",ke));if(this.options.channels&&this.options.channels.length>0)for(let L of this.options.channels)I.push(H("--channels",L));if(_e.length>0)I.push(H("--allowedTools",_e.join(",")));if(ce.length>0)I.push(H("--disallowedTools",ce.join(",")));if(Ee!==void 0)if(Array.isArray(Ee))I.push(H("--tools",Ee.join(",")));else I.push("--tools=default");if(Le&&Object.keys(Le).length>0&&!this.options.mcpServersViaInitialize)I.push(..._t("--mcp-config",o({mcpServers:Le})));if(me!==void 0)I.push(H("--setting-sources",me.join(",")));if(Xe)I.push("--strict-mcp-config");if(K)I.push(H("--permission-mode",K));if(j)I.push("--allow-dangerously-skip-permissions");if(z){if(k&&z===k)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");I.push(H("--fallback-model",z))}if(this.options.includeHookEvents)I.push("--include-hook-events");if(ge)I.push("--include-partial-messages");if(this.options.sessionMirror)I.push("--session-mirror");if(i!==void 0)I.push(H("--project-config-root",i));for(let L of e)I.push(H("--add-dir",L));if(qe||this.options.managedSettingsViaInitialize||this.options.mcpServersViaInitialize||this.options.readsInitializeAtBoot)I.push("--await-initialize");if(!qe&&Fe&&Fe.length>0)for(let L of Fe)if(L.type==="local")I.push(L.skipMcpDiscovery?H("--plugin-dir-no-mcp",L.path):H("--plugin-dir",L.path));else throw Error(`Unsupported plugin type: ${L.type}`);if(this.options.forkSession)I.push("--fork-session");if(this.options.resumeSessionAt)I.push(H("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)I.push(H("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)I.push(H("--session-id",this.options.sessionId));if(this.options.persistSession===!1)I.push("--no-session-persistence");if(this.options.managedSettingsViaInitialize)I.push("--managed-settings-in-initialize");else if(this.options.managedSettings)I.push(..._t("--managed-settings",this.options.managedSettings));let Re={...g??{}};if(this.options.settings)Re.settings=this.options.settings;let fe=Jo(Re,xe);for(let[L,ne]of Object.entries(fe))if(ne===null)I.push(`--${L}`);else en(I,L,ne);if(!v.CLAUDE_CODE_ENTRYPOINT)v.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete v.NODE_OPTIONS,d(v.DEBUG_CLAUDE_AGENT_SDK))v.DEBUG="1";else delete v.DEBUG;let Ie=_r(C),Se=Ie?C:m,ze=Ie?[...y,...I]:[...y,C,...I],oe={command:Se,args:ze,cwd:p,env:v,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)ue(`Spawning Claude Code (custom): ${Se} ${ze.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(oe);else ue(`Spawning Claude Code: ${Se} ${ze.join(" ")}`),this.process=this.spawnLocalProcess(oe);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(L)=>{ue(`[ProcessTransport] stdin write failed (child likely exited): ${L.code??L.message}`),this.ready=!1}),Rt.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let ye=this.process;ye.on("error",(L)=>{this.ready=!1;let ne=L,ee=ne.syscall!==void 0?ne.syscall.startsWith("spawn"):Nt(L);if(ee&&!ye.killed)Rt.untrack(ye);if(this.abortController.signal.aborted)this.exitError=vt(),D(L,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(ee&&Nt(L)){let{message:pe,telemetryMessage:tt,errorClass:Ut}=br(C,Ie),ot={telemetryMessage:`${tt}${oo(L)}`,errorClass:Ut,code:Ge(L)};this.exitError=D(ReferenceError(pe),ot),D(L,ot),ue(this.exitError.message)}else{let pe={telemetryMessage:ee?`Failed to spawn Claude Code process${oo(L)}`:`Claude Code process error${oo(L)}`,errorClass:ee?"spawn_failed":"process_error",code:Ge(L)};this.exitError=D(Error(`Failed to spawn Claude Code process: ${dt(L.message)}`),pe),D(L,pe),ue(this.exitError.message)}}),ye.on("exit",(L,ne)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=vt();else{let ee=this.getProcessExitError(L,ne);if(ee)this.exitError=ee,ue(ee.message)}}),this.ready=!this.abortController.signal.aborted}catch(e){throw this.ready=!1,e}}getProcessExitError(e,i){if(e!==0&&e!==null){let l=Number.isInteger(e)?e:void 0;return D(Error(`Claude Code process exited with code ${e}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process exited with code ${l??"unknown"}`,errorClass:"process_exited_nonzero",exitCode:l})}else if(i){let l=/^SIG[A-Z0-9]{1,8}$/.test(i)?i:"unknown";return D(Error(`Claude Code process terminated by signal ${i}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process terminated by signal ${l}`,errorClass:"process_killed_by_signal",signal:l})}return}formatStderrTail(){let e=Wt(dt(this.stderrTail),eo).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw tn();if(this.spawnResolve){this.pendingWrites.push(e);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){ue("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw D(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${_n(this.exitError)??"untagged exit error"}`,errorClass:sn(this.exitError,"errorClass"),code:Ge(this.exitError),exitCode:Rr(this.exitError),signal:sn(this.exitError,"signal")});ue(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))ue("[ProcessTransport] Write buffer full, data queued")}catch(i){throw this.ready=!1,Error(`Failed to write to process stdin: ${E(i)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?vt():Error("Query closed before spawn")),this.processStdin)this.processStdin.end(),this.processStdin=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;let e=this.process?.exitCode??null,i=this.process?.signalCode??null;if(!this.exitEventDelivered&&(e!==null&&e>=0||i!==null)){this.exitEventDelivered=!0;let m=this.abortController.signal.aborted?vt():this.getProcessExitError(e,i);if(m&&!this.exitError)this.exitError=m}let c=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},p=this.process;if(p&&!p.killed&&p.exitCode===null&&p.signalCode==null)setTimeout((m,y)=>{if(m.exitCode!==null||m.signalCode!=null){y();return}if(process.platform==="win32"){setTimeout((g,C)=>{if(g.exitCode===null)g.kill("SIGKILL");C()},5000,m,y).unref();return}m.kill("SIGTERM"),setTimeout((g)=>{if(g.exitCode===null)g.kill("SIGKILL")},5000,m).unref(),y()},hr,p,c).unref(),p.once("exit",()=>Rt.untrack(p));else if(p)Rt.untrack(p),c();this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise)await this.spawnPromise,this.spawnPromise=void 0;if(!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let e=gr({input:this.processStdout}),i=this.process?(()=>{let l=this.process,c=()=>e.close();return l.on("error",c),()=>l.off("error",c)})():void 0;if(this.exitError)e.close();try{for await(let l of e)if(l.trim()){let c;try{c=S(l)}catch(p){ue(`Non-JSON stdout: ${l}`);continue}yield c}if(this.exitError)throw this.exitError;await this.waitForExit()}finally{i?.(),e.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}if(this.processStdin)this.processStdin.end()}async waitForExit(){if(this.exitError)throw this.exitError;if(!this.process||this.process.exitCode===0||this.process.killed&&this.exitEventDelivered)return;return new Promise((e,i)=>{let l=(p,m)=>{if(this.abortController.signal.aborted){i(tn());return}let y=this.getProcessExitError(p,m);if(y)i(y);else e()};this.process.once("exit",l);let c=(p)=>{this.process.off("exit",l),i(p)};this.process.once("error",c),this.process.once("exit",()=>{this.process.off("error",c)})})}}function _r(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((l)=>e.endsWith(l))}function br(e,i){let l=i?"native binary":"executable",c=dt(e);if(mr(e))return{message:i?`Claude Code native binary at ${c} exists but failed to launch. This usually means the binary does not match this system's libc — e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${c} exists but failed to launch.`,telemetryMessage:`Claude Code ${l} exists at the configured path but failed to launch`,errorClass:"executable_launch_failed"};return{message:i?`Claude Code native binary not found at ${c}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${c}. Is options.pathToClaudeCodeExecutable set?`,telemetryMessage:`Claude Code ${l} not found at the configured path`,errorClass:"executable_not_found"}}function oo(e){let i=Ge(e);return i===void 0?"":` (${i})`}function vt(){return D(new Ke("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function tn(){return D(new Ke("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function sn(e,i){let l=Object.hasOwn(e,i)?Reflect.get(e,i):void 0;return typeof l==="string"?l:void 0}function Rr(e){let i=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof i==="number"?i:void 0}function vr(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as wr}from"fs";var We="@anthropic-ai/claude-agent-sdk";function kr(){if(process.platform!=="linux")return!1;let e=typeof process.report?.getReport==="function"?process.report.getReport():null;return e!=null&&e.header?.glibcVersionRuntime===void 0}function ln(e,i={}){let l=i.platform??process.platform,c=i.arch??process.arch,p=i.exists??wr,m=i.preferMusl??kr(),y="claude",g=l==="win32"?".exe":"",v=(l==="android"?[`${We}-linux-${c}-android`]:l==="linux"?m?[`${We}-linux-${c}-musl`,`${We}-linux-${c}`]:[`${We}-linux-${c}`,`${We}-linux-${c}-musl`]:[`${We}-${l}-${c}`]).map((b)=>`${b}/claude${g}`);for(let b of v)try{let _=e(b);if(p(_))return _}catch{}return null}function un({supportedDialogKinds:e,onUserDialog:i}){if(e!==void 0&&e.length>0&&!i)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.")}var Er=["signed_out","identity_changed","transient","refresh_failed"];function dn(e){return Er.some((i)=>i===e)}var wt=600000;var cn=600000,kt=["SessionStart","Setup"];var Et=60000,pn=cn,mn=Et+pn,Pr="startupHooksOpen",Dr=64;class so{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(e,i=Pe,l){this.clock=i;this.onRunning=l;this.limitMs=e??Et,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=e==null?pn:0}race(e){let i=new Promise((l,c)=>{this.rejectExpired=c});return this.arm(),Promise.race([e,i]).finally(()=>this.end())}note(e){if(this.rejectExpired===void 0||e.type!=="system")return;switch(e.subtype){case"hook_started":if(!kt.includes(e.hook_event)||this.followed.has(e.hook_id))return;if(this.followed.size<Dr)this.followed.add(e.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(e.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(e.hook_id)){if(this.unfollowedOpen===0||!kt.includes(e.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let e=Math.min(this.countedLeftMs,we);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=e,this.countedLeftMs>0)this.arm();else this.expire()},e)}countAgain(){let e=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=e,this.uncountedMs+=e,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let e=this.rejectExpired,i=`Subprocess initialization did not complete within ${this.limitMs}ms`,l=kt.join(" or "),c=Math.round(this.uncountedMs/1000),p=this.open(),m=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${se(this.reported,"hook")}`,y=[`${i}.`,...c>0?[`Not counted: ${c} ${se(c,"second")} in which Claude Code reported a ${l} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${l} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:p===0?`Claude Code reported ${m}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${m}, ${this.reported===1?"which had not finished":p===this.reported?"none of which had finished":`${p} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],g=Object.assign(D(Error(y.join(" ")),{telemetryMessage:i,errorClass:"initialize_timeout"}),{[Pr]:p});this.end(),e?.(g)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}var gn="SDK MCP server not found";var fn="No hook callback found for ID";class ro{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}get ended(){return this.isDone}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((e,i)=>{this.readResolve=e,this.readReject=i})}get readerIsWaiting(){return this.readResolve!==void 0&&!this.isDone}enqueue(e){if(this.readResolve){let i=this.readResolve;this.readResolve=void 0,this.readReject=void 0,i({done:!1,value:e})}else this.queue.push(e)}dropNewestQueued(e){let i=this.queue.findLastIndex(e);if(i!==-1)this.queue.splice(i,1)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let i=this.readReject;this.readResolve=void 0,this.readReject=void 0,i(e)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var io="startup_mark",hn="startupMark",Sn="startupMarkAgeMs",yn=64;function Cn(e){return"method"in e&&"id"in e&&e.id!==null}var bn=Object.freeze({}),Rn=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),xl=Symbol("swallow");class ao{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var vn=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var wn="2025-11-25";var Tr="notifications/tools/list_changed";function En(e){return n(e)&&!("id"in e)&&e.method===Tr}class Pt extends Mt{errorCode;constructor(e,i,l,c){super(e,i,c);this.errorCode=l}}var Pn=250,Ar=new Set(["interrupt","cancel_async_message"]),Mr=new Set(["initialize","get_binary_version"]),xr="CLAUDE_SDK_MCP_SERVERS_NOT_APPLIED",Dt="sdk-manifest-capture:",He=Symbol("suppressControlResponse");function Dn(e,i,l){for(let c of l){let p=c==="tools"?Jt(i):void 0;t(p?`[Query] MCP server '${e}': ${Nn(p)}`:`[Query] MCP server '${e}': ignoring malformed ${c} in its config`)}}class Tt{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;runEndCeilingMs;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new ro;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;hostMatcherOf=new WeakMap;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;promptHold;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;lastStartupFailureReason;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,i){let l={type:"system",subtype:"mirror_error",error:i,key:e,uuid:Q(),session_id:e.sessionId};this.inputStream.enqueue(l)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpServers.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0||this.workSecretAnswerer!==void 0}remoteControlCallGeneration=0;uiHost;workSecretAnswerer;constructor(e,i,l,c,p,m=new Map,y,g,C,v,b,_,P=!1,O=wt){this.transport=e;this.isSingleUserTurn=i;this.canUseTool=l;this.hooks=c;this.abortController=p;this.jsonSchema=y;this.initConfig=g;this.onElicitation=C;this.getOAuthToken=v;this.getHostAuthToken=b;this.onUserDialog=_;this.verbatimPrompts=P;this.runEndCeilingMs=O;for(let[k,z]of m)this.connectSdkMcpServer(k,z);if(this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((k)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,k()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{}),this.hasHookSetToBlock()||this.sendsLaunchFields()){let k=this.hasHookSetToBlock()?Error('Claude Code did not answer initialize, so a hook set to onFailure: "block" could not be confirmed and the prompt was not sent. Check the connection and start a new session.'):this.initConfig?.managedSettings!==void 0?Error("Claude Code did not answer initialize, so the managed settings could not be confirmed and the prompt was not sent. Start a new session."):void 0,z=k===void 0?void 0:setTimeout((W)=>void this.cleanup(W),mn,k);z?.unref?.(),this.promptHold=this.initialization.then(()=>(clearTimeout(z),!0),(W)=>(clearTimeout(z),this.cleanup(W),!1)),this.writeBehindPromptHold(this.promptHold,()=>{})}}writeBehindPromptHold(e,i){let l=e.then(async(p)=>{if(!p||this.abortController?.signal.aborted)return!1;return await i(),!0}),c=l.catch(()=>!0).then((p)=>{if(p&&this.promptHold===c)this.promptHold=void 0;return p});return this.promptHold=c,l}hasHookSetToBlock(){return Object.values(this.hooks??{}).some((e)=>Array.isArray(e)&&e.some((i)=>i?.onFailure!=null&&i.onFailure!=="continue"))}sendsLaunchFields(){return this.initConfig?.managedSettings!==void 0||this.initConfig?.mcpServers!==void 0}setError(e){this.inputStream.error(e)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((i)=>i.type==="system"&&i.subtype==="hook_progress"&&i.hook_id===e&&i.backgrounded!==!0)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let i of this.cleanupCallbacks)try{i()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let i of this.cancelControllers.values())i.abort();this.cancelControllers.clear(),this.transport.close()}catch(i){t(`[Query.cleanup] transport.close() failed: ${E(i)}`,{level:"error"})}try{let i=e??lo();for(let{reject:l}of this.pendingControlResponses.values())l(i);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:l}of this.pendingMcpResponses.values())l(i);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:l}of this.sdkMcpServers.values())l.close().catch(()=>{});if(this.sdkMcpServers.clear(),e)this.inputStream.error(e);else this.inputStream.done()}catch(i){}if(this.transport.waitForExit){let i=new AbortController;try{await Promise.race([this.transport.waitForExit(),x(2000,i.signal)])}catch{}finally{i.abort()}}}next(...[e]){return this.sdkMessages.next(...[e])}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let i=this.pendingControlResponses.get(e.response.request_id);if(i)i.handler(e.response);else{if(this.unmatchedControlResponses.size>=Tt.UNMATCHED_CONTROL_RESPONSES_MAX){let l=this.unmatchedControlResponses.keys().next().value;if(l!==void 0)this.unmatchedControlResponses.delete(l)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive"){if(io in e){let i=e[io];if(typeof i==="string"&&i.length<=yn)this.startupMark={mark:i,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let i=e.is_error?e.subtype==="success"?e.result:e.errors.map((l)=>l.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=i||void 0,this.lastStartupFailureReason=e.is_error&&"startup_failure_reason"in e&&typeof e.startup_failure_reason==="string"?e.startup_failure_reason:void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else if(!(e.type==="system"&&(e.subtype==="session_writes_lost"||e.subtype==="plugin_install"))){if(this.lastErrorResultText=void 0,this.lastStartupFailureReason=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(e)}catch(i){t(`[Query.readMessages] The frame observer threw: ${E(i)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let i=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(i!==void 0&&!(e instanceof Ke)&&e?.name!=="SSEHttpError"){let l=D(Error(`Claude Code returned an error result: ${i}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result",startupFailureReason:this.lastStartupFailureReason});t(`[Query.readMessages] Replacing exit error with result text. Original: ${E(e)}`),this.inputStream.error(l),this.cleanup(l);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){t(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){t(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let i=new AbortController;this.cancelControllers.set(e.request_id,i);try{let l;try{let c=await this.processControlRequest(e,i.signal);if(this.cleanupPerformed)return;if(c===He)return;let p={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:c}};l=o(p)+`
|
|
19
|
-
`}catch(c){if(this.cleanupPerformed)return;let p={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:E(c),...c instanceof Pt&&{error_code:c.errorCode}}};l=o(p)+`
|
|
20
|
-
`}try{await Promise.resolve(this.transport.write(l))}catch(c){t(`[Query.handleControlRequest] Response write failed: ${E(c)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===i)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let i=this.cancelControllers.get(e.request_id);if(i)i.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,i){if(vn.some((l)=>l===e.request.subtype))return t(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),He;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let l=e.request.computer_folder,c=await this.canUseTool(e.request.tool_name,e.request.input,{signal:i,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof l==="object"&&l!==null&&"path"in l&&typeof l.path==="string"&&"computer_name"in l&&typeof l.computer_name==="string"&&{computerFolder:{path:l.path,computer_name:l.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(c===null)return He;return{...c,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback"){if(!this.initializeHasBeenWritten){if(await this.initializeWritten,this.cleanupPerformed||i.aborted)return He}return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,i)}else if(e.request.subtype==="mcp_message"){let l=e.request,c=this.sdkMcpServers.get(l.server_name)?.transport;if(!c)throw Error(`${gn}: ${l.server_name}`);if(Cn(l.message))return{mcp_response:await this.handleMcpControlRequest(l.server_name,l,c)};else{if(c.onmessage)c.onmessage(l.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let l=e.request;if(this.onElicitation){let c=await this.onElicitation({serverName:l.mcp_server_name,message:l.message,mode:l.mode,url:l.url,elicitationId:l.elicitation_id,requestedSchema:l.requested_schema,title:l.title,displayName:l.display_name,description:l.description},{signal:i,requestId:e.request_id});if(c===null)return He;return c}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let l=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:i,requestId:e.request_id});if(l===null)return He;return l}return t(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),le("tengu_request_user_dialog_response_ignored",{shape:te("auto_cancel")}),He}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let l,c=await this.getOAuthToken({signal:i,onDecline:(p)=>{if(dn(p))l=p},...e.request.kind!==void 0&&{kind:e.request.kind},...(e.request.token_state==="refused"||e.request.token_state==="not_refused")&&{tokenState:e.request.token_state},...e.request.token_state==="refused"&&(e.request.refused_call==="model"||e.request.refused_call==="connector"||e.request.refused_call==="other")&&{refusedCall:e.request.refused_call},...Array.isArray(e.request.refused_bearer_sha256)&&{refusedBearerSha256:e.request.refused_bearer_sha256}})??null;return c===null&&l!==void 0?{accessToken:c,reason:l}:{accessToken:c}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let l=await this.getHostAuthToken({signal:i,status:e.request.status})??null;return typeof l==="string"||l===null?{authToken:l}:l}else if(e.request.subtype==="remote_control_work_secret"){let l=this.workSecretAnswerer;if(!l)throw Error("refreshWorkSecret callback is not provided.");if(!xn(l.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await l.refresh(l.sessionId,{signal:i})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:l,...c}=e.request;return this.uiHost.copy(c,{signal:i})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:l,...c}=e.request;return this.uiHost.promptRead(c,{signal:i})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:l,...c}=e.request;return this.uiHost.promptFill(c,{signal:i})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:l,...c}=e.request;return this.uiHost.promptPaint(c,{signal:i})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:l,...c}=e.request;return this.uiHost.promptSuggest(c,{signal:i})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:l,...c}=e.request;return this.uiHost.readSelection(c,{signal:i})}throw new Pt("Unsupported control request subtype: "+e.request.subtype,"Unsupported control request subtype","unsupported_request")}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let i,l;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){i=await this.captureSdkMcpServerManifests();for(let y of this.sdkMcpToolsChangedDuringCapture){let g=i!==void 0&&Object.hasOwn(i,y)?i[y]:void 0;if(g?.toolsListResult!==void 0)i[y]={initializeResult:g.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let m=this.buildInitializeRequest(i);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{l=this.request(m)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let p=(await l).response;if(this.hasHookSetToBlock()){let m=p.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&p.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(m!==void 0)throw this.cleanup(m),m}if(this.initConfig?.managedSettings!==void 0&&p.managed_settings_applied!==!0){let m=Error("Claude Code did not confirm the managed settings sent with managedSettingsDelivery 'initialize', so the session was ended and no further prompt was sent. For a cloud session, use 'argv', because it does not read this delivery. Otherwise check that no wrapper changes the launch flags or the initialize request.");throw this.cleanup(m),m}if(this.initConfig?.mcpServers!==void 0){let m=p.mcp_servers_applied;if(typeof m!=="boolean"){let y=typeof p.claude_code_version==="string"?` (version ${p.claude_code_version})`:"",g=new u(`This Claude Code${y} is too old to read MCP servers from the initialize request, so it started without them. The session was ended and no further prompt was sent. Use the Claude Code bundled with this SDK, update the one you start (pathToClaudeCodeExecutable or spawnClaudeCodeProcess) to at least the bundled version, or set mcpServersDelivery: 'argv', which puts the servers' env and headers on Claude Code's command line, where other users of the machine can read them.`,"Claude Code too old to read MCP servers from initialize");throw this.cleanup(g),g}if(!m&&e&&typeof process<"u")process.emitWarning("Claude Code reported that it did not load the MCP servers sent in the initialize request, so this session may be running without them. A cloud session never starts them; otherwise check that no wrapper removes --await-initialize from the launch.",{code:xr})}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&p.plugins_applied!==!0)t(`[Query.initialize] Claude Code reported plugins_applied=${String(p.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent in the initialize request; the process is running with the plugins it was launched with.`,{level:"warn"});return p}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[m,y]of Object.entries(this.hooks))if(y?.length>0)this.initHooksPayload[m]=y.map((g)=>{let C=[];for(let b of g.hooks){let _=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(_,b),C.push(_)}let v={matcher:g.matcher,hookCallbackIds:C,timeout:g.timeout,onFailure:g.onFailure};return this.hostMatcherOf.set(v,g),v})}for(let m of Object.values(this.initHooksPayload??{}).flat())m.whenUnanswered=this.hostMatcherOf.get(m)?.whenUnanswered;let i=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,l=Array.from(this.sdkMcpServers).flatMap(([m,{settings:y}])=>Object.keys(y).length>0?[[m,y]]:[]),c=l.length>0?Object.fromEntries(l):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:i,sdkMcpServerConfigs:c,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins,managedSettings:this.initConfig?.managedSettings,mcpServers:this.initConfig?.mcpServers}}async captureSdkMcpServerManifests(){let e=performance.now(),i=new Map,l=!1,c=async(_,P)=>{try{if(await this.sdkMcpServers.get(_)?.connection,l)return;let O=await this.handleMcpControlRequest(_,{server_name:_,message:{jsonrpc:"2.0",id:Dt+"initialize",method:"initialize",params:{protocolVersion:wn,capabilities:bn,clientInfo:{...Rn,version:"0.3.326"}}}},P);if(l)return;if(!("result"in O)){t(`[Query.captureSdkMcpServerManifests] '${_}' answered initialize with an error; leaving it to the CLI: ${o(O)}`,{level:"warn"});return}let k=O.result;P.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let z=k.capabilities,W=typeof z==="object"&&z!==null&&"tools"in z&&z.tools!==void 0&&z.tools!==null,K;if(W){let V=await this.handleMcpControlRequest(_,{server_name:_,message:{jsonrpc:"2.0",id:Dt+"tools-list",method:"tools/list"}},P);if(l)return;if(!("result"in V)){t(`[Query.captureSdkMcpServerManifests] '${_}' answered tools/list with an error; leaving it to the CLI: ${o(V)}`,{level:"warn"});return}if(V.result.nextCursor===void 0)K=V.result}let Ce=S(o(K===void 0?{initializeResult:k}:{initializeResult:k,toolsListResult:K}));i.set(_,{transport:P,manifest:Ce})}catch(O){if(!l)t(`[Query.captureSdkMcpServerManifests] '${_}': ${O}; the CLI will handshake it over the control channel`,{level:"warn"})}},p=Array.from(this.sdkMcpServers,([_,{transport:P}])=>c(_,P)),m=Promise.all(p).then(()=>"settled"),y=new Promise((_)=>{this.stopSdkMcpManifestCapture=()=>_("closed")}),g=await he(Promise.race([m,y]),Pn);l=!0,this.stopSdkMcpManifestCapture=void 0;let C=Math.round(performance.now()-e),v={servers:p.length,captured:i.size,elapsed_ms:C};if(g==="closed"){et("sdk_mcp_manifest_capture","closed",v);return}if(g===void 0)t(`[Query.captureSdkMcpServerManifests] ${i.size}/${p.length} in-process MCP servers captured within ${Pn} ms; the rest will handshake over the control channel`,{level:"warn"}),et("sdk_mcp_manifest_capture","deadline",v);else if(i.size<p.length)et("sdk_mcp_manifest_capture","partial",v);else bt("sdk_mcp_manifest_capture",v);if(i.size===0)return;let b=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([_,P])=>{let O=i.get(_);return O!==void 0&&O.transport===P.transport?[[_,O.manifest]]:[]}));if(Object.keys(b).length===0)return;return t(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(b).join(", ")}] captured in ${C} ms`),b}async interrupt(e){return w("sdk_interrupt",async()=>{let i=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),l=i.response?.still_queued;if(!Array.isArray(l))return;let c=i.response?.cancelled;return{still_queued:l.filter((p)=>typeof p==="string"),...Array.isArray(c)&&{cancelled:c.filter((p)=>typeof p==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,i){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:i})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((i,l)=>{let c=(m)=>{if(m.subtype==="success"){let{pending_permission_requests:y,pending_user_dialog_requests:g,pending_elicitation_requests:C,...v}=m;i(v)}else{let y=new u(m.error,"awaitControlResponse: CLI error verdict");l(D(y,{telemetryMessage:y.telemetryMessage,errorCode:An(m.error_code)}))}if(m.pending_permission_requests||m.pending_user_dialog_requests||m.pending_elicitation_requests)t("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){l(lo());return}let p=this.unmatchedControlResponses.get(e);if(p){this.unmatchedControlResponses.delete(e),c(p);return}this.pendingControlResponses.set(e,{handler:(m)=>{this.pendingControlResponses.delete(e),c(m)},reject:l})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,i){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:i})}async applyFlagSettings(e){return w("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,i){return w("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:i})})}async rewindFiles(e,i){return w("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:i?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,i){await this.request({subtype:"seed_read_state",path:e,mtime:i})}async setCwd(e,i){return w("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...i?.trustAccepted!==void 0&&{trust_accepted:i.trustAccepted},...i?.trustedDirectory!==void 0&&{trusted_directory:i.trustedDirectory}})).response)}async claimSession(e){let i=w("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),l=this.initialization;return this.initialization=i.then(async(c)=>{if(c?.initialize===void 0)return l;let p=c.initialize,m=await l.then((_)=>({hooks_applied:_.hooks_applied,plugins_applied:_.plugins_applied,managed_settings_applied:_.managed_settings_applied,mcp_servers_applied:_.mcp_servers_applied,code_running_mcp_tools_applied:_.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,managed_settings_applied:void 0,mcp_servers_applied:void 0,code_running_mcp_tools_applied:void 0})),y=p.hooks_applied??m.hooks_applied,g=p.plugins_applied??m.plugins_applied,C=p.managed_settings_applied??m.managed_settings_applied,v=p.mcp_servers_applied??m.mcp_servers_applied,b=p.code_running_mcp_tools_applied??m.code_running_mcp_tools_applied;return{...p,...y!==void 0&&{hooks_applied:y},...g!==void 0&&{plugins_applied:g},...C!==void 0&&{managed_settings_applied:C},...v!==void 0&&{mcp_servers_applied:v},...b!==void 0&&{code_running_mcp_tools_applied:b}}},()=>l),this.initialization.catch(()=>{}),i}async enableRemoteControl(e,i,l){let c=++this.remoteControlCallGeneration,p=this.workSecretAnswerer,m=l?.reattachSessionId||(l?.workSecret===void 0?void 0:Or(l.workSecret)),y=e&&l?.workSecret!==void 0&&l.refreshWorkSecret&&m!==void 0?{sessionId:m,refresh:l.refreshWorkSecret}:void 0;this.workSecretAnswerer=y;let g;try{g=(await this.request({subtype:"remote_control",enabled:e,...i!==void 0&&{name:i},reattach_session_id:l?.reattachSessionId,keep_session_on_exit:l?.keepSessionOnExit,work_secret:l?.workSecret})).response}catch(C){if(c===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw C}if(e&&c===this.remoteControlCallGeneration){let C=g.bridge_session_id,v=[y,p];this.workSecretAnswerer=typeof C==="string"?v.find((b)=>b!==void 0&&xn(b.sessionId,C)):void 0}return g}async submitFeedback(e,i){return(await this.request({subtype:"submit_feedback",description:e,surface:i?.surface,draft_id:i?.draft_id,type:i?.type,title:i?.title,area:i?.area,attach_transcript:i?.attach_transcript,save_locally:i?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,i){await this.request({subtype:"rename_session",title:e,source:"host",session_id:i})}async generateSessionTitle(e,i){return w("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:i?.persist})).response.title)}async askSideQuestion(e,i){return w("sdk_side_question",async()=>{let c=(await this.request({subtype:"side_question",question:e,...i?.history?.length&&{history:[...i.history]}},i)).response;return c.response===null?null:{response:c.response,synthetic:c.synthetic??!1,...c.refusal_fallback&&{refusalFallback:{originalModel:c.refusal_fallback.original_model,fallbackModel:c.refusal_fallback.fallback_model,content:c.refusal_fallback.content}}}},()=>i?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,i){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:i?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let i of e)if(i.request.subtype==="can_use_tool")this.handleControlRequest({...i,request:{...i.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let i of e)if(i.request.subtype==="request_user_dialog")this.handleControlRequest(i).catch(()=>{})}request(e,i){let l=i?.signal;if(l?.aborted)return Promise.reject(U(l.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(lo());let c=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(c);let p={request_id:c,type:"control_request",request:e},m=e.subtype==="initialize";return new Promise((y,g)=>{let C,v=!1,b=(k)=>{this.pendingControlResponses.delete(c),C?.(),y(k)},_=(k)=>{this.pendingControlResponses.delete(c),C?.(),g(k)};if(l){let k=()=>{if(_(U(l.reason??"Control request aborted")),!v)return;try{Promise.resolve(this.transport.write(o({type:"control_cancel_request",request_id:c})+`
|
|
21
|
-
`)).catch(()=>{})}catch{}};l.addEventListener("abort",k,{once:!0}),C=()=>{l.removeEventListener("abort",k)}}this.pendingControlResponses.set(c,{handler:(k)=>{if(k.subtype==="success")b(k);else _(D(Error(k.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:An(k.error_code)}));if(!m&&(k.pending_permission_requests||k.pending_user_dialog_requests||k.pending_elicitation_requests))t(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`);else{if(k.pending_permission_requests)this.processPendingPermissionRequests(k.pending_permission_requests);if(k.pending_user_dialog_requests)this.processPendingUserDialogRequests(k.pending_user_dialog_requests)}},reject:_});let P=o(p)+`
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`)).catch((c)=>{t(`[Query.sendMcpServerMessageToCli] Transport write failed: ${c}`,{level:"error"})})}handleMcpControlRequest(e,i,l){let c="id"in i.message?i.message.id:null,p=`${e}:${c}`;return new Promise((m,y)=>{let g=()=>{this.pendingMcpResponses.delete(p)},C=(b)=>{g(),m(b)},v=(b)=>{g(),y(b)};if(this.pendingMcpResponses.set(p,{resolve:C,reject:v}),l.onmessage)l.onmessage(i.message);else{g(),y(Error("No message handler registered"));return}})}}function lo(){return Error("Query closed before response received")}var Ir=/^[a-z][a-z0-9_]{0,63}$/;function An(e){return typeof e==="string"&&Ir.test(e)?e:void 0}function xn(e,i){if(e===i)return!0;let l=e.slice(e.lastIndexOf("_")+1),c=i.slice(i.lastIndexOf("_")+1);return l.length>=4&&l===c}function Or(e){try{let i=S(Buffer.from(e,"base64url").toString("utf8"));if(typeof i!=="object"||i===null||!("session_ingress_token"in i)||typeof i.session_ingress_token!=="string")return;let l=i.session_ingress_token,p=(l.startsWith("sk-ant-si-")?l.slice(10):l).split(".");if(p.length!==3||!p[1])return;let m=S(Buffer.from(p[1],"base64url").toString("utf8"));return typeof m==="object"&&m!==null&&"session_id"in m&&typeof m.session_id==="string"&&m.session_id?m.session_id:void 0}catch{return}}var uo=500,co=1048576;var Kr=[200,800];class po{send;pending=[];pendingEntries=0;pendingBytes=0;flushPromise=null;sendTimeoutMs;onError;maxPendingEntries;maxPendingBytes;backoffMs;constructor(e,i){this.send=e;let{sendTimeoutMs:l=60000,onError:c,maxPendingEntries:p=uo,maxPendingBytes:m=co,backoffMs:y=Kr}=i??{};this.sendTimeoutMs=l,this.onError=c,this.maxPendingEntries=p,this.maxPendingBytes=m,this.backoffMs=y}enqueue(e,i){let l=o(i).length;if(this.pending.push({filePath:e,entries:i,bytes:l}),this.pendingEntries+=i.length,this.pendingBytes+=l,this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)this.flushPromise=this.drain(),this.flushPromise.catch(()=>{})}async flush(){let e=this.drain();if(this.flushPromise=e,await e,this.flushPromise===e)this.flushPromise=null}async drain(){let e=this.flushPromise,i=this.pending.splice(0);if(this.pendingEntries=0,this.pendingBytes=0,e)await e;if(i.length===0)return;await this.doFlush(i)}async doFlush(e){let i=new Map;for(let l of e){let c=i.get(l.filePath);if(c)c.push(...l.entries);else i.set(l.filePath,l.entries.slice())}for(let[l,c]of i)await this.sendWithRetry(l,c)}async sendWithRetry(e,i){let l=this.backoffMs.length+1,c=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${e}`,p,m=1;for(;m<=l;m++)try{await F(this.send(e,i),this.sendTimeoutMs,c),p=void 0;break}catch(y){if(p=U(y),p.message===c)break;let g=this.backoffMs[m-1];if(g===void 0)break;await x(g)}if(p){t(`[TranscriptMirrorBatcher] flush failed for ${e} after ${m} attempt(s): ${p}`,{level:"error"});try{this.onError?.(e,p)}catch(y){t(`[TranscriptMirrorBatcher] onError callback threw: ${y}`,{level:"error"})}}}}var In=typeof globalThis==="object"?globalThis:global;var Te="1.9.0";var On=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ur(e){var i=new Set([e]),l=new Set,c=e.match(On);if(!c)return function(){return!1};var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};if(p.prerelease!=null)return function(C){return C===e};function m(g){return l.add(g),!1}function y(g){return i.add(g),!0}return function(C){if(i.has(C))return!0;if(l.has(C))return!1;var v=C.match(On);if(!v)return m(C);var b={major:+v[1],minor:+v[2],patch:+v[3],prerelease:v[4]};if(b.prerelease!=null)return m(C);if(p.major!==b.major)return m(C);if(p.major===0){if(p.minor===b.minor&&p.patch<=b.patch)return y(C);return m(C)}if(p.minor<=b.minor)return y(C);return m(C)}}var Kn=Ur(Te);var Nr=Te.split(".")[0],ct=Symbol.for("opentelemetry.js.api."+Nr),pt=In;function Ze(e,i,l,c){var p;if(c===void 0)c=!1;var m=pt[ct]=(p=pt[ct])!==null&&p!==void 0?p:{version:Te};if(!c&&m[e]){var y=Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return l.error(y.stack||y.message),!1}if(m.version!==Te){var y=Error("@opentelemetry/api: Registration of version v"+m.version+" for "+e+" does not match previously registered API v"+Te);return l.error(y.stack||y.message),!1}return m[e]=i,l.debug("@opentelemetry/api: Registered a global for "+e+" v"+Te+"."),!0}function Ae(e){var i,l,c=(i=pt[ct])===null||i===void 0?void 0:i.version;if(!c||!Kn(c))return;return(l=pt[ct])===null||l===void 0?void 0:l[e]}function Qe(e,i){i.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Te+".");var l=pt[ct];if(l)delete l[e]}var Lr=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var c=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=c.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=c.return))l.call(c)}finally{if(y)throw y.error}}return m},Fr=function(e,i,l){if(l||arguments.length===2){for(var c=0,p=i.length,m;c<p;c++)if(m||!(c in i)){if(!m)m=Array.prototype.slice.call(i,0,c);m[c]=i[c]}}return e.concat(m||Array.prototype.slice.call(i))},Ln=function(){function e(i){this._namespace=i.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return gt("debug",this._namespace,i)},e.prototype.error=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return gt("error",this._namespace,i)},e.prototype.info=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return gt("info",this._namespace,i)},e.prototype.warn=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return gt("warn",this._namespace,i)},e.prototype.verbose=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return gt("verbose",this._namespace,i)},e}();function gt(e,i,l){var c=Ae("diag");if(!c)return;return l.unshift(i),c[e].apply(c,Fr([],Lr(l),!1))}var re;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(re||(re={}));function Fn(e,i){if(e<re.NONE)e=re.NONE;else if(e>re.ALL)e=re.ALL;i=i||{};function l(c,p){var m=i[c];if(typeof m==="function"&&e>=p)return m.bind(i);return function(){}}return{error:l("error",re.ERROR),warn:l("warn",re.WARN),info:l("info",re.INFO),debug:l("debug",re.DEBUG),verbose:l("verbose",re.VERBOSE)}}var qr=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var c=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=c.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=c.return))l.call(c)}finally{if(y)throw y.error}}return m},zr=function(e,i,l){if(l||arguments.length===2){for(var c=0,p=i.length,m;c<p;c++)if(m||!(c in i)){if(!m)m=Array.prototype.slice.call(i,0,c);m[c]=i[c]}}return e.concat(m||Array.prototype.slice.call(i))},Hr="diag",Ue=function(){function e(){function i(p){return function(){var m=[];for(var y=0;y<arguments.length;y++)m[y]=arguments[y];var g=Ae("diag");if(!g)return;return g[p].apply(g,zr([],qr(m),!1))}}var l=this,c=function(p,m){var y,g,C;if(m===void 0)m={logLevel:re.INFO};if(p===l){var v=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return l.error((y=v.stack)!==null&&y!==void 0?y:v.message),!1}if(typeof m==="number")m={logLevel:m};var b=Ae("diag"),_=Fn((g=m.logLevel)!==null&&g!==void 0?g:re.INFO,p);if(b&&!m.suppressOverrideMessage){var P=(C=Error().stack)!==null&&C!==void 0?C:"<failed to generate stacktrace>";b.warn("Current logger will be overwritten from "+P),_.warn("Current logger will overwrite one already registered from "+P)}return Ze("diag",_,l,!0)};l.setLogger=c,l.disable=function(){Qe(Hr,l)},l.createComponentLogger=function(p){return new Ln(p)},l.verbose=i("verbose"),l.debug=i("debug"),l.info=i("info"),l.warn=i("warn"),l.error=i("error")}return e.instance=function(){if(!this._instance)this._instance=new e;return this._instance},e}();var jr=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var c=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=c.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=c.return))l.call(c)}finally{if(y)throw y.error}}return m},Br=function(e){var i=typeof Symbol==="function"&&Symbol.iterator,l=i&&e[i],c=0;if(l)return l.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&c>=e.length)e=void 0;return{value:e&&e[c++],done:!e}}};throw TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")},qn=function(){function e(i){this._entries=i?new Map(i):new Map}return e.prototype.getEntry=function(i){var l=this._entries.get(i);if(!l)return;return Object.assign({},l)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(i){var l=jr(i,2),c=l[0],p=l[1];return[c,p]})},e.prototype.setEntry=function(i,l){var c=new e(this._entries);return c._entries.set(i,l),c},e.prototype.removeEntry=function(i){var l=new e(this._entries);return l._entries.delete(i),l},e.prototype.removeEntries=function(){var i,l,c=[];for(var p=0;p<arguments.length;p++)c[p]=arguments[p];var m=new e(this._entries);try{for(var y=Br(c),g=y.next();!g.done;g=y.next()){var C=g.value;m._entries.delete(C)}}catch(v){i={error:v}}finally{try{if(g&&!g.done&&(l=y.return))l.call(y)}finally{if(i)throw i.error}}return m},e.prototype.clear=function(){return new e},e}();var Lu=Ue.instance();function jn(e){if(e===void 0)e={};return new qn(new Map(Object.entries(e)))}function Bn(e){return Symbol.for(e)}var Gr=function(){function e(i){var l=this;l._currentContext=i?new Map(i):new Map,l.getValue=function(c){return l._currentContext.get(c)},l.setValue=function(c,p){var m=new e(l._currentContext);return m._currentContext.set(c,p),m},l.deleteValue=function(c){var p=new e(l._currentContext);return p._currentContext.delete(c),p}}return e}(),Gn=new Gr;var $n={get:function(e,i){if(e==null)return;return e[i]},keys:function(e){if(e==null)return[];return Object.keys(e)}},Wn={set:function(e,i,l){if(e==null)return;e[i]=l}};var $r=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var c=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=c.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=c.return))l.call(c)}finally{if(y)throw y.error}}return m},Wr=function(e,i,l){if(l||arguments.length===2){for(var c=0,p=i.length,m;c<p;c++)if(m||!(c in i)){if(!m)m=Array.prototype.slice.call(i,0,c);m[c]=i[c]}}return e.concat(m||Array.prototype.slice.call(i))},Zn=function(){function e(){}return e.prototype.active=function(){return Gn},e.prototype.with=function(i,l,c){var p=[];for(var m=3;m<arguments.length;m++)p[m-3]=arguments[m];return l.call.apply(l,Wr([c],$r(p),!1))},e.prototype.bind=function(i,l){return l},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var Zr=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var c=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=c.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=c.return))l.call(c)}finally{if(y)throw y.error}}return m},Qr=function(e,i,l){if(l||arguments.length===2){for(var c=0,p=i.length,m;c<p;c++)if(m||!(c in i)){if(!m)m=Array.prototype.slice.call(i,0,c);m[c]=i[c]}}return e.concat(m||Array.prototype.slice.call(i))},mo="context",Vr=new Zn,At=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(i){return Ze(mo,i,Ue.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(i,l,c){var p,m=[];for(var y=3;y<arguments.length;y++)m[y-3]=arguments[y];return(p=this._getContextManager()).with.apply(p,Qr([i,l,c],Zr(m),!1))},e.prototype.bind=function(i,l){return this._getContextManager().bind(i,l)},e.prototype._getContextManager=function(){return Ae(mo)||Vr},e.prototype.disable=function(){this._getContextManager().disable(),Qe(mo,Ue.instance())},e}();var go=At.getInstance();var Vn=function(){function e(){}return e.prototype.inject=function(i,l){},e.prototype.extract=function(i,l){return i},e.prototype.fields=function(){return[]},e}();var fo=Bn("OpenTelemetry Baggage Key");function ho(e){return e.getValue(fo)||void 0}function Xn(){return ho(At.getInstance().active())}function Jn(e,i){return e.setValue(fo,i)}function es(e){return e.deleteValue(fo)}var So="propagation",Yr=new Vn,ts=function(){function e(){this.createBaggage=jn,this.getBaggage=ho,this.getActiveBaggage=Xn,this.setBaggage=Jn,this.deleteBaggage=es}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(i){return Ze(So,i,Ue.instance())},e.prototype.inject=function(i,l,c){if(c===void 0)c=Wn;return this._getGlobalPropagator().inject(i,l,c)},e.prototype.extract=function(i,l,c){if(c===void 0)c=$n;return this._getGlobalPropagator().extract(i,l,c)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Qe(So,Ue.instance())},e.prototype._getGlobalPropagator=function(){return Ae(So)||Yr},e}();var yo=ts.getInstance();import{copyFile as Xr,readFile as Jr,rm as ns,writeFile as ss}from"fs/promises";import{homedir as os}from"os";import{join as Co}from"path";function rs(e){return{globalConfig:Co(e||os(),".claude.json"),userSettings:Co(e||Co(os(),".claude"),"settings.json")}}function _o(e,i,l,c){return e!==void 0&&i===l?{backend:e,key:c}:void 0}async function Ve(e,i,l,c){if(c)return ei(c,e,i,l);try{if(l)await ss(i,l(await Jr(e)),{mode:384});else await Xr(e,i)}catch(p){if(r(p)===void 0)throw p;if(!h(p))await ns(i,{force:!0}).catch(()=>{}),t(`sessionStore resume: skipping ${e} (${r(p)})`)}}async function ei({backend:e,key:i},l,c,p){let m=await e.read([i]);if(!m.ok){if(m.error.code==="InvalidArgument")throw new u(`sessionStore resume: invalid v5 key for ${l}: ${m.error.argument}${m.error.reason?` (${m.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");t(`sessionStore resume: skipping ${l} (${m.error.code})`);return}let y=m.value.items[0];if(!y?.found)return;let g=Buffer.from(y.value);try{await ss(c,p?p(g):g,{mode:384})}catch(C){if(r(C)===void 0)throw C;if(!h(C))await ns(c,{force:!0}).catch(()=>{}),t(`sessionStore resume: skipping ${l} (${r(C)})`)}}import{createHash as ti}from"crypto";import{homedir as bd,userInfo as oi}from"os";var is="-credentials";function as(e=""){let i=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,l=i!==void 0?!i:!process.env.CLAUDE_CONFIG_DIR,c=i!==void 0?i.normalize("NFC"):R(),p=l?"":`-${ti("sha256").update(c).digest("hex").substring(0,8)}`;return`Claude Code${Hn().OAUTH_FILE_SUFFIX}${e}${p}`}var ni=/^[a-zA-Z0-9._-]+$/;function ls(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||oi().username}catch{e="claude-code-user"}if(!ni.test(e))return"claude-code-user";return e}class us{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;blockingReadRetryAt=0;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var Ed=new s(()=>new us);function si(e,i){if(e==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let l=i.filter((c)=>c.length>0&&!c.includes("("));if(l.length===0)return;return`canUseTool will not be invoked for: ${l.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function ds(e,i,l){if(!e)return;let c=si(i,l);if(c===void 0)return;process.emitWarning(c,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}var ri="CLAUDE_SDK_MCP_SERVERS_ARGV_DEPRECATED",ii="This app starts its own Claude Code (pathToClaudeCodeExecutable or spawnClaudeCodeProcess) and sets no mcpServersDelivery, so its MCP servers go on Claude Code's command line, where other users of the machine can read their env and headers. That default is deprecated: a future SDK release sends them over stdin instead ('initialize'), which a Claude Code older than the one bundled with this SDK cannot read, so those sessions would then fail to start. Set mcpServersDelivery: 'initialize' once that Claude Code is at least the bundled version, or mcpServersDelivery: 'argv' to stay on the command line. Either setting stops this warning.",cs=a({value:!1},(e)=>{e.value=!1});function ps(){if(cs.value)return;cs.value=!0,process.emitWarning(ii,{type:"DeprecationWarning",code:ri})}process.env.NoDefaultCurrentDirectoryInExePath="1";var fi=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function gs(e){let i;try{i=S(be(e.toString("utf8")))}catch{return e}if(!fs(i))return e;let l=!1;for(let p of fi)if(Object.hasOwn(i,p))delete i[p],l=!0;let c=i.env;if(fs(c)&&Object.hasOwn(c,"CLAUDE_CONFIG_DIR"))delete c.CLAUDE_CONFIG_DIR,l=!0;return l?o(i):e}function fs(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function hi(e,i){if(!e)return;let l=e;try{let c=S(e);if(c?.claudeAiOauth?.refreshToken)delete c.claudeAiOauth.refreshToken,l=o(c)}catch{}await Ss(i,l,{mode:384})}function Si(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=as(is);return new Promise((i)=>{ai("security",["find-generic-password","-a",ls(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(l,c)=>i(l?void 0:c.trim()||void 0))})}async function _s(e,i,l,c,p=60000,m){if(!T(i))return;let y=B(l,c),g=await F(e.load({projectKey:y,sessionId:i}),p,`SessionStore.load() timed out after ${p}ms for session ${i}`);if(!g||g.length===0)return;let C=J(pi(),`claude-resume-${li()}`);try{let v=J(C,"projects",y);await xt(v,{recursive:!0,mode:448});let b=J(v,`${i}.jsonl`);await nn(b,g);let _=c?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,P=_??J(ft(),".claude"),O;try{O=await di(J(P,".credentials.json"),"utf-8")}catch(j){if(!h(j))throw j}if(!_&&!(c??process.env).ANTHROPIC_API_KEY&&!(c??process.env).CLAUDE_CODE_OAUTH_TOKEN)O=await Si()??O;await hi(O,J(C,".credentials.json"));let k=rs(G("CLAUDE_CONFIG_DIR")),z=_||ft(),W=J(z,".claude.json");await Ve(W,J(C,".claude.json"),void 0,_o(m,W,k.globalConfig,N.globalConfig())),await Ve(J(P,".config.json"),J(C,".config.json"));for(let j of Un)if(j)await Ve(J(z,`.claude${j}.json`),J(C,`.claude${j}.json`));let K=J(P,"settings.json");if(await Ve(K,J(C,"settings.json"),gs,_o(m,K,k.userSettings,N.userSettings())),await Ve(J(P,"cowork_settings.json"),J(C,"cowork_settings.json"),gs),e.listSubkeys)await yi(e,{projectKey:y,sessionId:i},J(v,i),p);return C}catch(v){throw await It(C),v}}async function yi(e,i,l,c){let p=await F(e.listSubkeys({projectKey:i.projectKey,sessionId:i.sessionId}),c,`SessionStore.listSubkeys() timed out after ${c}ms for session ${i.sessionId}`);for(let m of p){let y=ht(l,m+".jsonl");if(!m||bo(m)||m.split(/[\\/]/).includes("..")||!y.startsWith(l+mi)){t(`[SessionStore] skipping unsafe subpath from listSubkeys: ${m}`,{level:"warn"});continue}let g=await F(e.load({projectKey:i.projectKey,sessionId:i.sessionId,subpath:m}),c,`SessionStore.load() timed out after ${c}ms for session ${i.sessionId} subpath ${m}`);if(!g||g.length===0)continue;let C=[],v=[];for(let b of g)if(zn(b))C.push(b);else v.push(b);if(v.length>0)await xt(ms(y),{recursive:!0}),await nn(y,v);if(C.length>0){let b=C.at(-1),_=ht(l,m+".meta.json");await xt(ms(_),{recursive:!0});let{type:P,...O}=b;await Ss(_,o(O),{mode:384})}}}function bs(e){let i=e?.accepted===!0&&(typeof e.directory!=="string"||!(ys.isAbsolute(e.directory)||Cs.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&i===void 0)t("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return i}var Ci=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Ro(e,i){let{isSingleUserTurn:l,resumeConfigDir:c,deferSpawn:p,readsStartupMarks:m}=i,{systemPrompt:y,settings:g,managedSettings:C,settingSources:v,sandbox:b,..._}=e??{},P,O,k,z;if(y===void 0)P="";else if(typeof y==="string")P=y;else if(Array.isArray(y))P=y;else if(y.type==="custom")P=y.prompt,z=y.snapshot;else if(y.type==="preset")O=y.append,k=y.excludeDynamicSections,z=y.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.326";let{abortController:W=lt(),additionalDirectories:K=[],projectConfigRoot:j,agent:Ce,agents:V,allowedTools:q=[],betas:ke,canUseTool:me,continue:de,cwd:ce,debug:Ee,debugFile:Le,disallowedTools:Xe=[],tools:Je,env:ge,executable:Fe=ie()?"bun":"node",executableArgs:qe=[],extraArgs:xe={},fallbackModel:_e,enableFileCheckpointing:I,toolConfig:Re,forkSession:fe,hooks:Ie,includeHookEvents:Se,includePartialMessages:ze,forwardSubagentText:oe,verbatimPrompts:ye=!1,onElicitation:L,onUserDialog:ne,supportedDialogKinds:ee,perTaskStopAffordance:pe,rapidFollowupPreempt:tt,workspaceTrust:Ut,persistSession:ot,sessionStore:De,sessionStoreFlush:ws,thinking:nt,effort:ks,maxThinkingTokens:Lt,maxTurns:Es,maxBudgetUsd:Ps,taskBudget:Ds,mcpServers:wo,model:Ts,outputFormat:ko,permissionMode:As,allowDangerouslySkipPermissions:Ms=!1,permissionPromptToolName:xs,permissionPrompts:Is,plugins:st,pluginDelivery:Ft="argv",managedSettingsDelivery:qt="argv",mcpServersDelivery:rt,getOAuthToken:Eo,getHostAuthToken:Po,workload:Do,resume:zt,resumeSessionAt:Os,resumeDropsTurn:Ks,sessionId:Us,skills:To,stderr:Ns,strictMcpConfig:Ls}=_,Ao=As;if(De&&ot===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. To avoid keeping a local copy, pass env: { ...process.env, CLAUDE_CONFIG_DIR: dir }, where dir is a new private directory such as fs.mkdtempSync(path.join(os.tmpdir(), 'claude-')), and delete dir when the query ends.");un({supportedDialogKinds:ee,onUserDialog:ne});let Fs=bs(Ut);if(De&&de&&!zt&&!De.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(De&&I)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(De&&_.spawnClaudeCodeProcess)t("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(ds(!!me,Ao??"default",q),Ft!=="argv"&&Ft!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let Mo=Ft==="initialize"&&st!==void 0&&st.length>0;if(qt!=="argv"&&qt!=="initialize")throw Error("Invalid managedSettingsDelivery. Expected 'argv' or 'initialize'.");let Ht=qt==="initialize"&&Boolean(C);if(rt!==void 0&&rt!=="argv"&&rt!=="initialize")throw Error("Invalid mcpServersDelivery. Expected 'argv' or 'initialize'.");let jt=_.pathToClaudeCodeExecutable;if(!jt){let Z=gi(import.meta.url),ae=ci(Z),ve=ln((Be)=>ae.resolve(Be));if(!ve)throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);jt=ve}let xo=ko?.type==="json_schema"?ko.schema:void 0,Y=ge?{...ge}:{...process.env};if(!Y.CLAUDE_CODE_ENTRYPOINT)Y.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!Y.CLAUDE_AGENT_SDK_VERSION)Y.CLAUDE_AGENT_SDK_VERSION="0.3.326";if(I)Y.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(Y).some((Z)=>Z.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))Y.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(m&&!Object.keys(Y).some((Z)=>Z.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))Y.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let Bt=Me(Y.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),qs=Number.isFinite(Bt)&&Bt>=0?Bt:wt;if(Eo)Y.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(Po)Y.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(Re?.askUserQuestion?.previewFormat)Y.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=Re.askUserQuestion.previewFormat;for(let[Z,ae]of[[Re?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[Re?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Z)Y[ae]="1";else if(!ge){for(let ve of Object.keys(Y))if(ve.toUpperCase()===ae)delete Y[ve]}let Gt={};if(yo.inject(go.active(),Gt),"traceparent"in Gt){for(let Z of["TRACEPARENT","TRACESTATE"])if(!(Z in(ge??{})))delete Y[Z]}for(let[Z,ae]of Object.entries(Gt)){let ve=Z.toUpperCase();if(!(ve in(ge??{})))Y[ve]=ae}let St={},Io=new Map;if(wo)for(let[Z,ae]of Object.entries(wo))if(ae.type==="sdk"&&ae.instance)Io.set(Z,ae);else St[Z]=ae;let it;if(nt)switch(nt.type){case"adaptive":it={type:"adaptive",display:nt.display};break;case"enabled":it={type:"enabled",budgetTokens:nt.budgetTokens,display:nt.display};break;case"disabled":it={type:"disabled"};break}else if(Lt!==void 0)it=Lt===0?{type:"disabled"}:{type:"enabled",budgetTokens:Lt};if(c){if(Y.CLAUDE_CONFIG_DIR=c,process.platform==="win32")Y.CLAUDE_SECURESTORAGE_CONFIG_DIR=ge?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??ge?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let yt=xe?.["sdk-url"]!==void 0||Object.keys(xe??{}).some((Z)=>Z.startsWith("sdk-url="))||qe.some((Z)=>/^--sdk-url(=|$)/.test(Z)),zs=Boolean(zt||de)&&!_.pathToClaudeCodeExecutable&&!_.spawnClaudeCodeProcess&&!yt,$t=yt?[]:(st??[]).filter((Z)=>Z.requiredByOrganization),Oo=Object.keys(St).length>0,Ko=rt==="initialize"&&Oo&&!yt;if(rt===void 0&&Oo&&!yt&&(_.pathToClaudeCodeExecutable||_.spawnClaudeCodeProcess))ps();let Uo=new no({abortController:W,additionalDirectories:K,projectConfigRoot:j,agent:Ce,betas:ke,cwd:ce,debug:Ee,debugFile:Le,executable:Fe,executableArgs:qe,extraArgs:{...xe,...Do&&{workload:Do}},readsInitializeAtBoot:zs||$t.length>0,pathToClaudeCodeExecutable:jt,env:Y,forkSession:fe,stderr:Ns,thinkingConfig:it,effort:ks,maxTurns:Es,maxBudgetUsd:Ps,taskBudget:Ds,model:Ts,fallbackModel:_e,jsonSchema:xo,permissionMode:Ao,allowDangerouslySkipPermissions:Ms,permissionPromptToolName:xs,permissionPrompts:Is,continueConversation:De?void 0:de,resume:zt,resumeSessionAt:Os,resumeDropsTurn:Ks,sessionId:Us,settings:typeof g==="object"?o(g):g,managedSettings:C&&!Ht?o(C):void 0,managedSettingsViaInitialize:Ht,settingSources:v,skills:To,allowedTools:q,disallowedTools:Xe,tools:Je,mcpServers:St,mcpServersViaInitialize:Ko,strictMcpConfig:Ls,canUseTool:!!me,hooks:!!Ie,includeHookEvents:Se,includePartialMessages:ze,persistSession:ot,sessionMirror:!!De,plugins:st,pluginsViaInitialize:Mo,sandbox:b,spawnClaudeCodeProcess:_.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:p}),Hs={systemPrompt:P,appendSystemPrompt:O,planModeInstructions:_.planModeInstructions,systemPromptSnapshot:z,appendSubagentSystemPrompt:_.appendSubagentSystemPrompt,toolAliases:_.toolAliases,codeRunningMcpTools:_.codeRunningMcpTools,excludeDynamicSections:k,agents:V,title:_.title,skills:To,webSearchIsolationExemptMcpServers:_.webSearchIsolationExemptMcpServers,promptSuggestions:_.promptSuggestions,agentProgressSummaries:_.agentProgressSummaries,forwardSubagentText:oe,supportedDialogKinds:ee,perTaskStopAffordance:pe,rapidFollowupPreempt:tt,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:Fs,plugins:Mo?st:$t.length>0?$t:void 0,managedSettings:Ht?C:void 0,mcpServers:Ko?St:void 0,captureSdkMcpManifests:!mt("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},Zt=new Tt(Uo,l,me,Ie,W,Io,xo,Hs,L,Eo,Po,ne,ye,qs);if(De){let Z=()=>J(Y.CLAUDE_CONFIG_DIR??J(ft(),".claude"),"projects"),ae=ws==="eager",ve=new po(async(Be,Qt)=>{let at=on(Be,Z());if(at)await De.append(at,Qt);else t(`[SessionStore] dropping mirror frame: filePath ${Be} is not under ${Z()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Be,Qt)=>{let at=on(Be,Z());if(at)Zt.reportMirrorError(at,Qt.message)},maxPendingEntries:ae?0:uo,maxPendingBytes:ae?0:co});Zt.setTranscriptMirrorBatcher(ve)}return{queryInstance:Zt,transport:Uo,abortController:W,processEnv:Y,verbatimPrompts:ye}}function vo(e,i,l,c){if(typeof i==="string")e.writePrompt(o({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:i}]},parent_tool_use_id:null,...c&&{client_composed:!0}})+`
|
|
25
|
-
`).catch((p)=>l.abort(p));else e.streamInput(i).catch((p)=>l.abort(p))}var _i=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function It(e){for(let i=0;;i++)try{return await hs(e,{recursive:!0,force:!0})}catch(l){if(i>=4||!_i.has(r(l)??""))return;await x((i+1)*100)}}function bi(e,i){e.waitForExit().catch(()=>{}).finally(()=>It(i))}function Ri({prompt:e,options:i}){if((i?.resume||i?.continue)&&i?.sessionStore)return vi(e,i);let{queryInstance:l,abortController:c,verbatimPrompts:p}=Ro(i,{isSingleUserTurn:typeof e==="string"});return vo(l,e,c,p),l}function vi(e,i){let{queryInstance:l,transport:c,abortController:p,processEnv:m,verbatimPrompts:y}=Ro({...i},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),g=ht(i.cwd??"."),C=i.sessionStore,v=i.loadTimeoutMs??60000,b=i.resume;return(async()=>{if(!b)b=(await F(C.listSessions(B(g,i.env)),v,`SessionStore.listSessions() timed out after ${v}ms`)).slice().sort((O,k)=>k.mtime-O.mtime)[0]?.sessionId;if(!b)return;return _s(C,b,g,i.env,i.loadTimeoutMs)})().then((P)=>{if(P){c.updateResume(b);let O={CLAUDE_CONFIG_DIR:P};if(process.platform==="win32"){let k=i.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??i.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";O.CLAUDE_SECURESTORAGE_CONFIG_DIR=k,m.CLAUDE_SECURESTORAGE_CONFIG_DIR=k}c.updateEnv(O),m.CLAUDE_CONFIG_DIR=P,l.addCleanupCallback(()=>bi(c,P))}if(!l.isClosed())c.spawn()}).catch((P)=>{let O=U(P);c.spawnAbort(O),l.setError(O)}),vo(l,e,p,y),l}async function wi(e={}){return(await Rs(e)).warm}async function Rs({options:e,initializeTimeoutMs:i}){let l,c=e?.resume;if((c||e?.continue)&&e?.sessionStore){let g=ht(e.cwd??".");if(!c){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let C=e.loadTimeoutMs??60000;c=(await F(e.sessionStore.listSessions(B(g,e.env)),C,`SessionStore.listSessions() timed out after ${C}ms`)).slice().sort((b,_)=>_.mtime-b.mtime)[0]?.sessionId}if(c)l=await _s(e.sessionStore,c,g,e.env,e.loadTimeoutMs)}let p,m,y;try{let z=function(){if(k)return;k=!0,_.close()},g=Ro(l&&c&&c!==e?.resume?{...e,resume:c}:e,{isSingleUserTurn:!1,resumeConfigDir:l,readsStartupMarks:!0});p=g.queryInstance;let{transport:C,abortController:v,verbatimPrompts:b}=g;m=C;let _=g.queryInstance;if(l){let K=l;_.addCleanupCallback(()=>{y=C.waitForExit().catch(()=>{}).then(()=>It(K))})}let O=new so(i,Pe,e?.onStartupHooksRunning);_.setFrameObserver((K)=>{if(O.note(K),K.type==="system"&&K.subtype==="hook_progress"&&K.backgrounded!==!0)_.dropUnreadHookProgress(K.hook_id)});try{await O.race(_.initializationResult())}catch(K){if(K instanceof Error&&"errorClass"in K&&K.errorClass==="initialize_timeout"&&Object.isExtensible(K)){let j=_.startupMarkReached();Object.assign(K,{[hn]:j?.mark??"none",...j&&{[Sn]:j.ageMs}})}throw K}finally{_.setFrameObserver(void 0)}let k=!1;return{warm:{query(K){if(k)throw Error("WarmQuery.query() can only be called once");k=!0;try{vo(_,K,v,b)}catch(j){throw _.close(),j}if(typeof K==="string")_.setIsSingleUserTurn(!0);return _},close:z,async[Symbol.asyncDispose](){k=!0,_.close(),await y}},query:_,transport:C}}catch(g){if(p?.close(),l&&!y){let C=m;y=(C?C.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>It(l))}throw await y,g}}async function ki({options:e,initializeTimeoutMs:i}={}){if(e?.resume||e?.continue||e?.forkSession)throw Error("prewarm(): resume/continue/forkSession describe a session; a spare has none — pass them to query() instead");let l=e?.cwd===void 0,c;if(e?.cwd!==void 0)c=e.cwd;else{let V=e?.env,q=V?.CLAUDE_CONFIG_DIR?.trim(),ke=V?.HOME?.trim(),me=V===void 0?R():q||J(ke||ft(),".claude"),de=bo(me)?me:J(ft(),".claude");if(!bo(de))throw Error("prewarm(): no absolute config home to park the spare under (neither CLAUDE_CONFIG_DIR nor HOME gives an absolute path); set one of them to an absolute path or pass options.cwd");let ce=J(de,"spares");await xt(ce,{recursive:!0,mode:448}),c=await ui(J(ce,"spare-"))}function p(){return l?hs(c,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()}let{workspaceTrust:m,...y}=e??{};if(m!==void 0)t("prewarm(): workspaceTrust is a per-session attestation — pass it to claim(); not sent to the spare",{level:"warn"});let{warm:g,query:C,transport:v}=await w("sdk_prewarm",async()=>{try{return await Rs({options:{...y,cwd:c,extraArgs:{...y.extraArgs,"await-claim":null}},initializeTimeoutMs:i??Et})}catch(V){throw await p(),V}}),b=Object.entries(e?.mcpServers??{}).filter(([,V])=>V.type==="sdk").map(([V])=>V),_;function P(){return _??=v.waitForExit().catch(()=>{}).then(p),_}let O=!1,k=!1,z=!1,W,K=new Promise((V,q)=>{W={resolve:V,reject:q}});K.catch(()=>{});let j=v.waitForExit().then(()=>{return},()=>{return});j.then(()=>{if(!O)z=!0,W.reject(Error("spare_exited: the spare process exited before it was claimed")),P()});let Ce={claimed:K,exited:j,claim({prompt:V,options:q}){if(O)throw Error("SpareProcess.claim() can only be called once");if(k||z)throw Error("SpareProcess.claim(): the spare was closed or has exited; start the session with query()");let ke=Ci.filter((oe)=>q.settings?.[oe]!==void 0);if(ke.length>0)throw new u(`SpareProcess.claim(): hook settings (${ke.join(", ")}) cannot be applied at claim; pass them to prewarm() in Options.settings, where they are in force before any hook, as on a cold start. Nothing was sent: this spare can still be claimed without them.`,"SpareProcess.claim(): hook settings cannot be applied at claim");let me=typeof q.cwd==="string"&&q.cwd.trim()!==""&&!ys.isAbsolute(q.cwd)&&!Cs.isAbsolute(q.cwd)&&q.cwd!=="~"&&!q.cwd.startsWith("~/")?ht(q.cwd):q.cwd;O=!0;let de=bs(q.workspaceTrust),ce=q.settings,Ee=n(ce),{model:Le,agent:Xe,fastMode:Je,permissions:ge,availableModels:Fe,disableAutoMode:qe,...xe}=Ee?ce:{},_e={model:Le,agent:Xe,fastMode:Je,permissions:ge,availableModels:Fe,disableAutoMode:qe},I=ce!==void 0&&(!Ee||Object.keys(xe).length>0)?C.applyFlagSettings(Ee?xe:ce):void 0,Re=C.claimSession({cwd:me,...q.permissionMode!==void 0&&{permission_mode:q.permissionMode},...q.env&&{env:q.env},...q.additionalDirectories&&{additional_directories:q.additionalDirectories},...q.appendSystemPrompt!==void 0&&{append_system_prompt:q.appendSystemPrompt},...q.title!==void 0&&{title:q.title},...q.agents&&{agents:q.agents},...de?.accepted===!0&&{workspace_trust:de},sdk_mcp_servers:b}),fe=[];if(q.model!==void 0)fe.push(["model",C.setModel(q.model)]);if(q.maxThinkingTokens!==void 0)fe.push(["maxThinkingTokens",C.setMaxThinkingTokens(q.maxThinkingTokens)]);let Ie=Object.values(_e).some((oe)=>oe!==void 0)?C.applyFlagSettings(_e):void 0,Se=ce!==void 0?Promise.all([I,Ie]):void 0;if(Se!==void 0)fe.push(["settings",Se]);for(let[,oe]of fe)oe.catch(()=>{});function ze(){v.endInput(),P()}if(Re.then(async(oe)=>{p();let ye={cwd:oe.cwd??me,sessionId:oe.session_id,parkedMs:oe.parked_ms,sdkMcpSettled:oe.sdk_mcp_settled},L=await Promise.allSettled(fe.map(([,pe])=>pe)),ne=L.flatMap((pe,tt)=>pe.status==="rejected"?[`${String(fe[tt][0])}: ${E(pe.reason)}`]:[]),ee=Se===void 0?void 0:L[fe.findIndex(([pe])=>pe==="settings")];if(ee?.status==="rejected")k=!0,C.close(),W.reject(Object.assign(new u(`settings_not_applied: ${E(ee.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:ye}));else if(ne.length>0)W.reject(Object.assign(new u(`option_not_applied: ${ne.join("; ")} — the prompt was sent and the session runs without these options`,"option_not_applied"),{claim:ye}));else W.resolve(ye)},(oe)=>{ze(),W.reject(oe)}),Se===void 0)return g.query(V);return Promise.all([Re,Se]).then(()=>{if(k)return;try{g.query(V)}catch{}},()=>{}),C},close(){if(k)return;if(k=!0,O)C.close();else g.close(),W.reject(Error("spare_closed: the spare was closed before it was claimed"));P()},async[Symbol.asyncDispose](){Ce.close(),await P()}};return Ce}async function Ei(e,i){let l=await import("./core-k67vj6j9.mjs");return l.getSessionInfo(e,i)}async function Pi(e,i,l){let c=await import("./core-sstebd83.mjs");return c.renameSession(e,i,l)}async function Di(e,i,l){let c=await import("./core-sstebd83.mjs");return c.tagSession(e,i,l)}async function Ti(e,i){let l=await import("./core-sstebd83.mjs");return l.archiveSession(e,i)}async function Ai(e,i){let l=await import("./core-sstebd83.mjs");return l.unarchiveSession(e,i)}async function Mi(e,i){let l=await import("./core-sstebd83.mjs");return l.deleteSession(e,i)}import{McpServer as xi}from"@modelcontextprotocol/sdk/server/mcp.js";import{normalizeObjectSchema as Ii}from"@modelcontextprotocol/sdk/server/zod-compat.js";import{toJsonSchemaCompat as Oi}from"@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";import{globalRegistry as vs}from"zod/v4";import{version as Ne}from"zod/v4/core";function Ki(e,i,l,c,p){let m={};if(p?.searchHint)m["anthropic/searchHint"]=p.searchHint;if(p?.alwaysLoad)m["anthropic/alwaysLoad"]=!0;return{name:e,description:i,inputSchema:l,handler:c,annotations:p?.annotations,_meta:Object.keys(m).length>0?m:void 0}}var Ui="CLAUDE_SDK_MCP_TOOL_SCHEMA_UNCONVERTIBLE";function Ni(e){let i=new xi({name:e.name,version:e.version??"1.0.0"},{capabilities:{tools:e.tools?{}:void 0},instructions:e.instructions});if(e.tools)e.tools.forEach((c)=>{let p=c.inputSchema;if(Fi(c.inputSchema)){let b=[];for(let[_,P]of Object.entries(c.inputSchema)){if(!Kt(P)){b.push([_,P]);continue}let O=qi(P),k=P.description;if(k&&!vs.has(O))vs.add(O,{description:k});b.push([_,O])}p=Object.fromEntries(b)}let m=i.registerTool(c.name,{description:c.description,inputSchema:p,annotations:c.annotations,_meta:e.alwaysLoad?{"anthropic/alwaysLoad":!0,...c._meta}:c._meta},c.handler);if(!Object.getOwnPropertyDescriptor(m,"enabled")?.configurable||!Object.isExtensible(m))return;let g=m.enabled,C,v;Object.defineProperty(m,"enabled",{configurable:!0,enumerable:!0,get(){if(!g||C===m.inputSchema)return g;try{let b=Ii(m.inputSchema);if(b)Oi(b,{strictUnions:!0,pipeStrategy:"input"});return C=m.inputSchema,!0}catch(b){if(v!==m.inputSchema){v=m.inputSchema;let _=Tn(E(b),"."),P=[`Tool "${c.name}" on SDK MCP server "${e.name}" was left out of the server's tool list, because its input schema cannot be converted to JSON Schema${_?`: ${_}`:""}. The server's other tools are unaffected.`,...Li(c.inputSchema,b)].join(" ");if(typeof process<"u"&&typeof process.emitWarning==="function")process.emitWarning(P,{code:Ui});else console.warn(P)}return!1}},set(b){g=b}})});let l=Ct(e.timeout);return{type:"sdk",name:e.name,instance:i,...l!==void 0&&{timeout:l}}}function Li(e,i){if(i instanceof ReferenceError)return["Something this tool's schema reads, such as a z.lazy target or a default value, is not defined yet. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back."];let p=`${Ne.major}.${Ne.minor}.${Ne.patch}`,m=Object.values(e).filter(Kt).map((_)=>_._zod?.version).find((_)=>typeof _?.major==="number"&&(_.major!==Ne.major||_.minor!==Ne.minor||_.patch!==Ne.patch)),y=m&&`this tool's schema was built with zod ${m.major}.${m.minor}.${m.patch}, and this SDK converts schemas with its own zod ${p}`,g=`${Ne.major}.${Ne.minor}`;if(!(i instanceof TypeError)){let _=["Change this tool's schema so that every field can be converted."];if(y)_.push(`A different zod version can also cause this: ${y}, so building the schema with zod ${g} may fix it.`);return _}let C="a schema this tool uses is not defined yet, or a zod 3 schema is nested inside a zod 4 one. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). Build the whole schema with zod 3 or with zod 4, not a mix of the two. A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back.";if(!m)return[`This can mean ${C}`];let v=[`The zod versions differ: ${y}. Conversion can fail across versions, so build the schema with zod ${g}, or use an SDK release that bundles your zod version.`],b=m.major===4&&m.minor<=3;if(b)v.push(`On zod ${m.major}.${m.minor}, a z.record given only one argument also causes this; pass both, as in z.record(keySchema, valueSchema).`);return v.push(`If ${b?"neither is the cause":"the version difference is not the cause"}, it can mean ${C}`),v}function Kt(e){return typeof e==="object"&&e!==null&&"_zod"in e}function Fi(e){return typeof e==="object"&&e!==null&&!("_zod"in e)&&!("_def"in e)&&typeof e.parse!=="function"}function qi(e){if(!(zi(e)?!je(e,!0):Ot(e)&&!je(e,!1))||e._zod.optin!=="optional"||e._zod.optout!=="optional"||typeof e.clone!=="function")return e;let l=e.clone();return l._zod.optin="defaulted",l}function zi(e){let i=e._zod.version;return i?.major===4&&i.minor<5}function je(e,i,l=new Set){if(!Kt(e)||l.has(e))return!1;l.add(e);let c=e._zod.def;switch(c.type){case"lazy":return!0;case"optional":return!i&&je(c.innerType,i,l);case"nullable":case"catch":case"readonly":return je(c.innerType,i,l);case"pipe":return je(c.in,i,l)||je(c.out,i,l);case"union":return c.options?.some((p)=>je(p,i,l))??!1;default:return!1}}function Ot(e,i=new Set){if(!Kt(e)||i.has(e))return!1;i.add(e);let l=e._zod.def;switch(l.type){case"default":case"prefault":return!0;case"optional":case"nullable":case"catch":case"readonly":return Ot(l.innerType,i);case"pipe":return Ot(l.in,i);case"union":return l.options?.some((c)=>Ot(c,i))??!1;default:return!1}}async function Hi(e){let{resolveSettingsForSdk:i}=await import("./core-y6bhrwmk.mjs");return i(e)}var ji=new Set(["bypassPermissions","auto","acceptEdits"]),Bi=new Set(["project"]),Gi=new Set(["project","local"]);function $i(e){let i=e.effective.permissions?.defaultMode;if(!i||!ji.has(i))return e.effective;for(let l=e.sources.length-1;l>=0;l--){let c=e.sources[l];if(c.settings.permissions?.defaultMode!==void 0){if((Yn.includes(i)?Gi:Bi).has(c.source)){let{defaultMode:m,...y}=e.effective.permissions??{};return{...e.effective,permissions:y}}return e.effective}}return e.effective}async function Wi(e,i){let{matchDeniedModelsForSdk:l}=await import("./core-ba5rrckm.mjs");return l(e,i)}export{Ke as AbortError,kn as BUILTIN_TOOL_NAMES,Qn as EXIT_REASONS,X as HOOK_EVENTS,Ye as LEGACY_TOOL_NAME_ALIASES,Lo as ORG_POLICY_LIMIT_PREFIXES,er as SYSTEM_PROMPT_DYNAMIC_BOUNDARY,No as USAGE_LIMIT_ERROR_PREFIXES,qo as USAGE_TRANSITION_PREFIXES,Fo as USAGE_WARNING_PREFIXES,Ti as archiveSession,Ni as createSdkMcpServer,Mi as deleteSession,$i as filterEscalatingDefaultMode,Ei as getSessionInfo,Wi as matchDeniedModels,ki as prewarm,Ri as query,Pi as renameSession,Hi as resolveSettings,wi as startup,Di as tagSession,Ki as tool,Ai as unarchiveSession};
|
|
16
|
+
import{me,d,f,s,a,Q,c,Gt,v,Tn,U,h,r,Ue,wn,_,jt,Fe,D,F,Se,R,oe,Be,j,yt,C,o,S,se,tn,we,Hn,t,P,ve,le,kt,ot,T,n,vt,Wn,rn,on,zn,Ce,sn,Vn,N,w,dn,B,Yn,cn,nr,xt,q,rr,or,Xn}from"./core-0vfvgmex.mjs";import{execFile as hi}from"child_process";import{randomUUID as mi}from"crypto";import{lstat as gi,mkdir as gt,mkdtemp as _i,readFile as Si,rm as Es,writeFile as ws}from"fs/promises";import{createRequire as yi}from"module";import{homedir as _t,tmpdir as Ci}from"os";import{dirname as ys,isAbsolute as Tr,join as Z,posix as ks,resolve as St,sep as bi,win32 as Rs}from"path";import{fileURLToPath as vi}from"url";import{setMaxListeners as Xs}from"events";var Zs=50;function ct(e=Zs){let i=new AbortController;return Xs(e,i.signal),i}var fa=new FinalizationRegistry(({parentSignalRef:e,handler:i})=>{e.deref()?.removeEventListener("abort",i)});var ha=new s(()=>new Set);var Js="ask-withdrawn-by-asker",ma=new DOMException(Js,"AbortError");var eo="call-cut-by-plugin",ga=new DOMException(eo,"AbortError");var _a={"user-cancel":new DOMException("user-cancel","AbortError"),"remote-cancel":new DOMException("remote-cancel","AbortError"),shutdown:new DOMException("shutdown","AbortError"),interrupt:new DOMException("interrupt","AbortError"),"turn-abort":new DOMException("turn-abort","AbortError"),background:new DOMException("background","AbortError"),"refusal-fallback-edit":new DOMException("refusal-fallback-edit","AbortError"),"recovery-timeout":new DOMException("recovery-timeout","AbortError"),"permission-stop":new DOMException("permission-stop","AbortError")};var to="server-fallback-tombstone";var Sa=new DOMException(to,"AbortError");var ro="subagent-park",ya=new DOMException(ro,"AbortError");import{spawn as yo}from"child_process";import{existsSync as Co}from"fs";import{createInterface as bo}from"readline";import{StringDecoder as vo}from"string_decoder";class De extends Error{}var no=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var tr={bearer:[/\bBearer\s+(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%[0-9A-Fa-f]{2}){7})[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]+|%[0-9A-Fa-f]{2})*/gi,"Bearer <token>"],basic:[/(:\s*)Basic\s+[A-Za-z0-9+/=]{8,}/gi,"$1Basic <token>"],sk:[/\bsk-[A-Za-z0-9_-]{20,}/g,"<token>"]},so=[/\bBearer\s{1,512}(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){15})(?:eyJ|(?=(?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){0,64}[0-9=]))/i,/:\s{0,512}Basic\s{1,512}(?=[A-Za-z0-9+/=]{16})(?=[A-Za-z0-9+/=]{0,64}[0-9=])/i,/\bsk-(?=[A-Za-z0-9_-]{20})(?=[A-Za-z0-9_-]{0,64}[0-9])/];var va=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${Xe("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${Xe("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),qr=[[ut("sk-ant-","[A-Za-z0-9_-]",8,sr(8)),"<token>"],[ut("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,sr(20)),"<token>"]],Gr=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],oo=`(?:${Gr.join("|")})`,Wr=[[new RegExp(`(^|[^A-Za-z0-9+])${oo}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],Vr=[[ut("gh[opusr]_","[A-Za-z0-9]",20,Xe("[A-Za-z0-9]")),"<token>"],[/github_pat_[A-Za-z0-9_]{82,}/g,"<token>"],[/sq0(?:atp|csp)-[A-Za-z0-9_-]{22,}/g,"<token>"],[/(^|[^A-Za-z0-9+/])EAAA[A-Za-z0-9+/=%_-]{56,}/g,"$1<token>"],[ut("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,Xe("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[ut("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",Xe("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${Xe("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[no,"hooks.slack.com/<redacted>"]];var io=[new RegExp("(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*)((?:[A-Za-z0-9_-]*?-)??)ey[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*","g"),"$1<jwt>"],ao=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,Yr=[[/(^|[^A-Za-z0-9+_-])AIza[A-Za-z0-9_-]{35}(?![A-Za-z0-9+=_-])/g,"$1<token>"],[/(^|[^A-Za-z0-9+_-])GOCSPX-[A-Za-z0-9_-]{28}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],Qr=[[/(^|[^A-Za-z0-9+_-])[sr]k_(?:live|test|prod)_(?=[A-Za-z0-9]{0,64}[0-9])[A-Za-z0-9]{24,}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],lo=[tr.bearer,tr.basic,...qr,tr.sk,...Wr],co=[...Vr,io,...Yr,...Qr],Ea=[[new RegExp(`sk-${sr(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...Gr.map((e)=>[new RegExp(`${e}[A-Z2-7]{16}`,"g"),"<token>"]),[/AIza[\w-]{35}/g,"<token>"],[/GOCSPX-[\w-]{28,}/g,"<token>"],[/[sr]k_(?:live|test|prod)_[A-Za-z0-9]{24,}/g,"<token>"]];function pt(e){return[...lo,...co].reduce((i,[l,u])=>i.replace(l,u),String(e))}var wa=[...so,...[...qr,...Wr,...Vr,...Yr,...Qr].map(([e])=>new RegExp(e.source,e.flags.replaceAll("g",""))),ao];function ut(e,i,l,u,p="",m="",y="g"){let g=`${i}{${l},}${p}`;return new RegExp(`(?:\\b${e}${m}${g}|${e}${u}${g})`,y)}function Xe(e){return`(?=${e}{0,64}[0-9])`}function sr(e){return`(?=[A-Za-z0-9_-]{0,64}?(?=[A-Za-z0-9]{${e}})(?=[A-Za-z0-9]{0,64}[0-9])(?=[A-Za-z0-9]{0,64}[A-Za-z]))`}import{randomUUID as uo}from"crypto";import{join as Xr}from"path";class Zr{debugFilePath=void 0;initPromise=null;logStem=null}var po=new s(()=>new Zr);function Jr(){return po.of(R().host)}function en(e){if(e.initPromise)return e.initPromise;if(!yt("DEBUG_CLAUDE_AGENT_SDK"))return e.debugFilePath=null,e.initPromise=Promise.resolve(),e.initPromise;let i=Xr(C(),"debug");return e.logStem=`sdk-${uo()}`,e.debugFilePath=Xr(i,`${e.logStem}.txt`),process.stderr.write(`SDK debug logs: ${e.debugFilePath}
|
|
17
|
+
`),e.initPromise=import("./core-3h0s3zzg.mjs").then(({getStorageBackend:l})=>l().mkdir(i)).catch(()=>{}),e.initPromise}function fo(e){return e.logStem===null?null:{namespace:"log",sessionId:e.logStem,channel:"debug"}}function nn(){let e=Jr();return en(e),e.debugFilePath??null}function ae(e,i){let l=Jr();if(l.debugFilePath===null)return;let p=`${new Date().toISOString()} ${e}
|
|
18
|
+
`;en(l).then(()=>{if(i!==void 0){let m=fo(l);if(m!==null)i.append(m,[{data:p}]).catch(()=>{});return}if(l.debugFilePath){let m=l.debugFilePath;import("./core-3h0s3zzg.mjs").then(({getStorageBackend:y})=>y().append(m,p)).catch(()=>{})}})}function ho(e){let i=e.trim();return i.startsWith("{")&&i.endsWith("}")}var mo=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),go=new Set(["ripgrep","network.tlsTerminate"]),_o=new Set(["__proto__","constructor","prototype"]),So=["httpProxyPort","socksProxyPort"];function an(e,i,l=""){let u=P(e)?{...e}:{};for(let[p,m]of Object.entries(i)){if(_o.has(p)||m===void 0)continue;let y=l?`${l}.${p}`:p,g=Object.hasOwn(u,p)?u[p]:void 0;if(mo.has(y)&&Array.isArray(g)&&Array.isArray(m))u[p]=f([...g,...m]);else if(P(g)&&P(m)&&!go.has(y))u[p]=an(g,m,y);else u[p]=m}return u}function Et(e,i){let l={...e};if(!i)return l;let u=l.settings;if(u&&!ho(u))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let p={};if(u)try{p=S(u)}catch{}let m=an(p.sandbox,i),y=i.credentials?.files,g=i.filesystem!==void 0||Array.isArray(y)&&y.some((x)=>P(x)&&x.mode==="deny"),b=m.filesystem;if(g&&i.filesystem?.disabled===void 0&&P(b)&&b.disabled===!0)delete b.disabled;let A=i.network,k=A?.allowedDomains!==void 0||(A?.deniedDomains?.length??0)>0||A?.strictAllowlist===!0,E=m.network;if(k&&P(E)){for(let x of So)if(A?.[x]===void 0&&E[x]!==void 0)delete E[x]}if(i.enabled===!0&&m.failIfUnavailable===void 0)m.failIfUnavailable=!0;return l.settings=o({...p,sandbox:m}),l}function W(e,i){return`${e}=${i}`}function wt(e,i){let l=String(i);if(l.length>1&&l.startsWith("-"))return[W(e,l)];return[e,l]}function ln(e,i,l){e.push(...wt(`--${i}`,l))}var Eo=2000,ir=2048,fn="sdk-exit-after-stderr-drained",wo=200;function ar(e){return e==="exit"?fn:e}class hn{#e=new Set;#t=!1;#r=()=>this.killAll();track(e){if(this.#e.add(e),!this.#t)this.#t=!0,process.on("exit",this.#r)}untrack(e){this.#e.delete(e)}isTracking(e){return this.#e.has(e)}get size(){return this.#e.size}killAll(){for(let e of this.#e)if(!e.killed)if(process.platform==="win32")try{e.stdin.end()}catch{}else e.kill("SIGTERM")}reset(){process.off("exit",this.#r),this.#t=!1,this.#e.clear()}}var Rt=new hn,ko=/[(),\u0000-\u001f\u007f-\u009f]/;function Ro(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!we(e))throw new c(`Invalid skill name ${o(e)}: the name contains an unpaired surrogate, which cannot survive the UTF-8 encoding of the CLI invocation; no skill discovered from the filesystem can have such a name.`,"skill name with unpaired surrogate rejected");if(e!==e.trim())throw new c(`Invalid skill name ${o(e)}: leading or trailing whitespace is not allowed — the Skill tool trims the invoked name, so a padded rule can never match. Remove the padding.`,"skill name with surrounding whitespace rejected");if(ko.test(e))throw new c(`Invalid skill name ${o(e)}: parentheses, commas, and control characters are not allowed in skill names. Skill names match the skill's directory name (or 'plugin:skill' for plugin-qualified skills); rename the skill if its directory name contains these characters.`,"invalid skill name rejected");if(e==="*")throw Error("Invalid skill name '*': use skills: 'all' to enable every skill.");if(e.endsWith(":*")||e.endsWith(" *"))throw new c(`Invalid skill name ${o(e)}: wildcard-suffix names are not allowed; list each skill by its exact name.`,"wildcard-suffix skill name rejected");if(e.startsWith("/"))throw new c(`Invalid skill name ${o(e)}: skill names may not start with '/'. Skills are invoked as slash commands, but the skills option takes the skill's canonical name — the directory name, or 'plugin:skill'.`,"skill name with leading slash rejected");if(e.includes("\\\\"))throw new c(`Invalid skill name ${o(e)}: consecutive backslashes are not allowed — the permission-rule parser collapses escaped backslashes, so the rule would name a different skill. Rename the skill.`,"skill name with consecutive backslashes rejected");if(e.endsWith("\\"))throw new c(`Invalid skill name ${o(e)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return e}class dr{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";abortHandler;forwardedAbort=ct();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||ct(),e.deferSpawn)this.spawnPromise=new Promise((i,l)=>{this.spawnResolve=i,this.spawnReject=l}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(i){throw this.spawnAbort(U(i)),i}let e=this.pendingWrites;if(this.pendingWrites=[],this.spawnResolve)this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0;for(let i of e)this.write(i);if(this.pendingEndInput)this.pendingEndInput=!1,this.processStdin?.end()}spawnAbort(e){if(this.spawnReject)this.spawnReject(e),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[]}updateEnv(e){if(this.options.env)Object.assign(this.options.env,e);else this.options.env={...e}}updateResume(e){this.options.resume=e}getDefaultExecutable(){return oe()?"bun":"node"}spawnLocalProcess(e){let{command:i,args:l,cwd:u,env:p,signal:m}=e,y=performance.now(),g=(this.options.hostSpawn??yo)(i,l,{cwd:u,stdio:["pipe","pipe","pipe"],signal:m,env:p,windowsHide:!0}),b=performance.now()-y;if(g.pid!==void 0&&this.options.onProcessSpawned)try{this.options.onProcessSpawned(g.pid,{spawnSyncMs:b})}catch(L){ae(`onProcessSpawned threw: ${h(L)}`)}let A=new vo("utf8"),k=!1,E=!1,x=!1,O,M=d(p.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;g.stderr.on("data",(L)=>{if(x)return;let G=A.write(L);if(this.stderrTail+=G,this.stderrTail.length>2*ir)this.stderrTail=tn(pt(this.stderrTail),ir);if(M)ae(G),this.options.stderr?.(G)}),g.stderr.on("error",(L)=>{ae(`[ProcessTransport] stderr read failed: ${L.code??L.message}`)});let H=()=>{if(x)return;if(x=!0,O)clearTimeout(O);g.emit(fn,g.exitCode,g.signalCode);let L=g.stderr;if(Po(L))L.unref();else L.destroy()};return g.stderr.once("close",()=>{if(this.stderrTail+=A.end(),k=!0,E)H()}),g.once("exit",()=>{if(E=!0,this.ready=!1,k)H();else O=setTimeout(H,wo)}),{stdin:g.stdin,stdout:g.stdout,get killed(){return g.killed},get exitCode(){return g.exitCode},get signalCode(){return g.signalCode},kill:g.kill.bind(g),on:(L,G)=>g.on(ar(L),G),once:(L,G)=>g.once(ar(L),G),off:(L,G)=>g.off(ar(L),G)}}initialize(){try{let{additionalDirectories:e=[],projectConfigRoot:i,agent:l,betas:u,cwd:p,executable:m=this.getDefaultExecutable(),executableArgs:y=[],extraArgs:g={},pathToClaudeCodeExecutable:b,env:A={...process.env},thinkingConfig:k,maxTurns:E,maxBudgetUsd:x,taskBudget:O,model:M,fallbackModel:H,jsonSchema:X,permissionMode:L,allowDangerouslySkipPermissions:G,permissionPromptToolName:de,permissionPrompts:V,continueConversation:K,resume:he,settingSources:pe,skills:ce,disallowedTools:Re=[],tools:Oe,mcpServers:ge,strictMcpConfig:Ae,canUseTool:tt,includePartialMessages:_e,plugins:Ke,pluginsViaInitialize:$e,sandbox:je}=this.options,{allowedTools:Te=[]}=this.options;if(ce!==void 0){let z=ce==="all"?["Skill"]:ce.map((te)=>`Skill(${Ro(te)})`),ne=new Set(Te);Te=[...Te,...z.filter((te)=>!ne.has(te))]}let I=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(k){switch(k.type){case"enabled":if(k.budgetTokens===void 0)I.push("--thinking=adaptive");else I.push(W("--max-thinking-tokens",k.budgetTokens));break;case"disabled":I.push("--thinking=disabled");break;case"adaptive":I.push("--thinking=adaptive");break}if(k.type!=="disabled"&&k.display)I.push(W("--thinking-display",k.display))}if(this.options.effort)I.push(W("--effort",this.options.effort));if(E)I.push(W("--max-turns",E));if(x!==void 0)I.push(W("--max-budget-usd",x));if(O)I.push(W("--task-budget",O.total));if(M)I.push(W("--model",M));if(l)I.push(W("--agent",l));if(u&&u.length>0)I.push(W("--betas",u.join(",")));if(X)I.push(W("--json-schema",o(X)));if(this.options.debugFile)I.push(W("--debug-file",this.options.debugFile));else if(this.options.debug)I.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let z=nn();if(z)I.push(W("--debug-file",z))}if(tt){if(de)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");I.push("--permission-prompt-tool=stdio")}else if(de)I.push(W("--permission-prompt-tool",de));if(V)I.push(W("--permission-prompts",V));if(K)I.push("--continue");if(he)I.push(W("--resume",he));if(this.options.channels&&this.options.channels.length>0)for(let z of this.options.channels)I.push(W("--channels",z));if(Te.length>0)I.push(W("--allowedTools",Te.join(",")));if(Re.length>0&&!this.options.disallowedToolsViaInitialize)I.push(W("--disallowedTools",Re.join(",")));if(Oe!==void 0)if(Array.isArray(Oe))I.push(W("--tools",Oe.join(",")));else I.push("--tools=default");if(ge&&Object.keys(ge).length>0&&!this.options.mcpServersViaInitialize)I.push(...wt("--mcp-config",o({mcpServers:ge})));if(pe!==void 0)I.push(W("--setting-sources",pe.join(",")));if(Ae)I.push("--strict-mcp-config");if(L)I.push(W("--permission-mode",L));if(G)I.push("--allow-dangerously-skip-permissions");if(H){if(M&&H===M)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");I.push(W("--fallback-model",H))}if(this.options.includeHookEvents)I.push("--include-hook-events");if(_e)I.push("--include-partial-messages");if(this.options.sessionMirror)I.push("--session-mirror");if(i!==void 0)I.push(W("--project-config-root",i));for(let z of e)I.push(W("--add-dir",z));if($e||this.options.managedSettingsViaInitialize||this.options.settingsViaInitialize||this.options.disallowedToolsViaInitialize||this.options.mcpServersViaInitialize||this.options.readsInitializeAtBoot)I.push("--await-initialize");if(!$e&&Ke&&Ke.length>0)for(let z of Ke)if(z.type==="local")I.push(z.skipMcpDiscovery?W("--plugin-dir-no-mcp",z.path):W("--plugin-dir",z.path));else throw Error(`Unsupported plugin type: ${z.type}`);if(this.options.forkSession)I.push("--fork-session");if(this.options.resumeSessionAt)I.push(W("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)I.push(W("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)I.push(W("--session-id",this.options.sessionId));if(this.options.persistSession===!1)I.push("--no-session-persistence");let be=[...this.options.settingsViaInitialize?["settings"]:[],...this.options.disallowedToolsViaInitialize?["disallowedTools"]:[]];if(be.length>0)I.push(W("--initialize-fields",be.join(",")));if(this.options.managedSettingsViaInitialize)I.push("--managed-settings-in-initialize");else if(this.options.managedSettings)I.push(...wt("--managed-settings",this.options.managedSettings));let Ve={...g??{}};if(this.options.settings)Ve.settings=this.options.settings;let Ie=Et(Ve,je);for(let[z,ne]of Object.entries(Ie))if(ne===null)I.push(`--${z}`);else ln(I,z,ne);if(!A.CLAUDE_CODE_ENTRYPOINT)A.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete A.NODE_OPTIONS,d(A.DEBUG_CLAUDE_AGENT_SDK))A.DEBUG="1";else delete A.DEBUG;let ue=Ao(b),ze=ue?b:m,ye=ue?[...y,...I]:[...y,b,...I],He={command:ze,args:ye,cwd:p,env:A,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)ae(`Spawning Claude Code (custom): ${ze} ${ye.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(He);else ae(`Spawning Claude Code: ${ze} ${ye.join(" ")}`),this.process=this.spawnLocalProcess(He);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(z)=>{ae(`[ProcessTransport] stdin write failed (child likely exited): ${z.code??z.message}`),this.ready=!1}),Rt.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let ee=this.process;ee.on("error",(z)=>{this.ready=!1;let ne=z,te=ne.syscall!==void 0?ne.syscall.startsWith("spawn"):jt(z);if(te&&!ee.killed)Rt.untrack(ee);if(this.abortController.signal.aborted)this.exitError=At(),v(z,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(te&&jt(z)){let{message:Me,telemetryMessage:Ee,errorClass:Ye}=To(b,ue),fe={telemetryMessage:`${Ee}${lr(z)}`,errorClass:Ye,code:Ue(z)};this.exitError=v(ReferenceError(Me),fe),v(z,fe),ae(this.exitError.message)}else{let Me={telemetryMessage:te?`Failed to spawn Claude Code process${lr(z)}`:`Claude Code process error${lr(z)}`,errorClass:te?"spawn_failed":"process_error",code:Ue(z)};this.exitError=v(Error(`Failed to spawn Claude Code process: ${pt(z.message)}`),Me),v(z,Me),ae(this.exitError.message)}}),ee.on("exit",(z,ne)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=At();else{let te=this.getProcessExitError(z,ne);if(te)this.exitError=te,ae(te.message)}}),this.ready=!this.abortController.signal.aborted}catch(e){throw this.ready=!1,e}}getProcessExitError(e,i){if(e!==0&&e!==null){let l=Number.isInteger(e)?e:void 0;return v(Error(`Claude Code process exited with code ${e}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process exited with code ${l??"unknown"}`,errorClass:"process_exited_nonzero",exitCode:l})}else if(i){let l=/^SIG[A-Z0-9]{1,8}$/.test(i)?i:"unknown";return v(Error(`Claude Code process terminated by signal ${i}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process terminated by signal ${l}`,errorClass:"process_killed_by_signal",signal:l})}return}formatStderrTail(){let e=tn(pt(this.stderrTail),ir).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw un();if(this.spawnResolve){this.pendingWrites.push(e);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){ae("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw v(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${Tn(this.exitError)??"untagged exit error"}`,errorClass:pn(this.exitError,"errorClass"),code:Ue(this.exitError),exitCode:Mo(this.exitError),signal:pn(this.exitError,"signal")});ae(`[ProcessTransport] Writing to stdin (${e.length} chars)`);try{if(!this.processStdin.write(e))ae("[ProcessTransport] Write buffer full, data queued")}catch(i){throw this.ready=!1,Error(`Failed to write to process stdin: ${h(i)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?At():Error("Query closed before spawn")),this.processStdin)this.processStdin.end(),this.processStdin=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;let e=this.process?.exitCode??null,i=this.process?.signalCode??null;if(!this.exitEventDelivered&&(e!==null&&e>=0||i!==null)){this.exitEventDelivered=!0;let m=this.abortController.signal.aborted?At():this.getProcessExitError(e,i);if(m&&!this.exitError)this.exitError=m}let u=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},p=this.process;if(p&&!p.killed&&p.exitCode===null&&p.signalCode==null)setTimeout((m,y)=>{if(m.exitCode!==null||m.signalCode!=null){y();return}if(process.platform==="win32"){setTimeout((g,b)=>{if(g.exitCode===null)g.kill("SIGKILL");b()},5000,m,y).unref();return}m.kill("SIGTERM"),setTimeout((g)=>{if(g.exitCode===null)g.kill("SIGKILL")},5000,m).unref(),y()},Eo,p,u).unref(),p.once("exit",()=>Rt.untrack(p));else if(p)Rt.untrack(p),u();this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise)await this.spawnPromise,this.spawnPromise=void 0;if(!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let e=bo({input:this.processStdout}),i=this.process?(()=>{let l=this.process,u=()=>e.close();return l.on("error",u),()=>l.off("error",u)})():void 0;if(this.exitError)e.close();try{for await(let l of e)if(l.trim()){let u;try{u=S(l)}catch(p){ae(`Non-JSON stdout: ${l}`);continue}yield u}if(this.exitError)throw this.exitError;await this.waitForExit()}finally{i?.(),e.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}if(this.processStdin)this.processStdin.end()}async waitForExit(){if(this.exitError)throw this.exitError;if(!this.process||this.process.exitCode===0||this.process.killed&&this.exitEventDelivered)return;return new Promise((e,i)=>{let l=(p,m)=>{if(this.abortController.signal.aborted){i(un());return}let y=this.getProcessExitError(p,m);if(y)i(y);else e()};this.process.once("exit",l);let u=(p)=>{this.process.off("exit",l),i(p)};this.process.once("error",u),this.process.once("exit",()=>{this.process.off("error",u)})})}}function Ao(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((l)=>e.endsWith(l))}function To(e,i){let l=i?"native binary":"executable",u=pt(e);if(Co(e))return{message:i?`Claude Code native binary at ${u} exists but failed to launch. This usually means the binary does not match this system's libc — e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${u} exists but failed to launch.`,telemetryMessage:`Claude Code ${l} exists at the configured path but failed to launch`,errorClass:"executable_launch_failed"};return{message:i?`Claude Code native binary not found at ${u}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${u}. Is options.pathToClaudeCodeExecutable set?`,telemetryMessage:`Claude Code ${l} not found at the configured path`,errorClass:"executable_not_found"}}function lr(e){let i=Ue(e);return i===void 0?"":` (${i})`}function At(){return v(new De("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function un(){return v(new De("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function pn(e,i){let l=Object.hasOwn(e,i)?Reflect.get(e,i):void 0;return typeof l==="string"?l:void 0}function Mo(e){let i=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof i==="number"?i:void 0}function Po(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as xo}from"fs";var Ze="@anthropic-ai/claude-agent-sdk";function Oo(){if(process.platform!=="linux")return!1;let e=typeof process.report?.getReport==="function"?process.report.getReport():null;return e!=null&&e.header?.glibcVersionRuntime===void 0}function mn(e,i={}){let l=i.platform??process.platform,u=i.arch??process.arch,p=i.exists??xo,m=i.preferMusl??Oo(),y="claude",g=l==="win32"?".exe":"",A=(l==="android"?[`${Ze}-linux-${u}-android`]:l==="linux"?m?[`${Ze}-linux-${u}-musl`,`${Ze}-linux-${u}`]:[`${Ze}-linux-${u}`,`${Ze}-linux-${u}-musl`]:[`${Ze}-${l}-${u}`]).map((k)=>`${k}/claude${g}`);for(let k of A)try{let E=e(k);if(p(E))return E}catch{}return null}function gn({supportedDialogKinds:e,onUserDialog:i}){if(e!==void 0&&e.length>0&&!i)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.")}function _n({hooks:e,jsonSchema:i,initConfig:l}){let u="hooks";try{let p={hooks:Object.entries(e??{}).map(([m,y])=>{if(!y)return[];if(!Array.isArray(y))throw new c(`hooks.${m} must be an array of matchers`,"A hook event is not an array of matchers");return y.map((g,b)=>{if(!Array.isArray(g?.hooks))throw new c(`hooks.${m}[${b}].hooks must be an array of callbacks`,"A hook matcher's hooks are not an array");return{matcher:g.matcher,timeout:g.timeout,onFailure:g.onFailure,whenUnanswered:g.whenUnanswered}})}),"outputFormat or jsonSchema":i,...l};for(let[m,y]of Object.entries(p))u=m,o(y)}catch(p){let[m]=h(p).split(`
|
|
19
|
+
`);throw new c(`The session was not started, because the ${u} option can't be sent to Claude Code: ${m?.replace(/\.$/,"")}. Fix that value and try again.`,"The session was not started: its initialize request can't be sent")}}var Io=["signed_out","identity_changed","transient","refresh_failed"];function Sn(e){return Io.some((i)=>i===e)}var Tt=600000;var yn=600000,Mt=["SessionStart","Setup"];var Pt=60000,Cn=yn,bn=Pt+Cn,Do="startupHooksOpen",No=64;class cr{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(e,i=Fe,l){this.clock=i;this.onRunning=l;this.limitMs=e??Pt,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=e==null?Cn:0}race(e){let i=new Promise((l,u)=>{this.rejectExpired=u});return this.arm(),Promise.race([e,i]).finally(()=>this.end())}note(e){if(this.rejectExpired===void 0||e.type!=="system")return;switch(e.subtype){case"hook_started":if(!Mt.includes(e.hook_event)||this.followed.has(e.hook_id))return;if(this.followed.size<No)this.followed.add(e.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(e.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(e.hook_id)){if(this.unfollowedOpen===0||!Mt.includes(e.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let e=Math.min(this.countedLeftMs,ve);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=e,this.countedLeftMs>0)this.arm();else this.expire()},e)}countAgain(){let e=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=e,this.uncountedMs+=e,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let e=this.rejectExpired,i=`Subprocess initialization did not complete within ${this.limitMs}ms`,l=Mt.join(" or "),u=Math.round(this.uncountedMs/1000),p=this.open(),m=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${se(this.reported,"hook")}`,y=[`${i}.`,...u>0?[`Not counted: ${u} ${se(u,"second")} in which Claude Code reported a ${l} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${l} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:p===0?`Claude Code reported ${m}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${m}, ${this.reported===1?"which had not finished":p===this.reported?"none of which had finished":`${p} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],g=Object.assign(v(Error(y.join(" ")),{telemetryMessage:i,errorClass:"initialize_timeout"}),{[Do]:p});this.end(),e?.(g)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}var vn="SDK MCP server not found";var En="No hook callback found for ID";class ur{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}get ended(){return this.isDone}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((e,i)=>{this.readResolve=e,this.readReject=i})}get readerIsWaiting(){return this.readResolve!==void 0&&!this.isDone}enqueue(e){if(this.readResolve){let i=this.readResolve;this.readResolve=void 0,this.readReject=void 0,i({done:!1,value:e})}else this.queue.push(e)}dropNewestQueued(e){let i=this.queue.findLastIndex(e);if(i!==-1)this.queue.splice(i,1)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let i=this.readReject;this.readResolve=void 0,this.readReject=void 0,i(e)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var pr="startup_mark",kn="startupMark",Rn="startupMarkAgeMs",An=64;function Mn(e){return"method"in e&&"id"in e&&e.id!==null}var Pn=Object.freeze({}),xn=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),bl=Symbol("swallow");class fr{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var On=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var In="2025-11-25";var Lo="notifications/tools/list_changed";function Dn(e){return n(e)&&!("id"in e)&&e.method===Lo}class Ot extends Gt{errorCode;constructor(e,i,l,u){super(e,i,u);this.errorCode=l}}var Nn=250,Ko=new Set(["interrupt","cancel_async_message"]),Fo=new Set(["initialize","get_binary_version"]),Uo="CLAUDE_SDK_MCP_SERVERS_NOT_APPLIED",It="sdk-manifest-capture:",qe=Symbol("suppressControlResponse");function Ln(e,i,l){for(let u of l){let p=u==="tools"?on(i):void 0;t(p?`[Query] MCP server '${e}': ${zn(p)}`:`[Query] MCP server '${e}': ignoring malformed ${u} in its config`)}}class Dt{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;runEndCeilingMs;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new ur;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;hostMatcherOf=new WeakMap;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;promptHold;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;lastStartupFailureReason;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,i){let l={type:"system",subtype:"mirror_error",error:i,key:e,uuid:me(),session_id:e.sessionId};this.inputStream.enqueue(l)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpServers.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0||this.workSecretAnswerer!==void 0}remoteControlCallGeneration=0;uiHost;workSecretAnswerer;constructor(e,i,l,u,p,m=new Map,y,g,b,A,k,E,x=!1,O=Tt){this.transport=e;this.isSingleUserTurn=i;this.canUseTool=l;this.hooks=u;this.abortController=p;this.jsonSchema=y;this.initConfig=g;this.onElicitation=b;this.getOAuthToken=A;this.getHostAuthToken=k;this.onUserDialog=E;this.verbatimPrompts=x;this.runEndCeilingMs=O;for(let[M,H]of m)this.connectSdkMcpServer(M,H);if(this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((M)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,M()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{}),this.hasHookSetToBlock()||this.sendsLaunchFields()){let M=this.hasHookSetToBlock()?Error('Claude Code did not answer initialize, so a hook set to onFailure: "block" could not be confirmed and the prompt was not sent. Check the connection and start a new session.'):this.initConfig?.managedSettings!==void 0?Error("Claude Code did not answer initialize, so the managed settings could not be confirmed and the prompt was not sent. Start a new session."):this.initConfig?.settings!==void 0||this.initConfig?.disallowedTools!==void 0?Error("Claude Code did not answer initialize, so the settings or disallowedTools sent in it could not be confirmed and the prompt was not sent. Start a new session."):void 0,H=M===void 0?void 0:setTimeout((X)=>void this.cleanup(X),bn,M);H?.unref?.(),this.promptHold=this.initialization.then(()=>(clearTimeout(H),!0),(X)=>(clearTimeout(H),this.cleanup(X),!1)),this.writeBehindPromptHold(this.promptHold,()=>{})}}writeBehindPromptHold(e,i){let l=e.then(async(p)=>{if(!p||this.abortController?.signal.aborted)return!1;return await i(),!0}),u=l.catch(()=>!0).then((p)=>{if(p&&this.promptHold===u)this.promptHold=void 0;return p});return this.promptHold=u,l}hasHookSetToBlock(){return Object.values(this.hooks??{}).some((e)=>Array.isArray(e)&&e.some((i)=>i?.onFailure!=null&&i.onFailure!=="continue"))}sendsLaunchFields(){return this.initConfig?.managedSettings!==void 0||this.initConfig?.settings!==void 0||this.initConfig?.disallowedTools!==void 0||this.initConfig?.mcpServers!==void 0}setError(e){this.inputStream.error(e)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((i)=>i.type==="system"&&i.subtype==="hook_progress"&&i.hook_id===e&&i.backgrounded!==!0)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let i of this.cleanupCallbacks)try{i()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let i of this.cancelControllers.values())i.abort();this.cancelControllers.clear(),this.transport.close()}catch(i){t(`[Query.cleanup] transport.close() failed: ${h(i)}`,{level:"error"})}try{let i=e??hr();for(let{reject:l}of this.pendingControlResponses.values())l(i);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:l}of this.pendingMcpResponses.values())l(i);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:l}of this.sdkMcpServers.values())l.close().catch(()=>{});if(this.sdkMcpServers.clear(),e)this.inputStream.error(e);else this.inputStream.done()}catch(i){}if(this.transport.waitForExit){let i=new AbortController;try{await Promise.race([this.transport.waitForExit(),D(2000,i.signal)])}catch{}finally{i.abort()}}}next(...[e]){return this.sdkMessages.next(...[e])}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let i=this.pendingControlResponses.get(e.response.request_id);if(i)i.handler(e.response);else{if(this.unmatchedControlResponses.size>=Dt.UNMATCHED_CONTROL_RESPONSES_MAX){let l=this.unmatchedControlResponses.keys().next().value;if(l!==void 0)this.unmatchedControlResponses.delete(l)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive"){if(pr in e){let i=e[pr];if(typeof i==="string"&&i.length<=An)this.startupMark={mark:i,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let i=e.is_error?e.subtype==="success"?e.result:e.errors.map((l)=>l.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=i||void 0,this.lastStartupFailureReason=e.is_error&&"startup_failure_reason"in e&&typeof e.startup_failure_reason==="string"?e.startup_failure_reason:void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else if(!(e.type==="system"&&(e.subtype==="session_writes_lost"||e.subtype==="plugin_install"))){if(this.lastErrorResultText=void 0,this.lastStartupFailureReason=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(e)}catch(i){t(`[Query.readMessages] The frame observer threw: ${h(i)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let i=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(i!==void 0&&!(e instanceof De)&&e?.name!=="SSEHttpError"){let l=v(Error(`Claude Code returned an error result: ${i}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result",startupFailureReason:this.lastStartupFailureReason});t(`[Query.readMessages] Replacing exit error with result text. Original: ${h(e)}`),this.inputStream.error(l),this.cleanup(l);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){t(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){t(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let i=new AbortController;this.cancelControllers.set(e.request_id,i);try{let l;try{let u=await this.processControlRequest(e,i.signal);if(this.cleanupPerformed)return;if(u===qe)return;let p={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:u}};l=o(p)+`
|
|
20
|
+
`}catch(u){if(this.cleanupPerformed)return;let p={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:h(u),...u instanceof Ot&&{error_code:u.errorCode}}};l=o(p)+`
|
|
21
|
+
`}try{await Promise.resolve(this.transport.write(l))}catch(u){t(`[Query.handleControlRequest] Response write failed: ${h(u)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===i)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let i=this.cancelControllers.get(e.request_id);if(i)i.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,i){if(On.some((l)=>l===e.request.subtype))return t(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),qe;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let l=e.request.computer_folder,u=await this.canUseTool(e.request.tool_name,e.request.input,{signal:i,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof l==="object"&&l!==null&&"path"in l&&typeof l.path==="string"&&"computer_name"in l&&typeof l.computer_name==="string"&&{computerFolder:{path:l.path,computer_name:l.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(u===null)return qe;return{...u,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback"){if(!this.initializeHasBeenWritten){if(await this.initializeWritten,this.cleanupPerformed||i.aborted)return qe}return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,i)}else if(e.request.subtype==="mcp_message"){let l=e.request,u=this.sdkMcpServers.get(l.server_name)?.transport;if(!u)throw Error(`${vn}: ${l.server_name}`);if(Mn(l.message))return{mcp_response:await this.handleMcpControlRequest(l.server_name,l,u)};else{if(u.onmessage)u.onmessage(l.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let l=e.request;if(this.onElicitation){let u=await this.onElicitation({serverName:l.mcp_server_name,message:l.message,mode:l.mode,url:l.url,elicitationId:l.elicitation_id,requestedSchema:l.requested_schema,title:l.title,displayName:l.display_name,description:l.description},{signal:i,requestId:e.request_id});if(u===null)return qe;return u}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let l=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:i,requestId:e.request_id});if(l===null)return qe;return l}return t(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),le("tengu_request_user_dialog_response_ignored",{shape:Q("auto_cancel")}),qe}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let l,u=await this.getOAuthToken({signal:i,onDecline:(p)=>{if(Sn(p))l=p},...e.request.kind!==void 0&&{kind:e.request.kind},...(e.request.token_state==="refused"||e.request.token_state==="not_refused")&&{tokenState:e.request.token_state},...e.request.token_state==="refused"&&(e.request.refused_call==="model"||e.request.refused_call==="connector"||e.request.refused_call==="other")&&{refusedCall:e.request.refused_call},...Array.isArray(e.request.refused_bearer_sha256)&&{refusedBearerSha256:e.request.refused_bearer_sha256}})??null;return u===null&&l!==void 0?{accessToken:u,reason:l}:{accessToken:u}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let l=await this.getHostAuthToken({signal:i,status:e.request.status,...e.request.token_state==="not_refused"&&{tokenState:e.request.token_state}})??null;return typeof l==="string"||l===null?{authToken:l}:l}else if(e.request.subtype==="remote_control_work_secret"){let l=this.workSecretAnswerer;if(!l)throw Error("refreshWorkSecret callback is not provided.");if(!Fn(l.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await l.refresh(l.sessionId,{signal:i})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:l,...u}=e.request;return this.uiHost.copy(u,{signal:i})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:l,...u}=e.request;return this.uiHost.promptRead(u,{signal:i})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:l,...u}=e.request;return this.uiHost.promptFill(u,{signal:i})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:l,...u}=e.request;return this.uiHost.promptPaint(u,{signal:i})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:l,...u}=e.request;return this.uiHost.promptSuggest(u,{signal:i})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:l,...u}=e.request;return this.uiHost.readSelection(u,{signal:i})}throw new Ot("Unsupported control request subtype: "+e.request.subtype,"Unsupported control request subtype","unsupported_request")}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let i,l;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){i=await this.captureSdkMcpServerManifests();for(let g of this.sdkMcpToolsChangedDuringCapture){let b=i!==void 0&&Object.hasOwn(i,g)?i[g]:void 0;if(b?.toolsListResult!==void 0)i[g]={initializeResult:b.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let y=this.buildInitializeRequest(i);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{l=this.request(y)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let p=(await l).response;if(this.hasHookSetToBlock()){let y=p.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&p.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(y!==void 0)throw this.cleanup(y),y}if(this.initConfig?.managedSettings!==void 0&&p.managed_settings_applied!==!0){let y=Error("Claude Code did not confirm the managed settings sent with managedSettingsDelivery 'initialize', so the session was ended and no further prompt was sent. For a cloud session, use 'argv', because it does not read this delivery. Otherwise check that no wrapper changes the launch flags or the initialize request.");throw this.cleanup(y),y}let m=[...this.initConfig?.settings!==void 0&&p.settings_applied!==!0?["settings"]:[],...this.initConfig?.disallowedTools!==void 0&&p.disallowed_tools_applied!==!0?["disallowedTools"]:[]];if(m.length>0){let y=Error(`Claude Code did not confirm the ${m.join(" and ")} sent in the initialize request, so the session was ended and no further prompt was sent. For a cloud session, set settingsDelivery and disallowedToolsDelivery to 'argv', because a cloud session does not read them from that request. Otherwise update Claude Code if it is older than this Agent SDK, and check that no wrapper changes the launch flags or the initialize request.`);throw this.cleanup(y),y}if(this.initConfig?.mcpServers!==void 0){let y=p.mcp_servers_applied;if(typeof y!=="boolean"){let g=typeof p.claude_code_version==="string"?` (version ${p.claude_code_version})`:"",b=new c(`This Claude Code${g} is too old to read MCP servers from the initialize request, so it started without them. The session was ended and no further prompt was sent. Use the Claude Code bundled with this SDK, update the one you start (pathToClaudeCodeExecutable or spawnClaudeCodeProcess) to at least the bundled version, or set mcpServersDelivery: 'argv', which puts the servers' env and headers on Claude Code's command line, where other users of the machine can read them.`,"Claude Code too old to read MCP servers from initialize");throw this.cleanup(b),b}if(!y&&e&&typeof process<"u")process.emitWarning("Claude Code reported that it did not load the MCP servers sent in the initialize request, so this session may be running without them. A cloud session never starts them; otherwise check that no wrapper removes --await-initialize from the launch.",{code:Uo})}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&p.plugins_applied!==!0)t(`[Query.initialize] Claude Code reported plugins_applied=${String(p.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent in the initialize request; the process is running with the plugins it was launched with.`,{level:"warn"});return p}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[m,y]of Object.entries(this.hooks))if(y?.length>0)this.initHooksPayload[m]=y.map((g)=>{let b=[];for(let k of g.hooks){let E=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(E,k),b.push(E)}let A={matcher:g.matcher,hookCallbackIds:b,timeout:g.timeout,onFailure:g.onFailure,contextOnly:g.contextOnly,replacedByFrame:g.replacedByFrame};return this.hostMatcherOf.set(A,g),A})}for(let m of Object.values(this.initHooksPayload??{}).flat())m.whenUnanswered=this.hostMatcherOf.get(m)?.whenUnanswered;let i=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,l=Array.from(this.sdkMcpServers).flatMap(([m,{settings:y}])=>Object.keys(y).length>0?[[m,y]]:[]),u=l.length>0?Object.fromEntries(l):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:i,sdkMcpServerConfigs:u,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins,managedSettings:this.initConfig?.managedSettings,settings:this.initConfig?.settings,disallowedTools:this.initConfig?.disallowedTools,mcpServers:this.initConfig?.mcpServers}}async captureSdkMcpServerManifests(){let e=performance.now(),i=new Map,l=!1,u=async(E,x)=>{try{if(await this.sdkMcpServers.get(E)?.connection,l)return;let O=await this.handleMcpControlRequest(E,{server_name:E,message:{jsonrpc:"2.0",id:It+"initialize",method:"initialize",params:{protocolVersion:In,capabilities:Pn,clientInfo:{...xn,version:"0.3.328"}}}},x);if(l)return;if(!("result"in O)){t(`[Query.captureSdkMcpServerManifests] '${E}' answered initialize with an error; leaving it to the CLI: ${o(O)}`,{level:"warn"});return}let M=O.result;x.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let H=M.capabilities,X=typeof H==="object"&&H!==null&&"tools"in H&&H.tools!==void 0&&H.tools!==null,L;if(X){let V=await this.handleMcpControlRequest(E,{server_name:E,message:{jsonrpc:"2.0",id:It+"tools-list",method:"tools/list"}},x);if(l)return;if(!("result"in V)){t(`[Query.captureSdkMcpServerManifests] '${E}' answered tools/list with an error; leaving it to the CLI: ${o(V)}`,{level:"warn"});return}if(V.result.nextCursor===void 0)L=V.result}let de=S(o(L===void 0?{initializeResult:M}:{initializeResult:M,toolsListResult:L}));i.set(E,{transport:x,manifest:de})}catch(O){if(!l)t(`[Query.captureSdkMcpServerManifests] '${E}': ${O}; the CLI will handshake it over the control channel`,{level:"warn"})}},p=Array.from(this.sdkMcpServers,([E,{transport:x}])=>u(E,x)),m=Promise.all(p).then(()=>"settled"),y=new Promise((E)=>{this.stopSdkMcpManifestCapture=()=>E("closed")}),g=await Se(Promise.race([m,y]),Nn);l=!0,this.stopSdkMcpManifestCapture=void 0;let b=Math.round(performance.now()-e),A={servers:p.length,captured:i.size,elapsed_ms:b};if(g==="closed"){ot("sdk_mcp_manifest_capture","closed",A);return}if(g===void 0)t(`[Query.captureSdkMcpServerManifests] ${i.size}/${p.length} in-process MCP servers captured within ${Nn} ms; the rest will handshake over the control channel`,{level:"warn"}),ot("sdk_mcp_manifest_capture","deadline",A);else if(i.size<p.length)ot("sdk_mcp_manifest_capture","partial",A);else kt("sdk_mcp_manifest_capture",A);if(i.size===0)return;let k=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([E,x])=>{let O=i.get(E);return O!==void 0&&O.transport===x.transport?[[E,O.manifest]]:[]}));if(Object.keys(k).length===0)return;return t(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(k).join(", ")}] captured in ${b} ms`),k}async interrupt(e){return T("sdk_interrupt",async()=>{let i=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),l=i.response?.still_queued;if(!Array.isArray(l))return;let u=i.response?.cancelled;return{still_queued:l.filter((p)=>typeof p==="string"),...Array.isArray(u)&&{cancelled:u.filter((p)=>typeof p==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,i){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:i})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((i,l)=>{let u=(m)=>{if(m.subtype==="success"){let{pending_permission_requests:y,pending_user_dialog_requests:g,pending_elicitation_requests:b,...A}=m;i(A)}else{let y=new c(m.error,"awaitControlResponse: CLI error verdict");l(v(y,{telemetryMessage:y.telemetryMessage,errorCode:Kn(m.error_code)}))}if(m.pending_permission_requests||m.pending_user_dialog_requests||m.pending_elicitation_requests)t("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){l(hr());return}let p=this.unmatchedControlResponses.get(e);if(p){this.unmatchedControlResponses.delete(e),u(p);return}this.pendingControlResponses.set(e,{handler:(m)=>{this.pendingControlResponses.delete(e),u(m)},reject:l})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,i){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:i})}async applyFlagSettings(e){return T("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,i){return T("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:i})})}async rewindFiles(e,i){return T("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:i?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,i){await this.request({subtype:"seed_read_state",path:e,mtime:i})}async setCwd(e,i){return T("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...i?.trustAccepted!==void 0&&{trust_accepted:i.trustAccepted},...i?.trustedDirectory!==void 0&&{trusted_directory:i.trustedDirectory}})).response)}async claimSession(e){let i=T("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),l=this.initialization;return this.initialization=i.then(async(u)=>{if(u?.initialize===void 0)return l;let p=u.initialize,m=await l.then((O)=>({hooks_applied:O.hooks_applied,plugins_applied:O.plugins_applied,managed_settings_applied:O.managed_settings_applied,settings_applied:O.settings_applied,disallowed_tools_applied:O.disallowed_tools_applied,mcp_servers_applied:O.mcp_servers_applied,code_running_mcp_tools_applied:O.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,managed_settings_applied:void 0,settings_applied:void 0,disallowed_tools_applied:void 0,mcp_servers_applied:void 0,code_running_mcp_tools_applied:void 0})),y=p.hooks_applied??m.hooks_applied,g=p.plugins_applied??m.plugins_applied,b=p.managed_settings_applied??m.managed_settings_applied,A=p.settings_applied??m.settings_applied,k=p.disallowed_tools_applied??m.disallowed_tools_applied,E=p.mcp_servers_applied??m.mcp_servers_applied,x=p.code_running_mcp_tools_applied??m.code_running_mcp_tools_applied;return{...p,...y!==void 0&&{hooks_applied:y},...g!==void 0&&{plugins_applied:g},...b!==void 0&&{managed_settings_applied:b},...A!==void 0&&{settings_applied:A},...k!==void 0&&{disallowed_tools_applied:k},...E!==void 0&&{mcp_servers_applied:E},...x!==void 0&&{code_running_mcp_tools_applied:x}}},()=>l),this.initialization.catch(()=>{}),i}async enableRemoteControl(e,i,l){let u=++this.remoteControlCallGeneration,p=this.workSecretAnswerer,m=l?.reattachSessionId||(l?.workSecret===void 0?void 0:jo(l.workSecret)),y=e&&l?.workSecret!==void 0&&l.refreshWorkSecret&&m!==void 0?{sessionId:m,refresh:l.refreshWorkSecret}:void 0;this.workSecretAnswerer=y;let g;try{g=(await this.request({subtype:"remote_control",enabled:e,...i!==void 0&&{name:i},reattach_session_id:l?.reattachSessionId,keep_session_on_exit:l?.keepSessionOnExit,work_secret:l?.workSecret})).response}catch(b){if(u===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw b}if(e&&u===this.remoteControlCallGeneration){let b=g.bridge_session_id,A=[y,p];this.workSecretAnswerer=typeof b==="string"?A.find((k)=>k!==void 0&&Fn(k.sessionId,b)):void 0}return g}async submitFeedback(e,i){return(await this.request({subtype:"submit_feedback",description:e,surface:i?.surface,draft_id:i?.draft_id,type:i?.type,title:i?.title,area:i?.area,attach_transcript:i?.attach_transcript,save_locally:i?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,i){await this.request({subtype:"rename_session",title:e,source:"host",session_id:i})}async generateSessionTitle(e,i){return T("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:i?.persist})).response.title)}async askSideQuestion(e,i){return T("sdk_side_question",async()=>{let u=(await this.request({subtype:"side_question",question:e,...i?.history?.length&&{history:[...i.history]}},i)).response;return u.response===null?null:{response:u.response,synthetic:u.synthetic??!1,...u.refusal_fallback&&{refusalFallback:{originalModel:u.refusal_fallback.original_model,fallbackModel:u.refusal_fallback.fallback_model,content:u.refusal_fallback.content}}}},()=>i?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,i){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:i?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let i of e)if(i.request.subtype==="can_use_tool")this.handleControlRequest({...i,request:{...i.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let i of e)if(i.request.subtype==="request_user_dialog")this.handleControlRequest(i).catch(()=>{})}request(e,i){let l=i?.signal;if(l?.aborted)return Promise.reject(U(l.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(hr());let u=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(u);let p={request_id:u,type:"control_request",request:e},m=e.subtype==="initialize";return new Promise((y,g)=>{let b,A=!1,k=(M)=>{this.pendingControlResponses.delete(u),b?.(),y(M)},E=(M)=>{this.pendingControlResponses.delete(u),b?.(),g(M)};if(l){let M=()=>{if(E(U(l.reason??"Control request aborted")),!A)return;try{Promise.resolve(this.transport.write(o({type:"control_cancel_request",request_id:u})+`
|
|
22
|
+
`)).catch(()=>{})}catch{}};l.addEventListener("abort",M,{once:!0}),b=()=>{l.removeEventListener("abort",M)}}this.pendingControlResponses.set(u,{handler:(M)=>{if(M.subtype==="success")k(M);else E(v(Error(M.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:Kn(M.error_code)}));if(!m&&(M.pending_permission_requests||M.pending_user_dialog_requests||M.pending_elicitation_requests))t(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`);else{if(M.pending_permission_requests)this.processPendingPermissionRequests(M.pending_permission_requests);if(M.pending_user_dialog_requests)this.processPendingUserDialogRequests(M.pending_user_dialog_requests)}},reject:E});let x=o(p)+`
|
|
23
|
+
`,O=()=>{if(l?.aborted)return;return A=!0,this.transport.write(x)};try{let M=this.promptHold,H=Ko.has(e.subtype)||this.sendsLaunchFields()&&!Fo.has(e.subtype);(M!==void 0&&H?this.writeBehindPromptHold(M,O):this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(O()):this.initializeWritten.then(O)).catch(E)}catch(M){E(M)}})}initializationResult(){return this.initialization}afterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(e());return this.initializeWritten.then(e)}writePrompt(e){if(this.promptHold!==void 0)return this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(e)).then(()=>{});return this.afterInitialize(()=>this.writeStreamMessage(e))}reinitialize(){return T("sdk_reinitialize",()=>this.initialize({first:!1}))}dropHookMatchers(e,i){let l=this.hooks?.[e]??[],u=l.filter((g)=>g.matcher!==i),p=l.length-u.length;if(p===0)return ot("sdk_drop_hook_matchers","no_match"),0;this.hooks={...this.hooks,[e]:u};let m=this.initHooksPayload,y=m?.[e];if(m!==void 0&&y!==void 0){let g=y.filter((b)=>b.matcher!==i);if(g.length>0)m[e]=g;else delete m[e]}return kt("sdk_drop_hook_matchers",{count:p}),p}async supportedCommands(){let{commands:e}=await this.initialization;return this.latestCommands??e}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,i){return T("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:i})})}async readMcpResource(e,i){return(await this.request({subtype:"mcp_read_resource",serverName:e,uri:i})).response}async enableChannel(e){return T("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,i,l){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:i,redirectUriOnly:l?.redirectUriOnly})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,i){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:i})).response}async claudeAuthenticate(e,i){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e,consoleProfile:i?.consoleProfile})).response}async claudeOAuthCallback(e,i){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:i})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(e){return(await this.request({subtype:"get_context_usage",...e})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(e){return(await this.request({subtype:"get_usage",...e?.skipBehaviors&&{skip_behaviors:!0}})).response}async getMemoryDialog(){return(await this.request({subtype:"get_memory_dialog"})).response}async getSkillsDialog(){return(await this.request({subtype:"get_skills_dialog"})).response}async getStatus(){return(await this.request({subtype:"get_status"})).response}async exportConversation(){return(await this.request({subtype:"export_conversation"})).response}async readCloudSessions(e,i){return(await this.request(e,i)).response}async getChromeDialog(){return(await this.request({subtype:"get_chrome_dialog"})).response}async getChromeBrowsers(){return(await this.request({subtype:"get_chrome_browsers"})).response}async selectChromeBrowser(e){return(await this.request({subtype:"select_chrome_browser",device_id:e})).response}async getSandboxDialog(){return(await this.request({subtype:"get_sandbox_dialog"})).response}async readFile(e,i){try{return(await this.request({subtype:"read_file",path:e,max_bytes:i?.maxBytes,encoding:i?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(e){return T("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...e?.holdOnCacheImpact&&{hold_on_cache_impact:!0},...e?.addPlugins&&e.addPlugins.length>0&&{add_plugins:e.addPlugins},...e?.refuseIfBusy&&{refuse_if_busy:!0}})).response,(i)=>i instanceof Error&&("errorCode"in i)&&i.errorCode==="reload_plugins_busy"?"reload_plugins_busy":"error")}async reloadSkills(){return T("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return T("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return T("sdk_mcp_set_servers",async()=>{let i={},l={};for(let[g,b]of Object.entries(e))if(b.type==="sdk"&&"instance"in b)i[g]=b;else l[g]=b;let u=new Set(this.sdkMcpServers.keys()),p=new Set(Object.keys(i));for(let g of u)if(!p.has(g))await this.disconnectSdkMcpServer(g);for(let[g,b]of Object.entries(i)){let A=this.sdkMcpServers.get(g);if(!A){this.connectSdkMcpServer(g,b);continue}let{settings:k,ignored:E}=rn(b);if(Ln(g,b,E),k.timeout!==A.settings.timeout||k.disableAutoBackground!==A.settings.disableAutoBackground||k.connectorId!==A.settings.connectorId)t(`[Query.setMcpServers] MCP server '${g}' is already registered, so the different timeout, disableAutoBackground or connectorId passed to setMcpServers is ignored; remove and re-add the server to change it`);if(k.tools!==void 0&&!Wn(k.tools,A.settings.tools))t(k.tools.length===0?`[Query.setMcpServers] MCP server '${g}': per-tool policy cleared`:`[Query.setMcpServers] MCP server '${g}': per-tool policy replaced (${k.tools.length} ${k.tools.length===1?"entry":"entries"})`),A.settings={...A.settings,tools:k.tools}}let m={};for(let g of Object.keys(i))m[g]={type:"sdk",name:g,...this.sdkMcpServers.get(g)?.settings};return(await this.request({subtype:"mcp_set_servers",servers:{...l,...m}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){t("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let i=0,l=[];for await(let u of e){if(i++,t(`[Query.streamInput] Processing message ${i}: ${u.type}`),this.abortController?.signal.aborted||this.promptHold!==void 0&&this.cleanupPerformed)break;let p=o(this.verbatimPrompts?{...u,client_composed:!0}:u)+`
|
|
24
|
+
`;if(this.promptHold===void 0)await Promise.resolve(this.writeStreamMessage(p));else l.push(this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(p)))}if(t(`[Query.streamInput] Finished processing ${i} messages from input stream`),this.promptHold!==void 0)l.push(this.promptHold);if((await Promise.all(l)).includes(!1))return;if(i>0&&this.hasBidirectionalNeeds())t("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();t("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(i){if(!(i instanceof De))throw i}}writeStreamMessage(e){return this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),this.transport.write(e)}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)t("[Query.readMessages] Run ended for single-turn query, closing stdin"),this.transport.endInput()}armRunEndCeiling(){if(this.clearRunEndCeiling(),this.runEnded||this.cleanupPerformed||this.runEndCeilingMs<=0)return;this.runEndCeilingTimer=setTimeout(()=>{t(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,ve)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return t("[Query.waitForRunEnd] Run already ended, returning immediately"),Promise.resolve();return new Promise((e)=>{let i=this.abortController?.signal;if(this.cleanupPerformed||i?.aborted){e();return}let l=()=>e();i?.addEventListener("abort",l,{once:!0}),this.addCleanupCallback(()=>{i?.removeEventListener("abort",l),e()}),this.runEndedResolve=()=>{i?.removeEventListener("abort",l),e()}})}handleHookCallbacks(e,i,l,u){let p=this.hookCallbacks.get(e);if(!p)throw Error(`${En}: ${e}`);return p(i,l,{signal:u})}connectSdkMcpServer(e,i){let l=new fr((y)=>this.sendMcpServerMessageToCli(e,y)),u=i.instance.connect(l).catch((y)=>{if(this.sdkMcpServers.get(e)?.transport===l)this.sdkMcpServers.delete(e);t(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${y}`,{level:"error"})}),{settings:p,ignored:m}=rn(i);Ln(e,i,m),this.sdkMcpServers.set(e,{transport:l,settings:p,connection:u})}async disconnectSdkMcpServer(e){let i=this.sdkMcpServers.get(e);if(i){let l=`${e}:${It}`;for(let[u,p]of this.pendingMcpResponses)if(u.startsWith(l))this.pendingMcpResponses.delete(u),p.reject(Error("MCP server was removed during the manifest capture"));if(await i.transport.close(),this.sdkMcpServers.get(e)===i)this.sdkMcpServers.delete(e)}}sendMcpServerMessageToCli(e,i){if("id"in i&&i.id!==null&&i.id!==void 0){let u=`${e}:${i.id}`,p=this.pendingMcpResponses.get(u);if(p){p.resolve(i),this.pendingMcpResponses.delete(u);return}if(typeof i.id==="string"&&i.id.startsWith(It)){t(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${i.id})`);return}}let l={type:"control_request",request_id:me(),request:{subtype:"mcp_message",server_name:e,message:i}};if(!this.initializeHasBeenWritten&&Dn(i))this.sdkMcpToolsChangedDuringCapture.add(e);this.afterInitialize(()=>this.transport.write(o(l)+`
|
|
25
|
+
`)).catch((u)=>{t(`[Query.sendMcpServerMessageToCli] Transport write failed: ${u}`,{level:"error"})})}handleMcpControlRequest(e,i,l){let u="id"in i.message?i.message.id:null,p=`${e}:${u}`;return new Promise((m,y)=>{let g=()=>{this.pendingMcpResponses.delete(p)},b=(k)=>{g(),m(k)},A=(k)=>{g(),y(k)};if(this.pendingMcpResponses.set(p,{resolve:b,reject:A}),l.onmessage)l.onmessage(i.message);else{g(),y(Error("No message handler registered"));return}})}}function hr(){return Error("Query closed before response received")}var $o=/^[a-z][a-z0-9_]{0,63}$/;function Kn(e){return typeof e==="string"&&$o.test(e)?e:void 0}function Fn(e,i){if(e===i)return!0;let l=e.slice(e.lastIndexOf("_")+1),u=i.slice(i.lastIndexOf("_")+1);return l.length>=4&&l===u}function jo(e){try{let i=S(Buffer.from(e,"base64url").toString("utf8"));if(typeof i!=="object"||i===null||!("session_ingress_token"in i)||typeof i.session_ingress_token!=="string")return;let l=i.session_ingress_token,p=(l.startsWith("sk-ant-si-")?l.slice(10):l).split(".");if(p.length!==3||!p[1])return;let m=S(Buffer.from(p[1],"base64url").toString("utf8"));return typeof m==="object"&&m!==null&&"session_id"in m&&typeof m.session_id==="string"&&m.session_id?m.session_id:void 0}catch{return}}var mr=500,gr=1048576;var zo=[200,800];class _r{send;pending=[];pendingEntries=0;pendingBytes=0;flushPromise=null;sendTimeoutMs;onError;maxPendingEntries;maxPendingBytes;backoffMs;constructor(e,i){this.send=e;let{sendTimeoutMs:l=60000,onError:u,maxPendingEntries:p=mr,maxPendingBytes:m=gr,backoffMs:y=zo}=i??{};this.sendTimeoutMs=l,this.onError=u,this.maxPendingEntries=p,this.maxPendingBytes=m,this.backoffMs=y}enqueue(e,i){let l=o(i).length;if(this.pending.push({filePath:e,entries:i,bytes:l}),this.pendingEntries+=i.length,this.pendingBytes+=l,this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)this.flushPromise=this.drain(),this.flushPromise.catch(()=>{})}async flush(){let e=this.drain();if(this.flushPromise=e,await e,this.flushPromise===e)this.flushPromise=null}async drain(){let e=this.flushPromise,i=this.pending.splice(0);if(this.pendingEntries=0,this.pendingBytes=0,e)await e;if(i.length===0)return;await this.doFlush(i)}async doFlush(e){let i=new Map;for(let l of e){let u=i.get(l.filePath);if(u)u.push(...l.entries);else i.set(l.filePath,l.entries.slice())}for(let[l,u]of i)await this.sendWithRetry(l,u)}async sendWithRetry(e,i){let l=this.backoffMs.length+1,u=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${e}`,p,m=1;for(;m<=l;m++)try{await F(this.send(e,i),this.sendTimeoutMs,u),p=void 0;break}catch(y){if(p=U(y),p.message===u)break;let g=this.backoffMs[m-1];if(g===void 0)break;await D(g)}if(p){t(`[TranscriptMirrorBatcher] flush failed for ${e} after ${m} attempt(s): ${p}`,{level:"error"});try{this.onError?.(e,p)}catch(y){t(`[TranscriptMirrorBatcher] onError callback threw: ${y}`,{level:"error"})}}}}var Un=typeof globalThis==="object"?globalThis:global;var Pe="1.9.0";var $n=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ho(e){var i=new Set([e]),l=new Set,u=e.match($n);if(!u)return function(){return!1};var p={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};if(p.prerelease!=null)return function(b){return b===e};function m(g){return l.add(g),!1}function y(g){return i.add(g),!0}return function(b){if(i.has(b))return!0;if(l.has(b))return!1;var A=b.match($n);if(!A)return m(b);var k={major:+A[1],minor:+A[2],patch:+A[3],prerelease:A[4]};if(k.prerelease!=null)return m(b);if(p.major!==k.major)return m(b);if(p.major===0){if(p.minor===k.minor&&p.patch<=k.patch)return y(b);return m(b)}if(p.minor<=k.minor)return y(b);return m(b)}}var jn=Ho(Pe);var Bo=Pe.split(".")[0],ft=Symbol.for("opentelemetry.js.api."+Bo),ht=Un;function Je(e,i,l,u){var p;if(u===void 0)u=!1;var m=ht[ft]=(p=ht[ft])!==null&&p!==void 0?p:{version:Pe};if(!u&&m[e]){var y=Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return l.error(y.stack||y.message),!1}if(m.version!==Pe){var y=Error("@opentelemetry/api: Registration of version v"+m.version+" for "+e+" does not match previously registered API v"+Pe);return l.error(y.stack||y.message),!1}return m[e]=i,l.debug("@opentelemetry/api: Registered a global for "+e+" v"+Pe+"."),!0}function xe(e){var i,l,u=(i=ht[ft])===null||i===void 0?void 0:i.version;if(!u||!jn(u))return;return(l=ht[ft])===null||l===void 0?void 0:l[e]}function et(e,i){i.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Pe+".");var l=ht[ft];if(l)delete l[e]}var qo=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var u=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=u.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=u.return))l.call(u)}finally{if(y)throw y.error}}return m},Go=function(e,i,l){if(l||arguments.length===2){for(var u=0,p=i.length,m;u<p;u++)if(m||!(u in i)){if(!m)m=Array.prototype.slice.call(i,0,u);m[u]=i[u]}}return e.concat(m||Array.prototype.slice.call(i))},Bn=function(){function e(i){this._namespace=i.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return mt("debug",this._namespace,i)},e.prototype.error=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return mt("error",this._namespace,i)},e.prototype.info=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return mt("info",this._namespace,i)},e.prototype.warn=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return mt("warn",this._namespace,i)},e.prototype.verbose=function(){var i=[];for(var l=0;l<arguments.length;l++)i[l]=arguments[l];return mt("verbose",this._namespace,i)},e}();function mt(e,i,l){var u=xe("diag");if(!u)return;return l.unshift(i),u[e].apply(u,Go([],qo(l),!1))}var ie;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(ie||(ie={}));function qn(e,i){if(e<ie.NONE)e=ie.NONE;else if(e>ie.ALL)e=ie.ALL;i=i||{};function l(u,p){var m=i[u];if(typeof m==="function"&&e>=p)return m.bind(i);return function(){}}return{error:l("error",ie.ERROR),warn:l("warn",ie.WARN),info:l("info",ie.INFO),debug:l("debug",ie.DEBUG),verbose:l("verbose",ie.VERBOSE)}}var Wo=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var u=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=u.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=u.return))l.call(u)}finally{if(y)throw y.error}}return m},Vo=function(e,i,l){if(l||arguments.length===2){for(var u=0,p=i.length,m;u<p;u++)if(m||!(u in i)){if(!m)m=Array.prototype.slice.call(i,0,u);m[u]=i[u]}}return e.concat(m||Array.prototype.slice.call(i))},Yo="diag",Ne=function(){function e(){function i(p){return function(){var m=[];for(var y=0;y<arguments.length;y++)m[y]=arguments[y];var g=xe("diag");if(!g)return;return g[p].apply(g,Vo([],Wo(m),!1))}}var l=this,u=function(p,m){var y,g,b;if(m===void 0)m={logLevel:ie.INFO};if(p===l){var A=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return l.error((y=A.stack)!==null&&y!==void 0?y:A.message),!1}if(typeof m==="number")m={logLevel:m};var k=xe("diag"),E=qn((g=m.logLevel)!==null&&g!==void 0?g:ie.INFO,p);if(k&&!m.suppressOverrideMessage){var x=(b=Error().stack)!==null&&b!==void 0?b:"<failed to generate stacktrace>";k.warn("Current logger will be overwritten from "+x),E.warn("Current logger will overwrite one already registered from "+x)}return Je("diag",E,l,!0)};l.setLogger=u,l.disable=function(){et(Yo,l)},l.createComponentLogger=function(p){return new Bn(p)},l.verbose=i("verbose"),l.debug=i("debug"),l.info=i("info"),l.warn=i("warn"),l.error=i("error")}return e.instance=function(){if(!this._instance)this._instance=new e;return this._instance},e}();var Qo=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var u=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=u.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=u.return))l.call(u)}finally{if(y)throw y.error}}return m},Xo=function(e){var i=typeof Symbol==="function"&&Symbol.iterator,l=i&&e[i],u=0;if(l)return l.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&u>=e.length)e=void 0;return{value:e&&e[u++],done:!e}}};throw TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")},Gn=function(){function e(i){this._entries=i?new Map(i):new Map}return e.prototype.getEntry=function(i){var l=this._entries.get(i);if(!l)return;return Object.assign({},l)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(i){var l=Qo(i,2),u=l[0],p=l[1];return[u,p]})},e.prototype.setEntry=function(i,l){var u=new e(this._entries);return u._entries.set(i,l),u},e.prototype.removeEntry=function(i){var l=new e(this._entries);return l._entries.delete(i),l},e.prototype.removeEntries=function(){var i,l,u=[];for(var p=0;p<arguments.length;p++)u[p]=arguments[p];var m=new e(this._entries);try{for(var y=Xo(u),g=y.next();!g.done;g=y.next()){var b=g.value;m._entries.delete(b)}}catch(A){i={error:A}}finally{try{if(g&&!g.done&&(l=y.return))l.call(y)}finally{if(i)throw i.error}}return m},e.prototype.clear=function(){return new e},e}();var Ad=Ne.instance();function Qn(e){if(e===void 0)e={};return new Gn(new Map(Object.entries(e)))}function Zn(e){return Symbol.for(e)}var Zo=function(){function e(i){var l=this;l._currentContext=i?new Map(i):new Map,l.getValue=function(u){return l._currentContext.get(u)},l.setValue=function(u,p){var m=new e(l._currentContext);return m._currentContext.set(u,p),m},l.deleteValue=function(u){var p=new e(l._currentContext);return p._currentContext.delete(u),p}}return e}(),Jn=new Zo;var es={get:function(e,i){if(e==null)return;return e[i]},keys:function(e){if(e==null)return[];return Object.keys(e)}},ts={set:function(e,i,l){if(e==null)return;e[i]=l}};var Jo=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var u=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=u.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=u.return))l.call(u)}finally{if(y)throw y.error}}return m},ei=function(e,i,l){if(l||arguments.length===2){for(var u=0,p=i.length,m;u<p;u++)if(m||!(u in i)){if(!m)m=Array.prototype.slice.call(i,0,u);m[u]=i[u]}}return e.concat(m||Array.prototype.slice.call(i))},rs=function(){function e(){}return e.prototype.active=function(){return Jn},e.prototype.with=function(i,l,u){var p=[];for(var m=3;m<arguments.length;m++)p[m-3]=arguments[m];return l.call.apply(l,ei([u],Jo(p),!1))},e.prototype.bind=function(i,l){return l},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var ti=function(e,i){var l=typeof Symbol==="function"&&e[Symbol.iterator];if(!l)return e;var u=l.call(e),p,m=[],y;try{while((i===void 0||i-- >0)&&!(p=u.next()).done)m.push(p.value)}catch(g){y={error:g}}finally{try{if(p&&!p.done&&(l=u.return))l.call(u)}finally{if(y)throw y.error}}return m},ri=function(e,i,l){if(l||arguments.length===2){for(var u=0,p=i.length,m;u<p;u++)if(m||!(u in i)){if(!m)m=Array.prototype.slice.call(i,0,u);m[u]=i[u]}}return e.concat(m||Array.prototype.slice.call(i))},Sr="context",ni=new rs,Nt=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(i){return Je(Sr,i,Ne.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(i,l,u){var p,m=[];for(var y=3;y<arguments.length;y++)m[y-3]=arguments[y];return(p=this._getContextManager()).with.apply(p,ri([i,l,u],ti(m),!1))},e.prototype.bind=function(i,l){return this._getContextManager().bind(i,l)},e.prototype._getContextManager=function(){return xe(Sr)||ni},e.prototype.disable=function(){this._getContextManager().disable(),et(Sr,Ne.instance())},e}();var yr=Nt.getInstance();var ns=function(){function e(){}return e.prototype.inject=function(i,l){},e.prototype.extract=function(i,l){return i},e.prototype.fields=function(){return[]},e}();var Cr=Zn("OpenTelemetry Baggage Key");function br(e){return e.getValue(Cr)||void 0}function ss(){return br(Nt.getInstance().active())}function os(e,i){return e.setValue(Cr,i)}function is(e){return e.deleteValue(Cr)}var vr="propagation",si=new ns,as=function(){function e(){this.createBaggage=Qn,this.getBaggage=br,this.getActiveBaggage=ss,this.setBaggage=os,this.deleteBaggage=is}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(i){return Je(vr,i,Ne.instance())},e.prototype.inject=function(i,l,u){if(u===void 0)u=ts;return this._getGlobalPropagator().inject(i,l,u)},e.prototype.extract=function(i,l,u){if(u===void 0)u=es;return this._getGlobalPropagator().extract(i,l,u)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){et(vr,Ne.instance())},e.prototype._getGlobalPropagator=function(){return xe(vr)||si},e}();var Er=as.getInstance();import{copyFile as oi,readFile as ii,rm as ds,writeFile as cs}from"fs/promises";import{homedir as ls}from"os";import{join as wr}from"path";function us(e){return{globalConfig:wr(e||ls(),".claude.json"),userSettings:wr(e||wr(ls(),".claude"),"settings.json")}}function kr(e,i,l,u){return e!==void 0&&i===l?{backend:e,key:u}:void 0}async function Ge(e,i,l,u){if(u)return ai(u,e,i,l);try{if(l)await cs(i,l(await ii(e)),{mode:384});else await oi(e,i)}catch(p){if(r(p)===void 0)throw p;if(!_(p))await ds(i,{force:!0}).catch(()=>{}),t(`sessionStore resume: skipping ${e} (${r(p)})`)}}async function ai({backend:e,key:i},l,u,p){let m=await e.read([i]);if(!m.ok){if(m.error.code==="InvalidArgument")throw new c(`sessionStore resume: invalid v5 key for ${l}: ${m.error.argument}${m.error.reason?` (${m.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");t(`sessionStore resume: skipping ${l} (${m.error.code})`);return}let y=m.value.items[0];if(!y?.found)return;let g=Buffer.from(y.value);try{await cs(u,p?p(g):g,{mode:384})}catch(b){if(r(b)===void 0)throw b;if(!_(b))await ds(u,{force:!0}).catch(()=>{}),t(`sessionStore resume: skipping ${l} (${r(b)})`)}}import{createHash as li}from"crypto";import{homedir as cc,userInfo as di}from"os";var ps="-credentials";function fs(e=""){let i=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,l=i!==void 0?!i:!process.env.CLAUDE_CONFIG_DIR,u=i!==void 0?i.normalize("NFC"):C(),p=l?"":`-${li("sha256").update(u).digest("hex").substring(0,8)}`;return`Claude Code${Vn().OAUTH_FILE_SUFFIX}${e}${p}`}var ci=/^[a-zA-Z0-9._-]+$/;function hs(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||di().username}catch{e="claude-code-user"}if(!ci.test(e))return"claude-code-user";return e}class ms{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;blockingReadRetryAt=0;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var mc=new s(()=>new ms);function Rr(e){let i=[],l=[];for(let[u,p]of Object.entries(e??{})){if(!Array.isArray(p?.mcpServers))continue;let m=l.length,y=p.mcpServers.map((g)=>{if(typeof g!=="object"||g===null)return g;let b=[];for(let[A,k]of Object.entries(g))if(k?.type==="sdk"&&"instance"in k)l.push({agentName:u,serverName:A}),b.push([A,{type:"sdk",name:k.name??A}]);else b.push([A,k]);return Object.fromEntries(b)});if(l.length>m)i.push([u,{...p,mcpServers:y}])}return{agents:i.length>0?{...e,...Object.fromEntries(i)}:e,ignored:l}}function Ar(e){for(let{agentName:i,serverName:l}of e)process.emitWarning(`Agent "${i}": MCP server "${l}" in its mcpServers was ignored, because a createSdkMcpServer() server works only in the top-level mcpServers option. Move it there and, if the agent has a tools list, add mcp__${l} to it. This will be an error in a later release.`,{code:"CLAUDE_SDK_AGENT_IN_PROCESS_SERVER"})}function ui(e,i){if(e==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let l=i.filter((u)=>u.length>0&&!u.includes("("));if(l.length===0)return;return`canUseTool will not be invoked for: ${l.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function gs(e,i,l){if(!e)return;let u=ui(i,l);if(u===void 0)return;process.emitWarning(u,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}var pi="CLAUDE_SDK_MCP_SERVERS_ARGV_DEPRECATED",fi="This app starts its own Claude Code (pathToClaudeCodeExecutable or spawnClaudeCodeProcess) and sets no mcpServersDelivery, so its MCP servers go on Claude Code's command line, where other users of the machine can read their env and headers. That default is deprecated: a future SDK release sends them over stdin instead ('initialize'), which a Claude Code older than the one bundled with this SDK cannot read, so those sessions would then fail to start. Set mcpServersDelivery: 'initialize' once that Claude Code is at least the bundled version, or mcpServersDelivery: 'argv' to stay on the command line. Either setting stops this warning.",_s=a({value:!1},(e)=>{e.value=!1});function Ss(){if(_s.value)return;_s.value=!0,process.emitWarning(fi,{type:"DeprecationWarning",code:pi})}process.env.NoDefaultCurrentDirectoryInExePath="1";var Ei=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Cs(e){let i;try{i=S(Ce(e.toString("utf8")))}catch{return e}if(!bs(i))return e;let l=!1;for(let p of Ei)if(Object.hasOwn(i,p))delete i[p],l=!0;let u=i.env;if(bs(u)&&Object.hasOwn(u,"CLAUDE_CONFIG_DIR"))delete u.CLAUDE_CONFIG_DIR,l=!0;return l?o(i):e}function bs(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function wi(e,i){if(!e)return;let l=e;try{let u=S(e);if(u?.claudeAiOauth?.refreshToken)delete u.claudeAiOauth.refreshToken,l=o(u)}catch{}await ws(i,l,{mode:384})}function ki(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=fs(ps);return new Promise((i)=>{hi("security",["find-generic-password","-a",hs(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(l,u)=>i(l?void 0:u.trim()||void 0))})}async function As(e,i,l,u,p=60000,m){if(!w(i))return;let y=B(l,u),g=await F(e.load({projectKey:y,sessionId:i}),p,`SessionStore.load() timed out after ${p}ms for session ${i}`);if(!g||g.length===0)return;let b=Z(Ci(),`claude-resume-${mi()}`);try{let A=Z(b,"projects",y);await gt(A,{recursive:!0,mode:448});let k=Z(A,`${i}.jsonl`);await dn(k,g);let E=u?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,x=E??Z(_t(),".claude"),O;try{O=await Si(Z(x,".credentials.json"),"utf-8")}catch(G){if(!_(G))throw G}if(!E&&!(u??process.env).ANTHROPIC_API_KEY&&!(u??process.env).CLAUDE_CODE_OAUTH_TOKEN)O=await ki()??O;await wi(O,Z(b,".credentials.json"));let M=us(j("CLAUDE_CONFIG_DIR")),H=E||_t(),X=Z(H,".claude.json");await Ge(X,Z(b,".claude.json"),void 0,kr(m,X,M.globalConfig,N.globalConfig())),await Ge(Z(x,".config.json"),Z(b,".config.json"));for(let G of sn)if(G)await Ge(Z(H,`.claude${G}.json`),Z(b,`.claude${G}.json`));let L=Z(x,"settings.json");await Ge(L,Z(b,"settings.json"),Cs,kr(m,L,M.userSettings,N.userSettings())),await Ge(Z(x,"cowork_settings.json"),Z(b,"cowork_settings.json"),Cs);for(let G of sn){let de=`hybrid-settings${G}.json`,V=Z(x,"state",de);if((await gi(V).catch(()=>{return}))?.isFile())await gt(Z(b,"state"),{recursive:!0,mode:448}),await Ge(V,Z(b,"state",de))}if(e.listSubkeys)await Ri(e,{projectKey:y,sessionId:i},Z(A,i),p);return b}catch(A){throw await Lt(b),A}}async function Ri(e,i,l,u){let p=await F(e.listSubkeys({projectKey:i.projectKey,sessionId:i.sessionId}),u,`SessionStore.listSubkeys() timed out after ${u}ms for session ${i.sessionId}`);for(let m of p){let y=St(l,m+".jsonl");if(!m||Tr(m)||m.split(/[\\/]/).includes("..")||!y.startsWith(l+bi)){t(`[SessionStore] skipping unsafe subpath from listSubkeys: ${m}`,{level:"warn"});continue}let g=await F(e.load({projectKey:i.projectKey,sessionId:i.sessionId,subpath:m}),u,`SessionStore.load() timed out after ${u}ms for session ${i.sessionId} subpath ${m}`);if(!g||g.length===0)continue;let b=[],A=[];for(let k of g)if(Yn(k))b.push(k);else A.push(k);if(A.length>0)await gt(ys(y),{recursive:!0}),await dn(y,A);if(b.length>0){let k=b.at(-1),E=St(l,m+".meta.json");await gt(ys(E),{recursive:!0});let{type:x,...O}=k;await ws(E,o(O),{mode:384})}}}function Ts(e){let i=e?.accepted===!0&&(typeof e.directory!=="string"||!(ks.isAbsolute(e.directory)||Rs.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&i===void 0)t("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return i}var Ai=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Mr(e,i){let{isSingleUserTurn:l,resumeConfigDir:u,deferSpawn:p,readsStartupMarks:m}=i,{systemPrompt:y,settings:g,managedSettings:b,settingSources:A,sandbox:k,...E}=e??{},x,O,M,H;if(y===void 0)x="";else if(typeof y==="string")x=y;else if(Array.isArray(y))x=y;else if(y.type==="custom")x=y.prompt,H=y.snapshot;else if(y.type==="preset")O=y.append,M=y.excludeDynamicSections,H=y.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.328";let{abortController:X=ct(),additionalDirectories:L=[],projectConfigRoot:G,agent:de,agents:V,allowedTools:K=[],betas:he,canUseTool:pe,continue:ce,cwd:Re,debug:Oe,debugFile:ge,disallowedTools:Ae=[],tools:tt,env:_e,executable:Ke=oe()?"bun":"node",executableArgs:$e=[],extraArgs:je={},fallbackModel:Te,enableFileCheckpointing:I,toolConfig:be,forkSession:Ve,hooks:Ie,includeHookEvents:ue,includePartialMessages:ze,forwardSubagentText:ye,verbatimPrompts:He=!1,onElicitation:ee,onUserDialog:z,supportedDialogKinds:ne,perTaskStopAffordance:te,rapidFollowupPreempt:Me,workspaceTrust:Ee,persistSession:Ye,sessionStore:fe,sessionStoreFlush:xs,thinking:rt,effort:Os,maxThinkingTokens:Ut,maxTurns:Is,maxBudgetUsd:Ds,taskBudget:Ns,mcpServers:xr,model:Ls,outputFormat:Or,permissionMode:Ks,allowDangerouslySkipPermissions:Fs=!1,permissionPromptToolName:Us,permissionPrompts:$s,plugins:nt,pluginDelivery:$t="argv",managedSettingsDelivery:zt="argv",settingsDelivery:Ht="argv",disallowedToolsDelivery:Bt="argv",mcpServersDelivery:st,getOAuthToken:Ir,getHostAuthToken:Dr,workload:Nr,resume:qt,resumeSessionAt:js,resumeDropsTurn:zs,sessionId:Hs,skills:Lr,stderr:Bs,strictMcpConfig:qs}=E,Kr=Ks;if(fe&&Ye===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. To avoid keeping a local copy, pass env: { ...process.env, CLAUDE_CONFIG_DIR: dir }, where dir is a new private directory such as fs.mkdtempSync(path.join(os.tmpdir(), 'claude-')), and delete dir when the query ends.");gn({supportedDialogKinds:ne,onUserDialog:z});let Gs=Ts(Ee);if(fe&&ce&&!qt&&!fe.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(fe&&I)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(fe&&E.spawnClaudeCodeProcess)t("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(gs(!!pe,Kr??"default",K),$t!=="argv"&&$t!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let Fr=$t==="initialize"&&nt!==void 0&&nt.length>0;if(zt!=="argv"&&zt!=="initialize")throw Error("Invalid managedSettingsDelivery. Expected 'argv' or 'initialize'.");let Wt=zt==="initialize"&&Boolean(b);if(Ht!=="argv"&&Ht!=="initialize")throw Error("Invalid settingsDelivery. Expected 'argv' or 'initialize'.");if(Bt!=="argv"&&Bt!=="initialize")throw Error("Invalid disallowedToolsDelivery. Expected 'argv' or 'initialize'.");let Ur=Bt==="initialize"&&Ae.length>0;if(st!==void 0&&st!=="argv"&&st!=="initialize")throw Error("Invalid mcpServersDelivery. Expected 'argv' or 'initialize'.");let Vt=E.pathToClaudeCodeExecutable;if(!Vt){let Y=vi(import.meta.url),re=yi(Y),ke=mn((Qe)=>re.resolve(Qe));if(!ke)throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);Vt=ke}let Yt=Or?.type==="json_schema"?Or.schema:void 0,J=_e?{..._e}:{...process.env};if(!J.CLAUDE_CODE_ENTRYPOINT)J.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!J.CLAUDE_AGENT_SDK_VERSION)J.CLAUDE_AGENT_SDK_VERSION="0.3.328";if(I)J.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(J).some((Y)=>Y.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))J.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(m&&!Object.keys(J).some((Y)=>Y.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))J.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let Qt=Be(J.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),Ws=Number.isFinite(Qt)&&Qt>=0?Qt:Tt;if(Ir)J.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(Dr)J.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(be?.askUserQuestion?.previewFormat)J.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=be.askUserQuestion.previewFormat;for(let[Y,re]of[[be?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[be?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Y)J[re]="1";else if(!_e){for(let ke of Object.keys(J))if(ke.toUpperCase()===re)delete J[ke]}let Xt={};if(Er.inject(yr.active(),Xt),"traceparent"in Xt){for(let Y of["TRACEPARENT","TRACESTATE"])if(!(Y in(_e??{})))delete J[Y]}for(let[Y,re]of Object.entries(Xt)){let ke=Y.toUpperCase();if(!(ke in(_e??{})))J[ke]=re}let Ct={},$r=new Map;if(xr)for(let[Y,re]of Object.entries(xr))if(re.type==="sdk"&&re.instance)$r.set(Y,re);else Ct[Y]=re;let it;if(rt)switch(rt.type){case"adaptive":it={type:"adaptive",display:rt.display};break;case"enabled":it={type:"enabled",budgetTokens:rt.budgetTokens,display:rt.display};break;case"disabled":it={type:"disabled"};break}else if(Ut!==void 0)it=Ut===0?{type:"disabled"}:{type:"enabled",budgetTokens:Ut};if(u){if(J.CLAUDE_CONFIG_DIR=u,process.platform==="win32")J.CLAUDE_SECURESTORAGE_CONFIG_DIR=_e?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??_e?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let bt=je?.["sdk-url"]!==void 0||Object.keys(je??{}).some((Y)=>Y.startsWith("sdk-url="))||$e.some((Y)=>/^--sdk-url(=|$)/.test(Y)),Vs=Boolean(qt||ce)&&!E.pathToClaudeCodeExecutable&&!E.spawnClaudeCodeProcess&&!bt,Zt=bt?[]:(nt??[]).filter((Y)=>Y.requiredByOrganization),jr=Object.keys(Ct).length>0,zr=st==="initialize"&&jr&&!bt,at=typeof g==="object"?o(g):g,lt;if(Ht==="initialize"&&(at===void 0||/^\{.*\}$/s.test(at.trim()))){let Y=Et(at===void 0?{}:{settings:at},k).settings;try{let re=Y?S(Y):void 0;lt=n(re)?re:void 0}catch{}}let{agents:Ys,ignored:Qs}=Rr(V),Hr={systemPrompt:x,appendSystemPrompt:O,planModeInstructions:E.planModeInstructions,systemPromptSnapshot:H,appendSubagentSystemPrompt:E.appendSubagentSystemPrompt,toolAliases:E.toolAliases,codeRunningMcpTools:E.codeRunningMcpTools,excludeDynamicSections:M,agents:Ys,title:E.title,skills:Lr,webSearchIsolationExemptMcpServers:E.webSearchIsolationExemptMcpServers,promptSuggestions:E.promptSuggestions,agentProgressSummaries:E.agentProgressSummaries,forwardSubagentText:ye,supportedDialogKinds:ne,perTaskStopAffordance:te,rapidFollowupPreempt:Me,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:Gs,plugins:Fr?nt:Zt.length>0?Zt:void 0,managedSettings:Wt?b:void 0,settings:lt,disallowedTools:Ur?Ae:void 0,mcpServers:zr?Ct:void 0,captureSdkMcpManifests:!yt("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")};if(_n({hooks:Ie,jsonSchema:Yt,initConfig:Hr}),Ar(Qs),st===void 0&&jr&&!bt&&(E.pathToClaudeCodeExecutable||E.spawnClaudeCodeProcess))Ss();let Br=new dr({abortController:X,additionalDirectories:L,projectConfigRoot:G,agent:de,betas:he,cwd:Re,debug:Oe,debugFile:ge,executable:Ke,executableArgs:$e,extraArgs:{...je,...Nr&&{workload:Nr}},readsInitializeAtBoot:Vs||Zt.length>0,pathToClaudeCodeExecutable:Vt,env:J,forkSession:Ve,stderr:Bs,thinkingConfig:it,effort:Os,maxTurns:Is,maxBudgetUsd:Ds,taskBudget:Ns,model:Ls,fallbackModel:Te,jsonSchema:Yt,permissionMode:Kr,allowDangerouslySkipPermissions:Fs,permissionPromptToolName:Us,permissionPrompts:$s,continueConversation:fe?void 0:ce,resume:qt,resumeSessionAt:js,resumeDropsTurn:zs,sessionId:Hs,settings:lt?void 0:at,settingsViaInitialize:lt!==void 0,disallowedToolsViaInitialize:Ur,managedSettings:b&&!Wt?o(b):void 0,managedSettingsViaInitialize:Wt,settingSources:A,skills:Lr,allowedTools:K,disallowedTools:Ae,tools:tt,mcpServers:Ct,mcpServersViaInitialize:zr,strictMcpConfig:qs,canUseTool:!!pe,hooks:!!Ie,includeHookEvents:ue,includePartialMessages:ze,persistSession:Ye,sessionMirror:!!fe,plugins:nt,pluginsViaInitialize:Fr,sandbox:lt?void 0:k,spawnClaudeCodeProcess:E.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,hostSpawn:e?.hostSpawn,deferSpawn:p}),Jt=new Dt(Br,l,pe,Ie,X,$r,Yt,Hr,ee,Ir,Dr,z,He,Ws);if(fe){let Y=()=>Z(J.CLAUDE_CONFIG_DIR??Z(_t(),".claude"),"projects"),re=xs==="eager",ke=new _r(async(Qe,er)=>{let dt=cn(Qe,Y());if(dt)await fe.append(dt,er);else t(`[SessionStore] dropping mirror frame: filePath ${Qe} is not under ${Y()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Qe,er)=>{let dt=cn(Qe,Y());if(dt)Jt.reportMirrorError(dt,er.message)},maxPendingEntries:re?0:mr,maxPendingBytes:re?0:gr});Jt.setTranscriptMirrorBatcher(ke)}return{queryInstance:Jt,transport:Br,abortController:X,processEnv:J,verbatimPrompts:He}}function Pr(e,i,l,u){if(typeof i==="string")e.writePrompt(o({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:i}]},parent_tool_use_id:null,...u&&{client_composed:!0}})+`
|
|
26
|
+
`).catch((p)=>l.abort(p));else e.streamInput(i).catch((p)=>l.abort(p))}var Ti=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function Lt(e){for(let i=0;;i++)try{return await Es(e,{recursive:!0,force:!0})}catch(l){if(i>=4||!Ti.has(r(l)??""))return;await D((i+1)*100)}}function Mi(e,i){e.waitForExit().catch(()=>{}).finally(()=>Lt(i))}function Pi({prompt:e,options:i}){if((i?.resume||i?.continue)&&i?.sessionStore)return xi(e,i);let{queryInstance:l,abortController:u,verbatimPrompts:p}=Mr(i,{isSingleUserTurn:typeof e==="string"});return Pr(l,e,u,p),l}function xi(e,i){let{queryInstance:l,transport:u,abortController:p,processEnv:m,verbatimPrompts:y}=Mr({...i},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),g=St(i.cwd??"."),b=i.sessionStore,A=i.loadTimeoutMs??60000,k=i.resume;return(async()=>{if(!k)k=(await F(b.listSessions(B(g,i.env)),A,`SessionStore.listSessions() timed out after ${A}ms`)).slice().sort((O,M)=>M.mtime-O.mtime)[0]?.sessionId;if(!k)return;return As(b,k,g,i.env,i.loadTimeoutMs)})().then((x)=>{if(x){u.updateResume(k);let O={CLAUDE_CONFIG_DIR:x};if(process.platform==="win32"){let M=i.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??i.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";O.CLAUDE_SECURESTORAGE_CONFIG_DIR=M,m.CLAUDE_SECURESTORAGE_CONFIG_DIR=M}u.updateEnv(O),m.CLAUDE_CONFIG_DIR=x,l.addCleanupCallback(()=>Mi(u,x))}if(!l.isClosed())u.spawn()}).catch((x)=>{let O=U(x);u.spawnAbort(O),l.setError(O)}),Pr(l,e,p,y),l}async function Oi(e={}){return(await Ms(e)).warm}async function Ms({options:e,initializeTimeoutMs:i}){let l,u=e?.resume;if((u||e?.continue)&&e?.sessionStore){let g=St(e.cwd??".");if(!u){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let b=e.loadTimeoutMs??60000;u=(await F(e.sessionStore.listSessions(B(g,e.env)),b,`SessionStore.listSessions() timed out after ${b}ms`)).slice().sort((k,E)=>E.mtime-k.mtime)[0]?.sessionId}if(u)l=await As(e.sessionStore,u,g,e.env,e.loadTimeoutMs)}let p,m,y;try{let H=function(){if(M)return;M=!0,E.close()},g=Mr(l&&u&&u!==e?.resume?{...e,resume:u}:e,{isSingleUserTurn:!1,resumeConfigDir:l,readsStartupMarks:!0});p=g.queryInstance;let{transport:b,abortController:A,verbatimPrompts:k}=g;m=b;let E=g.queryInstance;if(l){let L=l;E.addCleanupCallback(()=>{y=b.waitForExit().catch(()=>{}).then(()=>Lt(L))})}let O=new cr(i,Fe,e?.onStartupHooksRunning);E.setFrameObserver((L)=>{if(O.note(L),L.type==="system"&&L.subtype==="hook_progress"&&L.backgrounded!==!0)E.dropUnreadHookProgress(L.hook_id)});try{await O.race(E.initializationResult())}catch(L){if(L instanceof Error&&"errorClass"in L&&L.errorClass==="initialize_timeout"&&Object.isExtensible(L)){let G=E.startupMarkReached();Object.assign(L,{[kn]:G?.mark??"none",...G&&{[Rn]:G.ageMs}})}throw L}finally{E.setFrameObserver(void 0)}let M=!1;return{warm:{query(L){if(M)throw Error("WarmQuery.query() can only be called once");M=!0;try{Pr(E,L,A,k)}catch(G){throw E.close(),G}if(typeof L==="string")E.setIsSingleUserTurn(!0);return E},close:H,async[Symbol.asyncDispose](){M=!0,E.close(),await y}},query:E,transport:b}}catch(g){if(p?.close(),l&&!y){let b=m;y=(b?b.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>Lt(l))}throw await y,g}}function vs(e){t(`SpareProcess.onCommands() could not report the commands (${wn(e)??"unknown"})`,{level:"error"})}async function Ii({options:e,initializeTimeoutMs:i}={}){if(e?.resume||e?.continue||e?.forkSession)throw Error("prewarm(): resume/continue/forkSession describe a session; a spare has none — pass them to query() instead");let l=e?.cwd===void 0,u;if(e?.cwd!==void 0)u=e.cwd;else{let V=e?.env,K=V?.CLAUDE_CONFIG_DIR?.trim(),he=V?.HOME?.trim(),pe=V===void 0?C():K||Z(he||_t(),".claude"),ce=Tr(pe)?pe:Z(_t(),".claude");if(!Tr(ce))throw Error("prewarm(): no absolute config home to park the spare under (neither CLAUDE_CONFIG_DIR nor HOME gives an absolute path); set one of them to an absolute path or pass options.cwd");let Re=Z(ce,"spares");await gt(Re,{recursive:!0,mode:448}),u=await _i(Z(Re,"spare-"))}function p(){return l?Es(u,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()}let{workspaceTrust:m,...y}=e??{};if(m!==void 0)t("prewarm(): workspaceTrust is a per-session attestation — pass it to claim(); not sent to the spare",{level:"warn"});let{warm:g,query:b,transport:A}=await T("sdk_prewarm",async()=>{try{return await Ms({options:{...y,cwd:u,extraArgs:{...y.extraArgs,"await-claim":null}},initializeTimeoutMs:i??Pt})}catch(V){throw await p(),V}}),k=Object.entries(e?.mcpServers??{}).filter(([,V])=>V.type==="sdk").map(([V])=>V),E;function x(){return E??=A.waitForExit().catch(()=>{}).then(p),E}let O=!1,M=!1,H=!1,X,L=new Promise((V,K)=>{X={resolve:V,reject:K}});L.catch(()=>{});let G=A.waitForExit().then(()=>{return},()=>{return});G.then(()=>{if(!O)H=!0,X.reject(Error("spare_exited: the spare process exited before it was claimed")),x()});let de={claimed:L,exited:G,onCommands(V){b.setFrameObserver((K)=>{if(!O&&!M&&K.type==="system"&&K.subtype==="commands_changed"&&Array.isArray(K.commands))try{V(K.commands)}catch(he){vs(he)}}),T("sdk_spare_commands",async()=>{let K=await b.supportedCommands();if(!O&&!M&&!H)V(K)}).catch(vs)},claim({prompt:V,options:K}){if(O)throw Error("SpareProcess.claim() can only be called once");if(M||H)throw Error("SpareProcess.claim(): the spare was closed or has exited; start the session with query()");let he=Ai.filter((ee)=>K.settings?.[ee]!==void 0);if(he.length>0)throw new c(`SpareProcess.claim(): hook settings (${he.join(", ")}) cannot be applied at claim; pass them to prewarm() in Options.settings, where they are in force before any hook, as on a cold start. Nothing was sent: this spare can still be claimed without them.`,"SpareProcess.claim(): hook settings cannot be applied at claim");let pe=typeof K.cwd==="string"&&K.cwd.trim()!==""&&!ks.isAbsolute(K.cwd)&&!Rs.isAbsolute(K.cwd)&&K.cwd!=="~"&&!K.cwd.startsWith("~/")?St(K.cwd):K.cwd;O=!0;let{agents:ce,ignored:Re}=Rr(K.agents);Ar(Re);let Oe=Ts(K.workspaceTrust),ge=K.settings,Ae=n(ge),{model:tt,agent:_e,fastMode:Ke,permissions:$e,availableModels:je,disableAutoMode:Te,...I}=Ae?ge:{},be={model:tt,agent:_e,fastMode:Ke,permissions:$e,availableModels:je,disableAutoMode:Te},Ve=ge!==void 0&&(!Ae||Object.keys(I).length>0)?b.applyFlagSettings(Ae?I:ge):void 0,Ie=b.claimSession({cwd:pe,...K.permissionMode!==void 0&&{permission_mode:K.permissionMode},...K.env&&{env:K.env},...K.additionalDirectories&&{additional_directories:K.additionalDirectories},...K.appendSystemPrompt!==void 0&&{append_system_prompt:K.appendSystemPrompt},...K.title!==void 0&&{title:K.title},...ce&&{agents:ce},...Oe?.accepted===!0&&{workspace_trust:Oe},sdk_mcp_servers:k}),ue=[];if(K.model!==void 0)ue.push(["model",b.setModel(K.model)]);if(K.maxThinkingTokens!==void 0)ue.push(["maxThinkingTokens",b.setMaxThinkingTokens(K.maxThinkingTokens)]);let ze=Object.values(be).some((ee)=>ee!==void 0)?b.applyFlagSettings(be):void 0,ye=ge!==void 0?Promise.all([Ve,ze]):void 0;if(ye!==void 0)ue.push(["settings",ye]);for(let[,ee]of ue)ee.catch(()=>{});function He(){A.endInput(),x()}if(Ie.then(async(ee)=>{p();let z={cwd:ee.cwd??pe,sessionId:ee.session_id,parkedMs:ee.parked_ms,sdkMcpSettled:ee.sdk_mcp_settled},ne=await Promise.allSettled(ue.map(([,Ee])=>Ee)),te=ne.flatMap((Ee,Ye)=>Ee.status==="rejected"?[`${String(ue[Ye][0])}: ${h(Ee.reason)}`]:[]),Me=ye===void 0?void 0:ne[ue.findIndex(([Ee])=>Ee==="settings")];if(Me?.status==="rejected")M=!0,b.close(),X.reject(Object.assign(new c(`settings_not_applied: ${h(Me.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:z}));else if(te.length>0)X.reject(Object.assign(new c(`option_not_applied: ${te.join("; ")} — the prompt was sent and the session runs without these options`,"option_not_applied"),{claim:z}));else X.resolve(z)},(ee)=>{He(),X.reject(ee)}),ye===void 0)return g.query(V);return Promise.all([Ie,ye]).then(()=>{if(M)return;try{g.query(V)}catch{}},()=>{}),b},close(){if(M)return;if(M=!0,O)b.close();else g.close(),X.reject(Error("spare_closed: the spare was closed before it was claimed"));x()},async[Symbol.asyncDispose](){de.close(),await x()}};return de}async function Di(e,i){let l=await import("./core-b9ebje8h.mjs");return l.getSessionInfo(e,i)}async function Ni(e,i,l){let u=await import("./core-nv0a4kre.mjs");return u.renameSession(e,i,l)}async function Li(e,i,l){let u=await import("./core-nv0a4kre.mjs");return u.tagSession(e,i,l)}async function Ki(e,i){let l=await import("./core-nv0a4kre.mjs");return l.archiveSession(e,i)}async function Fi(e,i){let l=await import("./core-nv0a4kre.mjs");return l.unarchiveSession(e,i)}async function Ui(e,i){let l=await import("./core-nv0a4kre.mjs");return l.deleteSession(e,i)}import{McpServer as $i}from"@modelcontextprotocol/sdk/server/mcp.js";import{normalizeObjectSchema as ji}from"@modelcontextprotocol/sdk/server/zod-compat.js";import{toJsonSchemaCompat as zi}from"@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";import{globalRegistry as Ps}from"zod/v4";import{version as Le}from"zod/v4/core";function Hi(e,i,l,u,p){let m={};if(p?.searchHint)m["anthropic/searchHint"]=p.searchHint;if(p?.alwaysLoad)m["anthropic/alwaysLoad"]=!0;return{name:e,description:i,inputSchema:l,handler:u,annotations:p?.annotations,_meta:Object.keys(m).length>0?m:void 0}}var Bi="CLAUDE_SDK_MCP_TOOL_SCHEMA_UNCONVERTIBLE";function qi(e){let i=new $i({name:e.name,version:e.version??"1.0.0"},{capabilities:{tools:e.tools?{}:void 0},instructions:e.instructions});if(e.tools)e.tools.forEach((u)=>{let p=u.inputSchema;if(Wi(u.inputSchema)){let k=[];for(let[E,x]of Object.entries(u.inputSchema)){if(!Ft(x)){k.push([E,x]);continue}let O=Vi(x),M=x.description;if(M&&!Ps.has(O))Ps.add(O,{description:M});k.push([E,O])}p=Object.fromEntries(k)}let m=i.registerTool(u.name,{description:u.description,inputSchema:p,annotations:u.annotations,_meta:e.alwaysLoad?{"anthropic/alwaysLoad":!0,...u._meta}:u._meta},u.handler);if(!Object.getOwnPropertyDescriptor(m,"enabled")?.configurable||!Object.isExtensible(m))return;let g=m.enabled,b,A;Object.defineProperty(m,"enabled",{configurable:!0,enumerable:!0,get(){if(!g||b===m.inputSchema)return g;try{let k=ji(m.inputSchema);if(k)zi(k,{strictUnions:!0,pipeStrategy:"input"});return b=m.inputSchema,!0}catch(k){if(A!==m.inputSchema){A=m.inputSchema;let E=Hn(h(k),"."),x=[`Tool "${u.name}" on SDK MCP server "${e.name}" was left out of the server's tool list, because its input schema cannot be converted to JSON Schema${E?`: ${E}`:""}. The server's other tools are unaffected.`,...Gi(u.inputSchema,k)].join(" ");if(typeof process<"u"&&typeof process.emitWarning==="function")process.emitWarning(x,{code:Bi});else console.warn(x)}return!1}},set(k){g=k}})});let l=vt(e.timeout);return{type:"sdk",name:e.name,instance:i,...l!==void 0&&{timeout:l}}}function Gi(e,i){if(i instanceof ReferenceError)return["Something this tool's schema reads, such as a z.lazy target or a default value, is not defined yet. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back."];let p=`${Le.major}.${Le.minor}.${Le.patch}`,m=Object.values(e).filter(Ft).map((E)=>E._zod?.version).find((E)=>typeof E?.major==="number"&&(E.major!==Le.major||E.minor!==Le.minor||E.patch!==Le.patch)),y=m&&`this tool's schema was built with zod ${m.major}.${m.minor}.${m.patch}, and this SDK converts schemas with its own zod ${p}`,g=`${Le.major}.${Le.minor}`;if(!(i instanceof TypeError)){let E=["Change this tool's schema so that every field can be converted."];if(y)E.push(`A different zod version can also cause this: ${y}, so building the schema with zod ${g} may fix it.`);return E}let b="a schema this tool uses is not defined yet, or a zod 3 schema is nested inside a zod 4 one. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). Build the whole schema with zod 3 or with zod 4, not a mix of the two. A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back.";if(!m)return[`This can mean ${b}`];let A=[`The zod versions differ: ${y}. Conversion can fail across versions, so build the schema with zod ${g}, or use an SDK release that bundles your zod version.`],k=m.major===4&&m.minor<=3;if(k)A.push(`On zod ${m.major}.${m.minor}, a z.record given only one argument also causes this; pass both, as in z.record(keySchema, valueSchema).`);return A.push(`If ${k?"neither is the cause":"the version difference is not the cause"}, it can mean ${b}`),A}function Ft(e){return typeof e==="object"&&e!==null&&"_zod"in e}function Wi(e){return typeof e==="object"&&e!==null&&!("_zod"in e)&&!("_def"in e)&&typeof e.parse!=="function"}function Vi(e){if(!(Yi(e)?!We(e,!0):Kt(e)&&!We(e,!1))||e._zod.optin!=="optional"||e._zod.optout!=="optional"||typeof e.clone!=="function")return e;let l=e.clone();return l._zod.optin="defaulted",l}function Yi(e){let i=e._zod.version;return i?.major===4&&i.minor<5}function We(e,i,l=new Set){if(!Ft(e)||l.has(e))return!1;l.add(e);let u=e._zod.def;switch(u.type){case"lazy":return!0;case"optional":return!i&&We(u.innerType,i,l);case"nullable":case"catch":case"readonly":return We(u.innerType,i,l);case"pipe":return We(u.in,i,l)||We(u.out,i,l);case"union":return u.options?.some((p)=>We(p,i,l))??!1;default:return!1}}function Kt(e,i=new Set){if(!Ft(e)||i.has(e))return!1;i.add(e);let l=e._zod.def;switch(l.type){case"default":case"prefault":return!0;case"optional":case"nullable":case"catch":case"readonly":return Kt(l.innerType,i);case"pipe":return Kt(l.in,i);case"union":return l.options?.some((u)=>Kt(u,i))??!1;default:return!1}}async function Qi(e){let{resolveSettingsForSdk:i}=await import("./core-8fprsbvz.mjs");return i(e)}var Xi=new Set(["bypassPermissions","auto","acceptEdits"]),Zi=new Set(["project"]),Ji=new Set(["project","local"]);function ea(e){let i=e.effective.permissions?.defaultMode;if(!i||!Xi.has(i))return e.effective;for(let l=e.sources.length-1;l>=0;l--){let u=e.sources[l];if(u.settings.permissions?.defaultMode!==void 0){if((Xn.includes(i)?Ji:Zi).has(u.source)){let{defaultMode:m,...y}=e.effective.permissions??{};return{...e.effective,permissions:y}}return e.effective}}return e.effective}async function ta(e,i){let{matchDeniedModelsForSdk:l}=await import("./core-6w7w19rc.mjs");return l(e,i)}var ra=["You've hit your","You've reached your","You're out of usage credits","Your org is out of usage · add funds to continue","Your org is out of usage · contact your admin","Your seat type doesn't include usage credits","Your seat type doesn't include usage","Your usage allocation has been disabled by your admin","Your group's usage limit is set to $0","Fable 5 requires usage credits","You're out of extra usage","Your seat type doesn't include extra usage"];var na=["This service is disabled for your org"],sa=["You've used","You're close to"],oa=["You're now using usage credits","You're now using your usage allocation","Now using your usage allocation","Now using usage credits","Now using credits","You're now using extra usage","Now using extra usage"];export{De as AbortError,nr as BUILTIN_TOOL_NAMES,rr as EXIT_REASONS,q as HOOK_EVENTS,xt as LEGACY_TOOL_NAME_ALIASES,na as ORG_POLICY_LIMIT_PREFIXES,or as SYSTEM_PROMPT_DYNAMIC_BOUNDARY,ra as USAGE_LIMIT_ERROR_PREFIXES,oa as USAGE_TRANSITION_PREFIXES,sa as USAGE_WARNING_PREFIXES,Ki as archiveSession,qi as createSdkMcpServer,Ui as deleteSession,ea as filterEscalatingDefaultMode,Di as getSessionInfo,ta as matchDeniedModels,Ii as prewarm,Pi as query,Ni as renameSession,Qi as resolveSettings,Oi as startup,Li as tagSession,Hi as tool,Fi as unarchiveSession};
|