@henlii/pidance 0.2.28 → 0.2.29
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 +10 -9
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.json +1 -1
- package/.next/routes-manifest.json +8 -0
- package/.next/server/app/_global-error/page.js +3 -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.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js +2 -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.rsc +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -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 +1 -1
- package/.next/server/app/api/agent/running/route.js +1 -1
- package/.next/server/app/api/agent/submissions/[submissionId]/route.js +1 -0
- package/.next/server/app/api/agent/submissions/[submissionId]/route_client-reference-manifest.js +1 -0
- 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/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 +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/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]/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 +1 -1
- 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/api/worktrees/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.rsc +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +3 -3
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/page.js +15 -15
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +10 -9
- package/.next/server/chunks/188.js +1 -1
- package/.next/server/chunks/2356.js +2 -0
- package/.next/server/chunks/3379.js +1 -1
- package/.next/server/chunks/5274.js +1 -1
- package/.next/server/chunks/5304.js +2 -2
- package/.next/server/chunks/5582.js +1 -1
- package/.next/server/chunks/7594.js +3 -3
- package/.next/server/instrumentation.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/{Ni2HugOTDE44QzNWaiTkR → LtiVeS4MNenlNgRDmSFem}/_buildManifest.js +1 -1
- package/.next/static/chunks/9780-160be85d8ccc52df.js +1 -0
- package/.next/static/chunks/app/_global-error/page-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/about/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/events/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/[id]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/new/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/running/events/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/running/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/agent-settings/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/attachments/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/all-providers/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/login/[provider]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/providers/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-session/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/auth/ui-sessions/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/cwd/browse/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/cwd/validate/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/default-cwd/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/file-index/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/files/[...path]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/git/diff/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/git/status/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/home/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/message-media/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/models/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/models-config/raw/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/models-config/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/models-config/test/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/plugins/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/plugins/search/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/plugins/updates/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/preferences/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/project-assets/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/prompts/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/pty/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/archive/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/context/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/export/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/info/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/outline/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/state/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/sessions/search/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/settings/raw/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/settings/remote/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/skills/check/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/skills/install/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/skills/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/skills/search/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/skills/update/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/subagent-runs/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/update/apply/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/update/check/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/api/worktrees/route-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/app/page-6337d5a7b240fecc.js +25 -0
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-3154b10ff0f29211.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-3154b10ff0f29211.js +1 -0
- package/.next/static/css/4e6a21bd31d3e021.css +1 -0
- package/README.en.md +19 -15
- package/README.md +17 -13
- package/README.zh-CN.md +11 -204
- package/package.json +2 -2
- package/.next/static/chunks/9780-4b76db8fbfb345c2.js +0 -1
- package/.next/static/chunks/app/_global-error/page-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/about/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/bash-output/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/events/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/[id]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/new/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/running/events/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent/running/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/agent-settings/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/attachments/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/all-providers/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/api-key/[provider]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/login/[provider]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/logout/[provider]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/providers/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-session/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/auth/ui-sessions/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/cwd/browse/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/cwd/validate/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/default-cwd/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/file-index/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/files/[...path]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/git/diff/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/git/status/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/home/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/message-media/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/models/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/models-config/raw/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/models-config/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/models-config/test/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/plugins/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/plugins/search/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/plugins/updates/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/preferences/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/project-assets/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/prompts/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/pty/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/archive/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/context/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/export/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/info/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/outline/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/state/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/sessions/search/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/settings/raw/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/settings/remote/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/skills/check/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/skills/install/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/skills/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/skills/search/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/skills/update/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/subagent-runs/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/update/apply/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/update/check/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/api/worktrees/route-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/app/page-354e6fd7f7df840b.js +0 -25
- package/.next/static/chunks/next/dist/client/components/builtin/app-error-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/forbidden-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/not-found-005f7c16c8d63642.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-005f7c16c8d63642.js +0 -1
- package/.next/static/css/1c6fd1229e5153db.css +0 -1
- /package/.next/static/{Ni2HugOTDE44QzNWaiTkR → LtiVeS4MNenlNgRDmSFem}/_ssgManifest.js +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
exports.id=5274,exports.ids=[5274],exports.modules={10433:(a,b,c)=>{"use strict";c.d(b,{H7:()=>g,cS:()=>h});var d=c(89477),e=c(86697);let f="win32"===process.platform?"npm.cmd":"npm";function g(a=process.env,b=process.execPath){let c=a.npm_execpath?.trim();if(c&&(0,d.existsSync)(c))return c;let h=(0,e.join)((0,e.dirname)(b),f);return(0,d.existsSync)(h)?h:f}function h(a=process.env,b=g(a),c=process.execPath){let d=(0,e.dirname)(b===f?c:b);return{...a,PATH:`${d}${e.delimiter}${a.PATH??""}`}}},31974:(a,b,c)=>{"use strict";c.d(b,{ex:()=>z,i7:()=>A});var d=c(95398),e=c(89477),f=c(86697),g=c(37418),h=c(10433);let i=(0,g.promisify)(d.execFile),j="@henlii/pidance",k="https://registry.npmjs.org/",l="pidance.service";function m(a,b){return 0===b||"active"===a.trim()}function n(a){if(a.restartOk||a.laterActive)return{restarted:!0};let b=a.restartError?.trim();return{restarted:!1,message:b?`重启 ${l} 失败:${b}`:`重启 ${l} 失败`}}function o(a){if(a&&"object"==typeof a&&"stdout"in a){let b=a.stdout;if("string"==typeof b)return b;if(Buffer.isBuffer(b))return b.toString("utf8")}return""}function p(a){if(a&&"object"==typeof a&&"code"in a){let b=a.code;if("number"==typeof b&&Number.isFinite(b))return b}return null}function q(a,b){return b?["--user",a,l]:[a,l]}async function r(a,b){if("0"===b.PIDANCE_SYSTEMCTL_USER)return!1;if("1"===b.PIDANCE_SYSTEMCTL_USER)return!0;if(!b.XDG_RUNTIME_DIR&&!b.DBUS_SESSION_BUS_ADDRESS)return!1;try{let c=await a("systemctl",q("is-active",!0),{timeout:1e4,env:b});return m(String(c.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function s(a,b,c){try{let d=await a("systemctl",q("is-active",c),{timeout:1e4,env:b});return m(String(d.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function t(a){let b=a.execFileImpl??i,c=a.env??process.env,d=a.sleepImpl??(a=>new Promise(b=>{setTimeout(b,a)})),e=a.now??Date.now,f=await r(b,c);try{return await b("systemctl",q("restart",f),{timeout:21e4,env:c}),n({restartOk:!0,laterActive:!1})}catch(h){let a=h instanceof Error?h.message:String(h),g=e();if(await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});for(;e()-g<6e4;)if(await d(1500),await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});return n({restartOk:!1,restartError:a,laterActive:!1})}}function u(a=process.env){let b=(a.PIDANCE_NPM_REGISTRY||a.npm_config_registry||k).trim();return b?b.endsWith("/")?b:`${b}/`:k}function v(a,b){let c=w(a),d=w(b);if(!c||!d)return 0;for(let a=0;a<3;a++){if(c.core[a]>d.core[a])return 1;if(c.core[a]<d.core[a])return -1}return null===c.pre&&null===d.pre?0:null===c.pre?1:null===d.pre||c.pre<d.pre?-1:+(c.pre>d.pre)}function w(a){let b=a.trim().replace(/^v/i,""),c=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(b);return c?{core:[Number(c[1]),Number(c[2]),Number(c[3])],pre:c[4]??null}:null}async function x(a=u(),b=globalThis.fetch.bind(globalThis)){let c=new URL("@henlii%2Fpidance/latest",a.endsWith("/")?a:`${a}/`).toString();try{let a=await b(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(!a.ok)return null;let d=await a.json();return"string"==typeof d.version&&d.version.trim()?d.version.trim():null}catch{return null}}async function y(a=u(),b=Date.now(),c=globalThis.fetch.bind(globalThis),d=!1){let e=globalThis.__piPidanceLatestCache;if(!d&&e&&b-e.ts<18e5&&e.latest)return e.latest;let f=await x(a,c);return f&&(globalThis.__piPidanceLatestCache={latest:f,ts:b}),f}async function z(a){let b,c=a?.cwd??process.cwd(),d=a?.env??process.env,g=u(d),h=function(a=process.cwd()){for(let b of[(0,f.join)(a,"package.json"),(0,f.join)(a,"node_modules","@henlii","pidance","package.json")])try{if(!(0,e.existsSync)(b))continue;let a=JSON.parse((0,e.readFileSync)(b,"utf8"));if(a.name===j&&"string"==typeof a.version&&a.version.trim())return a.version.trim();let c=a.dependencies?.[j];if("string"==typeof c&&c.trim()&&!c.startsWith("file:"))return c.trim().replace(/^[\^~>=<\s]+/,"")}catch{}let b="0.2.
|
|
1
|
+
exports.id=5274,exports.ids=[5274],exports.modules={10433:(a,b,c)=>{"use strict";c.d(b,{H7:()=>g,cS:()=>h});var d=c(89477),e=c(86697);let f="win32"===process.platform?"npm.cmd":"npm";function g(a=process.env,b=process.execPath){let c=a.npm_execpath?.trim();if(c&&(0,d.existsSync)(c))return c;let h=(0,e.join)((0,e.dirname)(b),f);return(0,d.existsSync)(h)?h:f}function h(a=process.env,b=g(a),c=process.execPath){let d=(0,e.dirname)(b===f?c:b);return{...a,PATH:`${d}${e.delimiter}${a.PATH??""}`}}},31974:(a,b,c)=>{"use strict";c.d(b,{ex:()=>z,i7:()=>A});var d=c(95398),e=c(89477),f=c(86697),g=c(37418),h=c(10433);let i=(0,g.promisify)(d.execFile),j="@henlii/pidance",k="https://registry.npmjs.org/",l="pidance.service";function m(a,b){return 0===b||"active"===a.trim()}function n(a){if(a.restartOk||a.laterActive)return{restarted:!0};let b=a.restartError?.trim();return{restarted:!1,message:b?`重启 ${l} 失败:${b}`:`重启 ${l} 失败`}}function o(a){if(a&&"object"==typeof a&&"stdout"in a){let b=a.stdout;if("string"==typeof b)return b;if(Buffer.isBuffer(b))return b.toString("utf8")}return""}function p(a){if(a&&"object"==typeof a&&"code"in a){let b=a.code;if("number"==typeof b&&Number.isFinite(b))return b}return null}function q(a,b){return b?["--user",a,l]:[a,l]}async function r(a,b){if("0"===b.PIDANCE_SYSTEMCTL_USER)return!1;if("1"===b.PIDANCE_SYSTEMCTL_USER)return!0;if(!b.XDG_RUNTIME_DIR&&!b.DBUS_SESSION_BUS_ADDRESS)return!1;try{let c=await a("systemctl",q("is-active",!0),{timeout:1e4,env:b});return m(String(c.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function s(a,b,c){try{let d=await a("systemctl",q("is-active",c),{timeout:1e4,env:b});return m(String(d.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function t(a){let b=a.execFileImpl??i,c=a.env??process.env,d=a.sleepImpl??(a=>new Promise(b=>{setTimeout(b,a)})),e=a.now??Date.now,f=await r(b,c);try{return await b("systemctl",q("restart",f),{timeout:21e4,env:c}),n({restartOk:!0,laterActive:!1})}catch(h){let a=h instanceof Error?h.message:String(h),g=e();if(await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});for(;e()-g<6e4;)if(await d(1500),await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});return n({restartOk:!1,restartError:a,laterActive:!1})}}function u(a=process.env){let b=(a.PIDANCE_NPM_REGISTRY||a.npm_config_registry||k).trim();return b?b.endsWith("/")?b:`${b}/`:k}function v(a,b){let c=w(a),d=w(b);if(!c||!d)return 0;for(let a=0;a<3;a++){if(c.core[a]>d.core[a])return 1;if(c.core[a]<d.core[a])return -1}return null===c.pre&&null===d.pre?0:null===c.pre?1:null===d.pre||c.pre<d.pre?-1:+(c.pre>d.pre)}function w(a){let b=a.trim().replace(/^v/i,""),c=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(b);return c?{core:[Number(c[1]),Number(c[2]),Number(c[3])],pre:c[4]??null}:null}async function x(a=u(),b=globalThis.fetch.bind(globalThis)){let c=new URL("@henlii%2Fpidance/latest",a.endsWith("/")?a:`${a}/`).toString();try{let a=await b(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(!a.ok)return null;let d=await a.json();return"string"==typeof d.version&&d.version.trim()?d.version.trim():null}catch{return null}}async function y(a=u(),b=Date.now(),c=globalThis.fetch.bind(globalThis),d=!1){let e=globalThis.__piPidanceLatestCache;if(!d&&e&&b-e.ts<18e5&&e.latest)return e.latest;let f=await x(a,c);return f&&(globalThis.__piPidanceLatestCache={latest:f,ts:b}),f}async function z(a){let b,c=a?.cwd??process.cwd(),d=a?.env??process.env,g=u(d),h=function(a=process.cwd()){for(let b of[(0,f.join)(a,"package.json"),(0,f.join)(a,"node_modules","@henlii","pidance","package.json")])try{if(!(0,e.existsSync)(b))continue;let a=JSON.parse((0,e.readFileSync)(b,"utf8"));if(a.name===j&&"string"==typeof a.version&&a.version.trim())return a.version.trim();let c=a.dependencies?.[j];if("string"==typeof c&&c.trim()&&!c.startsWith("file:"))return c.trim().replace(/^[\^~>=<\s]+/,"")}catch{}let b="0.2.29".trim();return b&&"unknown"!==b?b:"0.0.0"}(c),{mode:i,installRoot:k}=function(a=process.cwd(),b=process.env){let c=function(a,b=process.env){let c=b.PIDANCE_INSTALL_ROOT?.trim();if(c)try{return(0,f.resolve)(c)}catch{return null}let d=a;try{d=(0,e.realpathSync)(a)}catch{d=(0,f.resolve)(a)}let g=d.replace(/\\/g,"/"),h=/^(.*)\/releases\/[^/]+\/node_modules\/@henlii\/pidance$/.exec(g);if(h)return(0,f.resolve)(h[1]);let i=/^(.*)\/releases\/[^/]+$/.exec(g);return i?(0,f.resolve)(i[1]):null}(a,b);if(c)return{mode:"formal-install",installRoot:c};try{let b=(0,f.join)(a,"package.json");if((0,e.existsSync)(b)&&JSON.parse((0,e.readFileSync)(b,"utf8")).name===j)return{mode:"workspace",installRoot:null}}catch{}return{mode:"unknown",installRoot:null}}(c,d),l=await y(g,a?.now,a?.fetchImpl,a?.forceRefresh===!0),m=null!=l&&v(l,h)>0,n=function(a=process.env){return"0"!==a.PIDANCE_ALLOW_SELF_UPGRADE}(d),o=n&&"formal-install"===i&&null!=k;return b=l?m?o?`可升级到 ${l}`:"workspace"===i?"当前为工作区/测试部署,仅提示有新版本;请在正式安装位(31415)一键升级":n?"未检测到正式安装目录,无法一键升级":"已禁用自升级(PIDANCE_ALLOW_SELF_UPGRADE=0)":"已是最新版本":"无法从 npm registry 获取最新版本",{currentVersion:h,latestVersion:l,updateAvailable:m,upgradeSupported:o,upgradeMode:i,installRoot:k,packageName:j,registry:g,reason:b,checkedAt:new Date(a?.now??Date.now()).toISOString()}}async function A(a){let b=a?.cwd??process.cwd(),c=a?.env??process.env,d=a?.execFileImpl??i,g=(b,c,d)=>{try{a?.onProgress?.({phase:b,percent:c,message:d})}catch{}};g("preparing",5,"准备升级…");let k=await z({cwd:b,env:c,fetchImpl:a?.fetchImpl});if(!k.upgradeSupported||!k.installRoot)return g("error",100,k.reason),{ok:!1,status:"not_supported",currentVersion:k.currentVersion,targetVersion:k.latestVersion,message:k.reason};let m=(a?.targetVersion?.trim()||k.latestVersion||"").trim();if(!m)return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:null,message:"无目标版本"};if(0>=v(m,k.currentVersion)&&!a?.targetVersion)return g("done",100,"已是最新版本"),{ok:!0,status:"already_latest",currentVersion:k.currentVersion,targetVersion:m,message:"已是最新版本"};if(!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(m))return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:m,message:"非法版本号"};let n=k.installRoot,o=(0,f.join)(n,"releases",m),p=k.registry;try{g("preparing",12,`创建发布目录 ${m}…`),(0,e.mkdirSync)(o,{recursive:!0});let b={name:`pidance-${m}`,version:"1.0.0",private:!0,dependencies:{[j]:m}};(0,e.writeFileSync)((0,f.join)(o,"package.json"),`${JSON.stringify(b,null,2)}
|
|
2
2
|
`,"utf8"),g("downloading",20,"正在从 npm 下载包…");let i=(0,h.H7)(c);await d(i,["install","--omit=dev",`--registry=${p}`,"--no-fund","--no-audit"],{cwd:o,env:{...(0,h.cS)(c,i),npm_config_registry:p},timeout:6e5,maxBuffer:8388608}),g("installing",82,"校验安装结果…");let q=(0,f.join)(o,"node_modules","@henlii","pidance","package.json");if(!(0,e.existsSync)(q))throw Error("安装后未找到 @henlii/pidance 包");let r=JSON.parse((0,e.readFileSync)(q,"utf8"));if(r.version!==m)throw Error(`安装版本不符:期望 ${m},实际 ${r.version??"?"}`);g("linking",88,"切换 current 符号链接…");let s=(0,f.join)(n,"current"),u=(0,f.join)(n,`.current-tmp-${process.pid}`);try{(0,e.existsSync)(u)&&(0,e.rmSync)(u,{force:!0,recursive:!0})}catch{}(0,e.symlinkSync)(o,u),(0,e.renameSync)(u,s);try{!function(a,b){let c=(0,f.join)(a,"releases");if(!(0,e.existsSync)(c))return;let d=new Set(b.map(a=>a.trim()).filter(Boolean));try{let b=(0,e.realpathSync)((0,f.join)(a,"current")),c=/\/releases\/([^/]+)$/.exec(b.replace(/\\/g,"/"));c&&d.add(c[1])}catch{}let g=c;try{g=(0,e.realpathSync)(c)}catch{return[]}let h=[];for(let a of(0,e.readdirSync)(c,{withFileTypes:!0})){let b;if(!a.isDirectory()||a.isSymbolicLink()||"."===a.name||".."===a.name||a.name.includes("/")||a.name.includes("\\")||d.has(a.name))continue;let i=(0,f.join)(c,a.name);try{b=(0,e.realpathSync)(i)}catch{continue}let j=g.endsWith("/")?g:`${g}/`;(b===g||b.startsWith(j))&&((0,e.rmSync)(i,{recursive:!0,force:!0}),h.push(a.name))}}(n,[m,k.currentVersion])}catch{}let v=!1;if(a?.restartService!==!1&&"1"!==c.PIDANCE_SKIP_SERVICE_RESTART){g("restarting",94,"正在重启服务…");let a=await t({execFileImpl:d,env:c});if(v=a.restarted,!a.restarted){let b={ok:!0,status:"upgraded",currentVersion:k.currentVersion,targetVersion:m,message:`已切换到 ${m},但${a.message??`重启 ${l} 失败`}`,restarted:!1};return g("done",100,b.message),b}}let w={ok:!0,status:"upgraded",currentVersion:k.currentVersion,targetVersion:m,message:v?`已升级到 ${m} 并重启服务`:`已升级到 ${m}(未重启服务)`,restarted:v};return g("done",100,w.message),w}catch(b){let a=b instanceof Error?b.message:String(b);return g("error",100,`升级失败:${a}`),{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:m,message:`升级失败:${a}`}}}},78335:()=>{},96487:()=>{}};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";exports.id=5304,exports.ids=[5304],exports.modules={2078:(a,b,c)=>{let d;c.d(b,{If:()=>o,Jz:()=>l,O:()=>q,iw:()=>m});var e=c(4984),f=c(29021),g=c(79748),h=c(33873),i=c(92783);function j(){return(0,h.join)((0,i.$M)(),"pidance-session-cache.json")}async function k(a){try{let b=await (0,g.stat)(a);return{path:a,mtimeMs:b.mtimeMs,size:b.size}}catch{return null}}async function l(a=(0,h.join)((0,i.$M)(),"sessions")){let b=[];try{b=(await (0,g.readdir)(a,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(b=>(0,h.join)(a,b.name))}catch{return[]}let c=[],d=[];for(let a of b)d.push((async()=>{try{for(let b of(await (0,g.readdir)(a)))b.endsWith(".jsonl")&&c.push((0,h.join)(a,b))}catch{}})());return await Promise.all(d),(await Promise.all(c.map(a=>k(a)))).filter(a=>null!==a)}function m(a=j()){try{let b=(0,f.readFileSync)(a,"utf8"),c=JSON.parse(b);if(!c||2!==c.version||!c.sessions||"object"!=typeof c.sessions)return null;return{version:2,sessions:c.sessions,discovery:c.discovery&&"object"==typeof c.discovery?c.discovery:{}}}catch{return null}}let n=!1;function o(a,b,c=j()){n=!0,d||(d=setTimeout(()=>{if(d=void 0,!n)return;n=!1;let e={version:2,sessions:Object.fromEntries(a),discovery:Object.fromEntries(b)},g=`${c}.tmp`;try{(0,f.writeFileSync)(g,JSON.stringify(e),"utf8"),(0,f.renameSync)(g,c)}catch{try{(0,f.existsSync)(g)&&(0,f.renameSync)(g,c)}catch{}}},1500))}function p(a){return"object"==typeof a&&null!==a&&"string"==typeof a.role&&"content"in a}async function q(a,b){try{let c,d,g=(0,e.createInterface)({input:(0,f.createReadStream)(a,{encoding:"utf8"}),crlfDelay:1/0}),h=null,i=0,j="";for await(let a of g){let b;if(!a.trim())continue;try{b=JSON.parse(a)}catch{continue}if(!h){if("session"!==b.type)return null;h=b;continue}if("session_info"===b.type){let a=b.name;"string"==typeof a&&a.trim()&&(c=a.trim());continue}if("message"!==b.type)continue;i++;let e=function(a){let b=a.message;if(!p(b)||"user"!==b.role)return;let c=b.timestamp;if("number"==typeof c)return c;let d=new Date(a.timestamp??"").getTime();return Number.isNaN(d)?void 0:d}(b);"number"==typeof e&&(d=Math.max(d??0,e));let f=b.message;if(!p(f)||"user"!==f.role&&"assistant"!==f.role)continue;let g=function(a){let b=a.content;return"string"==typeof b?b:Array.isArray(b)?b.filter(a=>!!(a&&"text"===a.type&&"string"==typeof a.text)).map(a=>a.text).join(" "):""}(f);g&&(j||"user"!==f.role||(j=g))}if(!h)return null;let k="string"==typeof h.timestamp?new Date(h.timestamp).getTime():NaN,l=new Date("number"==typeof d&&d>0?d:Number.isNaN(k)?b.mtimeMs:k);return{id:"string"==typeof h.id?h.id:"",cwd:"string"==typeof h.cwd?h.cwd:"",name:c,created:h.timestamp,modified:l.toISOString(),messageCount:i,firstMessage:j||"(no messages)",parentSessionPath:"string"==typeof h.parentSession?h.parentSession:void 0}}catch{return null}}},10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>w});var e=c(75430),f=c(92783),g=c(84127),h=c(82356),i=c(68642),j=c(99595),k=c(89358),l=c(31360),m=c(75377),n=c(63480),o=c(31119),p=c(11955),q=c(35948),r=c(58732),s=c(19228),t=c(36315),u=a([e,l,r,s]);function v(a){return"string"==typeof a&&a?a:void 0}[e,l,r,s]=u.then?(await u)():u;class x{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._scheduledRecheck=!1,this.onDestroyCallback=null,this._alive=!0,this.promptRunning=!1,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],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.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,t.Lm)(),this.toolRenderStates=new Map,this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,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}onDestroy(a){this.onDestroyCallback=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?.()}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp||this.listeners.length>0)return;if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if((this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp)&&!(this.listeners.length>0)){if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();this.destroyAsync()}},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,g.rV)(this.agentDir);return!0===(0,g.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,g.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(a){console.error("[pidance] failed to persist follow-up hold:",a)}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,g.rV)(this.agentDir),b=(0,g.ql)(a,`sessionQueue.${this.realSessionId}`),c=a=>Array.isArray(a)?a.filter(a=>"string"==typeof a&&a.trim().length>0):[];if(Array.isArray(b)){this.followUpQueue=c(b);return}let d=b&&"object"==typeof b?b:null;this.followUpQueue=c(d?.items),"number"==typeof d?.revision&&(this.followUpQueueRevision=d.revision)}updateFollowUpQueue(a){this.followUpQueue=a,this.followUpQueueRevision+=1}persistFollowUpQueue(){try{(0,g.xP)(`sessionQueue.${this.realSessionId}`,{items:this.followUpQueue,revision:this.followUpQueueRevision},this.agentDir)}catch(a){console.error("[pidance] failed to persist follow-up queue:",a)}}scheduleFollowUpFlush(){!this._alive||!this.runtime||this.flushingFollowUp||0===this.followUpQueue.length||this.isFollowUpHeld()||this.isSettled()&&(this.flushingFollowUp=!0,this.followUpFlushAsOne=!0===(0,g.rV)(this.agentDir).queueFlushAsOne,this.followUpFlushOriginal=[...this.followUpQueue],this.followUpFlushBatch=this.followUpFlushAsOne?[this.followUpFlushOriginal.join("\n\n")]:[...this.followUpFlushOriginal],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.sendNextFollowUp())}async sendNextFollowUp(){if(!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushCursor<this.followUpFlushBatch.length&&this.sendNextFollowUp()},80);this.followUpFlushConfirmed=!1;try{await this.send({type:"prompt",message:a}),this.removeDeliveredFollowUp()&&this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:[...this.followUpQueue]})}catch(b){let a=b instanceof Error?b.message:String(b);this.emit({type:"follow_up_flush_error",errorMessage:a}),this.abortFollowUpFlush()}}removeDeliveredFollowUp(){if(this.followUpFlushAsOne){let a=new Set(this.followUpFlushOriginal),b=this.followUpQueue.filter(b=>!a.has(b));return b.length!==this.followUpQueue.length&&(this.updateFollowUpQueue(b),this.persistFollowUpQueue(),!0)}let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return!1;let b=this.followUpQueue.indexOf(a);if(b<0)return!1;let c=[...this.followUpQueue];return c.splice(b,1),this.updateFollowUpQueue(c),this.persistFollowUpQueue(),!0}confirmFollowUpFlush(){if(!this.flushingFollowUp||this.followUpFlushConfirmed)return;let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return;this.followUpFlushConfirmed=!0,this.removeDeliveredFollowUp();let b=[...this.followUpQueue];(this.persistFollowUpQueue(),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:b}),this.followUpFlushAsOne)?this.finishFollowUpFlush():(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushBatch.length?this.finishFollowUpFlush():this.sendNextFollowUp())}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer(),this.followUpQueue.length>0&&!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,m.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=v(a.method);if("setStatus"===b){let b=v(a.statusKey)??v(a.key)??"default",c=v(a.statusText)??v(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=v(a.widgetKey)??v(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,l.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(q.uG,a);this.emit({type:"message_end",entryId:e,message:(0,q.FH)(a,Date.now())})}(0,l.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&&x.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=x.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);switch(a.type){case"agent_start":this.promptRunning=!0,(0,i.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,i.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,k.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done"});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.followUpFlushConfirmed?this.sendNextFollowUp():this.confirmFollowUpFlush():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let c="agent_settled"===a.type&&!this.flushingFollowUp&&(0===this.followUpQueue.length||this.isFollowUpHeld());this.resetIdleTimer(),c&&this.destroyAsync();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"){this.confirmFollowUpFlush();let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,l.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 d=a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(d={...d,turnMetrics:a})}let e="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||e){let a=this.contextUsageSnapshot();a&&(d={...d,contextUsage:a})}this.emit(this.withRenderedToolLines(d))}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,t.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,t.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,t.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,t.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<x.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,l.G1)(a):(0,l.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,s._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:s.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:s.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:s.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,o.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.followUpQueue.length>0&&!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()??[])};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:[...this.followUpQueue],followUpRevision:this.followUpQueueRevision};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,j.qF)(a):(0,j.l$)(a),c=this.session.sessionManager.appendCustomEntry(j.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,r.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(q.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,q.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a){if(!this.runtime)throw Error("SDK session is not alive");let b=a.type;"get_state"!==b&&"ensure_session"!==b&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let c=this.session;try{switch(b){case"prompt":{let b=(0,p.JT)(a),d=this.promptReceipts.get(b.submissionId);if(d)return d;let e=b.submissionId,f=this.promptInFlight.get(e);if(f)return f;let g=(0,r.Nu)(b.binaryBlocks,this.agentDir);if(this.bashRunning)throw Error("Cannot send a prompt while a shell command is running");if(c.isCompacting){if(b.images?.length||g.length>0)throw Error("Media attachments cannot be queued while compaction is in progress");let a={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.updateFollowUpQueue([...this.followUpQueue,b.message]),this.promptReceipts.set(b.submissionId,a),this.persistFollowUpQueue(),this.options.onSessionListInvalidate?.(),a}if(!(0,h.kP)(this.realSessionId))throw Error(h.GT);this.promptRunning=!0,this.lastStopReason=null,(0,i.NK)(this.realSessionId,Date.now()),this.notifyRunning();let j=(async()=>{try{await new Promise((d,f)=>{let h=!1,j=()=>{c.isStreaming||c.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,i.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done"}),this.resetIdleTimer())};c.prompt(b.message,{images:b.images??a.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(h=!0,g.length>0&&this.pendingBinaryBatches.push({submissionId:e,blocks:g}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),d())}}).then(()=>{if(!h){h=!0;try{(0,l.kb)(c.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),d()}j()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),j(),h||(h=!0,f(a))})});let d={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(e,d),d}catch(d){this.removePendingBinaryBatch(e),this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,i.PI)(this.realSessionId),this.notifyRunning();let a=d instanceof Error?d.message:String(d);this.emit({type:"prompt_error",errorMessage:a}),this.emit({type:"prompt_done"});let c={submissionId:b.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(e,c),d}finally{this.promptInFlight.delete(e)}})();return this.promptInFlight.set(e,j),j}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await c.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),d=String(a.modelId??""),e=(0,n.E)(c.modelRuntime,b,d);if(!e)try{e=(await c.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===d)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${d}`);return await c.setModel((0,o.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return c.model&&(0,o.yu)(c.model),c.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await c.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=String(a.message??"");if(!this.isRunning()&&!this.flushingFollowUp)return this.send({type:"prompt",message:b,images:a.images,streamingBehavior:"steer"});return await c.steer(b,a.images),null}case"set_follow_up_queue":{let b=Array.isArray(a.items)?a.items.filter(a=>"string"==typeof a&&a.trim().length>0):[];return this.flushingFollowUp&&this.abortFollowUpFlush(),this.updateFollowUpQueue(b),this.persistFollowUpQueue(),this.isSettled()&&b.length>0&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{ok:!0,queued:this.followUpQueue.length}}case"follow_up":return await c.followUp(String(a.message??""),a.images),null;case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return c.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return c.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return c.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return c.clearQueue();case"get_tools":{let a=c.getAllTools(),b=new Set(c.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 c.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of c.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of c.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=c.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 c.getSessionStats();case"bash":if(c.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 c.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return c.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return c.abortCompaction(),null;case"extension_ui_response":{let b=v(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=v(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=v(a.targetId);if(!b)throw Error("targetId is required");let d=await c.navigateTree(b,{summarize:a.summarize,customInstructions:v(a.customInstructions)});if(!d.cancelled&&this.realSessionFile){c.sessionManager.getLeafId();let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries(),d=b.at(-1)?.id;a&&d&&a!==d?(0,k.R3)(this.realSessionFile,a):this.realSessionFile&&(0,k.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:d.cancelled}}case"select_leaf_exact":{let b=v(a.entryId);if(!b)throw Error("entryId is required");if(this.options.navigationActions)return this.options.navigationActions.selectLeafExact(this.sessionId,b);let d=await c.navigateTree(b,{summarize:!1});if(!d.cancelled&&this.realSessionFile){let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,k.R3)(this.realSessionFile,a):(0,k.$9)(this.realSessionFile)}return{cancelled:d.cancelled}}case"branch_from_assistant":{let b=v(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");if(this.options.navigationActions)return this.options.navigationActions.branchFromAssistant(this.sessionId,b);throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=v(a.entryId);if(!b)throw Error("entryId is required");if(this.options.navigationActions)return this.options.navigationActions.createSessionFromLeaf(this.sessionId,b);throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=v(a.targetId);if(!b)throw Error("targetId is required");let d=void 0===a.label||null===a.label?void 0:String(a.label);return c.sessionManager.appendLabelChange(b,d),this.options.onSessionListInvalidate?.(),null}case"reload":return await c.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:c.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${b}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync()}async destroyAsync(){if(this.destroyPromise)return this.destroyPromise;if(this._alive||this.runtime){if(this.activeCommandCount>0){if(this._scheduledRecheck)return;this._scheduledRecheck=!0,setTimeout(()=>{this._scheduledRecheck=!1,!this.destroyPromise&&this._alive&&this.destroyAsync()},0);return}return 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)}this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],(0,i.PI)(this.realSessionId),this.onDestroyCallback?.(),this.notifyRunning()})(),this.destroyPromise}}}async function w(a){let b=new x(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{JT:()=>f});var d=c(35948);function e(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function f(a,b=e){return{type:"prompt",message:function(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:function(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");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}(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)}}},19228:(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(93686),j=c(87390),k=c(69271),l=c(58732),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)}})},31119:(a,b,c)=>{function d(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 e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},31360:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{G1:()=>j,Qu:()=>k,kW:()=>l,kb:()=>i});var e=c(75430),f=c(89477),g=c(89358),h=a([e]);function i(a){let b=a.getSessionFile();!b||((0,f.existsSync)(b)||a._rewriteFile?.(),(0,f.existsSync)(b)&&(a.flushed=!0))}function j(a,b){let c=e.SessionManager.open(a,b),d=(0,g.ek)(a);if(d&&c.getEntry(d)){if(c.getLeafId()!==d)try{c.branch(d)}catch{(0,g.$9)(a)}}else d&&(0,g.$9)(a);return c}function k(a,b){return e.SessionManager.create(a,b)}function l(a,b){var c;return c=j(a,b),{getEntries:()=>c.getEntries(),getLeafId:()=>c.getLeafId(),getTree:()=>c.getTree(),getHeader:()=>c.getHeader(),getSessionName:()=>c.getSessionName(),getSessionId:()=>c.getSessionId(),getSessionFile:()=>c.getSessionFile(),getCwd:()=>c.getCwd(),getEntry:a=>c.getEntry(a),getBranch:a=>void 0===a?c.getBranch():c.getBranch(a),buildSessionContext:()=>c.buildSessionContext(),appendSessionInfo:a=>c.appendSessionInfo(a),appendCustomEntry:(a,b)=>c.appendCustomEntry(a,b),appendModelChange:(a,b)=>c.appendModelChange(a,b),branch:a=>c.branch(a),createBranchedSession:a=>c.createBranchedSession(a),getSessionDir:()=>c.getSessionDir(),getLastEntryId:()=>(function(a){let b=a.getEntries();for(let a=b.length-1;a>=0;a--){let c=b[a];if(c&&"object"==typeof c&&"id"in c&&"string"==typeof c.id)return c.id}return null})(c)}}e=(h.then?(await h)():h)[0],d()}catch(a){d(a)}})},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{recoverFollowUpQueues:()=>q});var e=c(69453),f=c(31360),g=c(84127),h=c(10611),i=c(82356),j=a([e,f,h]);function k(){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 l(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function m(){return[...l().keys()]}[e,f,h]=j.then?(await j)():j;let s="",t=new Set,u=null;function n(){!function a(){let b=new Set(function(){let a=new Set(m());for(let[b,c]of k())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,i.AZ)(a),t.add(a);for(let a of[...t])b.has(a)||((0,i.Hl)(a),t.delete(a));if(0===b.size){u&&(clearInterval(u),u=null);return}u||(u=setInterval(()=>{a()},8e3),u.unref?.())}();let a=function(){let a=new Set(m());for(let[b,c]of k())c.isRunning()&&a.add(c.sessionId||b);return[...a]}(),b=function(){let a=[];for(let[b,c]of k()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==s)for(let b of(s=c,globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function o(a,b,c,d,e){return r(a,b,c,d,e)}function p(a){return Array.isArray(a)&&a.some(a=>"string"==typeof a&&a.trim().length>0)}async function q(){let a=(0,g.rV)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&p(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!p(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,g.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=k().get(b);if(a?.isAlive()||(0,i.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,f.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await o(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function r(a,b,c,d,f){let g=k(),j=l(),m=g.get(a);if(m?.isAlive())return{session:m,realSessionId:a};let o=j.get(a);if(o)return o;if(!(0,i.kP)(a))throw Error(i.GT);n();let p=(async()=>{try{let j=await (0,h.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>n(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=k(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,i.kP)(b),(0,i.Hl)(a))}}),l=j.sessionId,m=j.sessionFile;return m&&(0,e.O8)(l,m),l!==a&&(0,i.kP)(l),j.onDestroy(()=>{g.get(l)===j&&g.delete(l),a!==l&&g.get(a)===j&&g.delete(a),(0,i.Hl)(l),a!==l&&(0,i.Hl)(a),n()}),g.set(l,j),j.beginExtensionBinding(),{session:j,realSessionId:l}}catch(b){throw(0,i.Hl)(a),n(),b}})().finally(()=>{j.delete(a),n()});return j.set(a,p),p}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},36315:(a,b,c)=>{let d;c.d(b,{Lm:()=>i,Mf:()=>n,GD:()=>l,t_:()=>k,tU:()=>m});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","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=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function i(){if(void 0!==d)return d;try{d=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);h.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e)}catch{d=null}return d}function j(a,b=100){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{return null}}function k(a,b,c,d,e){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=i();if(!g)return null;try{let a=f(b,c,g,d);return a&&"object"==typeof a&&e?.(a),j(a)}catch{return null}}function l(a,b,c,d){let e=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!e)return null;let f=i();if(!f)return null;try{let a=e(b,f,c);return a&&"object"==typeof a&&d?.(a),j(a)}catch{return null}}function m(a,b,c=100){if("function"!=typeof a||!b)return null;try{let d=a(void 0,b);return j(d,c)}catch{return null}}function n(a,b,c,d=100){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return j(e,d)}catch{return null}}},36862:(a,b,c)=>{c.d(b,{KI:()=>i});var d=c(79646),e=c(29021),f=c(33873);let g=(0,c(28354).promisify)(d.execFile);async function h(a,b){let{stdout:c}=await g("git",["-C",a,...b],{timeout:1e4,maxBuffer:1048576,env:{...process.env,LC_ALL:"C"}});return c.trim()}async function i(a){let b,c=(globalThis.__piProjectCache||(globalThis.__piProjectCache=new Map),globalThis.__piProjectCache),d=c.get(a);if(d&&d.expiresAt>Date.now())return d.info;try{if(!(0,e.existsSync)(a))return b=function(a){let b=(0,f.dirname)(a);if(!b.endsWith("-worktrees"))return null;let c=b.slice(0,-10);return c&&(0,e.existsSync)((0,f.join)(c,".git"))?{projectRoot:c,branch:(0,f.basename)(a),isWorktree:!0,isTopLevel:!0}:null}(a)??{projectRoot:a,branch:null,isWorktree:!1,isTopLevel:!1},c.set(a,{info:b,expiresAt:Date.now()+6e4}),b;let[d,g,i,j]=(await h(a,["rev-parse","--path-format=absolute","--git-common-dir","--git-dir","--show-toplevel","--abbrev-ref","HEAD"])).split("\n").map(a=>a.trim()),k=a;try{k=(0,e.realpathSync)(a)}catch{}let l=i===k,m=g!==d&&l;b={projectRoot:m?(0,f.dirname)(d):a,branch:j&&"HEAD"!==j?j:null,isWorktree:m,isTopLevel:l}}catch{b={projectRoot:a,branch:null,isWorktree:!1,isTopLevel:!1}}return c.set(a,{info:b,expiresAt:Date.now()+6e4}),b}},54518:(a,b,c)=>{c.d(b,{ob:()=>k});var d=c(29021),e=c(33873);let f=/^[0-9a-f]{8}$/i,g=/^run-(\d+)$/,h=/^async-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function j(a,b){let c;try{c=JSON.parse(a)}catch{return}if(!i(c)||"message"!==c.type||!i(c.message)||"toolResult"!==c.message.role||"subagent"!==c.message.toolName||!i(c.message.details)||!Array.isArray(c.message.details.results))return;let d=c.message.details;for(let a of d.results)i(a)&&"string"==typeof a.sessionFile&&b.push({path:a.sessionFile,runId:"string"==typeof d.runId?d.runId:void 0,agent:"string"==typeof a.agent?a.agent:"string"==typeof d.agent?d.agent:void 0})}function k(a,b){let c=a.endsWith(".jsonl")?a.slice(0,-6):"";if(!c)return[];let k=new Set,l=new Set,m=[];for(let n of[...function(a){let b=[],c=-1;try{c=(0,d.openSync)(a,"r");let e="",f=0;for(;f<2097152&&b.length<512;){let a=Buffer.allocUnsafe(Math.min(65536,2097152-f)),g=(0,d.readSync)(c,a,0,a.length,f);if(!g)break;f+=g;let h=(e+=a.subarray(0,g).toString("utf8")).split(/\r?\n/);for(let a of(e=h.pop()??"",h))if(!(a.length>131072)&&(j(a,b),b.length>=512))break}e.length<=131072&&b.length<512&&j(e,b)}catch{}finally{c>=0&&(0,d.closeSync)(c)}return b}(a),...(function(a){let b=a.endsWith(".jsonl")?a.slice(0,-6):"",c=[];if(!b)return c;try{for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!f.test(a.name))continue;let h=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(h,{withFileTypes:!0}))if(!(!a.isDirectory()||a.isSymbolicLink())&&g.test(a.name)&&(c.push((0,e.join)(h,a.name,"session.jsonl")),c.length>=2048))return c}for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!h.test(a.name))continue;let f=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(f,{withFileTypes:!0}).filter(a=>a.isFile()&&!a.isSymbolicLink()&&a.name.endsWith(".jsonl")).map(a=>a.name).sort())if(c.push((0,e.join)(f,a)),c.length>=2048)return c}}catch{}return c})(a).map(a=>({path:a}))]){if(m.length>=256)break;let a=function(a,b){try{let c=(0,d.lstatSync)(a);if(!c.isFile()||c.isSymbolicLink()||!a.endsWith(".jsonl"))return null;let f=(0,d.realpathSync)(a),g=(0,d.realpathSync)(b),h=(0,e.relative)(g,f);if(!h||h.startsWith("..")||h.includes("/../")||h.includes("\\..\\"))return null;let i=g;for(let a of h.split(/[\\/]/))if(i=(0,e.join)(i,a),(0,d.lstatSync)(i).isSymbolicLink())return null;return f}catch{return null}}((0,e.resolve)(n.path),c);if(!a||!function(a,b){let c=(0,e.relative)((0,e.resolve)(b),(0,e.resolve)(a)).split(/[\\/]/);return!!(3===c.length&&f.test(c[0])&&g.test(c[1]))&&"session.jsonl"===c[2]||2===c.length&&h.test(c[0])&&c[1].endsWith(".jsonl")}(a,c)||k.has(a))continue;let j=(0,e.relative)((0,e.resolve)(c),(0,e.resolve)(a)).split(/[\\/]/),o=2===j.length&&h.test(j[0]),p=o?0:function(a){let b=g.exec((0,e.basename)((0,e.dirname)(a)));return b?Number(b[1]):null}(a);if(null===p||p<0)continue;let q=function(a){let b=-1;try{b=(0,d.openSync)(a,"r");let c=[],e=0,f=!1;for(;e<65536&&!f;){let a=Buffer.allocUnsafe(Math.min(4096,65536-e)),g=(0,d.readSync)(b,a,0,a.length,e);if(!g)break;let h=a.subarray(0,g),i=h.indexOf(10);c.push(i>=0?h.subarray(0,i):h),e+=g,f=i>=0}if(!f&&e>=65536)return null;let g=Buffer.concat(c).toString("utf8").replace(/\r$/,""),h=JSON.parse(g);if(!i(h)||"session"!==h.type||"string"!=typeof h.id||!h.id||"string"!=typeof h.cwd||"string"!=typeof h.timestamp)return null;return h}catch{return null}finally{b>=0&&(0,d.closeSync)(b)}}(a);if(!q||l.has(q.id)||q.id===b)continue;let r=o?j[0].slice(6):n.runId??(0,e.basename)((0,e.dirname)((0,e.dirname)(a)));k.add(a),l.add(q.id),m.push({path:a,header:q,runIndex:p,parentSessionId:b,runId:r,agent:n.agent})}return m}},54639:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(69420);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)}},58732:(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(92783),h=c(93686),i=c(35948),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)}})},63480:(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)}},68642:(a,b,c)=>{c.d(b,{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)}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={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"},e={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"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},69420:(a,b,c)=>{c.d(b,{Nw:()=>d});function d(a){return a.replace(/\\/g,"/")}},69453:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{O8:()=>r,dQ:()=>m,mD:()=>n,os:()=>q});var e=c(29021),f=c(33873),g=c(2078);c(99595);var h=c(36862),i=c(54518);c(92783);var j=c(31360),k=a([j]);async function l(){let a=await (0,g.Jz)(),b=(0,g.iw)(),c=new Map;if(b)for(let[a,d]of Object.entries(b.sessions))c.set(a,d);let d=a.filter(a=>{let b=c.get(a.path);return!b||b.m!==a.mtimeMs||b.s!==a.size}),j=d.length>0,k=new Map;for(let a of(await Promise.all(d.map(async a=>{let b=await (0,g.O)(a.path,a);b&&k.set(a.path,b)})),d)){let b=k.get(a.path);if(!b){c.delete(a.path);continue}c.set(a.path,{m:a.mtimeMs,s:a.size,i:b})}let l=new Set(a.map(a=>a.path)),m=0;for(let a of[...c.keys()])!l.has(a)&&(c.delete(a),m++);m>0&&(j=!0);let n=[...c.entries()].map(([a,b])=>({path:a,...b.i})).filter(a=>!!(a&&a.id)),o=new Map,p=new Map;for(let a of n){let b=(0,f.normalize)(a.path);o.has(b)||p.has(a.id)||(o.set(b,a.id),p.set(a.id,b))}let q=[...new Set(n.map(a=>a.cwd).filter(Boolean))],s=new Map;await Promise.all(q.map(async a=>{s.set(a,await (0,h.KI)(a))}));let t=new Set,u=new Set,v=n.sort((a,b)=>a.modified<b.modified?1:a.modified>b.modified?-1:0).flatMap(a=>{let b=(0,f.normalize)(a.path);if(t.has(b)||u.has(a.id))return[];t.add(b),u.add(a.id),r(a.id,a.path);let c=a.cwd?s.get(a.cwd):void 0;return[{path:a.path,id:a.id,cwd:a.cwd,name:a.name,created:a.created,modified:a.modified,messageCount:a.messageCount,firstMessage:a.firstMessage||"(no messages)",parentSessionId:a.parentSessionPath?o.get((0,f.normalize)(a.parentSessionPath)):void 0,projectRoot:c?.projectRoot??a.cwd,...c?.isWorktree&&c.branch?{worktreeBranch:c.branch}:{}}]}),w=new Map(v.map(a=>[(0,f.normalize)(a.path),a])),x=new Map(v.map(a=>[a.id,a])),y=new Set,z=new Set,A=[],B=new Map;if(b)for(let[a,c]of Object.entries(b.discovery))B.set(a,c);let C=v.map(a=>({parent:a,depth:0}));for(;C.length&&z.size<256;){let a=C.shift();if(!(a.depth>=16))for(let b of function(a,b,c,d){try{let f=(0,e.statSync)(a),g=c.get(a);if(g&&g.m===f.mtimeMs&&g.s===f.size)return g.c;let h=d(a,b);return c.set(a,{m:f.mtimeMs,s:f.size,c:h}),h}catch{return c.delete(a),[]}}(a.parent.path,a.parent.id,B,(a,b)=>(j=!0,(0,i.ob)(a,b).map(a=>({path:a.path,id:a.header.id,cwd:a.header.cwd,timestamp:a.header.timestamp,parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}}))))){let c=(0,f.normalize)(b.path);if(y.has(c)||z.has(b.id))continue;y.add(c),z.add(b.id);let d=w.get(c),e=x.get(b.id);if(d&&d.id!==b.id||e&&(0,f.normalize)(e.path)!==c)continue;let g=d??e;if(g){g.subagent={parentSessionId:b.parentSessionId,runId:b.runId,runIndex:b.runIndex,...b.agent?{agent:b.agent}:{}},g.readOnly=!0,C.push({parent:g,depth:a.depth+1});continue}t.has(c)||u.has(b.id)||(t.add(c),u.add(b.id),o.set(c,b.id),A.push({child:b}),C.push({parent:{path:b.path,id:b.id,cwd:b.cwd,created:b.timestamp,modified:b.timestamp,messageCount:0,firstMessage:"(no messages)",projectRoot:b.cwd},depth:a.depth+1}))}}let D=await Promise.all(A.map(async({child:a})=>{let b=await (0,h.KI)(a.cwd),c=a.timestamp;try{c=(0,e.statSync)(a.path).mtime.toISOString()}catch{}return r(a.id,a.path),{path:a.path,id:a.id,cwd:a.cwd,created:a.timestamp,modified:c,messageCount:0,firstMessage:"(no messages)",projectRoot:b?.projectRoot??a.cwd,...b?.isWorktree&&b.branch?{worktreeBranch:b.branch}:{},subagent:{parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}},readOnly:!0}}));return j&&(0,g.If)(c,B),[...v,...D]}async function m(){let a=globalThis.__piSessionListGeneration??0;if(globalThis.__piSessionListCache&&Date.now()-globalThis.__piSessionListCache.ts<t)return globalThis.__piSessionListCache.data;if(globalThis.__piSessionListPromise&&globalThis.__piSessionListPromiseGeneration===a)return globalThis.__piSessionListPromise;let b=l().then(b=>((globalThis.__piSessionListGeneration??0)===a&&(globalThis.__piSessionListCache={data:b,ts:Date.now()}),b)).finally(()=>{globalThis.__piSessionListPromise===b&&(globalThis.__piSessionListPromise=void 0,globalThis.__piSessionListPromiseGeneration=void 0)});return globalThis.__piSessionListPromise=b,globalThis.__piSessionListPromiseGeneration=a,b}j=(k.then?(await k)():k)[0];let t=3e4;function n(){globalThis.__piSessionListGeneration=(globalThis.__piSessionListGeneration??0)+1,globalThis.__piSessionListCache=void 0}function o(){return globalThis.__piSessionPathCache||(globalThis.__piSessionPathCache=new Map),globalThis.__piSessionPathCache}function p(){return globalThis.__piPathToSessionIdCache||(globalThis.__piPathToSessionIdCache=new Map),globalThis.__piPathToSessionIdCache}async function q(a){let b=o().get(a);if(b){if((0,e.existsSync)(b))return b;s(a)}await m();let c=o().get(a)??null;return c&&!(0,e.existsSync)(c)?(s(a),null):c}function r(a,b){let c=(0,f.normalize)(b),d=o(),e=p(),g=d.get(a),h=e.get(c);g&&g!==c&&e.get(g)===a&&e.delete(g),h&&h!==a&&d.get(h)===c&&d.delete(h),d.set(a,c),e.set(c,a)}function s(a){let b=o(),c=p(),d=b.get(a);b.delete(a),d&&c.get(d)===a&&c.delete(d)}d()}catch(a){d(a)}})},75377:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(36315);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={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),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},k=()=>{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})};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 l=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{k()},92,40),m=(0,e.Lm)()??j.theme;Promise.resolve().then(()=>b(l,m,{},h)).then(a=>{g||(f=a,k())}).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:j,pending:b,statuses:g,widgets:h,pendingSnapshot:c,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(),g.clear(),h.clear()}}}},82356:(a,b,c)=>{c.d(b,{AZ:()=>t,GT:()=>h,Hl:()=>u,kP:()=>s,wy:()=>v});var d=c(716),e=c(89477),f=c(86697),g=c(92783);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)}
|
|
2
|
-
`,{mode:384}),(0,e.renameSync)(c,a)}function r(a,b){
|
|
1
|
+
"use strict";exports.id=5304,exports.ids=[2356,5304],exports.modules={2078:(a,b,c)=>{let d;c.d(b,{If:()=>o,Jz:()=>l,O:()=>q,iw:()=>m});var e=c(4984),f=c(29021),g=c(79748),h=c(33873),i=c(92783);function j(){return(0,h.join)((0,i.$M)(),"pidance-session-cache.json")}async function k(a){try{let b=await (0,g.stat)(a);return{path:a,mtimeMs:b.mtimeMs,size:b.size}}catch{return null}}async function l(a=(0,h.join)((0,i.$M)(),"sessions")){let b=[];try{b=(await (0,g.readdir)(a,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(b=>(0,h.join)(a,b.name))}catch{return[]}let c=[],d=[];for(let a of b)d.push((async()=>{try{for(let b of(await (0,g.readdir)(a)))b.endsWith(".jsonl")&&c.push((0,h.join)(a,b))}catch{}})());return await Promise.all(d),(await Promise.all(c.map(a=>k(a)))).filter(a=>null!==a)}function m(a=j()){try{let b=(0,f.readFileSync)(a,"utf8"),c=JSON.parse(b);if(!c||2!==c.version||!c.sessions||"object"!=typeof c.sessions)return null;return{version:2,sessions:c.sessions,discovery:c.discovery&&"object"==typeof c.discovery?c.discovery:{}}}catch{return null}}let n=!1;function o(a,b,c=j()){n=!0,d||(d=setTimeout(()=>{if(d=void 0,!n)return;n=!1;let e={version:2,sessions:Object.fromEntries(a),discovery:Object.fromEntries(b)},g=`${c}.tmp`;try{(0,f.writeFileSync)(g,JSON.stringify(e),"utf8"),(0,f.renameSync)(g,c)}catch{try{(0,f.existsSync)(g)&&(0,f.renameSync)(g,c)}catch{}}},1500))}function p(a){return"object"==typeof a&&null!==a&&"string"==typeof a.role&&"content"in a}async function q(a,b){try{let c,d,g=(0,e.createInterface)({input:(0,f.createReadStream)(a,{encoding:"utf8"}),crlfDelay:1/0}),h=null,i=0,j="";for await(let a of g){let b;if(!a.trim())continue;try{b=JSON.parse(a)}catch{continue}if(!h){if("session"!==b.type)return null;h=b;continue}if("session_info"===b.type){let a=b.name;"string"==typeof a&&a.trim()&&(c=a.trim());continue}if("message"!==b.type)continue;i++;let e=function(a){let b=a.message;if(!p(b)||"user"!==b.role)return;let c=b.timestamp;if("number"==typeof c)return c;let d=new Date(a.timestamp??"").getTime();return Number.isNaN(d)?void 0:d}(b);"number"==typeof e&&(d=Math.max(d??0,e));let f=b.message;if(!p(f)||"user"!==f.role&&"assistant"!==f.role)continue;let g=function(a){let b=a.content;return"string"==typeof b?b:Array.isArray(b)?b.filter(a=>!!(a&&"text"===a.type&&"string"==typeof a.text)).map(a=>a.text).join(" "):""}(f);g&&(j||"user"!==f.role||(j=g))}if(!h)return null;let k="string"==typeof h.timestamp?new Date(h.timestamp).getTime():NaN,l=new Date("number"==typeof d&&d>0?d:Number.isNaN(k)?b.mtimeMs:k);return{id:"string"==typeof h.id?h.id:"",cwd:"string"==typeof h.cwd?h.cwd:"",name:c,created:h.timestamp,modified:l.toISOString(),messageCount:i,firstMessage:j||"(no messages)",parentSessionPath:"string"==typeof h.parentSession?h.parentSession:void 0}}catch{return null}}},10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>x});var e=c(75430),f=c(92783),g=c(84127),h=c(82356),i=c(68642),j=c(40673),k=c(99595),l=c(89358),m=c(31360),n=c(75377),o=c(63480),p=c(31119),q=c(11955),r=c(35948),s=c(58732),t=c(19228),u=c(36315),v=a([e,m,s,t]);function w(a){return"string"==typeof a&&a?a:void 0}[e,m,s,t]=v.then?(await v)():v;class y{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.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],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.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,u.Lm)(),this.toolRenderStates=new Map,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}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?.()}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp||this.listeners.length>0)return;if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if((this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp)&&!(this.listeners.length>0)){if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();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,g.rV)(this.agentDir);return!0===(0,g.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,g.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(a){console.error("[pidance] failed to persist follow-up hold:",a)}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,g.rV)(this.agentDir),b=(0,g.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,j.jG)(b);this.followUpQueue=c.items,this.followUpQueueRevision=c.revision}updateFollowUpQueue(a){this.followUpQueue=a,this.followUpQueueRevision+=1}persistFollowUpQueue(){try{(0,g.xP)(`sessionQueue.${this.realSessionId}`,(0,j.EP)({items:this.followUpQueue,revision:this.followUpQueueRevision}),this.agentDir)}catch(a){console.error("[pidance] failed to persist follow-up queue:",a)}}scheduleFollowUpFlush(){!this._alive||!this.runtime||this.flushingFollowUp||0===this.followUpQueue.length||this.isFollowUpHeld()||this.isSettled()&&(this.flushingFollowUp=!0,this.followUpFlushAsOne=!0===(0,g.rV)(this.agentDir).queueFlushAsOne,this.followUpFlushOriginal=[...this.followUpQueue],this.followUpFlushBatch=this.followUpFlushAsOne?[this.followUpFlushOriginal.join("\n\n")]:[...this.followUpFlushOriginal],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.sendNextFollowUp())}async sendNextFollowUp(){if(!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushCursor<this.followUpFlushBatch.length&&this.sendNextFollowUp()},80);this.followUpFlushConfirmed=!1;try{await this.send({type:"prompt",message:a}),this.removeDeliveredFollowUp()&&this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:[...this.followUpQueue]})}catch(b){let a=b instanceof Error?b.message:String(b);this.emit({type:"follow_up_flush_error",errorMessage:a}),this.abortFollowUpFlush()}}removeDeliveredFollowUp(){if(this.followUpFlushAsOne){let a=new Set(this.followUpFlushOriginal),b=this.followUpQueue.filter(b=>!a.has(b));return b.length!==this.followUpQueue.length&&(this.updateFollowUpQueue(b),this.persistFollowUpQueue(),!0)}let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return!1;let b=this.followUpQueue.indexOf(a);if(b<0)return!1;let c=[...this.followUpQueue];return c.splice(b,1),this.updateFollowUpQueue(c),this.persistFollowUpQueue(),!0}confirmFollowUpFlush(){if(!this.flushingFollowUp||this.followUpFlushConfirmed)return;let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return;this.followUpFlushConfirmed=!0,this.removeDeliveredFollowUp();let b=[...this.followUpQueue];(this.persistFollowUpQueue(),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:b}),this.followUpFlushAsOne)?this.finishFollowUpFlush():(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushBatch.length?this.finishFollowUpFlush():this.sendNextFollowUp())}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer(),this.followUpQueue.length>0&&!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,n.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=w(a.method);if("setStatus"===b){let b=w(a.statusKey)??w(a.key)??"default",c=w(a.statusText)??w(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=w(a.widgetKey)??w(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,m.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(r.uG,a);this.emit({type:"message_end",entryId:e,message:(0,r.FH)(a,Date.now())})}(0,m.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&&y.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=y.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);switch(a.type){case"agent_start":this.promptRunning=!0,(0,i.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,i.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,l.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done"});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.followUpFlushConfirmed?this.sendNextFollowUp():this.confirmFollowUpFlush():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let c="agent_settled"===a.type&&!this.flushingFollowUp&&(0===this.followUpQueue.length||this.isFollowUpHeld());this.resetIdleTimer(),c&&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"){this.confirmFollowUpFlush();let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,m.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 d=a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(d={...d,turnMetrics:a})}let e="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||e){let a=this.contextUsageSnapshot();a&&(d={...d,contextUsage:a})}this.emit(this.withRenderedToolLines(d))}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,u.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,u.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,u.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,u.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<y.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,m.G1)(a):(0,m.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,t._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:t.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:t.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:t.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,p.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.followUpQueue.length>0&&!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:[...this.followUpQueue],followUpRevision:this.followUpQueueRevision};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,k.qF)(a):(0,k.l$)(a),c=this.session.sessionManager.appendCustomEntry(k.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,s.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(r.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,r.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a){if(!this.runtime)throw Error("SDK session is not alive");let b=a.type;"get_state"!==b&&"ensure_session"!==b&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let c=this.session;try{switch(b){case"prompt":{let b=(0,q.JT)(a),d=this.promptReceipts.get(b.submissionId);if(d)return d;let e=b.submissionId,f=this.promptInFlight.get(e);if(f)return f;let g=(0,s.Nu)(b.binaryBlocks,this.agentDir);if(this.bashRunning)throw Error("Cannot send a prompt while a shell command is running");if(c.isCompacting){if(b.images?.length||g.length>0)throw Error("Media attachments cannot be queued while compaction is in progress");let a={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.updateFollowUpQueue([...this.followUpQueue,b.message]),this.promptReceipts.set(b.submissionId,a),this.persistFollowUpQueue(),this.options.onSessionListInvalidate?.(),a}if(!(0,h.kP)(this.realSessionId))throw Error(h.GT);this.promptRunning=!0,this.lastStopReason=null,(0,i.NK)(this.realSessionId,Date.now()),this.notifyRunning();let j=(async()=>{try{await new Promise((d,f)=>{let h=!1,j=()=>{c.isStreaming||c.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,i.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done"}),this.resetIdleTimer())};c.prompt(b.message,{images:b.images??a.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(h=!0,g.length>0&&this.pendingBinaryBatches.push({submissionId:e,blocks:g}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),d())}}).then(()=>{if(!h){h=!0;try{(0,m.kb)(c.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),d()}j()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),j(),h||(h=!0,f(a))})});let d={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(e,d),d}catch(d){this.removePendingBinaryBatch(e),this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,i.PI)(this.realSessionId),this.notifyRunning();let a=d instanceof Error?d.message:String(d);this.emit({type:"prompt_error",errorMessage:a}),this.emit({type:"prompt_done"});let c={submissionId:b.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(e,c),d}finally{this.promptInFlight.delete(e)}})();return this.promptInFlight.set(e,j),j}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await c.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),d=String(a.modelId??""),e=(0,o.E)(c.modelRuntime,b,d);if(!e)try{e=(await c.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===d)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${d}`);return await c.setModel((0,p.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return c.model&&(0,p.yu)(c.model),c.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await c.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=String(a.message??"");if(!this.isRunning()&&!this.flushingFollowUp)return this.send({type:"prompt",message:b,images:a.images,streamingBehavior:"steer"});return await c.steer(b,a.images),null}case"set_follow_up_queue":{let b=(0,j.g3)(a.items),c="number"==typeof a.expectedRevision&&Number.isFinite(a.expectedRevision)?a.expectedRevision:void 0;if(void 0!==c&&c!==this.followUpQueueRevision)return{ok:!1,conflict:!0,revision:this.followUpQueueRevision,items:[...this.followUpQueue]};return this.flushingFollowUp&&this.abortFollowUpFlush(),this.updateFollowUpQueue(b),this.persistFollowUpQueue(),this.isSettled()&&b.length>0&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{ok:!0,queued:this.followUpQueue.length,revision:this.followUpQueueRevision}}case"follow_up":return await c.followUp(String(a.message??""),a.images),null;case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return c.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return c.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return c.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return c.clearQueue();case"get_tools":{let a=c.getAllTools(),b=new Set(c.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 c.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of c.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of c.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=c.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 c.getSessionStats();case"bash":if(c.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 c.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return c.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return c.abortCompaction(),null;case"extension_ui_response":{let b=w(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=w(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=w(a.targetId);if(!b)throw Error("targetId is required");let d=await c.navigateTree(b,{summarize:a.summarize,customInstructions:w(a.customInstructions)});if(!d.cancelled&&this.realSessionFile){c.sessionManager.getLeafId();let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries(),d=b.at(-1)?.id;a&&d&&a!==d?(0,l.R3)(this.realSessionFile,a):this.realSessionFile&&(0,l.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:d.cancelled}}case"select_leaf_exact":{let b=w(a.entryId);if(!b)throw Error("entryId is required");let d=this.options.navigationActions;if(d){let a=()=>this.destroyExcluding(1);return await d.selectLeafExact(this.sessionId,b,a)}let e=await c.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,l.R3)(this.realSessionFile,a):(0,l.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=w(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=w(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=w(a.targetId);if(!b)throw Error("targetId is required");let d=void 0===a.label||null===a.label?void 0:String(a.label);return c.sessionManager.appendLabelChange(b,d),this.options.onSessionListInvalidate?.(),null}case"reload":return await c.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:c.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${b}`)}}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("Session writer is busy: a command is still in flight");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.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],(0,i.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 x(a){let b=new y(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{JT:()=>f});var d=c(35948);function e(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function f(a,b=e){return{type:"prompt",message:function(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:function(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");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}(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)}}},19228:(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(93686),j=c(87390),k=c(69271),l=c(58732),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)}})},31119:(a,b,c)=>{function d(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 e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},31360:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{G1:()=>j,Qu:()=>k,kW:()=>l,kb:()=>i});var e=c(75430),f=c(89477),g=c(89358),h=a([e]);function i(a){let b=a.getSessionFile();if(!b)return;let c=function(a){let b="function"!=typeof a._rewriteFile?null:{rewriteFile:()=>a._rewriteFile.call(a),markFlushed:()=>{a.flushed=!0}};if(!b)throw Error("Pi SDK 未提供会话文件写入入口(_rewriteFile / flushed)。请检查 @earendil-works/pi-coding-agent 版本(当前基线 0.85.1)与 pi-session-io 适配层。");return b}(a);(0,f.existsSync)(b)||c.rewriteFile(),(0,f.existsSync)(b)&&c.markFlushed()}function j(a,b){let c=e.SessionManager.open(a,b),d=(0,g.ek)(a);if(d&&c.getEntry(d)){if(c.getLeafId()!==d)try{c.branch(d)}catch{(0,g.$9)(a)}}else d&&(0,g.$9)(a);return c}function k(a,b){return e.SessionManager.create(a,b)}function l(a,b){var c;return c=j(a,b),{getEntries:()=>c.getEntries(),getLeafId:()=>c.getLeafId(),getTree:()=>c.getTree(),getHeader:()=>c.getHeader(),getSessionName:()=>c.getSessionName(),getSessionId:()=>c.getSessionId(),getSessionFile:()=>c.getSessionFile(),getCwd:()=>c.getCwd(),getEntry:a=>c.getEntry(a),getBranch:a=>void 0===a?c.getBranch():c.getBranch(a),buildSessionContext:()=>c.buildSessionContext(),appendSessionInfo:a=>c.appendSessionInfo(a),appendCustomEntry:(a,b)=>c.appendCustomEntry(a,b),appendModelChange:(a,b)=>c.appendModelChange(a,b),branch:a=>c.branch(a),createBranchedSession:a=>c.createBranchedSession(a),getSessionDir:()=>c.getSessionDir(),getLastEntryId:()=>(function(a){let b=a.getEntries();for(let a=b.length-1;a>=0;a--){let c=b[a];if(c&&"object"==typeof c&&"id"in c&&"string"==typeof c.id)return c.id}return null})(c)}}e=(h.then?(await h)():h)[0],d()}catch(a){d(a)}})},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{recoverFollowUpQueues:()=>q});var e=c(69453),f=c(31360),g=c(84127),h=c(40673),i=c(10611),j=c(82356),k=a([e,f,i]);function l(){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 m(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function n(){return[...m().keys()]}[e,f,i]=k.then?(await k)():k;let s="",t=new Set,u=null;function o(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of l())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,j.AZ)(a),t.add(a);for(let a of[...t])b.has(a)||((0,j.Hl)(a),t.delete(a));if(0===b.size){u&&(clearInterval(u),u=null);return}u||(u=setInterval(()=>{a()},8e3),u.unref?.())}();let a=function(){let a=new Set(n());for(let[b,c]of l())c.isRunning()&&a.add(c.sessionId||b);return[...a]}(),b=function(){let a=[];for(let[b,c]of l()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==s)for(let b of(s=c,globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function p(a,b,c,d,e){return r(a,b,c,d,e)}async function q(){let a=(0,g.rV)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&(0,h.aL)(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!(0,h.aL)(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,g.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=l().get(b);if(a?.isAlive()||(0,j.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,f.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await p(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function r(a,b,c,d,f){let g=l(),h=m(),k=g.get(a);if(k?.isAlive())return{session:k,realSessionId:a};let n=h.get(a);if(n)return n;if(!(0,j.kP)(a))throw Error(j.GT);o();let p=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>o(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=l(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,j.kP)(b),(0,j.Hl)(a))}}),k=h.sessionId,m=h.sessionFile;return m&&(0,e.O8)(k,m),k!==a&&(0,j.kP)(k),h.onDestroy(()=>{g.get(k)===h&&g.delete(k),a!==k&&g.get(a)===h&&g.delete(a),(0,j.Hl)(k),a!==k&&(0,j.Hl)(a),o()}),g.set(k,h),h.beginExtensionBinding(),{session:h,realSessionId:k}}catch(b){throw(0,j.Hl)(a),o(),b}})().finally(()=>{h.delete(a),o()});return h.set(a,p),p}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},36315:(a,b,c)=>{let d;c.d(b,{Lm:()=>i,Mf:()=>n,GD:()=>l,t_:()=>k,tU:()=>m});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","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=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function i(){if(void 0!==d)return d;try{d=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);h.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e)}catch{d=null}return d}function j(a,b=100){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{return null}}function k(a,b,c,d,e){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=i();if(!g)return null;try{let a=f(b,c,g,d);return a&&"object"==typeof a&&e?.(a),j(a)}catch{return null}}function l(a,b,c,d){let e=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!e)return null;let f=i();if(!f)return null;try{let a=e(b,f,c);return a&&"object"==typeof a&&d?.(a),j(a)}catch{return null}}function m(a,b,c=100){if("function"!=typeof a||!b)return null;try{let d=a(void 0,b);return j(d,c)}catch{return null}}function n(a,b,c,d=100){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return j(e,d)}catch{return null}}},36862:(a,b,c)=>{c.d(b,{KI:()=>i});var d=c(79646),e=c(29021),f=c(33873);let g=(0,c(28354).promisify)(d.execFile);async function h(a,b){let{stdout:c}=await g("git",["-C",a,...b],{timeout:1e4,maxBuffer:1048576,env:{...process.env,LC_ALL:"C"}});return c.trim()}async function i(a){let b,c=(globalThis.__piProjectCache||(globalThis.__piProjectCache=new Map),globalThis.__piProjectCache),d=c.get(a);if(d&&d.expiresAt>Date.now())return d.info;try{if(!(0,e.existsSync)(a))return b=function(a){let b=(0,f.dirname)(a);if(!b.endsWith("-worktrees"))return null;let c=b.slice(0,-10);return c&&(0,e.existsSync)((0,f.join)(c,".git"))?{projectRoot:c,branch:(0,f.basename)(a),isWorktree:!0,isTopLevel:!0}:null}(a)??{projectRoot:a,branch:null,isWorktree:!1,isTopLevel:!1},c.set(a,{info:b,expiresAt:Date.now()+6e4}),b;let[d,g,i,j]=(await h(a,["rev-parse","--path-format=absolute","--git-common-dir","--git-dir","--show-toplevel","--abbrev-ref","HEAD"])).split("\n").map(a=>a.trim()),k=a;try{k=(0,e.realpathSync)(a)}catch{}let l=i===k,m=g!==d&&l;b={projectRoot:m?(0,f.dirname)(d):a,branch:j&&"HEAD"!==j?j:null,isWorktree:m,isTopLevel:l}}catch{b={projectRoot:a,branch:null,isWorktree:!1,isTopLevel:!1}}return c.set(a,{info:b,expiresAt:Date.now()+6e4}),b}},40673:(a,b,c)=>{function d(a){return Array.isArray(a)?a.filter(a=>"string"==typeof a&&a.trim().length>0):[]}function e(a){return Array.isArray(a)?{items:d(a),revision:0}:a&&"object"==typeof a?{items:d(a.items),revision:"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0}:{items:[],revision:0}}function f(a){return{items:[...a.items],revision:a.revision}}function g(a){return e(a).items.length>0}c.d(b,{EP:()=>f,aL:()=>g,g3:()=>d,jG:()=>e})},54518:(a,b,c)=>{c.d(b,{ob:()=>k});var d=c(29021),e=c(33873);let f=/^[0-9a-f]{8}$/i,g=/^run-(\d+)$/,h=/^async-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function j(a,b){let c;try{c=JSON.parse(a)}catch{return}if(!i(c)||"message"!==c.type||!i(c.message)||"toolResult"!==c.message.role||"subagent"!==c.message.toolName||!i(c.message.details)||!Array.isArray(c.message.details.results))return;let d=c.message.details;for(let a of d.results)i(a)&&"string"==typeof a.sessionFile&&b.push({path:a.sessionFile,runId:"string"==typeof d.runId?d.runId:void 0,agent:"string"==typeof a.agent?a.agent:"string"==typeof d.agent?d.agent:void 0})}function k(a,b){let c=a.endsWith(".jsonl")?a.slice(0,-6):"";if(!c)return[];let k=new Set,l=new Set,m=[];for(let n of[...function(a){let b=[],c=-1;try{c=(0,d.openSync)(a,"r");let e="",f=0;for(;f<2097152&&b.length<512;){let a=Buffer.allocUnsafe(Math.min(65536,2097152-f)),g=(0,d.readSync)(c,a,0,a.length,f);if(!g)break;f+=g;let h=(e+=a.subarray(0,g).toString("utf8")).split(/\r?\n/);for(let a of(e=h.pop()??"",h))if(!(a.length>131072)&&(j(a,b),b.length>=512))break}e.length<=131072&&b.length<512&&j(e,b)}catch{}finally{c>=0&&(0,d.closeSync)(c)}return b}(a),...(function(a){let b=a.endsWith(".jsonl")?a.slice(0,-6):"",c=[];if(!b)return c;try{for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!f.test(a.name))continue;let h=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(h,{withFileTypes:!0}))if(!(!a.isDirectory()||a.isSymbolicLink())&&g.test(a.name)&&(c.push((0,e.join)(h,a.name,"session.jsonl")),c.length>=2048))return c}for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!h.test(a.name))continue;let f=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(f,{withFileTypes:!0}).filter(a=>a.isFile()&&!a.isSymbolicLink()&&a.name.endsWith(".jsonl")).map(a=>a.name).sort())if(c.push((0,e.join)(f,a)),c.length>=2048)return c}}catch{}return c})(a).map(a=>({path:a}))]){if(m.length>=256)break;let a=function(a,b){try{let c=(0,d.lstatSync)(a);if(!c.isFile()||c.isSymbolicLink()||!a.endsWith(".jsonl"))return null;let f=(0,d.realpathSync)(a),g=(0,d.realpathSync)(b),h=(0,e.relative)(g,f);if(!h||h.startsWith("..")||h.includes("/../")||h.includes("\\..\\"))return null;let i=g;for(let a of h.split(/[\\/]/))if(i=(0,e.join)(i,a),(0,d.lstatSync)(i).isSymbolicLink())return null;return f}catch{return null}}((0,e.resolve)(n.path),c);if(!a||!function(a,b){let c=(0,e.relative)((0,e.resolve)(b),(0,e.resolve)(a)).split(/[\\/]/);return!!(3===c.length&&f.test(c[0])&&g.test(c[1]))&&"session.jsonl"===c[2]||2===c.length&&h.test(c[0])&&c[1].endsWith(".jsonl")}(a,c)||k.has(a))continue;let j=(0,e.relative)((0,e.resolve)(c),(0,e.resolve)(a)).split(/[\\/]/),o=2===j.length&&h.test(j[0]),p=o?0:function(a){let b=g.exec((0,e.basename)((0,e.dirname)(a)));return b?Number(b[1]):null}(a);if(null===p||p<0)continue;let q=function(a){let b=-1;try{b=(0,d.openSync)(a,"r");let c=[],e=0,f=!1;for(;e<65536&&!f;){let a=Buffer.allocUnsafe(Math.min(4096,65536-e)),g=(0,d.readSync)(b,a,0,a.length,e);if(!g)break;let h=a.subarray(0,g),i=h.indexOf(10);c.push(i>=0?h.subarray(0,i):h),e+=g,f=i>=0}if(!f&&e>=65536)return null;let g=Buffer.concat(c).toString("utf8").replace(/\r$/,""),h=JSON.parse(g);if(!i(h)||"session"!==h.type||"string"!=typeof h.id||!h.id||"string"!=typeof h.cwd||"string"!=typeof h.timestamp)return null;return h}catch{return null}finally{b>=0&&(0,d.closeSync)(b)}}(a);if(!q||l.has(q.id)||q.id===b)continue;let r=o?j[0].slice(6):n.runId??(0,e.basename)((0,e.dirname)((0,e.dirname)(a)));k.add(a),l.add(q.id),m.push({path:a,header:q,runIndex:p,parentSessionId:b,runId:r,agent:n.agent})}return m}},54639:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(69420);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)}},58732:(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(92783),h=c(93686),i=c(35948),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)}})},63480:(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)}},68642:(a,b,c)=>{c.d(b,{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)}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={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"},e={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"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},69420:(a,b,c)=>{c.d(b,{Nw:()=>d});function d(a){return a.replace(/\\/g,"/")}},69453:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{O8:()=>r,dQ:()=>m,mD:()=>n,os:()=>q});var e=c(29021),f=c(33873),g=c(2078);c(99595);var h=c(36862),i=c(54518);c(92783);var j=c(31360),k=a([j]);async function l(){let a=await (0,g.Jz)(),b=(0,g.iw)(),c=new Map;if(b)for(let[a,d]of Object.entries(b.sessions))c.set(a,d);let d=a.filter(a=>{let b=c.get(a.path);return!b||b.m!==a.mtimeMs||b.s!==a.size}),j=d.length>0,k=new Map;for(let a of(await Promise.all(d.map(async a=>{let b=await (0,g.O)(a.path,a);b&&k.set(a.path,b)})),d)){let b=k.get(a.path);if(!b){c.delete(a.path);continue}c.set(a.path,{m:a.mtimeMs,s:a.size,i:b})}let l=new Set(a.map(a=>a.path)),m=0;for(let a of[...c.keys()])!l.has(a)&&(c.delete(a),m++);m>0&&(j=!0);let n=[...c.entries()].map(([a,b])=>({path:a,...b.i})).filter(a=>!!(a&&a.id)),o=new Map,p=new Map;for(let a of n){let b=(0,f.normalize)(a.path);o.has(b)||p.has(a.id)||(o.set(b,a.id),p.set(a.id,b))}let q=[...new Set(n.map(a=>a.cwd).filter(Boolean))],s=new Map;await Promise.all(q.map(async a=>{s.set(a,await (0,h.KI)(a))}));let t=new Set,u=new Set,v=n.sort((a,b)=>a.modified<b.modified?1:a.modified>b.modified?-1:0).flatMap(a=>{let b=(0,f.normalize)(a.path);if(t.has(b)||u.has(a.id))return[];t.add(b),u.add(a.id),r(a.id,a.path);let c=a.cwd?s.get(a.cwd):void 0;return[{path:a.path,id:a.id,cwd:a.cwd,name:a.name,created:a.created,modified:a.modified,messageCount:a.messageCount,firstMessage:a.firstMessage||"(no messages)",parentSessionId:a.parentSessionPath?o.get((0,f.normalize)(a.parentSessionPath)):void 0,projectRoot:c?.projectRoot??a.cwd,...c?.isWorktree&&c.branch?{worktreeBranch:c.branch}:{}}]}),w=new Map(v.map(a=>[(0,f.normalize)(a.path),a])),x=new Map(v.map(a=>[a.id,a])),y=new Set,z=new Set,A=[],B=new Map;if(b)for(let[a,c]of Object.entries(b.discovery))B.set(a,c);let C=v.map(a=>({parent:a,depth:0}));for(;C.length&&z.size<256;){let a=C.shift();if(!(a.depth>=16))for(let b of function(a,b,c,d){try{let f=(0,e.statSync)(a),g=c.get(a);if(g&&g.m===f.mtimeMs&&g.s===f.size)return g.c;let h=d(a,b);return c.set(a,{m:f.mtimeMs,s:f.size,c:h}),h}catch{return c.delete(a),[]}}(a.parent.path,a.parent.id,B,(a,b)=>(j=!0,(0,i.ob)(a,b).map(a=>({path:a.path,id:a.header.id,cwd:a.header.cwd,timestamp:a.header.timestamp,parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}}))))){let c=(0,f.normalize)(b.path);if(y.has(c)||z.has(b.id))continue;y.add(c),z.add(b.id);let d=w.get(c),e=x.get(b.id);if(d&&d.id!==b.id||e&&(0,f.normalize)(e.path)!==c)continue;let g=d??e;if(g){g.subagent={parentSessionId:b.parentSessionId,runId:b.runId,runIndex:b.runIndex,...b.agent?{agent:b.agent}:{}},g.readOnly=!0,C.push({parent:g,depth:a.depth+1});continue}t.has(c)||u.has(b.id)||(t.add(c),u.add(b.id),o.set(c,b.id),A.push({child:b}),C.push({parent:{path:b.path,id:b.id,cwd:b.cwd,created:b.timestamp,modified:b.timestamp,messageCount:0,firstMessage:"(no messages)",projectRoot:b.cwd},depth:a.depth+1}))}}let D=await Promise.all(A.map(async({child:a})=>{let b=await (0,h.KI)(a.cwd),c=a.timestamp;try{c=(0,e.statSync)(a.path).mtime.toISOString()}catch{}return r(a.id,a.path),{path:a.path,id:a.id,cwd:a.cwd,created:a.timestamp,modified:c,messageCount:0,firstMessage:"(no messages)",projectRoot:b?.projectRoot??a.cwd,...b?.isWorktree&&b.branch?{worktreeBranch:b.branch}:{},subagent:{parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}},readOnly:!0}}));return j&&(0,g.If)(c,B),[...v,...D]}async function m(){let a=globalThis.__piSessionListGeneration??0;if(globalThis.__piSessionListCache&&Date.now()-globalThis.__piSessionListCache.ts<t)return globalThis.__piSessionListCache.data;if(globalThis.__piSessionListPromise&&globalThis.__piSessionListPromiseGeneration===a)return globalThis.__piSessionListPromise;let b=l().then(b=>((globalThis.__piSessionListGeneration??0)===a&&(globalThis.__piSessionListCache={data:b,ts:Date.now()}),b)).finally(()=>{globalThis.__piSessionListPromise===b&&(globalThis.__piSessionListPromise=void 0,globalThis.__piSessionListPromiseGeneration=void 0)});return globalThis.__piSessionListPromise=b,globalThis.__piSessionListPromiseGeneration=a,b}j=(k.then?(await k)():k)[0];let t=3e4;function n(){globalThis.__piSessionListGeneration=(globalThis.__piSessionListGeneration??0)+1,globalThis.__piSessionListCache=void 0}function o(){return globalThis.__piSessionPathCache||(globalThis.__piSessionPathCache=new Map),globalThis.__piSessionPathCache}function p(){return globalThis.__piPathToSessionIdCache||(globalThis.__piPathToSessionIdCache=new Map),globalThis.__piPathToSessionIdCache}async function q(a){let b=o().get(a);if(b){if((0,e.existsSync)(b))return b;s(a)}await m();let c=o().get(a)??null;return c&&!(0,e.existsSync)(c)?(s(a),null):c}function r(a,b){let c=(0,f.normalize)(b),d=o(),e=p(),g=d.get(a),h=e.get(c);g&&g!==c&&e.get(g)===a&&e.delete(g),h&&h!==a&&d.get(h)===c&&d.delete(h),d.set(a,c),e.set(c,a)}function s(a){let b=o(),c=p(),d=b.get(a);b.delete(a),d&&c.get(d)===a&&c.delete(d)}d()}catch(a){d(a)}})},75377:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(36315);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()}}}},82356:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,sweepStaleRunningLeases:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(92783);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)}
|
|
2
|
+
`,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a=(0,g.$M)(),b=Date.now()){try{let c,{fresh:d,removed:g}=(c=j(a),(0,e.existsSync)(c)?o(a,()=>{let a=[],d=0;for(let g of(0,e.readdirSync)(c)){if(!g.endsWith(".json"))continue;let h=(0,f.join)(c,g),i=m(h);if(!r(i)){try{(0,e.unlinkSync)(h),d+=1}catch{}continue}b-i.heartbeatAt<=2e4&&l(i.pid)&&a.push(i)}return{fresh:a,removed:d}}):{fresh:[],removed:0});return{removed:g,active:d.length,skipped:!1}}catch(a){if(p(a))return{removed:0,active:0,skipped:!0};throw a}}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)}},84127:(a,b,c)=>{c.d(b,{ql:()=>i,rV:()=>h,xP:()=>j});var d=c(89477),e=c(86697),f=c(92783);function g(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function h(a=(0,f.$M)()){let b=g(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return"object"!=typeof a||null===a||Array.isArray(a)?{}:a}catch{return{}}}function i(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 j(a,b,c=(0,f.$M)()){!function(a,b){let c=g(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(h,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(h).mtimeMs>6e4&&(0,d.unlinkSync)(h)}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)(h)}catch{}}}(c,()=>{let f=h(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}(f,a,b);let i=g(c),j=(0,e.dirname)(i);(0,d.existsSync)(j)||(0,d.mkdirSync)(j,{recursive:!0,mode:448});let k=`${i}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(k,JSON.stringify(f,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(k,i)}catch(a){try{(0,d.unlinkSync)(k)}catch{}throw a}})}},87390:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{A$:()=>q,Nw:()=>j.Nw,bk:()=>p,mc:()=>o,wz:()=>k.wz});var e=c(29021),f=c(21820),g=c(33873),h=c.n(g),i=c(92783),j=c(69420),k=c(54639),l=c(93686),m=c(69453),n=a([l,m]);[l,m]=n.then?(await n)():n;async function o(){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 p(){return!0}function q(a,b){return!0}d()}catch(a){d(a)}})},89358:(a,b,c)=>{c.d(b,{$9:()=>j,R3:()=>i,ek:()=>h});var d=c(89477),e=c(86697),f=c(716);function g(a){return`${a}.leaf.json`}function h(a){let b=g(a);if(!(0,d.existsSync)(b))return null;try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));if(!a||"object"!=typeof a)return null;let c=a.leafId;return"string"==typeof c&&c?c:null}catch{return null}}function i(a,b){let c=g(a),h=(0,e.dirname)(c);(0,d.existsSync)(h)||(0,d.mkdirSync)(h,{recursive:!0});let i=JSON.stringify({version:1,leafId:b},null,2),j=(0,e.join)(h,`.leaf-${process.pid}-${(0,f.randomUUID)()}.tmp`);try{(0,d.writeFileSync)(j,i,{encoding:"utf8",flag:"wx"}),(0,d.renameSync)(j,c)}catch(a){try{(0,d.existsSync)(j)&&(0,d.unlinkSync)(j)}catch{}throw a}}function j(a){try{let b=g(a);(0,d.existsSync)(b)&&(0,d.unlinkSync)(b)}catch{}}},92783:(a,b,c)=>{c.d(b,{$M:()=>f});var d=c(62228),e=c(86697);function f(a=process.env){let b=a.PI_CODING_AGENT_DIR?.trim();if(b)return"~"===b?(0,d.homedir)():b.startsWith("~/")||b.startsWith("~\\")?(0,e.join)((0,d.homedir)(),b.slice(2)):b;return(0,e.join)((0,d.homedir)(),".pi","agent")}},93686:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Gt:()=>q,eq:()=>n,qo:()=>m,uF:()=>o,xd:()=>p});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(92783),k=c(87390),l=a([k]);k=(l.then?(await l)():l)[0];let q=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)}async function p(a,b,c=(0,j.$M)(),d=q){let l=n(c),m=function(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}`}(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}}d()}catch(a){d(a)}})},99595:(a,b,c)=>{c.d(b,{cP:()=>d,l$:()=>j,qF:()=>k});let d="pidance.activity",e=["result","warning","error","output"];class f extends Error{constructor(a){super(a),this.name="SessionActivityError"}}function g(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function h(a){return Buffer.byteLength(a,"utf8")}function i(a,b,c){if(void 0===a)return;if("string"!=typeof a)throw new f(`${b} must be a string`);let d=a.trim();if(""!==d){if(d.length>c)throw new f(`${b} exceeds maximum length ${c}`);return d}}function j(a){var b;let c,d;if(!g(a))throw new f("activity must be a plain object");let j=void 0===a.version?1:a.version;if(1!==j)throw new f(`unsupported activity version: ${String(j)}`);if(!("string"==typeof(b=a.kind)&&e.includes(b)))throw new f(`kind must be one of: ${e.join(", ")}`);if("string"!=typeof a.title)throw new f("title must be a string");let k=a.title.trim();if(""===k)throw new f("title is required");if(k.length>200)throw new f("title exceeds maximum length 200");if("string"!=typeof a.content)throw new f("content must be a string");let l=a.content.trim();if(l.length>32768)throw new f("content exceeds maximum length 32768");let m=i(a.source,"source",200),n=i(a.requestId,"requestId",200);if(void 0!==a.metadata){if(!g(a.metadata))throw new f("metadata must be a plain object");let b=function a(b,c,d){if(null===b)return null;if("string"==typeof b){if(h(b)>1024)throw new f("metadata string exceeds 1024 bytes");return b}if("number"==typeof b){if(!Number.isFinite(b))throw new f("metadata number must be finite");return b}if("boolean"==typeof b)return b;if("bigint"==typeof b||"function"==typeof b||"symbol"==typeof b||void 0===b||"object"!=typeof b)throw new f("metadata contains non-JSON value");if(d.has(b))throw new f("metadata contains circular reference");if(c>3)throw new f("metadata exceeds max depth 3");if(Array.isArray(b)){if(b.length>32)throw new f("metadata array exceeds 32 items");d.add(b);try{return b.map(b=>a(b,c+1,d))}finally{d.delete(b)}}let e=Object.getPrototypeOf(b);if(e!==Object.prototype&&null!==e)throw new f("metadata must be a plain JSON object or array");let g=Object.keys(b);if(g.length>20)throw new f("metadata exceeds 20 keys");d.add(b);try{let e=Object.create(null);for(let i of g){if("__proto__"===i||"constructor"===i||"prototype"===i)throw new f("metadata key is not allowed");if(h(i)>64)throw new f("metadata key exceeds 64 bytes");e[i]=a(b[i],c+1,d)}return e}finally{d.delete(b)}}(a.metadata,0,new WeakSet);if(!g(b)||Array.isArray(b))throw new f("metadata must be a plain object");0===Object.keys(c=b).length&&(c=void 0)}let o={version:1,kind:a.kind,title:k,content:l};void 0!==m&&(o.source=m),void 0!==n&&(o.requestId=n),void 0!==c&&(o.metadata=c);try{d=JSON.stringify(o)}catch{throw new f("activity is not JSON-serializable")}if(h(d)>48e3)throw new f("activity exceeds maximum serialized size 48000 bytes");return o}function k(a){if("customType"in a&&void 0!==a.customType)throw new f("customType is not allowed on append_activity");let b=a.activity;if(void 0!==b){if(!g(b))throw new f("activity must be a plain object");if("customType"in b&&void 0!==b.customType)throw new f("customType is not allowed on append_activity");return j(b)}let c={...a};return delete c.type,j(c)}}};
|