@henlii/pidance 0.2.36 → 0.2.39
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/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +13 -10
- package/.next/build-manifest.json +6 -6
- package/.next/prerender-manifest.json +18 -3
- package/.next/required-server-files.json +29 -9
- package/.next/routes-manifest.json +20 -0
- package/.next/server/app/_global-error/page.js +2 -3
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.meta +16 -5
- package/.next/server/app/_global-error.rsc +3 -3
- package/.next/server/app/_global-error.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +16 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js +1 -2
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.meta +16 -5
- package/.next/server/app/_not-found.rsc +7 -7
- package/.next/server/app/_not-found.segments/_full.segment.rsc +7 -7
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +20 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/about/route.js +1 -1
- package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
- package/.next/server/app/api/agent/[id]/events/route.js +2 -2
- package/.next/server/app/api/agent/[id]/route.js +1 -1
- package/.next/server/app/api/agent/new/route.js +1 -1
- package/.next/server/app/api/agent/running/events/route.js +2 -2
- package/.next/server/app/api/agent/running/route.js +1 -1
- package/.next/server/app/api/agent/submissions/[submissionId]/route.js +1 -1
- package/.next/server/app/api/agent-settings/route.js +2 -2
- package/.next/server/app/api/attachments/route.js +1 -1
- package/.next/server/app/api/auth/all-providers/route.js +1 -1
- package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
- package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/providers/route.js +1 -1
- package/.next/server/app/api/auth/ui-session/route.js +1 -1
- package/.next/server/app/api/auth/ui-sessions/[id]/route.js +1 -1
- package/.next/server/app/api/auth/ui-sessions/route.js +1 -1
- package/.next/server/app/api/cwd/browse/route.js +1 -1
- package/.next/server/app/api/cwd/create/route.js +1 -1
- package/.next/server/app/api/cwd/validate/route.js +1 -1
- package/.next/server/app/api/default-cwd/route.js +1 -1
- package/.next/server/app/api/file-index/route.js +1 -1
- package/.next/server/app/api/files/[...path]/route.js +3 -3
- package/.next/server/app/api/files/save-as/route.js +1 -1
- package/.next/server/app/api/git/diff/route.js +1 -1
- package/.next/server/app/api/git/status/route.js +1 -1
- package/.next/server/app/api/home/route.js +1 -1
- package/.next/server/app/api/message-media/route.js +1 -1
- package/.next/server/app/api/models/enabled/route.js +1 -0
- package/.next/server/app/api/models/enabled/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/models/refresh/route.js +1 -0
- package/.next/server/app/api/models/refresh/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/models/route.js +1 -1
- package/.next/server/app/api/models-config/raw/route.js +1 -1
- package/.next/server/app/api/models-config/route.js +1 -1
- package/.next/server/app/api/models-config/test/route.js +1 -1
- package/.next/server/app/api/plugins/route.js +1 -1
- package/.next/server/app/api/plugins/search/route.js +1 -1
- package/.next/server/app/api/plugins/updates/route.js +1 -1
- package/.next/server/app/api/preferences/route.js +1 -1
- package/.next/server/app/api/project-assets/route.js +2 -2
- package/.next/server/app/api/prompts/route.js +1 -1
- package/.next/server/app/api/pty/route.js +2 -2
- package/.next/server/app/api/sessions/[id]/archive/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/command-entry/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/info/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/lock/route.js +1 -0
- package/.next/server/app/api/sessions/[id]/lock/route_client-reference-manifest.js +1 -0
- package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/tool-results/[toolCallId]/route.js +1 -1
- package/.next/server/app/api/sessions/route.js +1 -1
- package/.next/server/app/api/sessions/search/route.js +1 -1
- package/.next/server/app/api/settings/raw/route.js +2 -2
- package/.next/server/app/api/settings/remote/route.js +1 -1
- package/.next/server/app/api/skills/check/route.js +1 -1
- package/.next/server/app/api/skills/install/route.js +1 -1
- package/.next/server/app/api/skills/route.js +2 -2
- package/.next/server/app/api/skills/search/route.js +1 -1
- package/.next/server/app/api/skills/update/route.js +1 -1
- package/.next/server/app/api/subagent-runs/route.js +1 -1
- package/.next/server/app/api/update/apply/route.js +2 -2
- package/.next/server/app/api/update/check/route.js +1 -1
- package/.next/server/app/icon.png/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.meta +11 -4
- package/.next/server/app/index.rsc +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +19 -3
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/page.js +13 -14
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +13 -10
- package/.next/server/chunks/1069.js +1 -1
- package/.next/server/chunks/1207.js +2 -2
- package/.next/server/chunks/1813.js +1 -1
- package/.next/server/chunks/2325.js +2 -2
- package/.next/server/chunks/2430.js +193 -0
- package/.next/server/chunks/329.js +1 -1
- package/.next/server/chunks/3379.js +1 -1
- package/.next/server/chunks/3960.js +1 -1
- package/.next/server/chunks/42.js +1 -0
- package/.next/server/chunks/4367.js +1 -1
- package/.next/server/chunks/4674.js +1 -1
- package/.next/server/chunks/4741.js +152 -7
- package/.next/server/chunks/4980.js +1 -1
- package/.next/server/chunks/5274.js +1 -1
- package/.next/server/chunks/5304.js +2 -2
- package/.next/server/chunks/5318.js +1 -1
- package/.next/server/chunks/5420.js +1 -0
- package/.next/server/chunks/5726.js +1 -1
- package/.next/server/chunks/7307.js +1 -1
- package/.next/server/chunks/7594.js +11 -10
- package/.next/server/chunks/7818.js +1 -0
- package/.next/server/chunks/8359.js +1 -1
- package/.next/server/chunks/8443.js +1 -0
- package/.next/server/chunks/8645.js +1 -1
- package/.next/server/chunks/9280.js +3 -3
- package/.next/server/chunks/940.js +1 -1
- package/.next/server/chunks/981.js +1 -1
- package/.next/server/chunks/9935.js +1 -1
- package/.next/server/instrumentation.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware-react-loadable-manifest.js +1 -1
- package/.next/server/middleware.js +151 -6
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/prefetch-hints.json +39 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/{1377.e883e13864574c26.js → 1377.540f9477711dcf8f.js} +1 -1
- package/.next/static/chunks/{3308.23eadd1744bb967c.js → 3308.c0a1a01bfd826d65.js} +2 -2
- package/.next/static/chunks/{370.57cfa27da8567918.js → 370.8e8f3cf8eb0e29dd.js} +1 -1
- package/.next/static/chunks/3794-0a1186eb85c3950f.js +52 -0
- package/.next/static/chunks/4bd1b696-8a4ab4fdf0ae305a.js +1 -0
- package/.next/static/chunks/6121.eb9023b1cbc78ee2.js +1 -0
- package/.next/static/chunks/{5519-9fb47277a49697d8.js → 7444-80a846a8795bf6f4.js} +1 -1
- package/.next/static/chunks/{776.fe8e64ab3669a915.js → 776.4d418d68f76336c7.js} +1 -1
- package/.next/static/chunks/{8233.a465d18b04719c6d.js → 8233.e3b47a59bd72a3b3.js} +1 -1
- package/.next/static/chunks/{90542734.b75ad0df50bf68f5.js → 90542734.ae439f2382f58c51.js} +1 -1
- package/.next/static/chunks/9780-864f35ace9287b0b.js +1 -0
- package/.next/static/chunks/app/_global-error/page-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/about/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/events/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/new/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/running/events/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/running/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/agent-settings/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/attachments/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/all-providers/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/login/[provider]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/providers/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-session/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-sessions/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/cwd/browse/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/cwd/create/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/cwd/validate/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/default-cwd/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/file-index/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/files/[...path]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/files/save-as/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/git/diff/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/git/status/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/home/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/message-media/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models/enabled/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models/refresh/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models-config/raw/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models-config/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/models-config/test/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/plugins/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/plugins/search/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/plugins/updates/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/preferences/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/project-assets/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/prompts/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/pty/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/archive/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/context/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/export/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/info/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/lock/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/outline/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/state/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/sessions/search/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/settings/raw/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/settings/remote/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/skills/check/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/skills/install/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/skills/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/skills/search/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/skills/update/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/subagent-runs/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/update/apply/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/api/update/check/route-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/app/page-5f78e55ff0d87ec7.js +24 -0
- package/.next/static/chunks/{da12927c.00775c0e4542fd3e.js → da12927c.476aa688a637649c.js} +2 -2
- package/.next/static/chunks/{e868780c-16e43c5968ccf2bf.js → e868780c-1584512c612787d7.js} +1 -1
- package/.next/static/chunks/framework-b33a8f5d57cd8d87.js +1 -0
- package/.next/static/chunks/main-1b407bf74905d84a.js +5 -0
- package/.next/static/chunks/{main-app-06b2b50b226e40d1.js → main-app-d353053e6467499a.js} +1 -1
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-8f70dda1817cd20c.js +1 -0
- package/.next/static/chunks/{webpack-d2379fd13c5c78c6.js → webpack-2423c4442766d244.js} +1 -1
- package/.next/static/css/ea117138d33e0b37.css +1 -0
- package/.next/static/vD56I5OFkAr4Y9TsF1L7c/_buildManifest.js +1 -0
- package/README.en.md +10 -1
- package/README.md +10 -1
- package/bin/pidance-auth-gate.js +41 -11
- package/bin/pidance-http-server.js +7 -0
- package/bin/pidance.js +5 -1
- package/bin/pty-ws.js +126 -3
- package/package.json +6 -4
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +0 -5
- package/.next/server/app/_global-error.segments/_head.segment.rsc +0 -5
- package/.next/server/app/_global-error.segments/_index.segment.rsc +0 -5
- package/.next/server/app/_not-found.segments/_head.segment.rsc +0 -6
- package/.next/server/app/_not-found.segments/_index.segment.rsc +0 -7
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +0 -5
- package/.next/server/app/index.segments/_head.segment.rsc +0 -6
- package/.next/server/app/index.segments/_index.segment.rsc +0 -7
- package/.next/server/chunks/188.js +0 -1
- package/.next/server/chunks/319.js +0 -45
- package/.next/server/chunks/6953.js +0 -1
- package/.next/static/9m7dmaudtohXTam6OFJrW/_buildManifest.js +0 -1
- package/.next/static/chunks/3794-907785a527d8128b.js +0 -32
- package/.next/static/chunks/4bd1b696-e356ca5ba0218e27.js +0 -1
- package/.next/static/chunks/6121.5b8cb3199531d194.js +0 -1
- package/.next/static/chunks/9780-190981a7d5f4799b.js +0 -1
- package/.next/static/chunks/app/_global-error/page-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/about/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/events/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/new/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/running/events/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/running/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/agent-settings/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/attachments/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/all-providers/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/login/[provider]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/providers/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-session/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-sessions/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/cwd/browse/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/cwd/create/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/cwd/validate/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/default-cwd/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/file-index/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/files/[...path]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/files/save-as/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/git/diff/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/git/status/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/home/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/message-media/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/models/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/models-config/raw/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/models-config/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/models-config/test/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/plugins/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/plugins/search/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/plugins/updates/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/preferences/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/project-assets/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/prompts/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/pty/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/archive/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/context/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/export/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/info/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/outline/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/state/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/sessions/search/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/settings/raw/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/settings/remote/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/skills/check/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/skills/install/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/skills/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/skills/search/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/skills/update/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/subagent-runs/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/update/apply/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/api/update/check/route-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/app/page-a67f4b63843f6c4b.js +0 -24
- package/.next/static/chunks/framework-711ef29bc66f648c.js +0 -1
- package/.next/static/chunks/main-8e7ef001ea9dd641.js +0 -5
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-7c63ab7d3880fba7.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-7c63ab7d3880fba7.js +0 -1
- package/.next/static/css/82b378f5d9cf6c9d.css +0 -1
- /package/.next/static/{9m7dmaudtohXTam6OFJrW → vD56I5OFkAr4Y9TsF1L7c}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>A,v7:()=>B});var e=c(75430),f=c(60396),g=c(35768),h=c(68524),i=c(89953),j=c(5815),k=c(69835),l=c(99014),m=c(85664),n=c(65107),o=c(95237),p=c(38195),q=c(62693),r=c(23828),s=c(31524),t=c(52960),u=c(13737),v=c(60185),w=c(28121),x=c(87538),y=a([e,k,o,v,w]);[e,k,o,v,w]=y.then?(await y)():y;let B="Session writer is busy: a command is still in flight";function z(a){return"string"==typeof a&&a?a:void 0}class C{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,x.Lm)(),this.toolRenderStates=new Map,this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,f.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of this.listeners)try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}hasActiveSubagentRun(){let a=this.realSessionFile;if(!a)return!1;try{let{runs:b}=(0,g._2)({limit:50});return(0,g.EE)(b,a)}catch{return!1}}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if(this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(!(this.listeners.length>0)){if(this.hasActiveSubagentRun())return void this.resetIdleTimer();this.destroyAsync().catch(()=>{})}}},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,h.rV)(this.agentDir);return!0===(0,h.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,h.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,h.rV)(this.agentDir),b=(0,h.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,l.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>l.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${l.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,l.S1)(this.followUpAdmittedAttemptIds,c);try{(0,h.xP)(`sessionQueue.${this.realSessionId}`,(0,l.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,l.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,k.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:k.Md,c=(0,k.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>l.ym)return!1;let b=0;for(let c of a){let a=(0,k.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:k.Md;if(a>d||(b+=a,c.previewPath&&null===(0,k.vy)(c.previewPath,this.agentDir)))return!1}return b<=k.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,l.Ot)(a)){if("model"!==d.role)continue;let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,l.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,l.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,k.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,k.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,l.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,l.ko)(a.text,"claimed",a.media):(0,l.ko)(a.text,"claimed"));c&&g.push((0,l.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let k=e.images.length?e.images:void 0,m="prompt";try{if(this.session.isStreaming)m="steer",await this.session.steer(d,k);else{let a=await this.send({type:"prompt",message:d,...k?.length?{images:k}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return m="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,t.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let n=(0,l.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(n),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,h.rV)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0,this.sendNextFollowUp()}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,l.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let k=new Set(d),m=(0,l.Ot)(c),n=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");n&&this.discardDeliveredModelMedia(m),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),n||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,p.t)(a=>{this.trackExtensionSideEffects(a),this.emit(a)}),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"rpc",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=z(a.method);if("setStatus"===b){let b=z(a.statusKey)??z(a.key)??"default",c=z(a.statusText)??z(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=z(a.widgetKey)??z(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,o.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(u.uG,a);this.emit({type:"message_end",entryId:e,message:(0,u.FH)(a,Date.now())})}(0,o.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&C.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=C.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,n.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld())&&!this.hasActiveSubagentRun();this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,o.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}this.emit(this.withRenderedToolLines(e))}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!0,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,a.partialResult,{expanded:!0,isPartial:!0},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedLines:d}:a}case"tool_call":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.input,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!c)return a;let d=(0,x.GD)(b,a.input,c,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b));return d?{...a,renderedCallLines:d}:a}case"tool_result":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!1,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,{content:a.content,details:a.details,isError:!0===a.isError,...void 0!==a.usage?{usage:a.usage}:{}},{expanded:!0,isPartial:!1},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedResultLines:d}:a}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,x.Mf)(d,a.message,this.renderBridgeTheme);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<C.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,o.G1)(a):(0,o.Qu)(b)),d=c.getCwd()||this.options.cwd,f=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let f=(0,w._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:w.Jv,label:"Send file to user",description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:w.Tv,async execute(a,b,c){let d=await f(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,e.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:w.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,s.yu)(a);return{...await (0,e.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,e.createAgentSessionRuntime)(h,{cwd:d,agentDir:f,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),activeCustomUi:this.extensionUi?.customSnapshot??null};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,l.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,m.qF)(a):(0,m.l$)(a),c=this.session.sessionManager.appendCustomEntry(m.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,v.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(u.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,u.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,t.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,v.Nu)(c.binaryBlocks,this.agentDir),k=c.images??a.images,l=this.resolvePromptImages(k);if(l.missing.length){console.error("[pidance] prompt image missing on disk:",l.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,r.D)(c.message)){let a=this.queueMediaFromPromptImages(k);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:l.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,i.kP)(this.realSessionId))throw Error(i.GT);this.promptRunning=!0,this.lastStopReason=null,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();let m=(async()=>{try{await new Promise((b,e)=>{let g=!1,i=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,j.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:l.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,h.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:h}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,o.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}i()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),i(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,t.K2)(g);if(d.isStreaming&&(0,t.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,m),m}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,q.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,s.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,s.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,t._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,t.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,t.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,t.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,t.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=z(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=z(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:z(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,n.R3)(this.realSessionFile,a):this.realSessionFile&&(0,n.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.selectLeafExact(this.sessionId,b,a)}let e=await d.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,n.R3)(this.realSessionFile,a):(0,n.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=z(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.branchFromAssistant(this.sessionId,b,a)}throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.createSessionFromLeaf(this.sessionId,b,a)}throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error(B);await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,j.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function A(a){let b=new C(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}function h(){return e()}},6032:(a,b,c)=>{c.d(b,{Y:()=>d,f:()=>e});let d="__new__";function e(a){return a.startsWith(d)}},23828:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},25252:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(50593);function e(){return globalThis.__piAdditionalAllowedRoots||(globalThis.__piAdditionalAllowedRoots=new Set),globalThis.__piAdditionalAllowedRoots}function f(a){if(!a)return;let b=(0,d.Nw)(a);e().add(b),globalThis.__piAllowedRootsCache?.roots.add(b)}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>w,A4:()=>o,DU:()=>q,EM:()=>t,Fn:()=>v,HG:()=>s,OF:()=>y,YZ:()=>f.Y});var e=c(40402),f=c(6032),g=c(95237),h=c(68524),i=c(2416),j=c(5815),k=c(89953),l=a([e,g,i]);function m(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function n(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function o(a){return m().get(a)}function p(){return[...n().keys()]}async function q(a){let b=n().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function r(){let a=new Set(p());for(let[b,c]of m())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function s(){return r()}[e,g,i]=l.then?(await l)():l;let A=new Map;function t(a,b=Date.now()){let c={},d=(0,j.MG)(),e=r(),f=new Set(e);for(let a of e){let e=d.get(a)??A.get(a)??b;A.set(a,e),c[a]=e}for(let a of[...A.keys()])f.has(a)||A.delete(a);return c}function u(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function v(a){let b=u();return b.add(a),()=>{b.delete(a)}}function w(){let a=[];for(let[b,c]of m()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let B="",C=[],D=new Set,E=null;function x(){!function a(){let b=new Set(function(){let a=new Set(p());for(let[b,c]of m())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,k.AZ)(a),D.add(a);for(let a of[...D])b.has(a)||((0,k.Hl)(a),D.delete(a));if(0===b.size){E&&(clearInterval(E),E=null);return}E||(E=setInterval(()=>{a()},8e3),E.unref?.())}();let a=s(),b=w(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c===B)return;B=c;let d=C.filter(b=>!a.includes(b)&&!(0,f.f)(b));if(C=[...a],d.length>0){let a=new Date().toISOString();setTimeout(()=>{for(let b of d)try{(0,h.xP)(`unreadSessionState.completedAt.${b}`,a)}catch(a){console.error("[pidance] failed to record unread completedAt:",a)}},0)}for(let b of u())try{b(a)}catch{}}async function y(a,b,c,d,e){return z(a,b,c,d,e)}async function z(a,b,c,d,f){let g=m(),h=n(),j=g.get(a);if(j?.isAlive())return{session:j,realSessionId:a};let l=h.get(a);if(l)return l;if(!(0,k.kP)(a))throw Error(k.GT);x();let o=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>x(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=m(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,k.kP)(b),(0,k.Hl)(a))}}),j=h.sessionId,l=h.sessionFile;return l&&(0,e.O8)(j,l),j!==a&&(0,k.kP)(j),h.onDestroy(()=>{g.get(j)===h&&g.delete(j),a!==j&&g.get(a)===h&&g.delete(a),(0,k.Hl)(j),a!==j&&(0,k.Hl)(a),x()}),g.set(j,h),h.beginExtensionBinding(),{session:h,realSessionId:j}}catch(b){throw(0,k.Hl)(a),x(),b}})().finally(()=>{h.delete(a),x()});return h.set(a,o),o}d()}catch(a){d(a)}})},28121:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>t,_D:()=>q,n3:()=>n});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(69835),j=c(80547),k=c(1060),l=c(60185),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===s)?a:[...a,s]}let t={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},35768:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>t,gd:()=>E,st:()=>s});var d=c(89477),e=c.n(d),f=c(62228),g=c.n(f),h=c(86697),i=c.n(h);let j=/^[A-Za-z0-9_-]{1,128}$/,k=/^output-\d+\.log$/,l=new Set(["queued","running","complete","failed","paused","stopped"]),m=new Set(["single","parallel","chain"]),n=new Set(["active_long_running","needs_attention"]),o={readdirSync:a=>e().readdirSync(a),lstatSync:a=>e().lstatSync(a),realpathSync:a=>e().realpathSync(a),readFileSync:(a,b)=>e().readFileSync(a,b),openSync:(a,b)=>e().openSync(a,b),readSync:(a,b,c,d,f)=>e().readSync(a,b,c,d,f),closeSync:a=>e().closeSync(a),fstatSync:a=>e().fstatSync(a),constants:e().constants};function p(a){return a.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}let q=new Set(["running","queued","paused"]);function r(a,b,c=Date.now(),d=9e5){let e="string"==typeof b?b:"";if(!e.endsWith(".jsonl"))return!1;let f=e.slice(0,-6),g=a=>{if("string"!=typeof a||!a||!a.startsWith(f))return!1;let b=a.charAt(f.length);return"/"===b||"\\"===b};for(let b of a??[]){if(!b||"object"!=typeof b||!q.has(b.state))continue;let a=b.lastUpdate??b.startedAt;if("number"!=typeof a||!(c-a>d)){for(let a of b.steps??[])if(g(a?.sessionFile))return!0}}return!1}function s(a){if(null==a||""===a)return 20;if(!/^\d+$/.test(a))return null;let b=Number(a);return!Number.isInteger(b)||b<1||b>50?null:b}function t(a={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),s=a.root??(b=a.scope,h=b?.tmpdir?.()??g().tmpdir(),i().join(h,`pi-subagents-${function(a){let b=a?.env??process.env,c=a&&Object.hasOwn(a,"getuid")?a.getuid:process.getuid?.bind(process);if("function"==typeof c)return`uid-${c()}`;for(let a of["USERNAME","USER","LOGNAME"]){let c=b[a];if(c)return`user-${p(c)}`}let d=a&&Object.hasOwn(a,"userInfo")?a.userInfo:g().userInfo;try{let a=d?.().username;if(a)return`user-${p(a)}`}catch{}let e=b.USERPROFILE??b.HOME;if(e)return`home-${p(e)}`;let f=a&&Object.hasOwn(a,"homedir")?a.homedir:g().homedir;try{let a=f?.();if(a)return`home-${p(a)}`}catch{}return"shared"}(b)}`,"async-subagent-runs"));try{let a=n.lstatSync(s);if(a.isSymbolicLink()||!a.isDirectory())return u(r,!1);e=n.realpathSync(s)}catch(a){return v(a),u(r,!1)}try{f=n.readdirSync(s)}catch(a){return v(a),u(r,!1)}f.length>256&&(f=f.slice(0,256));let D=[];for(let a of f)if(j.test(a))try{let b=function(a,b,c,d){var e,f;let g,h,j,n,o=i().join(b,d);try{g=a.lstatSync(o)}catch{return null}if(g.isSymbolicLink()||!g.isDirectory())return null;try{h=a.realpathSync(o)}catch{return null}if(!w(h,c))return null;let p=function(a,b,c){let d=x(a,b,c);if(!d)return null;let{fd:e,size:f}=d;try{if(f<=0||f>2097152)return null;let b=Buffer.alloc(f),c=0;for(;c<f;){let d=a.readSync(e,b,c,f-c,c);if(0===d)break;c+=d}let d=b.subarray(0,c).toString("utf8"),g=JSON.parse(d);if(!g||"object"!=typeof g||Array.isArray(g))return null;return g}catch{return null}finally{try{a.closeSync(e)}catch{}}}(a,i().join(o,"status.json"),c);if(!p)return null;let q=(e=p.state,"string"==typeof e&&l.has(e)?e:void 0);if(!q)return null;let r=(f=p.mode,("string"==typeof f&&m.has(f)?f:void 0)??"single"),s=A(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=z(p.activityState),v=A(p.endedAt),D=A(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=A(p.currentStep),H=A(p.chainStepCount),I=B(p.totalTokens),J=C(p.totalCost),K=function(a){if(!Array.isArray(a))return[];let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if(!d||"object"!=typeof d||Array.isArray(d)){b.push({index:c,agent:"unknown",status:"unknown"});continue}let e="string"==typeof d.agent&&d.agent?d.agent:"unknown",f={index:c,agent:e,status:"string"==typeof d.status&&d.status?d.status:"unknown"};"string"==typeof d.label&&(f.label=d.label),"string"==typeof d.model&&(f.model=d.model),"string"==typeof d.sessionFile&&(f.sessionFile=d.sessionFile),"string"==typeof d.error&&(f.error=d.error);let g=z(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=B(d.tokens);h&&(f.tokens=h);let i=C(d.totalCost)??A(d.costUsd);void 0!==i&&(f.costUsd=i);let j=A(d.startedAt);void 0!==j&&(f.startedAt=j);let k=A(d.endedAt);void 0!==k&&(f.endedAt=k),Array.isArray(d.recentOutput)&&(f.recentOutput=function(a){let b=[];for(let c of a){if(b.length>=8)break;"string"==typeof c&&b.push(c.length>200?c.slice(0,200):c)}return b}(d.recentOutput)),b.push(f)}return b}(p.steps),L=function(a,b,c){let d=y(a,b,c,65536);if(!d||!d.text)return[];let e=d.text;if(d.truncated){let a=e.indexOf("\n");a>=0&&(e=e.slice(a+1))}let f=e.split(/\r?\n/).filter(a=>a.trim().length>0),g=[];for(let a=f.length-1;a>=0&&g.length<20;a-=1)try{let b=JSON.parse(f[a]);if(!b||"object"!=typeof b||Array.isArray(b))continue;let c="string"==typeof b.type?b.type:void 0;if(!c)continue;let d={type:c},e=A(b.timestamp)??A(b.ts)??A(b.time);void 0!==e&&(d.timestamp=e);let h="string"==typeof b.message?b.message:"string"==typeof b.error?b.error:void 0;void 0!==h&&(d.message=h.length>200?h.slice(0,200):h),g.push(d)}catch{}return g.reverse(),g}(a,i().join(o,"events.jsonl"),c),M=function(a,b){if("string"!=typeof a||!a.trim())return null;let c=i().basename(a.trim());return k.test(c)?{absPath:i().join(b,c)}:null}(p.outputFile,o);if(M){let b=y(a,M.absPath,c,32768);if(b){let a=b.text;if(b.truncated){let b=a.indexOf("\n");b>=0&&(a=a.slice(b+1))}j=a,n=b.truncated}}let N={id:t,state:q,mode:r,startedAt:s,steps:K,recentEvents:L};return u&&(N.activityState=u),void 0!==v&&(N.endedAt=v),void 0!==D&&(N.lastUpdate=D),void 0!==E&&(N.cwd=E),void 0!==F&&(N.error=F),void 0!==G&&(N.currentStep=G),void 0!==H&&(N.chainStepCount=H),I&&(N.totalTokens=I),void 0!==J&&(N.totalCostUsd=J),void 0!==j&&(N.outputTail=j),void 0!==n&&(N.outputTruncated=n),N}(n,s,e,a);b&&D.push(b)}catch{}return{runs:(c=D,d=a=>{switch(a){case"running":return 0;case"queued":return 1;case"failed":case"stopped":case"paused":return 2;case"complete":return 3;default:return 4}},[...c].sort((a,b)=>{let c=d(a.state)-d(b.state);if(0!==c)return c;let e=a.lastUpdate??a.endedAt??a.startedAt;return(b.lastUpdate??b.endedAt??b.startedAt)-e})).slice(0,Math.min(q,50)),generatedAt:r,rootAvailable:!0}}function u(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function v(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function w(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function x(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!w(e,c))return null;let f="number"==typeof a.constants.O_NOFOLLOW?a.constants.O_NOFOLLOW:0,g=a.openSync(b,a.constants.O_RDONLY|f);try{let c=a.fstatSync?a.fstatSync(g):a.lstatSync(b);if(!c.isFile())return a.closeSync(g),null;return{fd:g,size:c.size}}catch{try{a.closeSync(g)}catch{}return null}}catch{return null}}function y(a,b,c,d){let e=x(a,b,c);if(!e)return null;let{fd:f,size:g}=e;try{if(0===g)return{text:"",truncated:!1,size:0};let b=Math.min(d,g),c=Math.max(0,g-b),e=Buffer.alloc(b),h=0;for(;h<b;){let d=a.readSync(f,e,h,b-h,c+h);if(0===d)break;h+=d}return{text:e.subarray(0,h).toString("utf8"),truncated:g>d,size:g}}finally{try{a.closeSync(f)}catch{}}}function z(a){return"string"==typeof a&&n.has(a)?a:void 0}function A(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=A(a.input),c=A(a.output),d=A(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function C(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:A(a.costUsd)}function D(a){let b=a.trim();if(!b)return"";let c=/^[a-zA-Z]:[\\/]/.test(b)||b.startsWith("\\\\")||b.startsWith("//"),d=c?i().win32:i().posix,e=c?b.replace(/\//g,"\\"):b.replace(/\\/g,"/"),f=d.normalize(e);return c?f.toLowerCase():f}function E(a,b){let c=new Map;for(let a of b){if(!0!==a.readOnly||"string"!=typeof a.id||!a.id||"string"!=typeof a.path||!a.path)continue;let b=D(a.path);b&&(c.has(b)||c.set(b,a.id))}let d=a.runs.map(a=>{let b=!1,d=a.steps.map(a=>{if(!a.sessionFile)return a;let d=D(a.sessionFile),e=d?c.get(d):void 0;if(!e){if(void 0===a.sessionId)return a;let c={...a};return delete c.sessionId,b=!0,c}return a.sessionId===e?a:(b=!0,{...a,sessionId:e})});return b?{...a,steps:d}:a}),e=!1;for(let b=0;b<d.length;b+=1)if(d[b]!==a.runs[b]){e=!0;break}return e?{...a,runs:d}:a}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>M,DQ:()=>L,Md:()=>I,Wl:()=>J,Yz:()=>H,mB:()=>Q});var e=c(29021),f=c(716),g=c(33873),h=c(80547),i=c(91898),j=c(60396),k=c(95237),l=c(52960),m=c(79495),n=c(81879),o=c(46935),p=c(31514),q=c(65107),r=c(56429),s=c(40402),t=c(85664),u=c(15461),v=c(76817),w=c(86226),x=c(68524),y=c(89953),z=c(50955),A=c(40239),B=c(5815),C=c(99911),D=c(26773),E=c(2416),F=c(68816),G=a([h,i,k,n,r,s,D,E]);[h,i,k,n,r,s,D,E]=G.then?(await G)():G;let L="Subagent sessions are read-only";class M extends Error{constructor(){super(L)}toString(){return this.message}}async function H(a,b){if(await b(a))throw new M}function I(a){let b=a instanceof Error?a.message:String(a);return a instanceof M||b===L?403:b.includes("Session not found")?404:(0,y.wE)(a)||b===y.GT||b===E.v7||"Session is being deleted"===b||b.includes("closed while its title")?409:500}function J(a){let b=a instanceof Error?a.message:String(a);return"cwd is required"===b||b.startsWith("Directory does not exist:")?400:I(a)}let N="Submission was cancelled",O={listAllSessions:s.dQ,resolveSessionPath:s.os,getRpcSession:r.A4,waitForSessionStart:r.DU,startRpcSession:r.OF,getRunningRpcSessionIds:r.HG,listPendingExtensionUi:r.$k,subscribeRunningSessions:r.Fn,allowFileRoot:h.wz,invalidateSessionListCache:s.mD,openSessionCwd:a=>(0,k.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,s.Zx)({filePath:a}),openSessionView:k.kW,reparentSessionFile:k.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:A.Iq},P=["systemPrompt"];function K(a){(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null);let b=(0,x.rV)().unreadSessionState;b&&"object"==typeof b&&!Array.isArray(b)&&(b.completedAt&&"object"==typeof b.completedAt&&(0,x.xP)(`unreadSessionState.completedAt.${a}`,null),b.readAt&&"object"==typeof b.readAt&&(0,x.xP)(`unreadSessionState.readAt.${a}`,null))}let Q=function(a={}){let b={...O,...a},c=(0,A.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:s.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=new Map,r=new Map,x=a=>{if(r.set(a.submissionId,{info:a,cancelRequested:!1,cancelApplied:!1}),!(r.size<=500))for(let[b,c]of r){if(r.size<=500)break;b!==a.submissionId&&"completed"===c.info.status&&r.delete(b)}},E=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},G=async(a,b)=>{if(!(0,y.kP)(a))throw Error(y.GT);try{return await b()}finally{(0,y.Hl)(a)}},I=async(a,b,c)=>(c?await c():await E(a),G(a,b)),J={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,A.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,A.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,A.rQ)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},getLiveSession:a=>J.getLive(a),isLive:a=>!!J.getLive(a),async ensureLive(a){if(await H(a,J.isReadOnly),h.has(a))throw Error("Session is being deleted");let c=J.getLive(a);if(c)return c;if((0,y.wy)(a))throw Error(y.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,L);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=h.get(a);if(c)return c;let d=(async()=>{await H(a,J.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{K(a)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),J.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,y.wy)(a)||(0,y.wy)(c))throw Error(y.GT);let f=(0,s.eP)(d)?.parentSession,h=(0,s.eP)(d)?.id===a?(0,z.ku)(d,a):[],j=b.getRpcSession(c)??b.getRpcSession(a),k=b.getRunningRpcSessionIds();if(j?.isAlive?.()&&(k.includes(a)||k.includes(c)))try{await j.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await J.destroyAsync(j?.sessionId??c),G(j?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,g.join)(c,a)!==d)){let e=(0,g.join)(c,a);try{let a=(0,s.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await I(a.id,()=>{b.reparentSessionFile(e,f)})):b.reparentSessionFile(e,f))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,q.$9)(d);let j=(0,g.resolve)(d.slice(0,-6)),k=(0,z.uq)(h,j,s.BR);try{K(a)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}try{(0,i.Fx)()}catch(a){console.error("[pidance] failed to sweep attachments:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),J.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:k}})})();return h.set(a,d),d.finally(()=>{h.get(a)===d&&h.delete(a)})},async start(a,c,d,e){if(await H(a,J.isReadOnly),h.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,L)},send:async(a,b)=>(await J.ensureLive(a)).send(b),async submitPrompt(a,b){await H(a,J.isReadOnly);let c=(0,l.JT)(b);try{let b=await J.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:"error"}}catch(b){if((0,y.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:(0,l.K2)(b)}}},async getAgentState(a,b){if(await J.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=J.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,y.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of P)delete c[a];return c}(d,b)}},async renameSession(a,c){await H(a,J.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=J.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await I(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await H(a,J.isReadOnly);let b=await J.ensureLive(a);await b.waitUntilReady?.();let c=await J.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,m.CL)(),f=await (0,m.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await J.destroyAsync(a),await J.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,n.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await J.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,{leafId:g,tree:h,context:i,header:j,sessionName:k}=(0,s.jK)(f,c),l=j?.parentSession?await (0,s.u1)(j.parentSession):void 0,m=(await b.listAllSessions()).find(b=>b.id===a),n=j?{path:e,id:j.id,cwd:j.cwd??"",name:k,created:j.timestamp,modified:j.timestamp,messageCount:i.totalMessageCount??i.messages.length,firstMessage:m?.firstMessage??"(no messages)",parentSessionId:l,...m?.subagent?{subagent:m.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:g,tree:h,context:i,header:j,sessionName:k,parentSessionId:l,info:n}},async getUserMessageOutline(a){let b=await J.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,s.CM)(d,c.getLeafId());return(0,C.Xm)((0,s.tY)(d,e))},async getContextPage(a,b){let c,d=await J.getReadView(a);if(!d)return{context:null};let e=d.manager,f=e.getEntries?.()??[],g=(0,s.Uv)(f,b.leafId,{deferThinking:b.deferThinking,deferToolResultImages:b.deferToolResultImages}),h=b.limit;if(b.around){let a=(0,o.PV)(g,b.around,h??o._w,{toEnd:!0===b.aroundToEnd});if(!a)return{context:null,notFound:b.around};c=a}else c=b.after?(0,o.WP)(g,b.after,h??o._w):b.before?(0,o.tr)(g,b.before,h??o._w):null!==h?(0,o.G1)(g,h):{...g,hasMoreBefore:!1,totalMessageCount:g.messages.length};return{context:c}},async getEntryThinking(a,b,c){let d=await J.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,p.mv)(f.type)?{thinking:(0,p.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await J.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await H(a,J.isReadOnly);let d=J.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,t.l$)(c),f=b.openSessionView(d).appendCustomEntry(t.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await H(a,J.isReadOnly),await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,u.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(u.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){let d;if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:e,modelId:g,toolNames:h,thinkingLevel:i,...j}=c,l="string"==typeof j.submissionId?j.submissionId:void 0,m=(d="string"==typeof j.message?j.message:"",`${a}\u0000${d}`);if(l){let a=r.get(l);if(a){if(a.info.fingerprint&&a.info.fingerprint!==m)throw a.info.status="conflict",Error("Submission conflict: this submissionId was already used with different content");if(a.cancelRequested)throw a.info.status="cancelled",Error(N);if(a.info.sessionId)return{sessionId:a.info.sessionId,data:null}}x({submissionId:l,status:"pending",fingerprint:m})}let n=`${D.YZ}${(0,f.randomUUID)()}`,{session:o,realSessionId:p}=await b.startRpcSession(n,"",a,h,L),q=l?r.get(l):void 0,s=q?.cancelRequested===!0;q&&(q.info.sessionId=p,q.info.status=s?"cancelled":"starting"),b.allowFileRoot(a),b.invalidateSessionListCache();try{if(s||(e&&g&&await o.send({type:"set_model",provider:e,modelId:g}),i&&await o.send({type:"set_thinking_level",level:i}),l&&r.get(l)?.cancelRequested))throw await J.destroyAsync(p),Error(N)}catch(a){throw q&&(q.info.error=a instanceof Error?a.message:String(a)),a}if("ensure_session"===j.type){try{let a=o.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,k.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:p,data:null}}let t=await o.send(j);return q&&(q.info.status="accepted",q.info.sessionId=p),{sessionId:p,data:t}},getSubmission(a){let b=r.get(a);return b?{...b.info}:null},cancelSubmission(a){let c=r.get(a);if(!c)return x({submissionId:a,status:"cancelled"}),r.get(a).cancelRequested=!0,Promise.resolve({submissionId:a,status:"pending"});c.cancelRequested=!0;let d=c.info.sessionId;if(!d)return c.info.status="cancelled",Promise.resolve({submissionId:a,status:"pending"});if(c.cancelApplied)return Promise.resolve({submissionId:a,status:"confirmed"});c.cancelApplied=!0,c.info.status="cancelled";let e=b.getRpcSession(d);return e?.isAlive()?(async()=>{try{await e.send({type:"abort"})}catch(a){console.error("[pidance] cancel submission abort failed:",a)}return{submissionId:a,status:"confirmed"}})():Promise.resolve({submissionId:a,status:"confirmed"})},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,B.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,D.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,F.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions(),g=(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=(0,A.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>h.has(a)),hits:d.hits.filter(a=>h.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(f===e)return{cancelled:!1};if(f===d.getLastEntryId())return(0,q.$9)(c),{cancelled:!1};if(!d.getEntry(f))throw Error(`Entry ${f} not found`);try{return d.branch(f),(0,q.R3)(c,f),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d)},async branchFromAssistant(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(!e)throw Error("Session has no leaf");let g=d.getBranch(e),h=d.getEntry(f);if(!h)throw Error("Entry not found");if("message"!==h.type||h.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let i=(0,v.wo)(g,f);try{return d.branch(i),i===d.getLastEntryId()?(0,q.$9)(c):(0,q.R3)(c,i),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d)},async createSessionFromLeaf(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a),h=g?.inner;return e=async()=>{let c=(h?.sessionFile||g?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=(0,k.kW)(c),e=d.getEntry(f);if(!e)throw Error("Invalid entry ID");let i=f;if("message"===e.type&&e.message?.role==="assistant"){let a=d.getLeafId();if(!a)throw Error("Session has no leaf");let b=d.getBranch(a);i=(0,v.wo)(b,f)}let j=d.getSessionDir(),l=(0,k.G1)(c,j),m=l.createBranchedSession(i);if(!m)throw Error("Failed to create session");(0,k.kb)(l);let n=(0,k.kW)(m,j),o=n.getSessionId();(0,s.O8)(o,m),b.invalidateSessionListCache();let p=h?.model;return p&&(0,w.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}},I(a,e,d)}},L={selectLeafExact:(a,b,c)=>J.selectLeafExact(a,b,c),branchFromAssistant:(a,b,c)=>J.branchFromAssistant(a,b,c),createSessionFromLeaf:(a,b,c)=>J.createSessionFromLeaf(a,b,c)};return J}();d()}catch(a){d(a)}})},38195:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(87538);function f(a,b,c,e,f,g,h){let i=(0,d.randomUUID)();return new Promise((d,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),e?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),d(a))},o=()=>n(f);e?.signal?.addEventListener("abort",o,{once:!0}),e?.timeout&&(k=setTimeout(()=>n(f),e.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function g(a){let b=new Map,c=new Map,g=new Map,h=new Map,i=new Map,j=null,k={select:(d,e,g)=>f(b,c,a,g,void 0,{method:"select",title:d,options:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(d,e,g)=>f(b,c,a,g,!1,{method:"confirm",title:d,message:e,timeout:g?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(d,e,g)=>f(b,c,a,g,void 0,{method:"input",title:d,placeholder:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:()=>()=>{},setStatus(b,c){c?g.set(b,c):g.delete(b),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(b,c,f){if("function"==typeof c){let a=(0,e.tU)(c,(0,e.Lm)());if(null===a)return;c=a}(void 0===c||Array.isArray(c))&&(null==c?h.delete(b):h.set(b,{lines:c,placement:f?.placement}),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:f?.placement}))},setFooter(){},setHeader(){},setTitle(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setTitle",title:b})},async custom(b){let c=(0,d.randomUUID)();return new Promise(d=>{let f,g=!1,h=b=>{g||(g=!0,i.delete(c),j?.id===c&&(j=null),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},l=()=>{if(g)return;let b=[];try{let a=f?.render?.(92);Array.isArray(a)&&(b=a.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}a({type:"extension_ui_request",id:c,method:"custom",lines:b}),j={id:c,lines:[...b]}};i.set(c,{handleInput:a=>{if("\x03"===a)return void h(void 0);try{f?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},done:h});let m=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{l()},92,40),n=(0,e.Lm)()??k.theme;Promise.resolve().then(()=>b(m,n,{},h)).then(a=>{g||(f=a,l())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),h(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"set_editor_text",text:b})},getEditorText:()=>"",editor:async(d,e)=>f(b,c,a,void 0,void 0,{method:"editor",title:d,prefill:e},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return new Proxy({fg:b,bg:b,bold:a,dim:a,italic:a},{get:(b,c)=>c in b?b[c]:"then"!==c?a:void 0})},getAllThemes:()=>[],getTheme(){},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>!1,setToolsExpanded(){}};return{uiContext:k,pending:b,statuses:g,widgets:h,pendingSnapshot:c,get customSnapshot(){return j},respond(a,c){let d=b.get(a);return!!d&&(d.resolve(c),!0)},inputCustom(a,b){let c=i.get(a);return!!c&&(c.handleInput(b),!0)},dispose(){for(let[a,d]of b)b.delete(a),c.delete(a),d.reject(Error("Extension UI disposed"));for(let a of i.values())a.done(void 0);i.clear(),j=null,g.clear(),h.clear()}}}},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},46935:(a,b,c)=>{c.d(b,{G1:()=>h,NN:()=>g,PV:()=>i,Uf:()=>d,WP:()=>j,_w:()=>e,tr:()=>k});let d=80,e=80;function f(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function g(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:f(e,b)}function h(a,b=d){let c=a.messages.length,e=f(b,d);if(c<=e)return{...a,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:c};let g=c-e;return{messages:a.messages.slice(g),entryIds:a.entryIds.slice(g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:c}}function i(a,b,c=e,d={}){let g=a.messages.length,h=a.entryIds.indexOf(b);if(h<0)return null;let j=f(c,e),k=Math.max(0,h-Math.max(1,Math.floor(j/2))),l=d.toEnd?g:Math.min(g,k+j);return{messages:a.messages.slice(k,l),entryIds:a.entryIds.slice(k,l),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:k>0,hasMoreAfter:l<g,totalMessageCount:g}}function j(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<0||g>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let h=Math.min(d,g+1+f(c,e));return{messages:a.messages.slice(g+1,h),entryIds:a.entryIds.slice(g+1,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:h<d,totalMessageCount:d}}function k(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let h=Math.max(0,g-f(c,e));return{messages:a.messages.slice(h,g),entryIds:a.entryIds.slice(h,g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:h>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{$3:()=>o,D_:()=>s,JT:()=>k,K2:()=>g,QR:()=>t,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(13737),e=c(99014);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}function s(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a||"set_follow_up_queue"===a||"dispatch_follow_up_queue"===a||"recall_follow_up_queue"===a}function t(a,b=h){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return k(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return n(a,b);if("follow_up"===c)return o(a,b);if("set_follow_up_queue"===c)return p(a,b);if("dispatch_follow_up_queue"===c)return q(a,b);if("recall_follow_up_queue"===c)return r(a,b);throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}[f,g]=h.then?(await h)():h;let k=`
|
|
1
|
+
"use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>I,v7:()=>J});var e=c(716),f=c(75430),g=c(60396),h=c(35768),i=c(95412),j=c(38199),k=c(68524),l=c(89953),m=c(5815),n=c(69835),o=c(99014),p=c(85664),q=c(65107),r=c(20316),s=c(95237),t=c(17697),u=c(62693),v=c(23828),w=c(31524),x=c(52960),y=c(13737),z=c(60185),A=c(28121),B=c(71069),C=c(41676),D=c(87538),E=c(97017),F=a([f,n,s,t,z,A]);[f,n,s,t,z,A]=F.then?(await F)():F;let J="Session writer is busy: a command is still in flight";function G(a){return"string"==typeof a&&""!==a?a:null}function H(a){return"string"==typeof a&&a?a:void 0}class K{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}static{this.RERENDER_MIN_INTERVAL_MS=100}static{this.RENDER_WIDTH_MIN=40}static{this.RENDER_WIDTH_MAX=240}static{this.RENDER_ROWS_MIN=10}static{this.RENDER_ROWS_MAX=200}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,D.Lm)(),this.renderWidth=D.Yg,this.renderRows=B.Tf,this.toolRenderStates=new Map,this.toolRenderScheduler=(0,E.w7)({minIntervalMs:K.RERENDER_MIN_INTERVAL_MS,recompute:a=>this.recomputeToolSlots(a),emit:(a,b)=>this.emitRenderedLinesUpdate(a,b)}),this.streamSnapshot=(0,j.b)(),this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,g.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}connectionSnapshot(){let a=this.streamSnapshot.snapshot();return this.streamRunSeq>0?{...a,streamRunSeq:this.streamRunSeq}:a}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of(this.streamSnapshot.remember(a),this.listeners))try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}hasActiveSubagentRun(){let a=this.realSessionFile;if(!a)return!1;try{let{runs:b}=(0,h._2)({limit:50});return(0,h.EE)(b,a)}catch{return!1}}hasActiveExternalWork(){return!!this.hasActiveSubagentRun()||(0,i.Vz)({sessionId:this.realSessionId,sessionFile:this.realSessionFile})}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if(this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(!(this.listeners.length>0)){if(this.hasActiveExternalWork())return void this.resetIdleTimer();this.destroyAsync().catch(()=>{})}}},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,k.rV)(this.agentDir);return!0===(0,k.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,k.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,k.rV)(this.agentDir),b=(0,k.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,o.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>o.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${o.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,o.S1)(this.followUpAdmittedAttemptIds,c);try{(0,k.xP)(`sessionQueue.${this.realSessionId}`,(0,o.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,o.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,n.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:n.Md,c=(0,n.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>o.ym)return!1;let b=0;for(let c of a){let a=(0,n.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:n.Md;if(a>d||(b+=a,c.previewPath&&null===(0,n.vy)(c.previewPath,this.agentDir)))return!1}return b<=n.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,o.Ot)(a)){if("model"!==d.role)continue;let a=(0,n.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,o.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,o.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,n.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,n.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,n.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,o.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,o.ko)(a.text,"claimed",a.media):(0,o.ko)(a.text,"claimed"));c&&g.push((0,o.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let k=e.images.length?e.images:void 0,l="prompt";try{if(this.session.isStreaming)l="steer",await this.session.steer(d,k);else{let a=await this.send({type:"prompt",message:d,...k?.length?{images:k}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return l="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,x.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let m=(0,o.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(m),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,k.rV)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0;let c=this.followUpFlushUnits[0];setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===c&&this.sendNextFollowUp()},0)}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,o.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let k=new Set(d),l=(0,o.Ot)(c),m=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");m&&this.discardDeliveredModelMedia(l),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),m||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,t.tZ)(a=>{this.trackExtensionSideEffects(a),this.emit(a)},{readComposerText:()=>(0,C.x)(this.realSessionId,this.agentDir)}),(0,D.DD)(a=>{this._alive&&this.emit({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"notify",message:a,notifyType:"warning"})}),(0,D.YJ)(()=>{(0,f.renderDiff)("+ added\n- removed\n context\n")}),(0,D.Sw)(),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"tui",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=H(a.method);if("setStatus"===b){let b=H(a.statusKey)??H(a.key)??"default",c=H(a.statusText)??H(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=H(a.widgetKey)??H(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,s.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(y.uG,a);this.emit({type:"message_end",entryId:e,message:(0,y.FH)(a,Date.now())})}(0,s.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&K.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=K.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,m.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,m.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,q.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld())&&!this.hasActiveExternalWork();this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,s.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}e=this.withToolDisplayMeta(e),this.emit(this.withRenderedToolLines(e))}withToolDisplayMeta(a){if("tool_execution_start"!==a.type)return a;try{let b=this.session.extensionRunner;if("function"!=typeof b?.getToolDefinition)return a;let c="string"==typeof a.toolName?a.toolName:"";if(""===c)return a;let d=b.getToolDefinition(c);if(!d)return a;let e="string"==typeof d.label?d.label.trim():"",f=""!==e&&e!==c?e:void 0,g="self"===d.renderShell?"self":void 0;if(void 0===f&&void 0===g)return a;return{...a,...void 0!==f?{toolLabel:f}:{},...void 0!==g?{toolShell:g}:{}}}catch{return a}}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_start":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId),d=c?this.getOrCreateToolRenderState(c):null;d&&(d.args=a.args,d.callRenderer={slot:"call",def:b});let e=this.buildToolRenderContext(a.toolCallId,a.args,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!e)return a;let f=(0,D.GD)(b,a.args,e,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b),this.renderWidth),g=d?.emittedCallLines??f;return d&&g&&(d.emittedCallLines=g),g?{...a,renderedCallLines:g}:a}case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;void 0!==a.args&&(d.args=a.args),d.resultRenderer={slot:"result",def:b,result:a.partialResult,isPartial:!0,isError:!0===a.isError};let e=this.renderToolSlotsNow(c,d);if(!e||(e.callLines&&this.emitRenderedLinesUpdate(c,{callLines:e.callLines}),!e.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:e.resultLines}),{...a,renderedLines:e.resultLines}}case"tool_execution_end":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;let e={..."object"==typeof a.result&&null!==a.result?a.result:{content:[]},isError:!0===a.isError};d.resultRenderer={slot:"result",def:b,result:e,isPartial:!1,isError:!0===a.isError};let f=this.renderToolSlotsNow(c,d);if(!f||(f.callLines&&this.emitRenderedLinesUpdate(c,{callLines:f.callLines}),!f.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:f.resultLines}),{...a,renderedResultLines:f.resultLines}}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,D.Mf)(d,a.message,this.renderBridgeTheme,this.renderWidth);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{this.scheduleToolRerender(a)},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0,args:void 0,callRenderer:void 0,resultRenderer:void 0,emittedCallLines:void 0,emittedResultLines:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}rerenderToolLines(){this.toolRenderScheduler.flushAll([...this.toolRenderStates.keys()])}scheduleToolRerender(a){let b=G(a);b&&this.toolRenderStates.has(b)&&this.toolRenderScheduler.request(b)}recomputeToolSlots(a){let b=this.toolRenderStates.get(a);return b?this.renderToolSlotsNow(a,b):null}renderToolSlotsNow(a,b){let c=null,d=null,e=b.resultRenderer&&"result"===b.resultRenderer.slot?b.resultRenderer:void 0;if(b.callRenderer){let d=this.buildToolRenderContext(a,b.args,{isPartial:e?.isPartial===!0,expanded:!0,isError:e?.isError===!0,resultSlot:!1});d&&(c=(0,D.GD)(b.callRenderer.def,b.args,d,b=>this.updateToolRenderLastComponent(a,!1,b),this.renderWidth))}let f=b.resultRenderer;if(f&&"result"===f.slot){let e=this.buildToolRenderContext(a,b.args,{isPartial:f.isPartial,expanded:!0,isError:f.isError,resultSlot:!0});if(e&&(d=(0,D.t_)(f.def,f.result,{expanded:!0,isPartial:f.isPartial},e,b=>this.updateToolRenderLastComponent(a,!0,b),this.renderWidth)),b.lastCallComponent){let a=(0,D.hR)(b.lastCallComponent,this.renderWidth);a&&(c=a)}}return(0,E.VQ)({callLines:c,resultLines:d},{callLines:b.emittedCallLines,resultLines:b.emittedResultLines})}recordEmittedToolLines(a,b){let c=this.toolRenderStates.get(a);c&&(b.callLines&&(c.emittedCallLines=b.callLines),b.resultLines&&(c.emittedResultLines=b.resultLines))}emitRenderedLinesUpdate(a,b){this.emit({type:"rendered_lines_update",toolCallId:a,...b.callLines?{renderedCallLines:b.callLines}:{},...b.resultLines?{renderedResultLines:b.resultLines}:{}}),this.recordEmittedToolLines(a,b)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<K.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,s.G1)(a):(0,s.Qu)(b)),d=c.getCwd()||this.options.cwd,e=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let e=(0,A._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:A.Jv,label:A.wc,description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:A.Tv,async execute(a,b,c){let d=await e(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,f.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:A.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,w.yu)(a);return{...await (0,f.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,f.createAgentSessionRuntime)(h,{cwd:d,agentDir:e,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),extensionTerminalInputListenerCount:this.extensionUi?.terminalInputListenerCount??0,activeCustomUi:this.extensionUi?.customSnapshot??null,extensionCapabilityNotices:this.extensionUi?.capabilityNoticeSnapshot??[]};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,o.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,p.qF)(a):(0,p.l$)(a),c=this.session.sessionManager.appendCustomEntry(p.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,z.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(y.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,y.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,x.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,z.Nu)(c.binaryBlocks,this.agentDir),i=c.images??a.images,j=this.resolvePromptImages(i);if(j.missing.length){console.error("[pidance] prompt image missing on disk:",j.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,v.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,v.D)(c.message)){let a=this.queueMediaFromPromptImages(i);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,v.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,v.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:j.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,l.kP)(this.realSessionId))throw Error(l.GT);this.promptRunning=!0,this.lastStopReason=null,(0,m.NK)(this.realSessionId,Date.now()),this.notifyRunning();let k=(async()=>{try{await new Promise((b,e)=>{let g=!1,i=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,m.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:j.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,h.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:h}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,s.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}i()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),i(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,x.K2)(g);if(d.isStreaming&&(0,x.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,m.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,k),k}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,u.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,w.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,w.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,x._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,x.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,x.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,x.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,x.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_command_argument_completions":{let b="string"==typeof a.name?a.name:"",c="string"==typeof a.prefix?a.prefix:"";if(!b)return{items:[]};let e=d.extensionRunner.getRegisteredCommands().find(a=>a.invocationName===b),f=e?.getArgumentCompletions;if("function"!=typeof f)return{items:[]};try{let a=await f.call(e,c);return{items:function(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){if("object"!=typeof c||null===c||"string"!=typeof c.value||""===c.value)continue;let a="string"==typeof c.label&&""!==c.label?c.label:c.value;b.push({value:c.value,label:a,..."string"==typeof c.description&&""!==c.description?{description:c.description}:{}})}return b}(a)}}catch{return{items:[]}}}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo,..."function"==typeof b.getArgumentCompletions?{hasArgumentCompletions:!0}:{}});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=H(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=H(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"terminal_input":{let b="string"==typeof a.data?a.data:"";return!0===a.assertFocus&&this.extensionUi?.setEditorFocus(!0,H(a.clientId)??"default"),this.extensionUi?.dispatchTerminalInput(b)??{consumed:!1}}case"editor_focus":{let b=!0===a.focused,c=H(a.clientId)??"default";return{focused:b,changed:this.extensionUi?.setEditorFocus(b,c)??!1}}case"extension_ui_mouse":{let b=H(a.id),c=a.event;return b&&c&&"object"==typeof c&&this.extensionUi?.inputCustomMouse(b,c),null}case"set_render_width":{let b="number"==typeof a.width?a.width:NaN;if(!Number.isFinite(b))return null;let c=Math.min(K.RENDER_WIDTH_MAX,Math.max(K.RENDER_WIDTH_MIN,Math.round(b)));if(c===this.renderWidth)return null;return this.renderWidth=c,this.extensionUi?.setRenderSize({width:c,rows:this.renderRows}),this.rerenderToolLines(),null}case"set_render_size":{let b="number"==typeof a.width?a.width:NaN,c="number"==typeof a.rows?a.rows:NaN;if(!Number.isFinite(b)||!Number.isFinite(c))return null;let d=Math.min(K.RENDER_WIDTH_MAX,Math.max(K.RENDER_WIDTH_MIN,Math.round(b))),e=Math.min(K.RENDER_ROWS_MAX,Math.max(K.RENDER_ROWS_MIN,Math.round(c))),f=d!==this.renderWidth;if(!f&&e===this.renderRows)return null;return this.renderWidth=d,this.renderRows=e,this.extensionUi?.setRenderSize({width:d,rows:e}),f&&this.rerenderToolLines(),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=H(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:H(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,q.R3)(this.realSessionFile,a):this.realSessionFile&&(0,q.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=H(a.entryId);if(!b)throw Error("entryId is required");return await this.navigateTreeCommand("select_leaf_exact",b)}case"branch_from_assistant":{let b=H(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");return await this.navigateTreeCommand("branch_from_assistant",b)}case"create_session_from_leaf":{let b=H(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c)return await c.createSessionFromLeaf(this.sessionId,b,{handoff:()=>this.destroyExcluding(1)});throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=H(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}async navigateTreeCommand(a,b){let c=this.session;if(this.bashRunning)throw Error("select_leaf_exact"===a?"Cannot switch branch while a shell command is running":"Cannot branch while a shell command is running");if(c.isStreaming)throw Error("Wait for the current response to finish before navigating the session tree.");if(c.isCompacting)throw Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");let d=c.sessionManager,e=(0,s.LH)(d),f="select_leaf_exact"===a?(0,r.fb)(e,b):(0,r.AM)(e,b);if("noop"===f.kind)return{cancelled:!1};let g=d.getLeafId();if(f.leafId===g)return f.clearSidecar&&this.realSessionFile&&((0,q.$9)(this.realSessionFile),this.options.onSessionListInvalidate?.()),{cancelled:!1};let h=this.options.navigationActions;if((await this.dispatchTreeNavigation({oldLeafId:g,targetLeafId:f.leafId,apply:async()=>{if(h&&this.realSessionFile){let c="select_leaf_exact"===a?h.selectLeafExact:h.branchFromAssistant;return await c.call(h,this.sessionId,b,{handoff:()=>this.destroyExcluding(1),liveWriter:{sessionManager:e,sessionFile:this.realSessionFile}})}return(0,r.h_)({sessionManager:e,sessionFile:this.realSessionFile,plan:f}),this.options.onSessionListInvalidate?.(),{cancelled:!1}}})).cancelled)return{cancelled:!0};try{await this.destroyExcluding(1)}catch{}return{cancelled:!1}}async dispatchTreeNavigation(a){let b=this.session,c=b.extensionRunner,d=new AbortController;b._branchSummaryAbortController=d;try{if(c.hasHandlers("session_before_tree")){let e=(0,f.collectEntriesForBranchSummary)(b.sessionManager,a.oldLeafId,a.targetLeafId),g=await c.emit({type:"session_before_tree",preparation:{targetId:a.targetLeafId,oldLeafId:a.oldLeafId,commonAncestorId:e.commonAncestorId,entriesToSummarize:e.entries,userWantsSummary:!1},signal:d.signal});if(g?.cancel)return{cancelled:!0}}if((await a.apply()).cancelled)return{cancelled:!0};return await c.emit({type:"session_tree",newLeafId:b.sessionManager.getLeafId(),oldLeafId:a.oldLeafId}),{cancelled:!1}}finally{b._branchSummaryAbortController=void 0}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error(J);await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.toolRenderScheduler.dispose(),this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,m.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function I(a){let b=new K(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}function h(){return e()}},6032:(a,b,c)=>{c.d(b,{Y:()=>d,f:()=>e});let d="__new__";function e(a){return a.startsWith(d)}},17697:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{tZ:()=>k});var e=c(716),f=c(29862),g=c(71069),h=c(87538),i=a([f]);let l=new(f=(i.then?(await i)():i)[0]).KeybindingsManager(f.TUI_KEYBINDINGS);function j(a,b,c,d,f,g,h){let i=(0,e.randomUUID)();return new Promise((e,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),d?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),e(a))},o=()=>n(f);d?.signal?.addEventListener("abort",o,{once:!0}),d?.timeout&&(k=setTimeout(()=>n(f),d.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function k(a,b={}){let c,d=new Map,f=new Map,i=new Map,m=new Map,n=new Map,o=null,p=!1,q=h.Yg,r=g.Tf,s=new Set,t=new Set,u=[],v=(a,b)=>{!function(a,b,c=16){a.push(b),a.length>c&&a.splice(0,a.length-c)}(u,{id:a,message:b,notifyType:"warning"})},w=new Set,x=()=>{a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"terminalInputListeners",count:w.size})},y=new Map,z=()=>{var a=Date.now();for(let[b,c]of y)c<=a&&y.delete(b);return y.size>0},A=b=>{if(t.has(b))return;t.add(b),console.warn(`[pidance] extension UI capability not supported on web: ${b}`);let c=(0,e.randomUUID)(),d=`Extension UI "${b}" is not supported by the Pidance web client.`;v(c,d),a({type:"extension_ui_request",id:c,method:"notify",message:d,notifyType:"warning"})},B=new Map,C=a=>{let b=B.get(a);if(b){B.delete(a);try{b.dispose?.()}catch(a){console.error("[pidance] widget dispose failed:",a)}}},D=(b,c)=>{m.has(b)&&(m.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:void 0,widgetPlacement:c}))},E={select:(b,c,e)=>j(d,f,a,e,void 0,{method:"select",title:b,options:c,timeout:e?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(b,c,e)=>j(d,f,a,e,!1,{method:"confirm",title:b,message:c,timeout:e?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(b,c,e)=>j(d,f,a,e,void 0,{method:"input",title:b,placeholder:c,timeout:e?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:b=>(((b,c)=>{if(t.has(b))return;t.add(b);let d=`Extension UI "${b}" is limited by the Pidance web client: ${c}`;console.warn(`[pidance] ${d}`);let f=(0,e.randomUUID)();v(f,d),a({type:"extension_ui_request",id:f,method:"notify",message:d,notifyType:"warning"})})("onTerminalInput","handlers only receive keys in two narrow windows: (1) with a widget present and the composer focused and empty, Down/Left start a selection, after which arrows, j, k, Enter and Escape are routed while the selection lasts; (2) while a collapsed extension panel exists, Escape, F1-F12, Alt+<char> and Ctrl+<char> (browser-reserved chords and Ctrl+Space excluded) are routed. Ordinary typing never reaches them."),w.add(b),x(),()=>{w.delete(b)&&x()}),setStatus(b,c){c?i.set(b,c):i.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingMessage",message:b??null})},setWorkingVisible(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingVisible",visible:!!b})},setWorkingIndicator(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingIndicator",frames:Array.isArray(b?.frames)?b.frames.filter(a=>"string"==typeof a):null,intervalMs:"number"==typeof b?.intervalMs?b.intervalMs:null})},setHiddenThinkingLabel(a){void 0!==a&&A("setHiddenThinkingLabel")},setWidget(b,c,d){"function"==typeof c?((b,c,d)=>{let f;C(b);let i=(0,h.Lm)();if(!i)return D(b,d);let j={requestRender:()=>{}},k=!1,l=()=>{if(k=!1,B.get(b)!==j)return;let c=(0,h.F$)(f,q);null!==c&&(m.set(b,{lines:c,placement:d}),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:d}))},n=(0,g.TQ)(()=>{k||B.get(b)!==j||(k=!0,queueMicrotask(l))},()=>q,()=>r,{isEditorFocused:z,onUnsupported:A});j.requestRender=n.requestRender;try{f=c(n,i)}catch(a){console.error("[pidance] widget factory failed:",a),D(b,d);return}let o=f;j.dispose="function"==typeof o?.dispose?()=>f.dispose():void 0,B.set(b,j),l()})(b,c,d?.placement):(C(b),(void 0===c||Array.isArray(c))&&(null==c?m.delete(b):m.set(b,{lines:c,placement:d?.placement}),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:d?.placement})))},setFooter(a){void 0!==a&&A("setFooter")},setHeader(a){void 0!==a&&A("setHeader")},setTitle(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setTitle",title:b})},async custom(b,c){let d=(0,e.randomUUID)(),f=function(a){if(!a||"object"!=typeof a||!0!==a.overlay)return null;let b=a.overlayOptions&&"object"==typeof a.overlayOptions?a.overlayOptions:{},c={anchor:"string"==typeof b.anchor?b.anchor:"center"},d=b.width;("number"==typeof d||"string"==typeof d)&&(c.width=d),"number"==typeof b.minWidth&&(c.minWidth=b.minWidth);let e=b.maxHeight;("number"==typeof e||"string"==typeof e)&&(c.maxHeight=e);let f=b.margin;if("number"==typeof f)c.margin=f;else if(f&&"object"==typeof f){let a={};for(let b of["top","right","bottom","left"])"number"==typeof f[b]&&(a[b]=f[b]);c.margin=a}return c}(c);return new Promise(e=>{let i,j=!1,k=b=>{j||(j=!0,s.delete(v),n.delete(d),o?.id===d&&(o=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}),e(b))},m=[],p=!1,t=!1,u=()=>{t||(a({type:"extension_ui_request",id:d,method:"custom",lines:m,...p?{hidden:p}:{},...f?{layout:f}:{}}),o={id:d,lines:[...m],...p?{hidden:p}:{},...f?{layout:f}:{}})},v=()=>{if(j)return;let a=[];try{let b=i?.render?.(q);Array.isArray(b)&&(a=b.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}m=a,u()};n.set(d,{handleInput:a=>{if("\x03"===a)return void k(void 0);try{i?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},handleMouse:a=>{try{i?.handleMouse?.(a)}catch(a){console.error("[pidance] custom UI mouse failed:",a)}},done:k});let w=(0,g.TQ)(()=>{v()},()=>q,()=>r,{isEditorFocused:z,onUnsupported:A});s.add(v);let x=(0,h.Lm)()??E.theme;c?.onHandle?.({hide(){t||j||(t=!0,p=!0,n.delete(d),o?.id===d&&(o=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}))},setHidden(a){if(!t){let b;b=!!a,p===b||(p=b,j||u())}},isHidden:()=>p,focus(){},unfocus(){},isFocused:()=>!t&&!p,getBounds:()=>void 0}),Promise.resolve().then(()=>b(w,x,l,k)).then(a=>{j||(i=a,v())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),k(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:b})},getEditorText(){try{return b.readComposerText?.()??""}catch(a){return console.error("[pidance] readComposerText failed:",a),""}},editor:async(b,c)=>j(d,f,a,void 0,void 0,{method:"editor",title:b,prefill:c},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){A("addAutocompleteProvider")},setEditorComponent(a){c=a,void 0!==a&&A("setEditorComponent")},getEditorComponent:()=>c,get theme(){let a,b;return(0,h.Lm)()??(a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b),{name:void 0,sourcePath:void 0,sourceInfo:void 0,fg:b,bg:b,bold:a,dim:a,italic:a,underline:a,inverse:a,strikethrough:a,getFgAnsi:()=>"",getBgAnsi:()=>"",getColorMode:()=>"truecolor",getThinkingBorderColor:()=>a,getBashModeBorderColor:()=>a})},getAllThemes:()=>(A("getAllThemes"),[]),getTheme(){A("getTheme")},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>p,setToolsExpanded(b){p=!!b,a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setToolsExpanded",toolsExpanded:p})}};return{uiContext:E,pending:d,statuses:i,widgets:m,pendingSnapshot:f,get customSnapshot(){return o},get terminalInputListenerCount(){return w.size},get capabilityNoticeSnapshot(){return u.map(a=>({...a}))},respond(a,b){let c=d.get(a);return!!c&&(c.resolve(b),!0)},inputCustom(a,b){let c=n.get(a);return!!c&&(c.handleInput(b),!0)},inputCustomMouse(a,b){let c=n.get(a);return!!c&&(c.handleMouse(b),!0)},setRenderSize(a){let b=Math.round(a.width),c=Math.round(a.rows);if(!Number.isFinite(b)||b<=0||!Number.isFinite(c)||c<=0||b===q&&c===r)return!1;for(let a of(q=b,r=c,[...s]))a();for(let a of[...B.values()])a.requestRender();return!0},dispatchTerminalInput(a){let b=a;for(let a of w){let c;try{c=a(b)}catch(a){console.error("[pidance] extension terminal input listener failed:",a);continue}if(c?.consume)return{consumed:!0,data:b};c?.data!==void 0&&(b=c.data)}return 0===b.length?{consumed:!0,data:b}:{consumed:!1,data:b}},setEditorFocus:(a,b="default")=>{let c=z();if(a?y.set(b,Date.now()+6e4):y.delete(b),c===z())return!1;for(let a of[...B.values()])a.requestRender();for(let a of[...s])a();return!0},dispose(){for(let[a,b]of(y.clear(),c=void 0,d))d.delete(a),f.delete(a),b.reject(Error("Extension UI disposed"));for(let a of n.values())a.done(void 0);for(let a of(n.clear(),o=null,w.clear(),[...B.keys()]))C(a);i.clear(),m.clear()}}}d()}catch(a){d(a)}})},20316:(a,b,c)=>{c.d(b,{AM:()=>g,fb:()=>f,h_:()=>h});var d=c(65107),e=c(76817);function f(a,b){if(b===a.getLeafId())return{kind:"noop"};if(b===a.getLastEntryId())return{kind:"branch",leafId:b,clearSidecar:!0};if(!a.getEntry(b))throw Error(`Entry ${b} not found`);return{kind:"branch",leafId:b,clearSidecar:!1}}function g(a,b){let c=a.getLeafId();if(!c)throw Error("Session has no leaf");let d=a.getEntry(b);if(!d)throw Error("Entry not found");if("message"!==d.type||d.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let f=(0,e.wo)(a.getBranch(c),b);return{kind:"branch",leafId:f,clearSidecar:f===a.getLastEntryId()}}function h(a){let{sessionManager:b,sessionFile:c,plan:e}=a;"noop"!==e.kind&&(c&&(e.clearSidecar?(0,d.$9)(c):(0,d.R3)(c,e.leafId)),b.branch(e.leafId))}},23828:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},25252:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(50593);function e(){return globalThis.__piAdditionalAllowedRoots||(globalThis.__piAdditionalAllowedRoots=new Set),globalThis.__piAdditionalAllowedRoots}function f(a){if(!a)return;let b=(0,d.Nw)(a);e().add(b),globalThis.__piAllowedRootsCache?.roots.add(b)}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>w,A4:()=>o,DU:()=>q,EM:()=>t,Fn:()=>v,HG:()=>s,OF:()=>y,YZ:()=>f.Y,getRegistry:()=>m});var e=c(40402),f=c(6032),g=c(95237),h=c(68524),i=c(2416),j=c(5815),k=c(89953),l=a([e,g,i]);function m(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function n(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function o(a){return m().get(a)}function p(){return[...n().keys()]}async function q(a){let b=n().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function r(){let a=new Set(p());for(let[b,c]of m())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function s(){return r()}[e,g,i]=l.then?(await l)():l;let A=new Map;function t(a,b=Date.now()){let c={},d=(0,j.MG)(),e=r(),f=new Set(e);for(let a of e){let e=d.get(a)??A.get(a)??b;A.set(a,e),c[a]=e}for(let a of[...A.keys()])f.has(a)||A.delete(a);return c}function u(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function v(a){let b=u();return b.add(a),()=>{b.delete(a)}}function w(){let a=[];for(let[b,c]of m()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let B="",C=[],D=new Set,E=null;function x(){!function a(){let b=new Set(function(){let a=new Set(p());for(let[b,c]of m())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,k.AZ)(a),D.add(a);for(let a of[...D])b.has(a)||((0,k.Hl)(a),D.delete(a));if(0===b.size){E&&(clearInterval(E),E=null);return}E||(E=setInterval(()=>{a()},8e3),E.unref?.())}();let a=s(),b=w(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c===B)return;B=c;let d=C.filter(b=>!a.includes(b)&&!(0,f.f)(b));if(C=[...a],d.length>0){let a=new Date().toISOString();setTimeout(()=>{for(let b of d)try{(0,h.xP)(`unreadSessionState.completedAt.${b}`,a)}catch(a){console.error("[pidance] failed to record unread completedAt:",a)}},0)}for(let b of u())try{b(a)}catch{}}async function y(a,b,c,d,e){return z(a,b,c,d,e)}async function z(a,b,c,d,f){let g=m(),h=n(),j=g.get(a);if(j?.isAlive())return{session:j,realSessionId:a};let l=h.get(a);if(l)return l;if(!(0,k.kP)(a))throw Error(k.GT);x();let o=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>x(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=m(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,k.kP)(b),(0,k.Hl)(a))}}),j=h.sessionId,l=h.sessionFile;return l&&(0,e.O8)(j,l),j!==a&&(0,k.kP)(j),h.onDestroy(()=>{g.get(j)===h&&g.delete(j),a!==j&&g.get(a)===h&&g.delete(a),(0,k.Hl)(j),a!==j&&(0,k.Hl)(a),x()}),g.set(j,h),h.beginExtensionBinding(),{session:h,realSessionId:j}}catch(b){throw(0,k.Hl)(a),x(),b}})().finally(()=>{h.delete(a),x()});return h.set(a,o),o}d()}catch(a){d(a)}})},28121:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>u,_D:()=>q,n3:()=>n,wc:()=>s});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(69835),j=c(80547),k=c(1060),l=c(60185),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="Send file to user",t="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===t)?a:[...a,t]}let u={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},29993:(a,b,c)=>{c.d(b,{_E:()=>i,r7:()=>h});var d=c(87538),e=c(70770);function f(a){return"object"!=typeof a||null===a||Array.isArray(a)?null:a}async function g(a){let b=await (0,e.aW)({cwd:a.cwd,agentDir:a.agentDir,loaderFactory:a.loaderFactory,bypassCache:a.bypassCache});return b.ok?b.value.extensions:null}async function h(a){let b=await g(a);if(!b)return null;let c=function(a){let b=new Map;for(let c of a){let a=c.entryRenderers;if(a instanceof Map)for(let[c,d]of a)"string"==typeof c&&""!==c&&"function"==typeof d&&(b.has(c)||b.set(c,d))}return b}(b);if(0===c.size)return null;let e=(0,d.Lm)();return e?a=>{let b=f(a)?.customType;if("string"!=typeof b)return null;let g=c.get(b);if(!g)return null;let h=(0,d.bn)(g,a,e);return h&&h.length>0?h:null}:null}async function i(a){let b=await g(a);if(!b)return null;let c=function(a){let b=new Map;for(let c of a){let a=c.messageRenderers;if(a instanceof Map)for(let[c,d]of a)"string"==typeof c&&""!==c&&"function"==typeof d&&(b.has(c)||b.set(c,d))}return b}(b);if(0===c.size)return null;let e=(0,d.Lm)();return e?a=>{let b=f(a)?.customType;if("string"!=typeof b)return null;let g=c.get(b);if(!g)return null;let h=(0,d.Mf)(g,a,e);return h&&h.length>0?h:null}:null}},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},35768:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>t,gd:()=>E,st:()=>s});var d=c(89477),e=c.n(d),f=c(62228),g=c.n(f),h=c(86697),i=c.n(h);let j=/^[A-Za-z0-9_-]{1,128}$/,k=/^output-\d+\.log$/,l=new Set(["queued","running","complete","failed","paused","stopped"]),m=new Set(["single","parallel","chain"]),n=new Set(["active_long_running","needs_attention"]),o={readdirSync:a=>e().readdirSync(a),lstatSync:a=>e().lstatSync(a),realpathSync:a=>e().realpathSync(a),readFileSync:(a,b)=>e().readFileSync(a,b),openSync:(a,b)=>e().openSync(a,b),readSync:(a,b,c,d,f)=>e().readSync(a,b,c,d,f),closeSync:a=>e().closeSync(a),fstatSync:a=>e().fstatSync(a),constants:e().constants};function p(a){return a.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}let q=new Set(["running","queued","paused"]);function r(a,b,c=Date.now(),d=9e5){let e="string"==typeof b?b:"";if(!e.endsWith(".jsonl"))return!1;let f=e.slice(0,-6),g=a=>{if("string"!=typeof a||!a||!a.startsWith(f))return!1;let b=a.charAt(f.length);return"/"===b||"\\"===b};for(let b of a??[]){if(!b||"object"!=typeof b||!q.has(b.state))continue;let a=b.lastUpdate??b.startedAt;if("number"!=typeof a||!(c-a>d)){for(let a of b.steps??[])if(g(a?.sessionFile))return!0}}return!1}function s(a){if(null==a||""===a)return 20;if(!/^\d+$/.test(a))return null;let b=Number(a);return!Number.isInteger(b)||b<1||b>50?null:b}function t(a={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),s=a.root??(b=a.scope,h=b?.tmpdir?.()??g().tmpdir(),i().join(h,`pi-subagents-${function(a){let b=a?.env??process.env,c=a&&Object.hasOwn(a,"getuid")?a.getuid:process.getuid?.bind(process);if("function"==typeof c)return`uid-${c()}`;for(let a of["USERNAME","USER","LOGNAME"]){let c=b[a];if(c)return`user-${p(c)}`}let d=a&&Object.hasOwn(a,"userInfo")?a.userInfo:g().userInfo;try{let a=d?.().username;if(a)return`user-${p(a)}`}catch{}let e=b.USERPROFILE??b.HOME;if(e)return`home-${p(e)}`;let f=a&&Object.hasOwn(a,"homedir")?a.homedir:g().homedir;try{let a=f?.();if(a)return`home-${p(a)}`}catch{}return"shared"}(b)}`,"async-subagent-runs"));try{let a=n.lstatSync(s);if(a.isSymbolicLink()||!a.isDirectory())return u(r,!1);e=n.realpathSync(s)}catch(a){return v(a),u(r,!1)}try{f=n.readdirSync(s)}catch(a){return v(a),u(r,!1)}f.length>256&&(f=f.slice(0,256));let D=[];for(let a of f)if(j.test(a))try{let b=function(a,b,c,d){var e,f;let g,h,j,n,o=i().join(b,d);try{g=a.lstatSync(o)}catch{return null}if(g.isSymbolicLink()||!g.isDirectory())return null;try{h=a.realpathSync(o)}catch{return null}if(!w(h,c))return null;let p=function(a,b,c){let d=x(a,b,c);if(!d)return null;let{fd:e,size:f}=d;try{if(f<=0||f>2097152)return null;let b=Buffer.alloc(f),c=0;for(;c<f;){let d=a.readSync(e,b,c,f-c,c);if(0===d)break;c+=d}let d=b.subarray(0,c).toString("utf8"),g=JSON.parse(d);if(!g||"object"!=typeof g||Array.isArray(g))return null;return g}catch{return null}finally{try{a.closeSync(e)}catch{}}}(a,i().join(o,"status.json"),c);if(!p)return null;let q=(e=p.state,"string"==typeof e&&l.has(e)?e:void 0);if(!q)return null;let r=(f=p.mode,("string"==typeof f&&m.has(f)?f:void 0)??"single"),s=A(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=z(p.activityState),v=A(p.endedAt),D=A(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=A(p.currentStep),H=A(p.chainStepCount),I=B(p.totalTokens),J=C(p.totalCost),K=function(a){if(!Array.isArray(a))return[];let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if(!d||"object"!=typeof d||Array.isArray(d)){b.push({index:c,agent:"unknown",status:"unknown"});continue}let e="string"==typeof d.agent&&d.agent?d.agent:"unknown",f={index:c,agent:e,status:"string"==typeof d.status&&d.status?d.status:"unknown"};"string"==typeof d.label&&(f.label=d.label),"string"==typeof d.model&&(f.model=d.model),"string"==typeof d.sessionFile&&(f.sessionFile=d.sessionFile),"string"==typeof d.error&&(f.error=d.error);let g=z(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=B(d.tokens);h&&(f.tokens=h);let i=C(d.totalCost)??A(d.costUsd);void 0!==i&&(f.costUsd=i);let j=A(d.startedAt);void 0!==j&&(f.startedAt=j);let k=A(d.endedAt);void 0!==k&&(f.endedAt=k),Array.isArray(d.recentOutput)&&(f.recentOutput=function(a){let b=[];for(let c of a){if(b.length>=8)break;"string"==typeof c&&b.push(c.length>200?c.slice(0,200):c)}return b}(d.recentOutput)),b.push(f)}return b}(p.steps),L=function(a,b,c){let d=y(a,b,c,65536);if(!d||!d.text)return[];let e=d.text;if(d.truncated){let a=e.indexOf("\n");a>=0&&(e=e.slice(a+1))}let f=e.split(/\r?\n/).filter(a=>a.trim().length>0),g=[];for(let a=f.length-1;a>=0&&g.length<20;a-=1)try{let b=JSON.parse(f[a]);if(!b||"object"!=typeof b||Array.isArray(b))continue;let c="string"==typeof b.type?b.type:void 0;if(!c)continue;let d={type:c},e=A(b.timestamp)??A(b.ts)??A(b.time);void 0!==e&&(d.timestamp=e);let h="string"==typeof b.message?b.message:"string"==typeof b.error?b.error:void 0;void 0!==h&&(d.message=h.length>200?h.slice(0,200):h),g.push(d)}catch{}return g.reverse(),g}(a,i().join(o,"events.jsonl"),c),M=function(a,b){if("string"!=typeof a||!a.trim())return null;let c=i().basename(a.trim());return k.test(c)?{absPath:i().join(b,c)}:null}(p.outputFile,o);if(M){let b=y(a,M.absPath,c,32768);if(b){let a=b.text;if(b.truncated){let b=a.indexOf("\n");b>=0&&(a=a.slice(b+1))}j=a,n=b.truncated}}let N={id:t,state:q,mode:r,startedAt:s,steps:K,recentEvents:L};return u&&(N.activityState=u),void 0!==v&&(N.endedAt=v),void 0!==D&&(N.lastUpdate=D),void 0!==E&&(N.cwd=E),void 0!==F&&(N.error=F),void 0!==G&&(N.currentStep=G),void 0!==H&&(N.chainStepCount=H),I&&(N.totalTokens=I),void 0!==J&&(N.totalCostUsd=J),void 0!==j&&(N.outputTail=j),void 0!==n&&(N.outputTruncated=n),N}(n,s,e,a);b&&D.push(b)}catch{}return{runs:(c=D,d=a=>{switch(a){case"running":return 0;case"queued":return 1;case"failed":case"stopped":case"paused":return 2;case"complete":return 3;default:return 4}},[...c].sort((a,b)=>{let c=d(a.state)-d(b.state);if(0!==c)return c;let e=a.lastUpdate??a.endedAt??a.startedAt;return(b.lastUpdate??b.endedAt??b.startedAt)-e})).slice(0,Math.min(q,50)),generatedAt:r,rootAvailable:!0}}function u(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function v(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function w(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function x(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!w(e,c))return null;let f="number"==typeof a.constants.O_NOFOLLOW?a.constants.O_NOFOLLOW:0,g=a.openSync(b,a.constants.O_RDONLY|f);try{let c=a.fstatSync?a.fstatSync(g):a.lstatSync(b);if(!c.isFile())return a.closeSync(g),null;return{fd:g,size:c.size}}catch{try{a.closeSync(g)}catch{}return null}}catch{return null}}function y(a,b,c,d){let e=x(a,b,c);if(!e)return null;let{fd:f,size:g}=e;try{if(0===g)return{text:"",truncated:!1,size:0};let b=Math.min(d,g),c=Math.max(0,g-b),e=Buffer.alloc(b),h=0;for(;h<b;){let d=a.readSync(f,e,h,b-h,c+h);if(0===d)break;h+=d}return{text:e.subarray(0,h).toString("utf8"),truncated:g>d,size:g}}finally{try{a.closeSync(f)}catch{}}}function z(a){return"string"==typeof a&&n.has(a)?a:void 0}function A(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=A(a.input),c=A(a.output),d=A(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function C(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:A(a.costUsd)}function D(a){let b=a.trim();if(!b)return"";let c=/^[a-zA-Z]:[\\/]/.test(b)||b.startsWith("\\\\")||b.startsWith("//"),d=c?i().win32:i().posix,e=c?b.replace(/\//g,"\\"):b.replace(/\\/g,"/"),f=d.normalize(e);return c?f.toLowerCase():f}function E(a,b){let c=new Map;for(let a of b){if(!0!==a.readOnly||"string"!=typeof a.id||!a.id||"string"!=typeof a.path||!a.path)continue;let b=D(a.path);b&&(c.has(b)||c.set(b,a.id))}let d=a.runs.map(a=>{let b=!1,d=a.steps.map(a=>{if(!a.sessionFile)return a;let d=D(a.sessionFile),e=d?c.get(d):void 0;if(!e){if(void 0===a.sessionId)return a;let c={...a};return delete c.sessionId,b=!0,c}return a.sessionId===e?a:(b=!0,{...a,sessionId:e})});return b?{...a,steps:d}:a}),e=!1;for(let b=0;b<d.length;b+=1)if(d[b]!==a.runs[b]){e=!0;break}return e?{...a,runs:d}:a}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>W,DQ:()=>V,Md:()=>M,Wl:()=>N,Yz:()=>L,mB:()=>_});var e=c(29021),f=c(716),g=c(33873),h=c(80547),i=c(91898),j=c(60396),k=c(95237),l=c(52960),m=c(79495),n=c(81879),o=c(46935),p=c(31514),q=c(65107),r=c(20316),s=c(74408),t=c(29993),u=c(67633),v=c(56429),w=c(40402),x=c(85664),y=c(15461),z=c(76817),A=c(86226),B=c(68524),C=c(89953),D=c(50955),E=c(40239),F=c(5815),G=c(99911),H=c(26773),I=c(2416),J=c(68816),K=a([h,i,k,n,s,u,v,w,H,I]);[h,i,k,n,s,u,v,w,H,I]=K.then?(await K)():K;let V="Subagent sessions are read-only";class W extends Error{constructor(){super(V)}toString(){return this.message}}async function L(a,b){if(await b(a))throw new W}function M(a){let b=a instanceof Error?a.message:String(a);return a instanceof W||b===V?403:b.includes("Session not found")?404:(0,C.wE)(a)||b===C.GT||b===I.v7||"Session is being deleted"===b||b.includes("closed while its title")?409:500}function N(a){let b=a instanceof Error?a.message:String(a);return"cwd is required"===b||b.startsWith("Directory does not exist:")?400:M(a)}let X="Submission was cancelled",Y={listAllSessions:w.dQ,resolveSessionPath:w.os,getRpcSession:v.A4,waitForSessionStart:v.DU,startRpcSession:v.OF,getRunningRpcSessionIds:v.HG,listPendingExtensionUi:v.$k,subscribeRunningSessions:v.Fn,allowFileRoot:h.wz,invalidateSessionListCache:w.mD,openSessionCwd:a=>(0,k.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,w.Zx)({filePath:a}),openSessionView:k.kW,reparentSessionFile:k.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:E.Iq},Z=["systemPrompt"];function O(a){return a.some(a=>"custom"===a.type&&"string"==typeof a.customType&&""!==a.customType&&!(0,w.Yx)(a.customType))}let $=new Set(["compaction","branch_summary"]);function P(a){return a.some(a=>"custom_message"===a.type&&"string"==typeof a.customType&&""!==a.customType&&!$.has(a.customType))}async function Q(a,b){let c=b.resolveToolMetaProvider??u.h;try{let d=(0,w.eP)(a)?.cwd;if(!d)return null;return await c({cwd:d,agentDir:b.archiveAgentDir?.()??(0,j.$M)()})}catch{return null}}function R(a){return a.some(a=>{if("message"!==a.type||a.message?.role!=="assistant")return!1;let b=a.message.content;return Array.isArray(b)&&b.some(a=>"object"==typeof a&&null!==a&&"toolCall"===a.type)})}async function S(a,b,c){let d=(0,w.eP)(b)?.cwd;if(!d)return null;let e=c.resolveEntryLinesProvider??t.r7;try{return await e({cwd:d,agentDir:c.archiveAgentDir?.()??(0,j.$M)()})}catch{return null}}async function T(a,b){let c=(0,w.eP)(a)?.cwd;if(!c)return null;let d=b.resolveMessageLinesProvider??t._E;try{return await d({cwd:c,agentDir:b.archiveAgentDir?.()??(0,j.$M)()})}catch{return null}}function U(a){(0,B.xP)(`sessionQueue.${a}`,null),(0,B.xP)(`sessionQueueHold.${a}`,null);let b=(0,B.rV)().unreadSessionState;b&&"object"==typeof b&&!Array.isArray(b)&&(b.completedAt&&"object"==typeof b.completedAt&&(0,B.xP)(`unreadSessionState.completedAt.${a}`,null),b.readAt&&"object"==typeof b.readAt&&(0,B.xP)(`unreadSessionState.readAt.${a}`,null))}let _=function(a={}){let b={...Y,...a},c=(0,E.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:w.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,E.$T)(b.archiveFs??E.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=new Map,t=new Map,u=a=>{if(t.set(a.submissionId,{info:a,cancelRequested:!1,cancelApplied:!1}),!(t.size<=500))for(let[b,c]of t){if(t.size<=500)break;b!==a.submissionId&&"completed"===c.info.status&&t.delete(b)}},v=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},B=async(a,b)=>{if(!(0,C.kP)(a))throw Error(C.GT);try{return await b()}finally{(0,C.Hl)(a)}},I=async(a,b,c)=>(c?await c():await v(a),B(a,b)),K={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,E.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,E.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,E.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,E.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,E.rQ)(b.archiveFs??E.Iq,b.archiveAgentDir?.()??(0,j.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},isLockedByOther:a=>!!a&&"string"==typeof a&&(0,C.wy)(a),getLiveSession:a=>K.getLive(a),isLive:a=>!!K.getLive(a),async ensureLive(a){if(await L(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");let c=K.getLive(a);if(c)return c;if((0,C.wy)(a))throw Error(C.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,M);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=h.get(a);if(c)return c;let d=(async()=>{await L(a,K.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{U(a)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,w.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,C.wy)(a)||(0,C.wy)(c))throw Error(C.GT);let f=(0,w.eP)(d)?.parentSession,h=(0,w.eP)(d)?.id===a?(0,D.ku)(d,a):[],j=b.getRpcSession(c)??b.getRpcSession(a),k=b.getRunningRpcSessionIds();if(j?.isAlive?.()&&(k.includes(a)||k.includes(c)))try{await j.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await K.destroyAsync(j?.sessionId??c),B(j?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,g.join)(c,a)!==d)){let e=(0,g.join)(c,a);try{let a=(0,w.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await I(a.id,()=>{b.reparentSessionFile(e,f)})):b.reparentSessionFile(e,f))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,q.$9)(d),(0,s.G1)(d);let j=(0,g.resolve)(d.slice(0,-6)),k=(0,D.uq)(h,j,w.BR,s.G1);try{U(a)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}try{(0,i.Fx)()}catch(a){console.error("[pidance] failed to sweep attachments:",a)}return(0,w.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:k}})})();return h.set(a,d),d.finally(()=>{h.get(a)===d&&h.delete(a)})},async start(a,c,d,e){if(await L(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,M)},send:async(a,b)=>(await K.ensureLive(a)).send(b),async submitPrompt(a,b){await L(a,K.isReadOnly);let c=(0,l.JT)(b);try{let b=await K.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:"error"}}catch(b){if((0,C.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:(0,l.K2)(b)}}},async getAgentState(a,b){if(await K.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=K.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,C.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of Z)delete c[a];return c}(d,b)}},async renameSession(a,c){await L(a,K.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=K.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await I(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await L(a,K.isReadOnly);let b=await K.ensureLive(a);await b.waitUntilReady?.();let c=await K.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,m.CL)(),f=await (0,m.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await K.destroyAsync(a),await K.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,n.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await K.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,g=f.getEntries?.()??[],h=O(g)?await S(g,e,b):null,i=P(g)?await T(e,b):null,j=R(g)?await Q(e,b):null,{leafId:k,tree:l,context:m,header:n,sessionName:o}=(0,w.jK)(f,{...c,...h?{entryLines:h}:{},...i?{messageLines:i}:{},...j?{toolMeta:j}:{}}),p=n?.parentSession?await (0,w.u1)(n.parentSession):void 0,q=(await b.listAllSessions()).find(b=>b.id===a),r=n?{path:e,id:n.id,cwd:n.cwd??"",name:o,created:n.timestamp,modified:n.timestamp,messageCount:m.totalMessageCount??m.messages.length,firstMessage:q?.firstMessage??"(no messages)",parentSessionId:p,...q?.subagent?{subagent:q.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:k,tree:l,context:m,header:n,sessionName:o,parentSessionId:p,info:r}},async getUserMessageOutline(a){let b=await K.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,w.CM)(d,c.getLeafId());return(0,G.Xm)((0,w.tY)(d,e))},async getContextPage(a,c){let d,e=await K.getReadView(a);if(!e)return{context:null};let f=e.manager,g=f.getEntries?.()??[],h=O(g)?await S(g,e.filePath,b):null,i=P(g)?await T(e.filePath,b):null,j=R(g)?await Q(e.filePath,b):null,k=(0,w.Ew)(g,f.getLeafId?.(),c.leafId),l=(0,w.Uv)(g,k,{deferThinking:c.deferThinking,deferToolResultImages:c.deferToolResultImages,...h?{entryLines:h}:{},...i?{messageLines:i}:{},...j?{toolMeta:j}:{}}),m=c.limit;if(c.around){let a=(0,o.PV)(l,c.around,m??o._w,{toEnd:!0===c.aroundToEnd});if(!a)return{context:null,notFound:c.around};d=a}else d=c.after?(0,o.WP)(l,c.after,m??o._w):c.before?(0,o.tr)(l,c.before,m??o._w):null!==m?(0,o.G1)(l,m):{...l,hasMoreBefore:!1,totalMessageCount:l.messages.length};return{context:d}},async getEntryThinking(a,b,c){let d=await K.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,p.mv)(f.type)?{thinking:(0,p.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await K.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await L(a,K.isReadOnly);let d=K.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,x.l$)(c),f=b.openSessionView(d).appendCustomEntry(x.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await L(a,K.isReadOnly),await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,y.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(y.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){let d;if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:e,modelId:g,toolNames:h,thinkingLevel:i,...j}=c,l="string"==typeof j.submissionId?j.submissionId:void 0,m=(d="string"==typeof j.message?j.message:"",`${a}\u0000${d}`);if(l){let a=t.get(l);if(a){if(a.info.fingerprint&&a.info.fingerprint!==m)throw a.info.status="conflict",Error("Submission conflict: this submissionId was already used with different content");if(a.cancelRequested)throw a.info.status="cancelled",Error(X);if(a.info.sessionId)return{sessionId:a.info.sessionId,data:null}}u({submissionId:l,status:"pending",fingerprint:m})}let n=`${H.YZ}${(0,f.randomUUID)()}`,{session:o,realSessionId:p}=await b.startRpcSession(n,"",a,h,M),q=l?t.get(l):void 0,r=q?.cancelRequested===!0;q&&(q.info.sessionId=p,q.info.status=r?"cancelled":"starting"),b.allowFileRoot(a),b.invalidateSessionListCache();try{if(r||(e&&g&&await o.send({type:"set_model",provider:e,modelId:g}),i&&await o.send({type:"set_thinking_level",level:i}),l&&t.get(l)?.cancelRequested))throw await K.destroyAsync(p),Error(X)}catch(a){throw q&&(q.info.error=a instanceof Error?a.message:String(a)),a}if("ensure_session"===j.type){try{let a=o.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,k.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:p,data:null}}let s=await o.send(j);return q&&(q.info.status="accepted",q.info.sessionId=p),{sessionId:p,data:s}},getSubmission(a){let b=t.get(a);return b?{...b.info}:null},cancelSubmission(a){let c=t.get(a);if(!c)return u({submissionId:a,status:"cancelled"}),t.get(a).cancelRequested=!0,Promise.resolve({submissionId:a,status:"pending"});c.cancelRequested=!0;let d=c.info.sessionId;if(!d)return c.info.status="cancelled",Promise.resolve({submissionId:a,status:"pending"});if(c.cancelApplied)return Promise.resolve({submissionId:a,status:"confirmed"});c.cancelApplied=!0,c.info.status="cancelled";let e=b.getRpcSession(d);return e?.isAlive()?(async()=>{try{await e.send({type:"abort"})}catch(a){console.error("[pidance] cancel submission abort failed:",a)}return{submissionId:a,status:"confirmed"}})():Promise.resolve({submissionId:a,status:"confirmed"})},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,F.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,H.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,J.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions({allowStale:!0}),g=(0,E.$T)(b.archiveFs??E.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=(0,E.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>h.has(a)),hits:d.hits.filter(a=>h.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=d?.liveWriter;if(g)try{return(0,r.h_)({sessionManager:g.sessionManager,sessionFile:g.sessionFile,plan:(0,r.fb)(g.sessionManager,f)}),{cancelled:!1}}finally{b.invalidateSessionListCache()}let h=b.getRpcSession(a);if(h?.isAlive?.()&&h.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c);try{return(0,r.h_)({sessionManager:d,sessionFile:c,plan:(0,r.fb)(d,f)}),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d?.handoff)},async branchFromAssistant(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let f=c.trim(),g=d?.liveWriter;if(g)try{return(0,r.h_)({sessionManager:g.sessionManager,sessionFile:g.sessionFile,plan:(0,r.AM)(g.sessionManager,f)}),{cancelled:!1}}finally{b.invalidateSessionListCache()}let h=b.getRpcSession(a);if(h?.isAlive?.()&&h.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c);try{return(0,r.h_)({sessionManager:d,sessionFile:c,plan:(0,r.AM)(d,f)}),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d?.handoff)},async createSessionFromLeaf(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a),h=g?.inner;return e=async()=>{let c=(h?.sessionFile||g?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=(0,k.kW)(c),e=d.getEntry(f);if(!e)throw Error("Invalid entry ID");let i=f;if("message"===e.type&&e.message?.role==="assistant"){let a=d.getLeafId();if(!a)throw Error("Session has no leaf");let b=d.getBranch(a);i=(0,z.wo)(b,f)}let j=d.getSessionDir(),l=(0,k.G1)(c,j),m=l.createBranchedSession(i);if(!m)throw Error("Failed to create session");(0,k.kb)(l);let n=(0,k.kW)(m,j),o=n.getSessionId();(0,w.O8)(o,m),b.invalidateSessionListCache();let p=h?.model;return p&&(0,A.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}},I(a,e,d?.handoff)}},M={selectLeafExact:(a,b,c)=>K.selectLeafExact(a,b,c),branchFromAssistant:(a,b,c)=>K.branchFromAssistant(a,b,c),createSessionFromLeaf:(a,b,c)=>K.createSessionFromLeaf(a,b,c)};return K}();d()}catch(a){d(a)}})},38199:(a,b,c)=>{function d(a){let b=a.toolCallId;return"string"==typeof b&&""!==b?b:null}function e(a){let b=a.message,c=b?.id??a.messageId;return"string"==typeof c&&""!==c?c:null}function f(a){return Array.isArray(a)&&0!==a.length&&a.every(a=>"string"==typeof a)?a:null}function g(){let a=null,b=new Map;return{remember(c){switch(c.type){case"agent_start":case"agent_end":case"prompt_done":case"agent_settled":a=null,b.clear();return;case"message_start":case"message_update":{let b=c.message;if(!b||"user"===b.role)return;a=c;return}case"message_end":a=null;return;case"tool_execution_start":{let a=d(c);if(!a)return;b.set(a,{start:c,update:null,renderedUpdate:null,callLines:null,resultLines:null});return}case"tool_execution_update":{let a=d(c);if(!a)return;let e=b.get(a);if(!e)return;e.update=c,null!==f(c.renderedLines)&&(e.renderedUpdate=c);return}case"rendered_lines_update":{let a=d(c);if(!a)return;let e=b.get(a);if(!e)return;let g=f(c.renderedCallLines);g&&(e.callLines=g);let h=f(c.renderedResultLines);h&&(e.resultLines=h);return}case"tool_execution_end":{let a=d(c);if(!a)return;b.delete(a);return}default:return}},snapshot(){let c=[];for(let e of(a&&c.push(a),b.values())){c.push(e.callLines?{...e.start,renderedCallLines:e.callLines}:e.start);let a=e.update??e.renderedUpdate;a&&(!Object.prototype.hasOwnProperty.call(a,"renderedLines")&&e.renderedUpdate?c.push({...a,renderedLines:e.renderedUpdate.renderedLines}):c.push(a)),e.resultLines&&c.push({type:"rendered_lines_update",toolCallId:d(e.start),renderedResultLines:e.resultLines})}return{isStreaming:null!==a||b.size>0,events:c}},reset(){a=null,b.clear()}}}function h(a,b){if("message_start"===a.type){let c=e(a);return!!c&&b.events.some(a=>("message_start"===a.type||"message_update"===a.type)&&e(a)===c)}if("message_update"===a.type)return b.events.some(b=>b===a);if("tool_execution_start"===a.type||"tool_execution_update"===a.type){let c=d(a);return!!c&&b.events.some(b=>b.type===a.type&&d(b)===c)}if("rendered_lines_update"===a.type){let c=d(a);return!!c&&b.events.some(a=>"rendered_lines_update"===a.type&&d(a)===c)}return!1}c.d(b,{W:()=>h,b:()=>g})},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},41676:(a,b,c)=>{c.d(b,{x:()=>f});var d=c(89477),e=c(68524);function f(a,b){if(!a)return"";try{let c=(0,d.statSync)((0,e.m6)(b),{throwIfNoEntry:!1});if(!c||c.size>4194304)return"";return function(a,b){let c=a.drafts;if("object"!=typeof c||null===c||Array.isArray(c))return"";let d=c[b];if("object"!=typeof d||null===d||Array.isArray(d))return"";let e=d.value;return"string"==typeof e?e:""}((0,e.rV)(b),a)}catch(a){return console.error("[pidance] readComposerDraftText failed:",a),""}}},46935:(a,b,c)=>{c.d(b,{G1:()=>o,NN:()=>n,PV:()=>p,Uf:()=>d,WP:()=>q,_w:()=>e,tr:()=>r});let d=100,e=100;function f(a,b,c){if(b<=0||a[b]?.role==="user")return b;let d=Math.max(0,b-Math.max(0,c));for(let c=b-1;c>=d;c--)if(a[c]?.role==="user")return c;return b}function g(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function h(a){return"toolResult"!==a.role}function i(a){return Math.max(200,6*(Number.isFinite(a)&&a>0?Math.floor(a):1))}function j(a,b,c){let d=0,e=b;for(;e>0&&d<c;)h(a[--e])&&d++;return Math.max(e,b-i(c))}function k(a,b,c){for(let d=b;d<c;d++){let b=a[d];if(b&&h(b))return!0}return!1}function l(a,b,c){if(k(a,b,c))return b;let d=b;for(;d>0;){let b=a[--d];if(b&&h(b))return d}return 0}function m(a,b,c){if(k(a,b,c))return c;for(let b=c;b<a.length;b++){let c=a[b];if(c&&h(c))return b+1}return c}function n(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:g(e,b)}function o(a,b=d){let c=a.messages.length,e=g(b,d),h=j(a.messages,c,e),k=f(a.messages,h,e),m=l(a.messages,Math.max(k,c-i(e)),c);return{messages:a.messages.slice(m),entryIds:a.entryIds.slice(m),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:m>0,hasMoreAfter:!1,totalMessageCount:c}}function p(a,b,c=e,d={}){let h=a.messages.length,i=a.entryIds.indexOf(b);if(i<0)return null;let j=g(c,e),n=Math.max(1,Math.floor(j/2)),o=a.messages,q=Math.max(0,f(o,Math.max(0,i-n),n)),r=d.toEnd?h:Math.min(h,q+j),s=q,t=r;if(!k(o,s,t)){let a=l(o,s,t);a!==s?s=a:t=m(o,s,t)}return{messages:a.messages.slice(s,t),entryIds:a.entryIds.slice(s,t),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:s>0,hasMoreAfter:t<h,totalMessageCount:h}}function q(a,b,c=e){let d=a.messages.length,f=a.entryIds.indexOf(b);if(f<0||f>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let j=g(c,e),l=a.messages,n=function(a,b,c){let d=0,e=b;for(;e<a.length&&d<c;)h(a[e])&&d++,e++;return Math.min(e,b+i(c))}(l,f+1,j),o=m(l,f+1,n),p=o!==n||k(l,f+1,n)?o:d;return{messages:a.messages.slice(f+1,p),entryIds:a.entryIds.slice(f+1,p),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:p<d,totalMessageCount:d}}function r(a,b,c=e){let d=a.messages.length,h=a.entryIds.indexOf(b);if(h<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let k=g(c,e),m=j(a.messages,h,k),n=f(a.messages,m,k),o=l(a.messages,Math.max(n,h-i(k)),h);return{messages:a.messages.slice(o,h),entryIds:a.entryIds.slice(o,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:o>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{$3:()=>o,D_:()=>s,JT:()=>k,K2:()=>g,QR:()=>t,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(13737),e=c(99014);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}function s(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a||"set_follow_up_queue"===a||"dispatch_follow_up_queue"===a||"recall_follow_up_queue"===a}function t(a,b=h){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return k(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return n(a,b);if("follow_up"===c)return o(a,b);if("set_follow_up_queue"===c)return p(a,b);if("dispatch_follow_up_queue"===c)return q(a,b);if("recall_follow_up_queue"===c)return r(a,b);throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}[f,g]=h.then?(await h)():h;let k=`
|
|
2
2
|
.pidance-activity{margin:1.5rem 0;padding:1rem 1.25rem;border:1px solid #ccc;border-radius:8px;background:#fafafa;color:#222;font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:14px;line-height:1.45}
|
|
3
3
|
.pidance-activity h2{margin:0 0 0.75rem;font-size:1.1rem;font-weight:600}
|
|
4
4
|
.pidance-activity-card{margin:0.75rem 0;padding:0.75rem 1rem;border:1px solid #ddd;border-radius:6px;background:#fff}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
.pidance-activity-kind{display:inline-block;padding:0.1rem 0.45rem;border-radius:4px;background:#eee;font-weight:600;text-transform:uppercase;letter-spacing:0.03em;font-size:11px}
|
|
11
11
|
.pidance-activity-card h3{margin:0 0 0.5rem;font-size:1rem;font-weight:600;word-break:break-word}
|
|
12
12
|
.pidance-activity-content{margin:0;padding:0.5rem 0.65rem;border-radius:4px;background:#f5f5f5;color:#111;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;white-space:pre-wrap;word-break:break-word;overflow-x:auto}
|
|
13
|
-
`.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(60396),h=c(69835),i=c(13737),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},62693:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},68524:(a,b,c)=>{c.d(b,{Gc:()=>q,Nj:()=>p,UQ:()=>i,fN:()=>r,m6:()=>h,ql:()=>n,rV:()=>j,xP:()=>o});var d=c(89477),e=c(86697),f=c(60396),g=c(75052);function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function i(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function j(a=(0,f.$M)()){let b=h(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return i(a)?a:{}}catch{return{}}}function k(a,b){let c=h(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(g,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(g).mtimeMs>6e4&&(0,d.unlinkSync)(g)}catch{}if(Date.now()>=i)throw Error("Timed out acquiring Pidance preferences lock");!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,10)}()}try{return b()}finally{(0,d.closeSync)(j);try{(0,d.unlinkSync)(g)}catch{}}}function l(a,b){let c=h(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(g,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(g,c)}catch(a){try{(0,d.unlinkSync)(g)}catch{}throw a}}function m(a,b){let c=b.split("."),d=a;for(let a of c){if("object"!=typeof d||null===d)return;d=d[a]}return d}function n(a,b){return m(a,b)}function o(a,b,c=(0,f.$M)()){k(c,()=>{let d=j(c);!function(a,b,c){let d=b.split("."),e=a;for(let a=0;a<d.length-1;a++){let b=d[a],c=e[b];("object"!=typeof c||null===c||Array.isArray(c))&&(e[b]={}),e=e[b]}let f=d[d.length-1];null==c?delete e[f]:e[f]=c}(d,a,b),l(d,c)})}function p(a){let b={},c=[];for(let[d,e]of Object.entries(a)){if("sessionQueue"===d||d.startsWith("sessionQueue.")){c.push(d);continue}b[d]=e}return{patch:b,dropped:c}}function q(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(i(d)&&i(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(c,a),e=function(a,b,c){let d={};for(let[e,f]of Object.entries(b)){let b=a[e],g=c[e];if(i(f)&&i(b)){for(let a of Object.keys(f)){let c=`${e}.${a}`,f=b[a],h=i(g)?g[a]:void 0;JSON.stringify(f)!==JSON.stringify(h)&&(d[c]=h??null)}continue}JSON.stringify(b)!==JSON.stringify(g)&&(d[e]=g??null)}return d}(c,a,d);return Object.keys(e).length>0&&l(d,b),e})}function r(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=(0,g.W)(c,a);if(0===d.length)return{};l(c,b);let e={};for(let a of d)e[a]=m(c,a)??null;return e})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f&&"system"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
|
|
13
|
+
`.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(60396),h=c(69835),i=c(13737),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},62693:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},67633:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{h:()=>j});var e=c(70770),f=c(28121),g=a([f]);function h(a){return"object"!=typeof a||null===a||Array.isArray(a)?null:a}function i(a,b){if(!b)return null;let c={},d=b.label;if("string"==typeof d){let b=d.trim();""!==b&&b!==a&&(c.label=b)}return"self"===b.renderShell&&(c.renderShell="self"),void 0===c.label&&void 0===c.renderShell?null:c}async function j(a){let b=await (0,e.aW)({cwd:a.cwd,agentDir:a.agentDir,loaderFactory:a.loaderFactory,bypassCache:a.bypassCache});if(!b.ok)return null;let c=function(a){let b=new Map;for(let c of a){let a=h(c);if(!a)continue;let d=a.tools;if(d instanceof Map)for(let[a,c]of d){if("string"!=typeof a||""===a||b.has(a))continue;let d=i(a,h(h(c)?.definition));d&&b.set(a,d)}}if(!b.has(f.Jv)){let a=i(f.Jv,{label:f.wc});a&&b.set(f.Jv,a)}return b}(b.value.extensions);return 0===c.size?null:a=>c.get(a)??null}f=(g.then?(await g)():g)[0],d()}catch(a){d(a)}})},68524:(a,b,c)=>{c.d(b,{Gc:()=>q,Nj:()=>p,UQ:()=>i,fN:()=>r,m6:()=>h,ql:()=>n,rV:()=>j,xP:()=>o});var d=c(89477),e=c(86697),f=c(60396),g=c(75052);function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function i(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function j(a=(0,f.$M)()){let b=h(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return i(a)?a:{}}catch{return{}}}function k(a,b){let c=h(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(g,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(g).mtimeMs>6e4&&(0,d.unlinkSync)(g)}catch{}if(Date.now()>=i)throw Error("Timed out acquiring Pidance preferences lock");!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,10)}()}try{return b()}finally{(0,d.closeSync)(j);try{(0,d.unlinkSync)(g)}catch{}}}function l(a,b){let c=h(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(g,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(g,c)}catch(a){try{(0,d.unlinkSync)(g)}catch{}throw a}}function m(a,b){let c=b.split("."),d=a;for(let a of c){if("object"!=typeof d||null===d)return;d=d[a]}return d}function n(a,b){return m(a,b)}function o(a,b,c=(0,f.$M)()){k(c,()=>{let d=j(c);!function(a,b,c){let d=b.split("."),e=a;for(let a=0;a<d.length-1;a++){let b=d[a],c=e[b];("object"!=typeof c||null===c||Array.isArray(c))&&(e[b]={}),e=e[b]}let f=d[d.length-1];null==c?delete e[f]:e[f]=c}(d,a,b),l(d,c)})}function p(a){let b={},c=[];for(let[d,e]of Object.entries(a)){if("sessionQueue"===d||d.startsWith("sessionQueue.")){c.push(d);continue}b[d]=e}return{patch:b,dropped:c}}function q(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(i(d)&&i(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(c,a),e=function(a,b,c){let d={};for(let[e,f]of Object.entries(b)){let b=a[e],g=c[e];if(i(f)&&i(b)){for(let a of Object.keys(f)){let c=`${e}.${a}`,f=b[a],h=i(g)?g[a]:void 0;JSON.stringify(f)!==JSON.stringify(h)&&(d[c]=h??null)}continue}JSON.stringify(b)!==JSON.stringify(g)&&(d[e]=g??null)}return d}(c,a,d);return Object.keys(e).length>0&&l(d,b),e})}function r(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=(0,g.W)(c,a);if(0===d.length)return{};l(c,b);let e={};for(let a of d)e[a]=m(c,a)??null;return e})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{entryId:"string"==typeof d.id?d.id:void 0,messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",entryId:d.entryId,messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
|
|
14
14
|
SELECT
|
|
15
15
|
m.session_id AS session_id,
|
|
16
16
|
m.role AS role,
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
snippet(message_fts, 0, '\xab', '\xbb', '…', 12) AS snippet
|
|
21
21
|
FROM message_fts
|
|
22
22
|
JOIN messages m ON m.rowid = message_fts.rowid
|
|
23
|
-
WHERE message_fts MATCH ?
|
|
23
|
+
WHERE message_fts MATCH ? AND m.role <> 'system'
|
|
24
24
|
ORDER BY m.timestamp DESC
|
|
25
25
|
LIMIT ?
|
|
26
26
|
`;try{return a.prepare(e).all(d,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:"string"==typeof a.snippet&&a.snippet.trim()?a.snippet.trim():l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch(a){if(function(a){if(!(a instanceof Error))return!1;let b=a.message.toLowerCase();return b.includes("fts5")||b.includes("unterminated string")||b.includes("syntax error")}(a))return[];throw a}},e=function(a){let b=a.trim();if(!b)return"";if(i.test(b))return b;let c=[];for(let a of b.matchAll(j)){let b=a[1],d=a[2];if(void 0===b&&d&&k.has(d.toLowerCase()))continue;let e=b??d??"";e.length>0&&c.push(e)}return c.map(a=>`"${a.replace(/"/g,'""')}"`).join(" ")}(b);if(!e)return[];let f=d(e);if(f.length>0||i.test(b.trim()))return f;let g=function(a){let b=a.trim();if(!b||i.test(b))return null;let c=[];for(let a of b.matchAll(j)){let b=a[1],d=a[2];if(void 0===b&&d&&k.has(d.toLowerCase()))continue;let e=b??d??"";e.length>0&&c.push(e)}return c.length<=1?null:c.map(a=>`"${a.replace(/"/g,'""')}"`).join(" OR ")}(b);if(g&&g!==e){let a=d(g);if(a.length>0)return a}try{let d=`
|
|
@@ -32,19 +32,20 @@
|
|
|
32
32
|
m.id AS message_id,
|
|
33
33
|
m.content AS snippet
|
|
34
34
|
FROM messages m
|
|
35
|
-
WHERE m.content LIKE ? ESCAPE '\\'
|
|
35
|
+
WHERE m.content LIKE ? ESCAPE '\\' AND m.role <> 'system'
|
|
36
36
|
ORDER BY m.timestamp DESC
|
|
37
37
|
LIMIT ?
|
|
38
|
-
`,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$t:()=>w,Gt:()=>z,Lj:()=>y,Md:()=>x,eq:()=>n,fb:()=>u,fm:()=>v,ki:()=>r,qo:()=>m,uF:()=>o,vy:()=>t,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let x=0x1900000,y=0x6400000,z=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=z){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,u=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),u,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}function s(a,b,c){let d=a.trim();if(!d)return null;try{let a=(0,k.Nw)((0,e.realpathSync)(n(b))),f=(0,k.Nw)((0,e.realpathSync)(d));if(f!==a&&!f.startsWith(`${a}/`)||!(0,e.statSync)(f).isFile())return null;return c(f)}catch{return null}}function t(a,b=(0,j.$M)()){return s(a,b,a=>(0,e.statSync)(a).size)}function u(a,b=(0,j.$M)(),c=0x1900000){return s(a,b,a=>(0,e.statSync)(a).size>c?null:(0,e.readFileSync)(a).toString("base64"))}function v(a,b=(0,j.$M)()){return s(a,b,a=>{try{return(0,e.unlinkSync)(a),!0}catch{return!1}})??!1}function w(a=(0,j.$M)()){let b=[];return function a(b,c){for(let d of(()=>{try{return(0,e.readdirSync)(b,{withFileTypes:!0})}catch{return[]}})()){let g=(0,f.join)(b,d.name);if(d.isDirectory()){a(g,c);continue}if(d.isFile())try{let a=(0,e.statSync)(g);c.push({path:(0,k.Nw)(g),size:a.size,mtimeMs:a.mtimeMs})}catch{}}}(m(a),b),b}d()}catch(a){d(a)}})},75052:(a,b,c)=>{function d(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function e(a,b){let c=b.split("."),e=a;for(let a=0;a<c.length-1;a+=1){let b=c[a],f=e[b];if(!d(f)){let a={};e[b]=a,e=a;continue}e=f}let f=c[c.length-1];return{container:e,last:f,existed:Object.prototype.hasOwnProperty.call(e,f)}}function f(a){return!(!a||"string"!=typeof a.key||0===a.key.length||"sessionQueue"===a.key||a.key.startsWith("sessionQueue."))&&("add"===a.op||"remove"===a.op?"sidebarUi.projectRoots"===a.key||"sidebarUi.pinnedSessionIds"===a.key||"sidebarUi.ungroupedSessionIds"===a.key||"sidebarUi.collapsedProjectRoots"===a.key:"set"===a.op)}function g(a,b){let c=[],g=a=>{c.includes(a)||c.push(a)};for(let c of b){if(!f(c))continue;if("set"===c.op){let{container:b,last:d,existed:f}=e(a,c.key);if(null===c.value||void 0===c.value){if(!f)continue;delete b[d],g(c.key);continue}if(JSON.stringify(b[d])===JSON.stringify(c.value))continue;b[d]=c.value,g(c.key);continue}let b=function(a,b){let c=a;for(let a of b.split(".")){if(!d(c))return;c=c[a]}return c}(a,c.key),h=Array.isArray(b)?b.filter(a=>!0):[],i=c.value;if("string"!=typeof i||0===i.length)continue;if("add"===c.op){if(h.includes(i))continue;h.push(i)}else{if(!h.includes(i))continue;let a=h.filter(a=>a!==i);h.length=0,h.push(...a)}let{container:j,last:k}=e(a,c.key);j[k]=h,g(c.key)}return c}c.d(b,{F:()=>f,W:()=>g})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>
|
|
38
|
+
`,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$t:()=>w,Gt:()=>z,Lj:()=>y,Md:()=>x,eq:()=>n,fb:()=>u,fm:()=>v,ki:()=>r,qo:()=>m,uF:()=>o,vy:()=>t,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let x=0x1900000,y=0x6400000,z=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=z){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,u=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),u,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}function s(a,b,c){let d=a.trim();if(!d)return null;try{let a=(0,k.Nw)((0,e.realpathSync)(n(b))),f=(0,k.Nw)((0,e.realpathSync)(d));if(f!==a&&!f.startsWith(`${a}/`)||!(0,e.statSync)(f).isFile())return null;return c(f)}catch{return null}}function t(a,b=(0,j.$M)()){return s(a,b,a=>(0,e.statSync)(a).size)}function u(a,b=(0,j.$M)(),c=0x1900000){return s(a,b,a=>(0,e.statSync)(a).size>c?null:(0,e.readFileSync)(a).toString("base64"))}function v(a,b=(0,j.$M)()){return s(a,b,a=>{try{return(0,e.unlinkSync)(a),!0}catch{return!1}})??!1}function w(a=(0,j.$M)()){let b=[];return function a(b,c){for(let d of(()=>{try{return(0,e.readdirSync)(b,{withFileTypes:!0})}catch{return[]}})()){let g=(0,f.join)(b,d.name);if(d.isDirectory()){a(g,c);continue}if(d.isFile())try{let a=(0,e.statSync)(g);c.push({path:(0,k.Nw)(g),size:a.size,mtimeMs:a.mtimeMs})}catch{}}}(m(a),b),b}d()}catch(a){d(a)}})},70770:(a,b,c)=>{c.d(b,{Zd:()=>f,aW:()=>g});var d=c(86697);function e(a){return"object"!=typeof a||null===a||Array.isArray(a)?null:a}function f(){let a=globalThis.__piPidanceLoadedExtensionsCache;a&&(a.entries.clear(),a.inFlight.clear(),a.generation+=1)}async function g(a){let b=(0,d.resolve)(a.cwd),f=`${b}\0${a.agentDir?(0,d.resolve)(a.agentDir):""}`,g=(globalThis.__piPidanceLoadedExtensionsCache||(globalThis.__piPidanceLoadedExtensionsCache={entries:new Map,inFlight:new Map,generation:0}),globalThis.__piPidanceLoadedExtensionsCache);if(!a.bypassCache){let a=g.entries.get(f);if(a&&a.expiresAt>Date.now())return a.value;a&&g.entries.delete(f);let b=g.inFlight.get(f);if(b)return b}let h=(a.loaderFactory??function(a,b){return async()=>{let d=await Promise.resolve().then(c.bind(c,75430));if(!d.DefaultResourceLoader)throw Error("DefaultResourceLoader is not available");let f=new d.DefaultResourceLoader(b?{cwd:a,agentDir:b}:{cwd:a});await f.reload();let g=f.getExtensions(),h=Array.isArray(g?.extensions)?g.extensions.filter(a=>null!==e(a)):[],i=Array.isArray(g?.errors)?g.errors:[];return{extensions:h,runtime:e(g?.runtime)??{},errors:i}}})(b,a.agentDir),i=g.generation,j=Promise.resolve().then(h).then(a=>({ok:!0,value:a})).catch(a=>({ok:!1,error:a instanceof Error?a.message:String(a)})).then(b=>(a.bypassCache||g.generation!==i||g.entries.set(f,{value:b,expiresAt:Date.now()+3e4}),b)).finally(()=>{g.inFlight.get(f)===j&&g.inFlight.delete(f)});return a.bypassCache||g.inFlight.set(f,j),j}},71069:(a,b,c)=>{c.d(b,{TQ:()=>e,Tf:()=>d});let d=40;function e(a,b=92,c=d,f={}){let g="function"==typeof b?b:()=>b,h="function"==typeof c?c:()=>c,i=Object.freeze({render:()=>[],invalidate:()=>{},handleInput:()=>{},getText:()=>"",setText:()=>{}}),j=f.isEditorFocused,k=!1,l={terminal:Object.freeze({get columns(){return g()},get rows(){return h()},kittyProtocolActive:!1}),requestRender:a,stop(){k||(k=!0,f.onUnsupported?.("tui.stop()/start() (external editor handover)"))},start(){}};return Object.defineProperty(l,"focusedComponent",{enumerable:!0,get:()=>j?.()===!0?i:void 0}),Object.freeze(l)}},75052:(a,b,c)=>{function d(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function e(a,b){let c=b.split("."),e=a;for(let a=0;a<c.length-1;a+=1){let b=c[a],f=e[b];if(!d(f)){let a={};e[b]=a,e=a;continue}e=f}let f=c[c.length-1];return{container:e,last:f,existed:Object.prototype.hasOwnProperty.call(e,f)}}function f(a){return!(!a||"string"!=typeof a.key||0===a.key.length||"sessionQueue"===a.key||a.key.startsWith("sessionQueue."))&&("add"===a.op||"remove"===a.op?"sidebarUi.projectRoots"===a.key||"sidebarUi.pinnedSessionIds"===a.key||"sidebarUi.ungroupedSessionIds"===a.key||"sidebarUi.collapsedProjectRoots"===a.key:"set"===a.op)}function g(a,b){let c=[],g=a=>{c.includes(a)||c.push(a)};for(let c of b){if(!f(c))continue;if("set"===c.op){let{container:b,last:d,existed:f}=e(a,c.key);if(null===c.value||void 0===c.value){if(!f)continue;delete b[d],g(c.key);continue}if(JSON.stringify(b[d])===JSON.stringify(c.value))continue;b[d]=c.value,g(c.key);continue}let b=function(a,b){let c=a;for(let a of b.split(".")){if(!d(c))return;c=c[a]}return c}(a,c.key),h=Array.isArray(b)?b.filter(a=>!0):[],i=c.value;if("string"!=typeof i||0===i.length)continue;if("add"===c.op){if(h.includes(i))continue;h.push(i)}else{if(!h.includes(i))continue;let a=h.filter(a=>a!==i);h.length=0,h.push(...a)}let{container:j,last:k}=e(a,c.key);j[k]=h,g(c.key)}return c}c.d(b,{F:()=>f,W:()=>g})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>q,K:()=>n});var d=c(89477),e=c(60396),f=c(92395);let g=Math.round(2400),h="[…]",i=`Create a concise title for this session based on the conversation above.
|
|
39
39
|
|
|
40
40
|
Requirements:
|
|
41
41
|
- Match the primary language used by the user.
|
|
42
42
|
- Describe the user's concrete goal or the outcome, not the act of chatting.
|
|
43
43
|
- Use 4-12 words for space-separated languages, or 8-24 characters for CJK text when practical.
|
|
44
44
|
- Do not call any tools.
|
|
45
|
-
- Return only the title as plain text, with no quotes, label, markdown, or explanation.`;function
|
|
45
|
+
- Return only the title as plain text, with no quotes, label, markdown, or explanation.`;function j(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function k(a){return"string"==typeof a?a.trim():""}function l(a){return"number"==typeof a&&Number.isFinite(a)?a:0}function m(a){return"string"==typeof a.content?Array.from(a.content).length:0}async function n(a){let{messages:b,modelId:c,baseUrl:d,apiKey:e,headers:f,signal:k}=a;if(!b.some(a=>"user"===a.role))throw Error("The session has no user messages to name");let n=function(a,b=6e3){let c=-1;for(let b=a.length-1;b>=0;b--)if("assistant"===a[b].role){c=b;break}let d=[];return a.forEach((a,b)=>{var e;let f;if("user"!==a.role&&"assistant"!==a.role)return;let g="string"==typeof(e=a.content)?e.trim():Array.isArray(e)?e.filter(a=>j(a)&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n").trim():"";if(!g)return;let h="user"===a.role?800:b===c?600:300;d.push({role:a.role,content:(f=Array.from(g)).length<=h?g:`${f.slice(0,h).join("")}…`})}),function(a,b=6e3){if(a.reduce((a,b)=>a+m(b),0)<=b||a.length<2)return a;let c=h.length+2,d=Math.round(g/6e3*b),e=[],f=0;for(;f<a.length;f++){let b=c+m(a[f]);if(e.length>0&&b>d)break;e.push(a[f]),c=b}let i=[];for(let d=a.length-1;d>=f;d--){let e=c+m(a[d]);if(e>b)break;i.unshift(a[d]),c=e}if(f+i.length>=a.length)return a;let j=e[e.length-1];return[...e.slice(0,-1),{...j,content:`${String(j.content)}
|
|
46
|
+
${h}`},...i]}(d,b)}(b,Math.max(1,6e3-(Array.from(i).length+2))),o=function(a){let b=a.at(-1);if(!b||"user"!==b.role)return a;let c="string"==typeof b.content?`${b.content}
|
|
46
47
|
|
|
47
|
-
${
|
|
48
|
+
${i}`:[...Array.isArray(b.content)?b.content:[],{type:"text",text:i}];return[...a.slice(0,-1),{...b,content:c}]}(n);o===n&&n.push({role:"user",content:i});let p=o.map(a=>({role:"assistant"===a.role?"assistant":"user",content:a.content})),q=new AbortController,r=setTimeout(()=>q.abort(),9e4),s=()=>q.abort();k?.addEventListener("abort",s,{once:!0});try{var t;let a,b,g=d.replace(/\/+$/,""),h=await fetch(`${g}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,...f},body:JSON.stringify({model:c,messages:p,max_tokens:64}),signal:q.signal}),i=await h.text();if(!h.ok)throw Error(i.slice(0,500)||`HTTP ${h.status}`);try{a=JSON.parse(i)}catch{throw Error("The model did not return a usable session title")}let k=function(a){if(!j(a))return"";let b=a.choices;if(Array.isArray(b)){let a=b[0];if(j(a)){let b=a.message;if(j(b)&&"string"==typeof b.content)return b.content;if("string"==typeof a.text)return a.text}}return"string"==typeof a.output_text?a.output_text:""}(a);if(!k)throw Error("The model did not return a session title");return{title:function(a){let b=a.trim(),c=b.match(/^```(?:json|text)?\s*([\s\S]*?)\s*```$/i);if(c&&(b=c[1].trim()),b.startsWith("{"))try{let a=JSON.parse(b);"string"==typeof a.title&&(b=a.title.trim())}catch{}if(b=(b=(function(a){for(let[b,c]of[['"','"'],["'","'"],["`","`"],["“","”"],["「","」"],["『","』"]])if(a.startsWith(b)&&a.endsWith(c)&&a.length>b.length+c.length)return a.slice(b.length,-c.length).trim();return a})(b=(b=b.split(/\r?\n/,1)[0]??"").replace(/^(?:session\s+title|title|标题)\s*[::-]\s*/i,"")).replace(/\s+/g," ").trim()).replace(/[。.!]+$/u,"").trim(),!/[\p{L}\p{N}]/u.test(b))throw Error("The model did not return a usable session title");let d=Array.from(b);return d.length>80&&(b=d.slice(0,80).join("").trim()),b}(k),...j(a)&&j(a.usage)?{usage:(t=a.usage,b=j(t.prompt_tokens_details)?t.prompt_tokens_details:{},{input:l(t.prompt_tokens),output:l(t.completion_tokens),cacheRead:l(b.cached_tokens),cacheWrite:l(b.cache_creation_input_tokens),total:l(t.total_tokens)})}:{}}}finally{clearTimeout(r),k?.removeEventListener("abort",s)}}function o(a){if(!a)return;let b=a.match(/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(b){let a=process.env[b[1]];return a&&a.length>0?a:void 0}return a}function p(a){if(!j(a))return{};let b={};for(let[c,d]of Object.entries(a))"string"==typeof d&&(b[c]=d);return b}function q(a){let b,c=a?.settingsPath??(0,e.pA)(),g=a?.modelsPath??(0,e.Mc)(),h=(0,f.wq)(c),i=k(h.defaultProvider),l=k(h.defaultModel);if(!i||!l)throw Error("No default model configured: set defaultProvider/defaultModel in settings.json");try{if(!(0,d.existsSync)(g))throw Error("missing");b=JSON.parse((0,d.readFileSync)(g,"utf8"))}catch{throw Error(`models.json not found or unreadable: ${g}`)}if(!j(b))throw Error(`models.json is not an object: ${g}`);let m=j(b.providers)?b.providers:{},n=j(m[i])?m[i]:void 0;if(!n)throw Error(`Model provider not found in models.json: ${i}`);let q=Array.isArray(n.models)?n.models:[],r=j(n.modelOverrides)?n.modelOverrides:{},s=q.find(a=>j(a)&&k(a.id)===l)??r[l],t=j(s)?s:void 0;if(!t)throw Error(`Model not found in models.json: ${i}/${l}`);let u=o(k(t.apiKey))??o(k(n.apiKey));if(!u)throw Error(`No API key found for "${i}"`);let v=k(t.baseUrl)||k(n.baseUrl);if(!v)throw Error(`baseUrl is required for "${i}"`);return{provider:i,modelId:l,baseUrl:v,api:k(t.api)||k(n.api)||"openai-completions",apiKey:u,headers:{...p(n.headers),...p(t.headers)}}}},80547:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{A$:()=>r,Nw:()=>j.Nw,bk:()=>q,mc:()=>p,uK:()=>o,wz:()=>k.wz});var e=c(29021),f=c(21820),g=c(33873),h=c.n(g),i=c(60396),j=c(50593),k=c(25252),l=c(69835),m=c(40402),n=a([l,m]);[l,m]=n.then?(await n)():n;let s=/^[a-zA-Z]:[\\/]/;function o(a){return s.test(a)||a.startsWith("\\\\")||a.startsWith("//")}async function p(){let a=Date.now(),b=globalThis.__piAllowedRootsCache;if(b&&b.expiresAt>a)return b.roots;let c=await (0,m.dQ)(),d=function(a){let b=new Set;for(let c of a)!0!==c.readOnly&&c.cwd&&b.add((0,j.Nw)(c.cwd)),!0!==c.readOnly&&c.projectRoot&&b.add((0,j.Nw)(c.projectRoot));return b}(c);try{for(let a of(0,e.readdirSync)((0,f.homedir)()))/^pi-cwd-\d{8}$/.test(a)&&d.add((0,j.Nw)(h().join((0,f.homedir)(),a)))}catch{}for(let a of(0,k.HM)())d.add(a);try{d.add((0,l.qo)((0,i.$M)()))}catch{}return globalThis.__piAllowedRootsCache={roots:d,expiresAt:a+5e3},d}function q(){return!0}function r(a,b){return!0}d()}catch(a){d(a)}})},81879:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{by:()=>p});var e=c(55511),f=c(79646),g=c(29021),h=c(21820),i=c(33873),j=c(28354),k=c(53023),l=c(93127),m=a([k,l]);[k,l]=m.then?(await m)():m;let q=(0,j.promisify)(f.execFile);async function n(){try{let{stdout:a}=await q("which",["pi"],{timeout:5e3,env:process.env}),b=a.trim().split("\n")[0]?.trim();if(b&&(0,g.existsSync)(b))return b}catch{}for(let a of[(0,i.join)(process.env.HOME||"",".nvm/versions/node",process.version,"bin/pi"),"/usr/local/bin/pi",(0,i.join)(process.env.HOME||"",".local/bin/pi")])if(a&&(0,g.existsSync)(a))return a;return null}async function o(a,b){let c=await n();if(!c)throw Error("pi CLI not found on PATH; install pi to export HTML sessions");await q(c,["--export",a,b],{cwd:process.cwd(),timeout:3e4,env:{...process.env,PI_OFFLINE:"1",PI_SKIP_VERSION_CHECK:"1"},maxBuffer:1048576})}async function p(a,b){if("jsonl"===b.format)return{body:(0,l.wr)(a,{leafId:b.leafId&&b.leafId.length>0?b.leafId:void 0}),contentType:l.rW,fileName:(0,l.ye)(a)};let c=(0,i.join)((0,h.tmpdir)(),"pidance-export");(0,g.mkdirSync)(c,{recursive:!0});let d=(0,i.basename)(a,".jsonl"),f=`pi-session-${d}.html`,j=(0,e.randomUUID)(),m=(0,i.join)(c,`${j}.html`),n=(0,i.join)(c,`${j}-branch.jsonl`),p=b.leafId&&b.leafId.length>0?b.leafId:void 0,q=a;try{var r;let b;if(void 0!==p){let b=(0,l.wr)(a,{leafId:p});(0,g.writeFileSync)(n,b,"utf8"),q=n}await o(q,m);let c=(r=(r=(0,g.readFileSync)(m,"utf8")).replace(/\r\n/g,"\n"),r=(b=(a,b,c,d)=>{let e=c.replace(/\r\n/g,"\n"),f=d.replace(/\r\n/g,"\n"),g=a.split(e).length-1;if(1!==g)throw Error(`Failed to patch exported HTML: ${b} expected 1 match, found ${g}`);return a.replace(e,f)})(r,"sortChildren",` function sortChildren(node) {
|
|
48
49
|
node.children.sort((a, b) =>
|
|
49
50
|
new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
|
|
50
51
|
);
|
|
@@ -97,7 +98,7 @@ ${g}`:[...Array.isArray(b.content)?b.content:[],{type:"text",text:g}];return[...
|
|
|
97
98
|
}
|
|
98
99
|
containsActive.set(node, has);
|
|
99
100
|
}
|
|
100
|
-
}`));return{body:(0,k.Uj)(c,q),contentType:"text/html; charset=utf-8",fileName:f}}finally{(0,g.rmSync)(m,{force:!0}),(0,g.rmSync)(n,{force:!0})}}d()}catch(a){d(a)}})},86226:(a,b,c)=>{c.d(b,{yN:()=>d});function d(a,b){return!a&&!!b}},87538:(a,b,c)=>{let d;c.d(b,{Lm:()=>
|
|
101
|
-
`,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a){return(a instanceof Error?a.message:String(a)).includes("locked by another Pidance process")}function t(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;try{return o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;return!(f&&f.pid!==process.pid&&r(f))&&(q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c}),!0)})}catch(a){if(p(a))return!1;throw a}}function u(a,b=(0,g.$M)(),c=Date.now()){if(a)try{o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;f&&f.pid!==process.pid&&r(f)||q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c})})}catch(a){if(!p(a))throw a}}function v(a,b=(0,g.$M)()){if(a)try{o(b,()=>{let c=k(b,a),d=(0,e.existsSync)(c)?m(c):null;if(!d||d.pid===process.pid)try{(0,e.unlinkSync)(c)}catch{}})}catch(a){if(!p(a))throw a}}function w(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;let d=(0,e.existsSync)(k(b,a))?m(k(b,a)):null;return!!d&&d.pid!==process.pid&&r(d)}},91898:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Fx:()=>k});var e=c(29021),f=c(33873),g=c(60396),h=c(69835),i=c(68524),j=a([h]);function k(a={}){let b=a.agentDir??(0,g.$M)(),c=a.ttlMs??2592e6,d=a.now??Date.now(),j=(0,h.$t)(b),l=j.filter(a=>d-a.mtimeMs>c);if(0===l.length)return{scanned:j.length,candidates:0,deleted:0,bytes:0,complete:!0};let m=function(a,b=(0,g.$M)()){let c=function(a){let b=(0,i.m6)(a);if(!(0,e.existsSync)(b))return{};try{let a=JSON.parse((0,e.readFileSync)(b,"utf8"));return(0,i.UQ)(a)?a:null}catch{return null}}(b);if(null===c)return null;let d=function(a){if(!(0,e.existsSync)(a))return[];let b=[],c=a=>{let d=(()=>{try{return(0,e.readdirSync)(a,{withFileTypes:!0})}catch{return null}})();if(null===d)return!1;for(let e of d){let d=(0,f.join)(a,e.name);if(e.isDirectory()){if(!c(d))return!1;continue}e.isFile()&&e.name.endsWith(".jsonl")&&b.push(d)}return!0};return c(a)?b:null}((0,f.join)(b,"sessions"));if(null===d)return null;let h=new Set,j=a.map(a=>{var b;return{path:a,escaped:(b=a,JSON.stringify(b).slice(1,-1))}}),k=a=>{for(let b of j)!h.has(b.path)&&(a.includes(b.path)||a.includes(b.escaped))&&h.add(b.path)};for(let a of(k(JSON.stringify(c)),d)){let b;if(h.size===j.length)break;try{b=(0,e.readFileSync)(a,"utf8")}catch{return null}k(b)}return h}(l.map(a=>a.path),b);if(null===m)return{scanned:j.length,candidates:l.length,deleted:0,bytes:0,complete:!1};let n=0,o=0;for(let a of l)!m.has(a.path)&&(0,h.fm)(a.path,b)&&(n+=1,o+=a.size);return{scanned:j.length,candidates:l.length,deleted:n,bytes:o,complete:!0}}h=(j.then?(await j)():j)[0],d()}catch(a){d(a)}})},92395:(a,b,c)=>{c.d(b,{Ej:()=>q,FN:()=>j,J7:()=>s,Tj:()=>r,oT:()=>m,wq:()=>i,xH:()=>t});var d=c(89477),e=c(86697),f=c(60396);function g(a){return(0,e.join)((0,e.resolve)(a),".pi","settings.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a){if(!(0,d.existsSync)(a))return{};try{let b=JSON.parse((0,d.readFileSync)(a,"utf8"));return h(b)?{...b}:{}}catch{return{}}}function j(a,b){let c=(0,e.dirname)(a);(0,d.mkdirSync)(c,{recursive:!0});let f=`${a}.${process.pid}.${Date.now()}.tmp`,g=`${JSON.stringify(b,null,2)}
|
|
101
|
+
}`));return{body:(0,k.Uj)(c,q),contentType:"text/html; charset=utf-8",fileName:f}}finally{(0,g.rmSync)(m,{force:!0}),(0,g.rmSync)(n,{force:!0})}}d()}catch(a){d(a)}})},86226:(a,b,c)=>{c.d(b,{yN:()=>d});function d(a,b){return!a&&!!b}},87538:(a,b,c)=>{let d;c.d(b,{Yg:()=>h,Lm:()=>y,hR:()=>C,bn:()=>F,Mf:()=>E,GD:()=>B,t_:()=>A,F$:()=>D,DD:()=>s,YJ:()=>w,Sw:()=>x});let e=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"dark","vars":{"cyan":"#00d7ff","blue":"#5f87ff","green":"#b5bd68","red":"#cc6666","yellow":"#ffff00","text":"#d4d4d4","gray":"#808080","dimGray":"#666666","darkGray":"#505050","accent":"#8abeb7","selectedBg":"#3a3a4a","userMsgBg":"#343541","toolPendingBg":"#282832","toolSuccessBg":"#283228","toolErrorBg":"#3c2828","customMsgBg":"#2d2838"},"colors":{"accent":"accent","border":"blue","borderAccent":"cyan","borderMuted":"darkGray","success":"green","error":"red","warning":"yellow","muted":"gray","dim":"dimGray","text":"text","thinkingText":"gray","selectedBg":"selectedBg","scrollbarTrack":"darkGray","scrollbarThumb":"text","searchMatchBg":"selectedBg","searchMatchText":"text","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#9575cd","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"gray","mdHeading":"#f0c674","mdLink":"#81a2be","mdLinkUrl":"dimGray","mdCode":"accent","mdCodeBlock":"green","mdCodeBlockBorder":"gray","mdQuote":"gray","mdQuoteBorder":"gray","mdHr":"gray","mdListBullet":"accent","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"gray","syntaxComment":"#6A9955","syntaxKeyword":"#569CD6","syntaxFunction":"#DCDCAA","syntaxVariable":"#9CDCFE","syntaxString":"#CE9178","syntaxNumber":"#B5CEA8","syntaxType":"#4EC9B0","syntaxOperator":"#D4D4D4","syntaxPunctuation":"#D4D4D4","thinkingOff":"darkGray","thinkingMinimal":"#6e6e6e","thinkingLow":"#5f87af","thinkingMedium":"#81a2be","thinkingHigh":"#b294bb","thinkingXhigh":"#d183e8","thinkingMax":"#ff5fff","bashMode":"green"},"export":{"pageBg":"#18181e","cardBg":"#1e1e24","infoBg":"#3c3728"}}');function f(a){let b=a.replace("#",""),c=Number.parseInt(3===b.length?b.split("").map(a=>a+a).join(""):b,16);return{r:c>>16&255,g:c>>8&255,b:255&c}}class g{constructor(a,b,c="truecolor",d){for(const[b,e]of(this.fgAnsiMap=new Map,this.bgAnsiMap=new Map,this.mode=c,this.name=d?.name,Object.entries({...a,thinkingMax:a.thinkingMax??a.thinkingXhigh})))this.fgAnsiMap.set(b,function(a,b){if(""===a)return"\x1b[39m";if("number"==typeof a)return`\x1b[38;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[38;2;${b};${c};${d}m`}return"\x1b[38;5;7m"}throw Error(`Invalid color value: ${String(a)}`)}(e,c));for(const[a,d]of Object.entries(b))this.bgAnsiMap.set(a,function(a,b){if(""===a)return"\x1b[49m";if("number"==typeof a)return`\x1b[48;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[48;2;${b};${c};${d}m`}return"\x1b[48;5;0m"}throw Error(`Invalid color value: ${String(a)}`)}(d,c))}fg(a,b){let c=this.fgAnsiMap.get(a);if(!c)throw Error(`Unknown theme color: ${a}`);return`${c}${b}\x1b[39m`}bg(a,b){let c=this.bgAnsiMap.get(a);if(!c)throw Error(`Unknown theme background color: ${a}`);return`${c}${b}\x1b[49m`}bold(a){return`\x1b[1m${a}\x1b[22m`}italic(a){return`\x1b[3m${a}\x1b[23m`}underline(a){return`\x1b[4m${a}\x1b[24m`}inverse(a){return`\x1b[7m${a}\x1b[27m`}strikethrough(a){return`\x1b[9m${a}\x1b[29m`}getFgAnsi(a){let b=this.fgAnsiMap.get(a);if(!b)throw Error(`Unknown theme color: ${a}`);return b}getBgAnsi(a){let b=this.bgAnsiMap.get(a);if(!b)throw Error(`Unknown theme background color: ${a}`);return b}getColorMode(){return this.mode}getThinkingBorderColor(a){let b={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"}[a]??"thinkingOff";return a=>this.fg(b,a)}getBashModeBorderColor(){return a=>this.fg("bashMode",a)}}let h=100,i=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]),j=Symbol.for("@earendil-works/pi-coding-agent:theme"),k=Symbol.for("@mariozechner/pi-coding-agent:theme"),l="Extension renderers that rely on the SDK theme helpers will not draw their themed content (for example the built-in edit tool's diff): Pidance could not hand its theme to the shared pi theme slot.",m=/Theme not initialized/i,n=!1,o=null,p=new Set,q=[],r=null;function s(a){if(r=a,a)for(let b of q.splice(0))a(b)}function t(a,b){if(!p.has(a)){if(p.add(a),console.warn(`[pidance] ${b}`),!r)return void q.push(b);try{r(b)}catch(a){console.warn("[pidance] render bridge warning sink failed:",a)}}}function u(a){let b=a instanceof Error?a.message:String(a);m.test(b)&&t("sdk-theme-uninitialized",`${l} (${b})`)}let v=null;function w(a){v=a}function x(){if(null!==o)return o;if(!v)return null;try{return v(),o=!0,!0}catch(a){return o=!1,t("sdk-theme-verify",`${l} (self-check failed: ${a instanceof Error?a.message:String(a)})`),!1}}function y(){if(void 0!==d)return d;try{let a=function(a){let b={...a.colors,thinkingMax:a.colors.thinkingMax??a.colors.thinkingXhigh},c=a.vars??{},d={},e={};for(let[a,f]of Object.entries(b)){let b=function a(b,c,d=new Set){if("number"==typeof b||""===b||b.startsWith("#"))return b;if(d.has(b))throw Error(`Circular variable reference detected: ${b}`);if(!(b in c))throw Error(`Variable reference not found: ${b}`);return d.add(b),a(c[b],c,d)}(f,c);i.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e);d=a,function(a){if(!n){n=!0;try{let b=globalThis;b[j]=a,b[k]=a}catch(a){t("sdk-theme-install",`${l} (install failed: ${a instanceof Error?a.message:String(a)})`);return}}}(a)}catch{d=null}return d}function z(a,b=h){if(!a||"object"!=typeof a||"function"!=typeof a.render)return null;try{let c=a.render(b);if(!function(a){if(!Array.isArray(a)||0===a.length||!a.every(a=>"string"==typeof a)||a.length>500)return!1;let b=0;for(let c of a)if(c.length>4e3||(b+=c.length)>204800)return!1;return!0}(c))return null;return c}catch(a){return u(a),null}}function A(a,b,c,d,e,f=h){let g=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!g)return null;let i=y();if(!i)return null;try{let a=g(b,c,i,d);return a&&"object"==typeof a&&e?.(a),z(a,f)}catch(a){return u(a),null}}function B(a,b,c,d,e=h){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=y();if(!g)return null;try{let a=f(b,g,c);return a&&"object"==typeof a&&d?.(a),z(a,e)}catch(a){return u(a),null}}function C(a,b=h){return z(a,b)}function D(a,b=h){return C(a,b)}function E(a,b,c,d=h){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return z(e,d)}catch(a){return u(a),null}}function F(a,b,c,d=h){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return z(e,d)}catch(a){return u(a),null}}},89953:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,wE:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(60396);let h="Session is locked by another Pidance process (writable host ownership)",i="Timed out acquiring Pidance running-lease lock";function j(a){return(0,f.join)(a,"pidance-running-leases")}function k(a,b){let c=b.replace(/[^a-zA-Z0-9._-]+/g,"_").slice(0,180);return(0,f.join)(j(a),`${c}.json`)}function l(a){if(!Number.isFinite(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"EPERM"===a.code}}function m(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.sessionId||"number"!=typeof b.heartbeatAt)return null;return{pid:b.pid,sessionId:b.sessionId,heartbeatAt:b.heartbeatAt,startedAt:"number"==typeof b.startedAt?b.startedAt:b.heartbeatAt}}catch{return null}}function n(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.token)return null;return{pid:b.pid,token:b.token}}catch{return null}}function o(a,b){let c=j(a);(0,e.existsSync)(c)||(0,e.mkdirSync)(c,{recursive:!0,mode:448});let g=(0,f.join)(c,".lease-lock"),h=(0,d.randomBytes)(8).toString("hex"),k=Date.now()+3e3,m=!1;for(;!m;){let a=`${g}.${process.pid}.${h}.tmp`;try{(0,e.writeFileSync)(a,JSON.stringify({pid:process.pid,token:h}),{mode:384}),(0,e.linkSync)(a,g),m=!0}catch(b){if("EEXIST"!==b.code){try{(0,e.unlinkSync)(a)}catch{}throw b}}try{(0,e.unlinkSync)(a)}catch{}if(m)break;let b=n(g);if(b&&!l(b.pid)){try{n(g)?.token===b.token&&(0,e.unlinkSync)(g)}catch{}continue}if(!b)try{Date.now()-(0,e.statSync)(g).mtimeMs>1e4&&(0,e.unlinkSync)(g)}catch{}if(Date.now()>=k)throw Error(i);!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,5)}()}try{return b()}finally{try{n(g)?.token===h&&(0,e.unlinkSync)(g)}catch{}}}function p(a){return a instanceof Error&&a.message===i}function q(a,b){let c=`${a}.${process.pid}.tmp`;(0,e.writeFileSync)(c,`${JSON.stringify(b)}
|
|
102
|
+
`,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a){return(a instanceof Error?a.message:String(a)).includes("locked by another Pidance process")}function t(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;try{return o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;return!(f&&f.pid!==process.pid&&r(f))&&(q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c}),!0)})}catch(a){if(p(a))return!1;throw a}}function u(a,b=(0,g.$M)(),c=Date.now()){if(a)try{o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;f&&f.pid!==process.pid&&r(f)||q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c})})}catch(a){if(!p(a))throw a}}function v(a,b=(0,g.$M)()){if(a)try{o(b,()=>{let c=k(b,a),d=(0,e.existsSync)(c)?m(c):null;if(!d||d.pid===process.pid)try{(0,e.unlinkSync)(c)}catch{}})}catch(a){if(!p(a))throw a}}function w(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;let d=(0,e.existsSync)(k(b,a))?m(k(b,a)):null;return!!d&&d.pid!==process.pid&&r(d)}},91898:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Fx:()=>k});var e=c(29021),f=c(33873),g=c(60396),h=c(69835),i=c(68524),j=a([h]);function k(a={}){let b=a.agentDir??(0,g.$M)(),c=a.ttlMs??2592e6,d=a.now??Date.now(),j=(0,h.$t)(b),l=j.filter(a=>d-a.mtimeMs>c);if(0===l.length)return{scanned:j.length,candidates:0,deleted:0,bytes:0,complete:!0};let m=function(a,b=(0,g.$M)()){let c=function(a){let b=(0,i.m6)(a);if(!(0,e.existsSync)(b))return{};try{let a=JSON.parse((0,e.readFileSync)(b,"utf8"));return(0,i.UQ)(a)?a:null}catch{return null}}(b);if(null===c)return null;let d=function(a){if(!(0,e.existsSync)(a))return[];let b=[],c=a=>{let d=(()=>{try{return(0,e.readdirSync)(a,{withFileTypes:!0})}catch{return null}})();if(null===d)return!1;for(let e of d){let d=(0,f.join)(a,e.name);if(e.isDirectory()){if(!c(d))return!1;continue}e.isFile()&&e.name.endsWith(".jsonl")&&b.push(d)}return!0};return c(a)?b:null}((0,f.join)(b,"sessions"));if(null===d)return null;let h=new Set,j=a.map(a=>{var b;return{path:a,escaped:(b=a,JSON.stringify(b).slice(1,-1))}}),k=a=>{for(let b of j)!h.has(b.path)&&(a.includes(b.path)||a.includes(b.escaped))&&h.add(b.path)};for(let a of(k(JSON.stringify(c)),d)){let b;if(h.size===j.length)break;try{b=(0,e.readFileSync)(a,"utf8")}catch{return null}k(b)}return h}(l.map(a=>a.path),b);if(null===m)return{scanned:j.length,candidates:l.length,deleted:0,bytes:0,complete:!1};let n=0,o=0;for(let a of l)!m.has(a.path)&&(0,h.fm)(a.path,b)&&(n+=1,o+=a.size);return{scanned:j.length,candidates:l.length,deleted:n,bytes:o,complete:!0}}h=(j.then?(await j)():j)[0],d()}catch(a){d(a)}})},92395:(a,b,c)=>{c.d(b,{Ej:()=>q,FN:()=>j,J7:()=>s,Tj:()=>r,oK:()=>g,oT:()=>m,wq:()=>i,xH:()=>t});var d=c(89477),e=c(86697),f=c(60396);function g(a){return(0,e.join)((0,e.resolve)(a),".pi","settings.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a){if(!(0,d.existsSync)(a))return{};try{let b=JSON.parse((0,d.readFileSync)(a,"utf8"));return h(b)?{...b}:{}}catch{return{}}}function j(a,b){let c=(0,e.dirname)(a);(0,d.mkdirSync)(c,{recursive:!0});let f=`${a}.${process.pid}.${Date.now()}.tmp`,g=`${JSON.stringify(b,null,2)}
|
|
102
103
|
`;try{(0,d.writeFileSync)(f,g,{flag:"wx",mode:384}),(0,d.renameSync)(f,a)}catch(a){try{(0,d.unlinkSync)(f)}catch{}throw a}}function k(a){return"string"==typeof a&&a.length>0?a:void 0}function l(a,b){return"all"===a||"one-at-a-time"===a?a:b}class m{constructor(a={}){this.dirty=!1;const b=a.agentDir??(0,f.$M)();this.globalPath=(0,e.join)((0,e.resolve)(b),"settings.json"),this.global=i(this.globalPath)}static create(a,b){return new m({agentDir:b})}view(){return this.global}getDefaultProvider(){return k(this.view().defaultProvider)}getDefaultModel(){return k(this.view().defaultModel)}getDefaultThinkingLevel(){return k(this.view().defaultThinkingLevel)}getSteeringMode(){return l(this.view().steeringMode,"one-at-a-time")}getFollowUpMode(){return l(this.view().followUpMode,"one-at-a-time")}getCompactionSettings(){let a=h(this.view().compaction)?this.view().compaction:{};return{enabled:"boolean"!=typeof a.enabled||a.enabled,reserveTokens:"number"==typeof a.reserveTokens?a.reserveTokens:16384,keepRecentTokens:"number"==typeof a.keepRecentTokens?a.keepRecentTokens:2e4}}getRetrySettings(){let a=h(this.view().retry)?this.view().retry:{};return{enabled:"boolean"!=typeof a.enabled||a.enabled,maxRetries:"number"==typeof a.maxRetries?a.maxRetries:3,baseDelayMs:"number"==typeof a.baseDelayMs?a.baseDelayMs:2e3}}getPackages(){return this.global.packages}setDefaultProvider(a){this.global.defaultProvider=a,this.dirty=!0}setDefaultModel(a){this.global.defaultModel=a,this.dirty=!0}setDefaultModelAndProvider(a,b){this.global.defaultProvider=a,this.global.defaultModel=b,this.dirty=!0}setDefaultThinkingLevel(a){this.global.defaultThinkingLevel=a,this.dirty=!0}setSteeringMode(a){this.global.steeringMode=a,this.dirty=!0}setFollowUpMode(a){this.global.followUpMode=a,this.dirty=!0}setCompactionEnabled(a){let b=h(this.global.compaction)?{...this.global.compaction}:{};b.enabled=a,this.global.compaction=b,this.dirty=!0}setRetryEnabled(a){let b=h(this.global.retry)?{...this.global.retry}:{};b.enabled=a,this.global.retry=b,this.dirty=!0}setPackages(a){this.global.packages=a,this.dirty=!0}async flush(){this.dirty&&(j(this.globalPath,this.global),this.dirty=!1)}flushSync(){this.dirty&&(j(this.globalPath,this.global),this.dirty=!1)}}function n(a){return Array.isArray(a)?a:[]}function o(a){return"string"==typeof a?a:a.source}function p(a){return"string"!=typeof a&&Array.isArray(a.extensions)&&0===a.extensions.length&&Array.isArray(a.skills)&&0===a.skills.length&&Array.isArray(a.prompts)&&0===a.prompts.length&&Array.isArray(a.themes)&&0===a.themes.length}function q(a,b={}){return"global"===a?n(i(b.agentDir?(0,e.join)((0,e.resolve)(b.agentDir),"settings.json"):(0,f.pA)()).packages):b.cwd?n(i(g(b.cwd)).packages):[]}function r(a,b,c={}){if("global"===a){let a=c.agentDir?(0,e.join)((0,e.resolve)(c.agentDir),"settings.json"):(0,f.pA)(),d=i(a);d.packages=b,j(a,d);return}if(!c.cwd)throw Error("project packages 需要 cwd");let d=g(c.cwd),h=i(d);h.packages=b,j(d,h)}function s(a,b,c,d={}){let e=q(b,d),f=!1,g=e.map(b=>o(b)!==a?b:(f=!0,c)?{..."string"==typeof b?{source:b}:b,extensions:[],skills:[],prompts:[],themes:[]}:o(b));return!!f&&(r(b,g,d),!0)}function t(a){let b=new Map;for(let c of q("global",a))b.set(`global\0${o(c)}`,p(c));if(a.cwd)for(let c of q("project",a))b.set(`project\0${o(c)}`,p(c));return b}},93127:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nw:()=>h,Zq:()=>k,rW:()=>l,wr:()=>i,ye:()=>j});var e=c(33873),f=c(95237),g=a([f]);f=(g.then?(await g)():g)[0];class k extends Error{constructor(a){super(a),this.name="SessionExportError",this.code="bad-request"}}function h(a){return null===a||""===a?"html":"jsonl"===a?"jsonl":null}function i(a,b={}){let c=(0,f.kW)(a);return function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new k(`Invalid leafId: ${d}`);let e=void 0!==d?a.getBranch(d):a.getBranch(),g=(b.now??(()=>new Date))().toISOString(),h={type:"session",version:f.iR,id:a.getSessionId(),timestamp:g,cwd:a.getCwd()},i=[JSON.stringify(h)],j=null;for(let a of e){let b={...a,parentId:j};i.push(JSON.stringify(b)),j=a.id}return`${i.join("\n")}
|
|
103
|
-
`}(c,b)}function j(a){let b=(0,e.basename)(a,".jsonl");return`pi-session-${b}.jsonl`}let l="application/x-ndjson; charset=utf-8";d()}catch(a){d(a)}})},99014:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>p,Pt:()=>n,S1:()=>g,X_:()=>o,gC:()=>m,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return a.map(a=>a.text)}function n(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function o(a,b){return{text:[...m(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:p(a)}}function p(a){return a.flatMap(a=>a.media??[])}},99911:(a,b,c)=>{c.d(b,{Xm:()=>d});function d(a){let b=[];for(let d of a){if(d?.type!=="message")continue;let a=d.message;if(!a||"user"!==a.role)continue;let e="string"==typeof d.id&&d.id?d.id:null;if(e){var c;b.push({entryId:e,ordinal:b.length,text:"string"==typeof(c=a.content)?c:Array.isArray(c)?c.filter(a=>a?.type==="text"&&"string"==typeof a.text).map(a=>a.text).join("\n"):"",..."number"==typeof a.timestamp?{timestamp:a.timestamp}:{}})}}return b}}};
|
|
104
|
+
`}(c,b)}function j(a){let b=(0,e.basename)(a,".jsonl");return`pi-session-${b}.jsonl`}let l="application/x-ndjson; charset=utf-8";d()}catch(a){d(a)}})},95412:(a,b,c)=>{c.d(b,{Vz:()=>e});let d=Symbol.for("@agegr/pi-web/session-liveness/v1");function e(a){let b=function(){let a=globalThis[d];if(a)return a;let b={providers:new Map,warned:new Set};return globalThis[d]=b,b}(),c=new Set([a.sessionId,a.sessionFile].filter(a=>!!a));if(0===c.size)return!1;for(let[a,d]of b.providers)if(c.has(d.sessionId)||void 0!==d.sessionFile&&c.has(d.sessionFile))try{if(!0===d.isActive())return!0}catch(c){b.warned.has(a)||(b.warned.add(a),console.warn(`[pidance] session liveness provider 抛错,按不活跃处理: ${d.name}`,c))}return!1}},97017:(a,b,c)=>{function d(a,b){if(!b||a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1)if(a[c]!==b[c])return!1;return!0}function e(a,b){let c={};return a.callLines&&!d(a.callLines,b.callLines)&&(c.callLines=a.callLines),a.resultLines&&!d(a.resultLines,b.resultLines)&&(c.resultLines=a.resultLines),c.callLines||c.resultLines?c:null}function f(a){let b=a.now??(()=>Date.now()),c=a.setTimer??((a,b)=>setTimeout(a,b)),d=a.clearTimer??(a=>{clearTimeout(a)}),e=new Map,f=!1,g=a=>{let b=e.get(a);return b||(b={rendering:!1,pending:!1,timer:null,lastRunAt:void 0},e.set(a,b)),b},h=(c,d)=>{if(d.rendering){d.pending=!0;return}d.rendering=!0,d.lastRunAt=b();try{let b=a.recompute(c);null!=b&&a.emit(c,b)}catch(b){a.onError?.(b)}finally{d.rendering=!1,d.pending&&(d.pending=!1,i(c))}},i=d=>{if(f)return;let e=g(d);if(e.rendering){e.pending=!0;return}let i=void 0===e.lastRunAt?1/0:b()-e.lastRunAt;if(i<a.minIntervalMs){if(null!==e.timer)return;e.timer=c(()=>{e.timer=null,h(d,e)},a.minIntervalMs-i);return}h(d,e)},j=a=>{if(f)return;let b=g(a);null!==b.timer&&(d(b.timer),b.timer=null),h(a,b)};return{request:i,flush:j,flushAll(a){for(let b of a)j(b)},isRendering:a=>e.get(a)?.rendering===!0,dispose(){for(let a of(f=!0,e.values()))null!==a.timer&&(d(a.timer),a.timer=null),a.pending=!1;e.clear()}}}c.d(b,{VQ:()=>e,w7:()=>f})},99014:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>p,Pt:()=>n,S1:()=>g,X_:()=>o,gC:()=>m,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return a.map(a=>a.text)}function n(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function o(a,b){return{text:[...m(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:p(a)}}function p(a){return a.flatMap(a=>a.media??[])}},99911:(a,b,c)=>{c.d(b,{Xm:()=>d});function d(a){let b=[];for(let d of a){if(d?.type!=="message")continue;let a=d.message;if(!a||"user"!==a.role)continue;let e="string"==typeof d.id&&d.id?d.id:null;if(e){var c;b.push({entryId:e,ordinal:b.length,text:"string"==typeof(c=a.content)?c:Array.isArray(c)?c.filter(a=>a?.type==="text"&&"string"==typeof a.text).map(a=>a.text).join("\n"):"",..."number"==typeof a.timestamp?{timestamp:a.timestamp}:{}})}}return b}}};
|