@bastani/atomic 0.9.5-alpha.7 → 0.9.5-alpha.9
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/CHANGELOG.md +33 -2
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +17 -0
- package/dist/builtin/intercom/README.md +27 -21
- package/dist/builtin/intercom/broker/broker.ts +3 -6
- package/dist/builtin/intercom/broker/paths.ts +42 -5
- package/dist/builtin/intercom/broker/spawn.ts +78 -10
- package/dist/builtin/intercom/config.ts +6 -3
- package/dist/builtin/intercom/contact-supervisor-tool.ts +6 -4
- package/dist/builtin/intercom/index-heavy.ts +1 -1
- package/dist/builtin/intercom/index.ts +162 -130
- package/dist/builtin/intercom/intercom-tool.ts +9 -3
- package/dist/builtin/intercom/package.json +10 -1
- package/dist/builtin/intercom/result-renderers.ts +1 -1
- package/dist/builtin/intercom/ui/compose.ts +2 -2
- package/dist/builtin/intercom/ui/inline-message.ts +2 -2
- package/dist/builtin/intercom/ui/session-list.ts +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +11 -0
- package/dist/builtin/mcp/README.md +6 -6
- package/dist/builtin/mcp/direct-tools.ts +41 -23
- package/dist/builtin/mcp/index.ts +31 -4
- package/dist/builtin/mcp/init.ts +4 -43
- package/dist/builtin/mcp/metadata-hydration.ts +37 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/proxy-info-modes.ts +67 -14
- package/dist/builtin/mcp/startup-warmup.ts +98 -0
- package/dist/builtin/mcp/tool-result-renderer.ts +3 -3
- package/dist/builtin/subagents/CHANGELOG.md +18 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.ts +14 -25
- package/dist/builtin/subagents/src/extension/startup-maintenance.ts +89 -0
- package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +23 -18
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +20 -10
- package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +13 -3
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +10 -2
- package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +28 -1
- package/dist/builtin/subagents/src/tui/render-event-formatting.ts +15 -48
- package/dist/builtin/subagents/src/tui/render-layout.ts +9 -0
- package/dist/builtin/subagents/src/tui/render-widget-graph.ts +27 -25
- package/dist/builtin/subagents/src/tui/render-widget.ts +72 -66
- package/dist/builtin/subagents/src/tui/render.ts +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +29 -0
- package/dist/builtin/workflows/README.md +4 -2
- package/dist/builtin/workflows/builtin/goal-artifacts.ts +3 -1
- package/dist/builtin/workflows/builtin/goal-prompts.ts +23 -2
- package/dist/builtin/workflows/builtin/goal-reducer.ts +21 -0
- package/dist/builtin/workflows/builtin/goal-review.ts +60 -6
- package/dist/builtin/workflows/builtin/goal-runner.ts +71 -22
- package/dist/builtin/workflows/builtin/goal-types.ts +7 -1
- package/dist/builtin/workflows/builtin/ralph-core.ts +52 -4
- package/dist/builtin/workflows/builtin/ralph-review-gate.ts +10 -3
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +23 -2
- package/dist/builtin/workflows/builtin/ralph-runner.ts +38 -16
- package/dist/builtin/workflows/builtin/review-convergence.ts +111 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/create-spec/SKILL.md +2 -0
- package/dist/builtin/workflows/skills/impeccable/SKILL.md +16 -13
- package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -0
- package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +58 -0
- package/dist/builtin/workflows/skills/impeccable/reference/android.md +40 -0
- package/dist/builtin/workflows/skills/impeccable/reference/animate.md +2 -0
- package/dist/builtin/workflows/skills/impeccable/reference/audit.md +2 -0
- package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +139 -0
- package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +69 -62
- package/dist/builtin/workflows/skills/impeccable/reference/critique.md +21 -7
- package/dist/builtin/workflows/skills/impeccable/reference/document.md +1 -1
- package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +92 -0
- package/dist/builtin/workflows/skills/impeccable/reference/init.md +29 -7
- package/dist/builtin/workflows/skills/impeccable/reference/ios.md +45 -0
- package/dist/builtin/workflows/skills/impeccable/reference/layout.md +25 -1
- package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +23 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +2 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +75 -14
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +1 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +31 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +64 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +118 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +16 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +66 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +42 -10
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +30 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +4 -6
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +660 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-before-edit.mjs +516 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +1764 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +61 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +4 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +2 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +13 -16
- package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +17 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +104 -37
- package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +9 -0
- package/dist/builtin/workflows/src/durable/backend.ts +12 -0
- package/dist/builtin/workflows/src/durable/child-primitive.ts +12 -8
- package/dist/builtin/workflows/src/durable/dbos-backend.ts +63 -2
- package/dist/builtin/workflows/src/durable/dbos-envelope.ts +28 -0
- package/dist/builtin/workflows/src/durable/resume-catalog.ts +12 -0
- package/dist/builtin/workflows/src/durable/resume-runtime.ts +5 -2
- package/dist/builtin/workflows/src/durable/stage-primitive.ts +165 -27
- package/dist/builtin/workflows/src/durable/types.ts +30 -1
- package/dist/builtin/workflows/src/engine/primitives/task.ts +1 -0
- package/dist/builtin/workflows/src/engine/run-durable-finalize.ts +1 -2
- package/dist/builtin/workflows/src/engine/run-returned-status.ts +50 -16
- package/dist/builtin/workflows/src/engine/run.ts +32 -32
- package/dist/builtin/workflows/src/engine/runtime.ts +5 -0
- package/dist/builtin/workflows/src/extension/extension-factory.ts +3 -0
- package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +9 -2
- package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +137 -27
- package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +22 -6
- package/dist/builtin/workflows/src/extension/public-types.ts +1 -1
- package/dist/builtin/workflows/src/extension/workflow-command-completions.ts +13 -1
- package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +19 -4
- package/dist/builtin/workflows/src/extension/workflow-command-surfaces.ts +9 -0
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +2 -0
- package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +48 -23
- package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +20 -8
- package/dist/builtin/workflows/src/extension/workflow-tool.ts +24 -8
- package/dist/builtin/workflows/src/runs/background/status.ts +4 -3
- package/dist/builtin/workflows/src/runs/foreground/executor-continuation.ts +13 -3
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +29 -8
- package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +2 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +4 -3
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +18 -19
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-unresolved-overflow.ts +38 -0
- package/dist/builtin/workflows/src/runs/shared/worktree-git.ts +155 -20
- package/dist/builtin/workflows/src/runs/shared/worktree-types.ts +6 -0
- package/dist/builtin/workflows/src/runs/shared/worktree.ts +2 -1
- package/dist/builtin/workflows/src/shared/persistence-restore-helpers.ts +18 -1
- package/dist/builtin/workflows/src/shared/persistence-restore.ts +23 -5
- package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +4 -0
- package/dist/builtin/workflows/src/shared/returned-run-status.ts +116 -0
- package/dist/builtin/workflows/src/shared/workflow-failures-decisions.ts +2 -0
- package/dist/builtin/workflows/src/tui/graph-view-render-helpers.ts +21 -3
- package/dist/builtin/workflows/src/tui/graph-view-state.ts +3 -0
- package/dist/builtin/workflows/src/tui/graph-view-types.ts +3 -0
- package/dist/builtin/workflows/src/tui/status-list.ts +22 -15
- package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +4 -4
- package/dist/bun/internal-intercom-broker.d.ts +6 -0
- package/dist/bun/internal-intercom-broker.d.ts.map +1 -0
- package/dist/bun/internal-intercom-broker.js +39 -0
- package/dist/bun/internal-intercom-broker.js.map +1 -0
- package/dist/bun/split-loader.d.ts.map +1 -1
- package/dist/bun/split-loader.js +21 -8
- package/dist/bun/split-loader.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +21 -2
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +163 -11
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +10 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +12 -3
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-models.d.ts +2 -2
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +1 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +2 -0
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +152 -4
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +15 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-runner.js +36 -20
- package/dist/core/compaction/context-compaction-runner.js.map +1 -1
- package/dist/core/copilot-anthropic-sse-repair.d.ts +23 -0
- package/dist/core/copilot-anthropic-sse-repair.d.ts.map +1 -0
- package/dist/core/copilot-anthropic-sse-repair.js +340 -0
- package/dist/core/copilot-anthropic-sse-repair.js.map +1 -0
- package/dist/core/copilot-gemini-reasoning.d.ts +16 -8
- package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
- package/dist/core/copilot-gemini-reasoning.js +27 -22
- package/dist/core/copilot-gemini-reasoning.js.map +1 -1
- package/dist/core/copilot-hosts.d.ts +12 -0
- package/dist/core/copilot-hosts.d.ts.map +1 -0
- package/dist/core/copilot-hosts.js +33 -0
- package/dist/core/copilot-hosts.js.map +1 -0
- package/dist/core/extensions/agent-events.d.ts +1 -1
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts +8 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +2 -1
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +6 -0
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +72 -29
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +5 -5
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts +1 -0
- package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.js +24 -9
- package/dist/core/openai-responses-payload-sanitizer.js.map +1 -1
- package/dist/core/sdk-types.d.ts +2 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +6 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -0
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/slash-commands.d.ts +2 -0
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +141 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main-deferred-startup.d.ts +12 -0
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +23 -2
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main-early-input.d.ts +41 -0
- package/dist/main-early-input.d.ts.map +1 -0
- package/dist/main-early-input.js +154 -0
- package/dist/main-early-input.js.map +1 -0
- package/dist/main.d.ts +0 -6
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -14
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +0 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +15 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +25 -0
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +21 -9
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +41 -28
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-hotkeys-debug.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-hotkeys-debug.js +1 -0
- package/dist/modes/interactive/interactive-hotkeys-debug.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +318 -185
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +12 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +39 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +6 -2
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +3 -1
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +0 -3
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +36 -10
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.js +5 -1
- package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +26 -22
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/global-theme.js +26 -2
- package/dist/modes/interactive/theme/global-theme.js.map +1 -1
- package/dist/utils/fs-watch.d.ts +24 -1
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js +60 -5
- package/dist/utils/fs-watch.js.map +1 -1
- package/docs/compaction.md +8 -0
- package/docs/development.md +4 -0
- package/docs/extensions.md +5 -0
- package/docs/json.md +3 -1
- package/docs/providers.md +1 -0
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +3 -1
- package/docs/settings.md +27 -1
- package/docs/subagents.md +4 -0
- package/docs/terminal-setup.md +4 -0
- package/docs/usage.md +2 -2
- package/docs/windows.md +4 -0
- package/docs/workflows.md +21 -9
- package/npm-shrinkwrap.json +513 -23
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-gemini-reasoning.js","sourceRoot":"","sources":["../../src/core/copilot-gemini-reasoning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAyD7E,gFAAgF;AAChF,MAAM,wBAAwB,GAAG,qBAAqB,CAAC;AAEvD,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,mCAAmC,CAAC,KAAgB;IAClE,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACxC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAE1C,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC,aAAa,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IAAiC,CAAC,UAAU,CAAC;IACjE,IAAI,OAAO,UAAU,KAAK,UAAU,EAAE,CAAC;QACpC,OAAoC,CAAC,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACjF,CAAC;IAED,UAAU,CAAC,KAAK,GAAG,OAAO,CAAC;AAC7B,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\n\n/**\n * Round-trips GitHub Copilot Gemini \"thought signatures\" so multi-turn tool use\n * does not silently die after the first tool call.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models (e.g. `gemini-3.1-pro-preview`) are served\n * through Copilot's CAPI gateway, which proxies to Google's GenAI API. Gemini\n * is a thinking model: when it emits a function/tool call it also returns an\n * opaque **thought signature** that must be sent back, verbatim, on the next\n * request or Gemini refuses to continue the reasoning chain.\n *\n * CAPI carries that signature in a non-standard OpenAI-completions field named\n * **`reasoning_opaque`** (an encrypted blob) on the assistant message / streamed\n * delta, and on replay it reads the same `reasoning_opaque` back off the\n * assistant message and re-attaches the signature to each Gemini function-call\n * part (keyed by `tool_call.id`). The underlying OpenAI-completions client\n * (`@earendil-works/pi-ai`) does not understand `reasoning_opaque`; it captures\n * thought signatures only from the OpenRouter-style\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data }]` shape, which\n * CAPI never emits. So the real Gemini thought signature was being dropped on\n * the way in and never replayed on the way out.\n *\n * With the signature missing, CAPI substitutes the sentinel\n * `skip_thought_signature_validator` on the first replayed function call, and\n * Gemini responds with an empty candidate / `finish_reason: \"stop\"` and zero\n * output tokens — the harness sees a degenerate empty completion, retries with\n * the same signature-less history, and eventually gives up: \"Gemini just stops\n * responding.\"\n *\n * What this does\n * --------------\n * Two gated, self-contained transforms bridge CAPI's `reasoning_opaque` to the\n * `reasoning_details` mechanism the client already round-trips:\n *\n * - **Inbound** ({@link rewriteCopilotGeminiSseData} via\n * {@link createCopilotGeminiSseStream}): rewrites the CAPI Gemini SSE\n * stream so each streamed delta that carries both `reasoning_opaque` and a\n * `tool_calls[].id` gains a\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data: <opaque> }]`\n * entry. The client then stores it as the tool call's `thoughtSignature`.\n * CAPI confirms `reasoning_opaque` rides on the same streamed delta as the\n * first (id-bearing) tool-call chunk, so the association is exact.\n * - **Outbound** ({@link restoreCopilotGeminiReasoningOpaque} from the\n * `onPayload` hook): converts the `reasoning_details` the client re-emits on\n * replayed assistant messages back into a single `reasoning_opaque` field on\n * that assistant message, which is the only shape CAPI reads.\n *\n * Both transforms are gated to GitHub Copilot Gemini and are no-ops for every\n * other provider/model (and for Gemini turns that carry no thought signature).\n */\n\ntype JsonObject = { [key: string]: JsonValue };\ntype JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\n/** OpenRouter-style encrypted reasoning detail the pi-ai client round-trips. */\nconst REASONING_ENCRYPTED_TYPE = \"reasoning.encrypted\";\n\nfunction isPlainObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Inject `reasoning_details` into a parsed CAPI Gemini streaming chunk so the\n * pi-ai OpenAI-completions parser captures the Gemini thought signature.\n *\n * For each `choices[].delta` that carries a non-empty `reasoning_opaque` string\n * and a `tool_calls[]` entry with an `id`, adds a single\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data: <opaque> }]`\n * entry keyed by that tool-call id. Returns whether the chunk was mutated.\n *\n * No-op when the delta already has `reasoning_details`, has no id-bearing tool\n * call (e.g. argument-continuation deltas or pure-text thought chunks), or has\n * no `reasoning_opaque`.\n */\nexport function injectCopilotGeminiReasoningDetails(chunk: JsonValue): boolean {\n if (!isPlainObject(chunk)) return false;\n const choices = chunk.choices;\n if (!Array.isArray(choices)) return false;\n\n let mutated = false;\n for (const choice of choices) {\n if (!isPlainObject(choice)) continue;\n const delta = choice.delta;\n if (!isPlainObject(delta)) continue;\n\n const opaque = delta.reasoning_opaque;\n if (typeof opaque !== \"string\" || opaque.length === 0) continue;\n\n // Already carries the encrypted detail (don't double-inject / clobber).\n if (Array.isArray(delta.reasoning_details) && delta.reasoning_details.length > 0) {\n continue;\n }\n\n const toolCalls = delta.tool_calls;\n if (!Array.isArray(toolCalls)) continue;\n const idBearing = toolCalls.find(\n (call): call is JsonObject =>\n isPlainObject(call) && typeof call.id === \"string\" && call.id.length > 0,\n );\n if (!idBearing) continue;\n\n delta.reasoning_details = [\n { type: REASONING_ENCRYPTED_TYPE, id: idBearing.id as string, data: opaque },\n ];\n mutated = true;\n }\n return mutated;\n}\n\n/**\n * Rewrite the JSON payload of a single SSE `data:` line. Returns the original\n * string unchanged when it is not a Gemini chunk that needs a thought signature\n * bridged, or when parsing fails (fail-open: never corrupt the stream).\n */\nexport function rewriteCopilotGeminiSseData(dataPayload: string): string {\n // Cheap gate: only chunks that actually carry a thought signature are touched.\n if (!dataPayload.includes(\"reasoning_opaque\")) return dataPayload;\n let parsed: JsonValue;\n try {\n parsed = JSON.parse(dataPayload) as JsonValue;\n } catch {\n return dataPayload;\n }\n if (!injectCopilotGeminiReasoningDetails(parsed)) return dataPayload;\n return JSON.stringify(parsed);\n}\n\n/** Rewrite one SSE line, preserving a trailing carriage return when present. */\nfunction rewriteSseLine(line: string): string {\n const hasCr = line.endsWith(\"\\r\");\n const core = hasCr ? line.slice(0, -1) : line;\n if (!core.startsWith(\"data:\")) return line;\n const payload = core.slice(\"data:\".length).trimStart();\n if (payload.length === 0 || payload === \"[DONE]\") return line;\n const rewritten = rewriteCopilotGeminiSseData(payload);\n if (rewritten === payload) return line;\n const rebuilt = `data: ${rewritten}`;\n return hasCr ? `${rebuilt}\\r` : rebuilt;\n}\n\n/**\n * Wrap a CAPI Gemini SSE byte stream so `reasoning_opaque` is bridged into\n * `reasoning_details`. Buffers across chunk boundaries and rewrites whole lines\n * only; bytes that are not affected pass through unchanged.\n *\n * Implemented as a `ReadableStream` over the source reader (rather than a\n * `TransformStream` piped via `pipeThrough`) so the transform pulls lazily and\n * propagates cancellation to the upstream body.\n */\nexport function createCopilotGeminiSseStream(\n source: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = source.getReader();\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let buffer = \"\";\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n // Loop until we emit at least one chunk or close, so a read that yields no\n // complete line still makes progress without relying on the runtime to\n // re-invoke pull after a no-enqueue return.\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n buffer += decoder.decode();\n if (buffer.length > 0) {\n controller.enqueue(encoder.encode(rewriteSseLine(buffer)));\n buffer = \"\";\n }\n controller.close();\n return;\n }\n buffer += decoder.decode(value, { stream: true });\n let newlineIndex = buffer.indexOf(\"\\n\");\n let out = \"\";\n while (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n out += `${rewriteSseLine(line)}\\n`;\n newlineIndex = buffer.indexOf(\"\\n\");\n }\n if (out.length > 0) {\n controller.enqueue(encoder.encode(out));\n return;\n }\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Convert the `reasoning_details` the pi-ai client re-emits on replayed\n * assistant messages back into the single `reasoning_opaque` field CAPI reads.\n *\n * For GitHub Copilot Gemini payloads, each assistant message that carries a\n * `reasoning_details` entry of `type: \"reasoning.encrypted\"` has its `data`\n * (the original CAPI thought-signature blob) promoted to `reasoning_opaque`,\n * and the now-redundant `reasoning_details` removed. No-op for every other\n * provider/model and for payloads without such messages.\n */\nexport function restoreCopilotGeminiReasoningOpaque(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload as JsonValue)) return payload;\n const payloadObject = payload as JsonObject;\n const messages = payloadObject.messages;\n if (!Array.isArray(messages)) return payload;\n\n let mutated = false;\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const details = message.reasoning_details;\n if (!Array.isArray(details) || details.length === 0) return message;\n const encrypted = details.find(\n (detail): detail is JsonObject =>\n isPlainObject(detail) &&\n detail.type === REASONING_ENCRYPTED_TYPE &&\n typeof detail.data === \"string\" &&\n detail.data.length > 0,\n );\n if (!encrypted) return message;\n mutated = true;\n const { reasoning_details: _omitted, ...rest } = message;\n return { ...rest, reasoning_opaque: encrypted.data as string };\n });\n\n if (!mutated) return payload;\n return { ...payloadObject, messages: nextMessages };\n}\n\n/** Whether the URL targets Copilot's CAPI gateway (`*.githubcopilot.com`). */\nfunction isCopilotApiHost(url: string): boolean {\n try {\n const host = new URL(url).hostname.toLowerCase();\n // Exact host or a real subdomain only — never a look-alike suffix such as\n // `notgithubcopilot.com` (CodeQL: incomplete URL substring sanitization).\n return host === \"githubcopilot.com\" || host.endsWith(\".githubcopilot.com\");\n } catch {\n return false;\n }\n}\n\n/** Resolve the request URL string from a `fetch` input argument. */\nfunction resolveRequestUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n const url = (input as { url?: unknown }).url;\n if (typeof url === \"string\") return url;\n }\n return undefined;\n}\n\n/**\n * Rewrite a streaming CAPI Gemini response so its SSE body bridges\n * `reasoning_opaque` into `reasoning_details`. Returns the original response\n * untouched for non-Copilot hosts, non-event-stream responses, or bodyless\n * responses, keeping the blast radius to streaming CAPI Gemini turns only.\n */\nexport function maybeRewriteCopilotGeminiResponse(\n url: string | undefined,\n response: Response,\n): Response {\n if (!url || !isCopilotApiHost(url)) return response;\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) return response;\n if (!response.body) return response;\n const transformed = createCopilotGeminiSseStream(response.body);\n return new Response(transformed, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\nlet originalFetch: typeof fetch | undefined;\n\n/**\n * Install a `globalThis.fetch` wrapper that rewrites CAPI Gemini SSE responses\n * to bridge `reasoning_opaque` into `reasoning_details` (see\n * {@link createCopilotGeminiSseStream}). Idempotent.\n *\n * The OpenAI SDK used by the `openai-completions` provider resolves\n * `globalThis.fetch` at client-construction time, and a new client is built per\n * request, so wrapping the global before the first request is reliably picked\n * up. Non-Copilot hosts and non-event-stream responses are returned untouched,\n * keeping the blast radius to streaming CAPI Gemini turns only.\n */\nexport function installCopilotGeminiReasoningInterceptor(): void {\n if (originalFetch) return;\n if (typeof globalThis.fetch !== \"function\") return;\n const base = globalThis.fetch;\n originalFetch = base;\n const boundFetch = base.bind(globalThis);\n\n const wrapped = (async (input, init) => {\n const response = await boundFetch(input, init);\n try {\n return maybeRewriteCopilotGeminiResponse(resolveRequestUrl(input), response);\n } catch {\n return response;\n }\n }) as typeof fetch;\n\n // Preserve `fetch.preconnect` so the wrapper remains a drop-in replacement.\n const preconnect = (base as { preconnect?: unknown }).preconnect;\n if (typeof preconnect === \"function\") {\n (wrapped as { preconnect?: unknown }).preconnect = preconnect.bind(globalThis);\n }\n\n globalThis.fetch = wrapped;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"copilot-gemini-reasoning.js","sourceRoot":"","sources":["../../src/core/copilot-gemini-reasoning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2CAA2C,EAAE,MAAM,mCAAmC,CAAC;AAChG,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAyD7E,gFAAgF;AAChF,MAAM,wBAAwB,GAAG,qBAAqB,CAAC;AAEvD,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;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AAG,MAAM,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC;YACH,OAAO,mCAAmC,CAAC,iBAAiB,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,CAAC;QACjF,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,QAAQ,CAAC;QAClB,CAAC;IACH,CAAC,CAAiB,CAAC;IAEnB,4EAA4E;IAC5E,MAAM,UAAU,GAAI,IAAiC,CAAC,UAAU,CAAC;IACjE,IAAI,OAAO,UAAU,KAAK,UAAU,EAAE,CAAC;QACpC,OAAoC,CAAC,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACjF,CAAC;IAED,UAAU,CAAC,KAAK,GAAG,OAAO,CAAC;AAC7B,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,wCAAwC;IACtD,iCAAiC,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { maybeRepairCopilotAnthropicMessagesResponse } from \"./copilot-anthropic-sse-repair.ts\";\nimport { isCopilotApiHost } from \"./copilot-hosts.ts\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\n\n/**\n * Round-trips GitHub Copilot Gemini \"thought signatures\" so multi-turn tool use\n * does not silently die after the first tool call.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models (e.g. `gemini-3.1-pro-preview`) are served\n * through Copilot's CAPI gateway, which proxies to Google's GenAI API. Gemini\n * is a thinking model: when it emits a function/tool call it also returns an\n * opaque **thought signature** that must be sent back, verbatim, on the next\n * request or Gemini refuses to continue the reasoning chain.\n *\n * CAPI carries that signature in a non-standard OpenAI-completions field named\n * **`reasoning_opaque`** (an encrypted blob) on the assistant message / streamed\n * delta, and on replay it reads the same `reasoning_opaque` back off the\n * assistant message and re-attaches the signature to each Gemini function-call\n * part (keyed by `tool_call.id`). The underlying OpenAI-completions client\n * (`@earendil-works/pi-ai`) does not understand `reasoning_opaque`; it captures\n * thought signatures only from the OpenRouter-style\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data }]` shape, which\n * CAPI never emits. So the real Gemini thought signature was being dropped on\n * the way in and never replayed on the way out.\n *\n * With the signature missing, CAPI substitutes the sentinel\n * `skip_thought_signature_validator` on the first replayed function call, and\n * Gemini responds with an empty candidate / `finish_reason: \"stop\"` and zero\n * output tokens — the harness sees a degenerate empty completion, retries with\n * the same signature-less history, and eventually gives up: \"Gemini just stops\n * responding.\"\n *\n * What this does\n * --------------\n * Two gated, self-contained transforms bridge CAPI's `reasoning_opaque` to the\n * `reasoning_details` mechanism the client already round-trips:\n *\n * - **Inbound** ({@link rewriteCopilotGeminiSseData} via\n * {@link createCopilotGeminiSseStream}): rewrites the CAPI Gemini SSE\n * stream so each streamed delta that carries both `reasoning_opaque` and a\n * `tool_calls[].id` gains a\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data: <opaque> }]`\n * entry. The client then stores it as the tool call's `thoughtSignature`.\n * CAPI confirms `reasoning_opaque` rides on the same streamed delta as the\n * first (id-bearing) tool-call chunk, so the association is exact.\n * - **Outbound** ({@link restoreCopilotGeminiReasoningOpaque} from the\n * `onPayload` hook): converts the `reasoning_details` the client re-emits on\n * replayed assistant messages back into a single `reasoning_opaque` field on\n * that assistant message, which is the only shape CAPI reads.\n *\n * Both transforms are gated to GitHub Copilot Gemini and are no-ops for every\n * other provider/model (and for Gemini turns that carry no thought signature).\n */\n\ntype JsonObject = { [key: string]: JsonValue };\ntype JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\n/** OpenRouter-style encrypted reasoning detail the pi-ai client round-trips. */\nconst REASONING_ENCRYPTED_TYPE = \"reasoning.encrypted\";\n\nfunction isPlainObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Inject `reasoning_details` into a parsed CAPI Gemini streaming chunk so the\n * pi-ai OpenAI-completions parser captures the Gemini thought signature.\n *\n * For each `choices[].delta` that carries a non-empty `reasoning_opaque` string\n * and a `tool_calls[]` entry with an `id`, adds a single\n * `reasoning_details: [{ type: \"reasoning.encrypted\", id, data: <opaque> }]`\n * entry keyed by that tool-call id. Returns whether the chunk was mutated.\n *\n * No-op when the delta already has `reasoning_details`, has no id-bearing tool\n * call (e.g. argument-continuation deltas or pure-text thought chunks), or has\n * no `reasoning_opaque`.\n */\nexport function injectCopilotGeminiReasoningDetails(chunk: JsonValue): boolean {\n if (!isPlainObject(chunk)) return false;\n const choices = chunk.choices;\n if (!Array.isArray(choices)) return false;\n\n let mutated = false;\n for (const choice of choices) {\n if (!isPlainObject(choice)) continue;\n const delta = choice.delta;\n if (!isPlainObject(delta)) continue;\n\n const opaque = delta.reasoning_opaque;\n if (typeof opaque !== \"string\" || opaque.length === 0) continue;\n\n // Already carries the encrypted detail (don't double-inject / clobber).\n if (Array.isArray(delta.reasoning_details) && delta.reasoning_details.length > 0) {\n continue;\n }\n\n const toolCalls = delta.tool_calls;\n if (!Array.isArray(toolCalls)) continue;\n const idBearing = toolCalls.find(\n (call): call is JsonObject =>\n isPlainObject(call) && typeof call.id === \"string\" && call.id.length > 0,\n );\n if (!idBearing) continue;\n\n delta.reasoning_details = [\n { type: REASONING_ENCRYPTED_TYPE, id: idBearing.id as string, data: opaque },\n ];\n mutated = true;\n }\n return mutated;\n}\n\n/**\n * Rewrite the JSON payload of a single SSE `data:` line. Returns the original\n * string unchanged when it is not a Gemini chunk that needs a thought signature\n * bridged, or when parsing fails (fail-open: never corrupt the stream).\n */\nexport function rewriteCopilotGeminiSseData(dataPayload: string): string {\n // Cheap gate: only chunks that actually carry a thought signature are touched.\n if (!dataPayload.includes(\"reasoning_opaque\")) return dataPayload;\n let parsed: JsonValue;\n try {\n parsed = JSON.parse(dataPayload) as JsonValue;\n } catch {\n return dataPayload;\n }\n if (!injectCopilotGeminiReasoningDetails(parsed)) return dataPayload;\n return JSON.stringify(parsed);\n}\n\n/** Rewrite one SSE line, preserving a trailing carriage return when present. */\nfunction rewriteSseLine(line: string): string {\n const hasCr = line.endsWith(\"\\r\");\n const core = hasCr ? line.slice(0, -1) : line;\n if (!core.startsWith(\"data:\")) return line;\n const payload = core.slice(\"data:\".length).trimStart();\n if (payload.length === 0 || payload === \"[DONE]\") return line;\n const rewritten = rewriteCopilotGeminiSseData(payload);\n if (rewritten === payload) return line;\n const rebuilt = `data: ${rewritten}`;\n return hasCr ? `${rebuilt}\\r` : rebuilt;\n}\n\n/**\n * Wrap a CAPI Gemini SSE byte stream so `reasoning_opaque` is bridged into\n * `reasoning_details`. Buffers across chunk boundaries and rewrites whole lines\n * only; bytes that are not affected pass through unchanged.\n *\n * Implemented as a `ReadableStream` over the source reader (rather than a\n * `TransformStream` piped via `pipeThrough`) so the transform pulls lazily and\n * propagates cancellation to the upstream body.\n */\nexport function createCopilotGeminiSseStream(\n source: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = source.getReader();\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let buffer = \"\";\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n // Loop until we emit at least one chunk or close, so a read that yields no\n // complete line still makes progress without relying on the runtime to\n // re-invoke pull after a no-enqueue return.\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n buffer += decoder.decode();\n if (buffer.length > 0) {\n controller.enqueue(encoder.encode(rewriteSseLine(buffer)));\n buffer = \"\";\n }\n controller.close();\n return;\n }\n buffer += decoder.decode(value, { stream: true });\n let newlineIndex = buffer.indexOf(\"\\n\");\n let out = \"\";\n while (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n out += `${rewriteSseLine(line)}\\n`;\n newlineIndex = buffer.indexOf(\"\\n\");\n }\n if (out.length > 0) {\n controller.enqueue(encoder.encode(out));\n return;\n }\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Convert the `reasoning_details` the pi-ai client re-emits on replayed\n * assistant messages back into the single `reasoning_opaque` field CAPI reads.\n *\n * For GitHub Copilot Gemini payloads, each assistant message that carries a\n * `reasoning_details` entry of `type: \"reasoning.encrypted\"` has its `data`\n * (the original CAPI thought-signature blob) promoted to `reasoning_opaque`,\n * and the now-redundant `reasoning_details` removed. No-op for every other\n * provider/model and for payloads without such messages.\n */\nexport function restoreCopilotGeminiReasoningOpaque(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload as JsonValue)) return payload;\n const payloadObject = payload as JsonObject;\n const messages = payloadObject.messages;\n if (!Array.isArray(messages)) return payload;\n\n let mutated = false;\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const details = message.reasoning_details;\n if (!Array.isArray(details) || details.length === 0) return message;\n const encrypted = details.find(\n (detail): detail is JsonObject =>\n isPlainObject(detail) &&\n detail.type === REASONING_ENCRYPTED_TYPE &&\n typeof detail.data === \"string\" &&\n detail.data.length > 0,\n );\n if (!encrypted) return message;\n mutated = true;\n const { reasoning_details: _omitted, ...rest } = message;\n return { ...rest, reasoning_opaque: encrypted.data as string };\n });\n\n if (!mutated) return payload;\n return { ...payloadObject, messages: nextMessages };\n}\n\n/** Resolve the request URL string from a `fetch` input argument. */\nfunction resolveRequestUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n const url = (input as { url?: unknown }).url;\n if (typeof url === \"string\") return url;\n }\n return undefined;\n}\n\n/**\n * Rewrite a streaming CAPI Gemini response so its SSE body bridges\n * `reasoning_opaque` into `reasoning_details`. Returns the original response\n * untouched for non-Copilot hosts, non-event-stream responses, or bodyless\n * responses, keeping the blast radius to streaming CAPI Gemini turns only.\n */\nexport function maybeRewriteCopilotGeminiResponse(\n url: string | undefined,\n response: Response,\n): Response {\n if (!url || !isCopilotApiHost(url)) return response;\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) return response;\n if (!response.body) return response;\n const transformed = createCopilotGeminiSseStream(response.body);\n return new Response(transformed, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\n/**\n * Apply Copilot response-body transforms before pi-ai parses streamed provider\n * output. Anthropic Messages repair gets first refusal for `/v1/messages`\n * streams; other Copilot event streams keep the existing Gemini reasoning bridge.\n */\nexport function maybeRewriteCopilotProviderResponse(\n url: string | undefined,\n response: Response,\n): Response {\n const anthropicRepaired = maybeRepairCopilotAnthropicMessagesResponse(url, response);\n if (anthropicRepaired !== response) return anthropicRepaired;\n return maybeRewriteCopilotGeminiResponse(url, response);\n}\n\nlet originalFetch: typeof fetch | undefined;\n\n/**\n * Install a `globalThis.fetch` wrapper that applies Copilot-only stream\n * compatibility shims before pi-ai parses provider output. Currently this\n * includes the Gemini `reasoning_opaque` bridge and the Anthropic Messages\n * terminal `message_stop` repair. Idempotent.\n *\n * SDK clients resolve `globalThis.fetch` at client-construction time, and a new\n * client is built per request, so wrapping the global before the first request\n * is reliably picked up. Non-Copilot hosts and non-event-stream responses are\n * returned untouched by the underlying shims.\n */\nexport function installCopilotResponseInterceptor(): void {\n if (originalFetch) return;\n if (typeof globalThis.fetch !== \"function\") return;\n const base = globalThis.fetch;\n originalFetch = base;\n const boundFetch = base.bind(globalThis);\n\n const wrapped = (async (input, init) => {\n const response = await boundFetch(input, init);\n try {\n return maybeRewriteCopilotProviderResponse(resolveRequestUrl(input), response);\n } catch {\n return response;\n }\n }) as typeof fetch;\n\n // Preserve `fetch.preconnect` so the wrapper remains a drop-in replacement.\n const preconnect = (base as { preconnect?: unknown }).preconnect;\n if (typeof preconnect === \"function\") {\n (wrapped as { preconnect?: unknown }).preconnect = preconnect.bind(globalThis);\n }\n\n globalThis.fetch = wrapped;\n}\n\n/** Backward-compatible name for the original Gemini-only interceptor export. */\nexport function installCopilotGeminiReasoningInterceptor(): void {\n installCopilotResponseInterceptor();\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Shared strict host predicates for GitHub Copilot CAPI endpoints. */
|
|
2
|
+
/**
|
|
3
|
+
* Whether the URL targets a GitHub Copilot CAPI gateway.
|
|
4
|
+
*
|
|
5
|
+
* Accepts the public/enterprise githubcopilot.com gateway family and the GHE
|
|
6
|
+
* tenant routing shape Atomic derives from *.ghe.com server URLs:
|
|
7
|
+
* copilot-api.<enterprise>.ghe.com. The suffix checks are label-aware so
|
|
8
|
+
* look-alikes such as githubcopilot.com.evil.test or
|
|
9
|
+
* copilot-api.company.ghe.com.evil.test are rejected.
|
|
10
|
+
*/
|
|
11
|
+
export declare function isCopilotApiHost(url: URL | string): boolean;
|
|
12
|
+
//# sourceMappingURL=copilot-hosts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-hosts.d.ts","sourceRoot":"","sources":["../../src/core/copilot-hosts.ts"],"names":[],"mappings":"AAAA,uEAAuE;AAWvE;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,OAAO,CAa3D","sourcesContent":["/** Shared strict host predicates for GitHub Copilot CAPI endpoints. */\n\nconst GITHUB_COPILOT_HOST = \"githubcopilot.com\";\nconst GHE_COPILOT_API_HOST_PREFIX = \"copilot-api.\";\nconst GHE_HOST_SUFFIX = \".ghe.com\";\nconst DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction hasValidDnsLabels(hostFragment: string): boolean {\n return hostFragment.split(\".\").every((label) => DNS_LABEL_PATTERN.test(label));\n}\n\n/**\n * Whether the URL targets a GitHub Copilot CAPI gateway.\n *\n * Accepts the public/enterprise githubcopilot.com gateway family and the GHE\n * tenant routing shape Atomic derives from *.ghe.com server URLs:\n * copilot-api.<enterprise>.ghe.com. The suffix checks are label-aware so\n * look-alikes such as githubcopilot.com.evil.test or\n * copilot-api.company.ghe.com.evil.test are rejected.\n */\nexport function isCopilotApiHost(url: URL | string): boolean {\n let host: string;\n try {\n host = (typeof url === \"string\" ? new URL(url).hostname : url.hostname).toLowerCase();\n } catch {\n return false;\n }\n\n if (host === GITHUB_COPILOT_HOST || host.endsWith(`.${GITHUB_COPILOT_HOST}`)) return true;\n if (!host.startsWith(GHE_COPILOT_API_HOST_PREFIX) || !host.endsWith(GHE_HOST_SUFFIX)) return false;\n\n const enterpriseHost = host.slice(GHE_COPILOT_API_HOST_PREFIX.length, -GHE_HOST_SUFFIX.length);\n return enterpriseHost.length > 0 && hasValidDnsLabels(enterpriseHost);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Shared strict host predicates for GitHub Copilot CAPI endpoints. */
|
|
2
|
+
const GITHUB_COPILOT_HOST = "githubcopilot.com";
|
|
3
|
+
const GHE_COPILOT_API_HOST_PREFIX = "copilot-api.";
|
|
4
|
+
const GHE_HOST_SUFFIX = ".ghe.com";
|
|
5
|
+
const DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
6
|
+
function hasValidDnsLabels(hostFragment) {
|
|
7
|
+
return hostFragment.split(".").every((label) => DNS_LABEL_PATTERN.test(label));
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Whether the URL targets a GitHub Copilot CAPI gateway.
|
|
11
|
+
*
|
|
12
|
+
* Accepts the public/enterprise githubcopilot.com gateway family and the GHE
|
|
13
|
+
* tenant routing shape Atomic derives from *.ghe.com server URLs:
|
|
14
|
+
* copilot-api.<enterprise>.ghe.com. The suffix checks are label-aware so
|
|
15
|
+
* look-alikes such as githubcopilot.com.evil.test or
|
|
16
|
+
* copilot-api.company.ghe.com.evil.test are rejected.
|
|
17
|
+
*/
|
|
18
|
+
export function isCopilotApiHost(url) {
|
|
19
|
+
let host;
|
|
20
|
+
try {
|
|
21
|
+
host = (typeof url === "string" ? new URL(url).hostname : url.hostname).toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
if (host === GITHUB_COPILOT_HOST || host.endsWith(`.${GITHUB_COPILOT_HOST}`))
|
|
27
|
+
return true;
|
|
28
|
+
if (!host.startsWith(GHE_COPILOT_API_HOST_PREFIX) || !host.endsWith(GHE_HOST_SUFFIX))
|
|
29
|
+
return false;
|
|
30
|
+
const enterpriseHost = host.slice(GHE_COPILOT_API_HOST_PREFIX.length, -GHE_HOST_SUFFIX.length);
|
|
31
|
+
return enterpriseHost.length > 0 && hasValidDnsLabels(enterpriseHost);
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=copilot-hosts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-hosts.js","sourceRoot":"","sources":["../../src/core/copilot-hosts.ts"],"names":[],"mappings":"AAAA,uEAAuE;AAEvE,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAChD,MAAM,2BAA2B,GAAG,cAAc,CAAC;AACnD,MAAM,eAAe,GAAG,UAAU,CAAC;AACnC,MAAM,iBAAiB,GAAG,wCAAwC,CAAC;AAEnE,SAAS,iBAAiB,CAAC,YAAoB;IAC7C,OAAO,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AACjF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAiB;IAChD,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;IACxF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,KAAK,mBAAmB,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,mBAAmB,EAAE,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1F,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;QAAE,OAAO,KAAK,CAAC;IAEnG,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,MAAM,EAAE,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAC/F,OAAO,cAAc,CAAC,MAAM,GAAG,CAAC,IAAI,iBAAiB,CAAC,cAAc,CAAC,CAAC;AACxE,CAAC","sourcesContent":["/** Shared strict host predicates for GitHub Copilot CAPI endpoints. */\n\nconst GITHUB_COPILOT_HOST = \"githubcopilot.com\";\nconst GHE_COPILOT_API_HOST_PREFIX = \"copilot-api.\";\nconst GHE_HOST_SUFFIX = \".ghe.com\";\nconst DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction hasValidDnsLabels(hostFragment: string): boolean {\n return hostFragment.split(\".\").every((label) => DNS_LABEL_PATTERN.test(label));\n}\n\n/**\n * Whether the URL targets a GitHub Copilot CAPI gateway.\n *\n * Accepts the public/enterprise githubcopilot.com gateway family and the GHE\n * tenant routing shape Atomic derives from *.ghe.com server URLs:\n * copilot-api.<enterprise>.ghe.com. The suffix checks are label-aware so\n * look-alikes such as githubcopilot.com.evil.test or\n * copilot-api.company.ghe.com.evil.test are rejected.\n */\nexport function isCopilotApiHost(url: URL | string): boolean {\n let host: string;\n try {\n host = (typeof url === \"string\" ? new URL(url).hostname : url.hostname).toLowerCase();\n } catch {\n return false;\n }\n\n if (host === GITHUB_COPILOT_HOST || host.endsWith(`.${GITHUB_COPILOT_HOST}`)) return true;\n if (!host.startsWith(GHE_COPILOT_API_HOST_PREFIX) || !host.endsWith(GHE_HOST_SUFFIX)) return false;\n\n const enterpriseHost = host.slice(GHE_COPILOT_API_HOST_PREFIX.length, -GHE_HOST_SUFFIX.length);\n return enterpriseHost.length > 0 && hasValidDnsLabels(enterpriseHost);\n}\n"]}
|
|
@@ -92,7 +92,7 @@ export interface ToolExecutionEndEvent {
|
|
|
92
92
|
result: unknown;
|
|
93
93
|
isError: boolean;
|
|
94
94
|
}
|
|
95
|
-
export type ModelSelectSource = "set" | "cycle" | "restore";
|
|
95
|
+
export type ModelSelectSource = "set" | "cycle" | "restore" | "fallback";
|
|
96
96
|
/** Fired when a new model is selected */
|
|
97
97
|
export interface ModelSelectEvent {
|
|
98
98
|
type: "model_select";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-events.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAqB,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMxD,uDAAuD;AACvD,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,YAAY,EAAE,CAAC;CACzB;AAED,wEAAwE;AACxE,MAAM,WAAW,0BAA0B;IAC1C,IAAI,EAAE,yBAAyB,CAAC;IAChC,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,8FAA8F;AAC9F,MAAM,WAAW,0BAA0B;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AA;CAAE,CAAC","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
|
|
1
|
+
{"version":3,"file":"agent-events.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAqB,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMxD,uDAAuD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E,OAAO,GAAG,UAAU,CAAC;CACzC;AAED,sCAAsC;AACtC,MAAM,MAAM,gBAAgB,GACzB;IAAE,MAAM,EAAE,UAAU,CAAA;CAAE,GACtB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,GAC9D;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,CAAC","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-events.js","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
|
|
1
|
+
{"version":3,"file":"agent-events.js","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import type { ExtensionFactory } from "./types.ts";
|
|
2
2
|
declare function loadVirtualModules(): Promise<Record<string, object>>;
|
|
3
|
+
/**
|
|
4
|
+
* Persistent on-disk cache for jiti-transpiled extension modules.
|
|
5
|
+
* jiti keys cache entries by source-content hash, so entries self-invalidate
|
|
6
|
+
* when extension sources change; stale sibling version dirs are pruned
|
|
7
|
+
* in the background.
|
|
8
|
+
*/
|
|
9
|
+
declare function getTranspileCacheDir(): string;
|
|
3
10
|
export interface ExtensionCacheToken {
|
|
4
11
|
cwd: string;
|
|
5
12
|
generation: number;
|
|
@@ -21,11 +28,11 @@ declare function findPackageRoot(packageName: string, searchPaths?: string[]): s
|
|
|
21
28
|
* In Bun binary mode, virtualModules is used instead.
|
|
22
29
|
*/
|
|
23
30
|
declare function getAliases(): Record<string, string>;
|
|
24
|
-
/** Internal hooks for extension-loader alias regression tests. */
|
|
25
31
|
export declare const extensionLoaderTestHooks: {
|
|
26
32
|
loadVirtualModules: typeof loadVirtualModules;
|
|
27
33
|
getAliases: typeof getAliases;
|
|
28
34
|
findPackageRoot: typeof findPackageRoot;
|
|
35
|
+
getTranspileCacheDir: typeof getTranspileCacheDir;
|
|
29
36
|
};
|
|
30
37
|
export declare function loadExtensionModule(extensionPath: string, cacheToken?: ExtensionCacheToken): Promise<ExtensionFactory | undefined>;
|
|
31
38
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAMnD,iBAAe,kBAAkB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAqCnE;AAoDD,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAOrE;AAiBD;;;;;;;;GAQG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAQ5E;AAMD;;;GAGG;AACH,iBAAS,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoD5C;AAED,kEAAkE;AAClE,eAAO,MAAM,wBAAwB;;;;CAIpC,CAAC;AAUF,wBAAsB,mBAAmB,CACvC,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,mBAAmB,GAC/B,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAmCvC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAMnD,iBAAe,kBAAkB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAqCnE;AAoBD;;;;;GAKG;AACH,iBAAS,oBAAoB,IAAI,MAAM,CAMtC;AAqBD,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAOrE;AAiBD;;;;;;;;GAQG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAQ5E;AAMD;;;GAGG;AACH,iBAAS,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoD5C;AAED,eAAO,MAAM,wBAAwB;;;;;CAKpC,CAAC;AAUF,wBAAsB,mBAAmB,CACvC,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,mBAAmB,GAC/B,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAmCvC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n fs.mkdirSync(_transpileCacheDir, { recursive: true });\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n getTranspileCacheDir,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
@@ -72,6 +72,7 @@ function getTranspileCacheDir() {
|
|
|
72
72
|
if (_transpileCacheDir)
|
|
73
73
|
return _transpileCacheDir;
|
|
74
74
|
_transpileCacheDir = getExtensionTranspileCacheDir();
|
|
75
|
+
fs.mkdirSync(_transpileCacheDir, { recursive: true });
|
|
75
76
|
pruneStaleTranspileCaches(_transpileCacheDir);
|
|
76
77
|
return _transpileCacheDir;
|
|
77
78
|
}
|
|
@@ -185,11 +186,11 @@ function getAliases() {
|
|
|
185
186
|
};
|
|
186
187
|
return _aliases;
|
|
187
188
|
}
|
|
188
|
-
/** Internal hooks for extension-loader alias regression tests. */
|
|
189
189
|
export const extensionLoaderTestHooks = {
|
|
190
190
|
loadVirtualModules,
|
|
191
191
|
getAliases,
|
|
192
192
|
findPackageRoot,
|
|
193
|
+
getTranspileCacheDir,
|
|
193
194
|
};
|
|
194
195
|
/**
|
|
195
196
|
* Extension paths already evaluated via native import() in this process. Bun on
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-virtual-modules.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,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EAAE,KAAK,EAAE;YACvD,CAAC,CAAC,SAAS;gBACT,CAAC,CAAC,EAAE,OAAO,EAAE,oBAAoB,EAAE,EAAE;gBACrC,CAAC,CAAC,EAAE,CAAC;QACT,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;KACjG,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,aAAa,EAAE,UAAU,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACzG,IAAI,SAAS,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC1C,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,OAAO,GAAG,MAA0B,CAAC;IAC3C,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IACpD,IAAI,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACpC,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader-virtual-modules.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,E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EAAE,CAAC;QACT,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;KACjG,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,aAAa,EAAE,UAAU,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACzG,IAAI,SAAS,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC1C,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,OAAO,GAAG,MAA0B,CAAC;IAC3C,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IACpD,IAAI,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACpC,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n fs.mkdirSync(_transpileCacheDir, { recursive: true });\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n getTranspileCacheDir,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
@@ -23,7 +23,10 @@ export declare class FooterDataProvider {
|
|
|
23
23
|
private refreshInFlight;
|
|
24
24
|
private refreshPending;
|
|
25
25
|
private disposed;
|
|
26
|
+
private gitWatchersStarted;
|
|
26
27
|
constructor(cwd: string);
|
|
28
|
+
/** Start post-frame git branch watching. Branch discovery remains lazy for first render. */
|
|
29
|
+
startGitWatcher(): void;
|
|
27
30
|
/** Current git branch, null if not in repo, "detached" if detached HEAD */
|
|
28
31
|
getGitBranch(): string | null;
|
|
29
32
|
/** Extension status texts set via ctx.ui.setStatus() */
|
|
@@ -41,12 +44,15 @@ export declare class FooterDataProvider {
|
|
|
41
44
|
setCwd(cwd: string): void;
|
|
42
45
|
/** Internal: cleanup */
|
|
43
46
|
dispose(): void;
|
|
47
|
+
private ensureGitPaths;
|
|
44
48
|
private notifyBranchChange;
|
|
45
49
|
private scheduleRefresh;
|
|
46
50
|
private refreshGitBranchAsync;
|
|
47
51
|
private resolveGitBranchSync;
|
|
48
52
|
private resolveGitBranchAsync;
|
|
49
53
|
private clearGitWatchers;
|
|
54
|
+
private installHeadPollingFallback;
|
|
55
|
+
private installReftableTablesListPolling;
|
|
50
56
|
private scheduleGitWatcherRetry;
|
|
51
57
|
private handleGitWatcherError;
|
|
52
58
|
private readReftableTablesListFingerprint;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"footer-data-provider.d.ts","sourceRoot":"","sources":["../../src/core/footer-data-provider.ts"],"names":[],"mappings":"AAiGA;;;GAGG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAO;IAEhD,OAAO,CAAC,iBAAiB,CAA6B;IACtD,OAAO,CAAC,YAAY,CAAwC;IAC5D,OAAO,CAAC,QAAQ,CAA0C;IAC1D,OAAO,CAAC,WAAW,CAA0B;IAC7C,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,qBAAqB,CAA4D;IACzF,OAAO,CAAC,eAAe,CAA0B;IACjD,OAAO,CAAC,yBAAyB,CAA0B;IAC3D,OAAO,CAAC,sBAAsB,CAAuB;IACrD,OAAO,CAAC,6BAA6B,CAAuB;IAC5D,OAAO,CAAC,mCAAmC,CAA4D;IACvG,OAAO,CAAC,qBAAqB,CAAyB;IACtD,OAAO,CAAC,sBAAsB,CAAK;IACnC,OAAO,CAAC,YAAY,CAA8C;IAClE,OAAO,CAAC,oBAAoB,CAA8C;IAC1E,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,GAAG,EAAE,MAAM,EAItB;IAED,2EAA2E;IAC3E,YAAY,IAAI,MAAM,GAAG,IAAI,CAK5B;IAED,wDAAwD;IACxD,oBAAoB,IAAI,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAElD;IAED,qEAAqE;IACrE,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAG/C;IAED,qCAAqC;IACrC,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAM9D;IAED,yCAAyC;IACzC,sBAAsB,IAAI,IAAI,CAE7B;IAED,4EAA4E;IAC5E,yBAAyB,IAAI,MAAM,CAElC;IAED,gDAAgD;IAChD,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE7C;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAexB;IAED,wBAAwB;IACxB,OAAO,IAAI,IAAI,CAQd;IAED,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,eAAe;YAYT,qBAAqB;IA0BnC,OAAO,CAAC,oBAAoB;YAcd,qBAAqB;IAgBnC,OAAO,CAAC,gBAAgB;IAwBxB,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,iCAAiC;IAczC,OAAO,CAAC,uBAAuB;IAU/B,OAAO,CAAC,4BAA4B;IASpC,OAAO,CAAC,eAAe;CAyEvB;AAED,yGAAyG;AACzG,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC5C,kBAAkB,EAClB,cAAc,GAAG,sBAAsB,GAAG,2BAA2B,GAAG,gBAAgB,CACxF,CAAC","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\nimport { createGitEnvironment } from \"../utils/git-env.ts\";\n\ntype GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nfunction findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tenv: createGitEnvironment(),\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise<string | null> {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tenv: createGitEnvironment(),\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map<string, string>();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate reftableTablesListFingerprint: string | null = null;\n\tprivate reftableTablesListWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap<string, string> {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise<string | null> {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath && this.reftableTablesListWatchFileListener) {\n\t\t\tunwatchFile(this.reftableTablesListPath, this.reftableTablesListWatchFileListener);\n\t\t}\n\t\tthis.reftableTablesListPath = null;\n\t\tthis.reftableTablesListFingerprint = null;\n\t\tthis.reftableTablesListWatchFileListener = null;\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate readReftableTablesListFingerprint(): string | null {\n\t\tif (!this.reftableTablesListPath || !existsSync(this.reftableTablesListPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stat = statSync(this.reftableTablesListPath);\n\t\t\tconst content = readFileSync(this.reftableTablesListPath, \"utf8\");\n\t\t\treturn `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${content}`;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate scheduleReftableRefresh(): void {\n\t\tconst fingerprint = this.readReftableTablesListFingerprint();\n\t\tif (fingerprint !== null && fingerprint === this.reftableTablesListFingerprint) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.reftableTablesListFingerprint = fingerprint;\n\t\tthis.scheduleRefresh();\n\t}\n\n\tprivate handleReftableDirectoryEvent(filename: string | Buffer | null): void {\n\t\tif (filename === \"tables.list\") {\n\t\t\tthis.scheduleReftableRefresh();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleRefresh();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tif (!this.gitPaths) return;\n\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.handleGitWatcherError(),\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\t\tif (current.mtimeMs !== previous.mtimeMs || current.ctimeMs !== previous.ctimeMs || current.size !== previous.size) {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t};\n\t\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t\t}\n\t\tif (!this.headWatcher && !pollGitHead) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableTablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tthis.reftableTablesListFingerprint = this.readReftableTablesListFingerprint();\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t(_eventType, filename) => {\n\t\t\t\t\tthis.handleReftableDirectoryEvent(filename);\n\t\t\t\t},\n\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t);\n\t\t\tif (!this.reftableWatcher) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tablesListPath = this.reftableTablesListPath;\n\t\t\tif (tablesListPath && existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleReftableRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t\t);\n\t\t\t\tif (!this.reftableTablesListWatcher) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.reftableTablesListWatchFileListener = (current, previous) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.scheduleReftableRefresh();\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\twatchFile(tablesListPath, { interval: 250 }, this.reftableTablesListWatchFileListener);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\"\n>;\n"]}
|
|
1
|
+
{"version":3,"file":"footer-data-provider.d.ts","sourceRoot":"","sources":["../../src/core/footer-data-provider.ts"],"names":[],"mappings":"AAiGA;;;GAGG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAO;IAEhD,OAAO,CAAC,iBAAiB,CAA6B;IACtD,OAAO,CAAC,YAAY,CAAwC;IAC5D,OAAO,CAAC,QAAQ,CAA0C;IAC1D,OAAO,CAAC,WAAW,CAA0B;IAC7C,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,qBAAqB,CAA4D;IACzF,OAAO,CAAC,eAAe,CAA0B;IACjD,OAAO,CAAC,yBAAyB,CAA0B;IAC3D,OAAO,CAAC,sBAAsB,CAAuB;IACrD,OAAO,CAAC,6BAA6B,CAAuB;IAC5D,OAAO,CAAC,mCAAmC,CAA4D;IACv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O,CAAC,uBAAuB;IAU/B,OAAO,CAAC,4BAA4B;IASpC,OAAO,CAAC,eAAe;CAqEvB;AAED,yGAAyG;AACzG,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC5C,kBAAkB,EAClB,cAAc,GAAG,sBAAsB,GAAG,2BAA2B,GAAG,gBAAgB,CACxF,CAAC","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, isSafeFsWatchPathError, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\nimport { createGitEnvironment } from \"../utils/git-env.ts\";\n\ntype GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nfunction findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tenv: createGitEnvironment(),\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise<string | null> {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tenv: createGitEnvironment(),\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map<string, string>();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate reftableTablesListFingerprint: string | null = null;\n\tprivate reftableTablesListWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\tprivate gitWatchersStarted = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t}\n\n\t/** Start post-frame git branch watching. Branch discovery remains lazy for first render. */\n\tstartGitWatcher(): void {\n\t\tif (this.disposed || this.gitWatchersStarted) return;\n\t\tthis.gitWatchersStarted = true;\n\t\tthis.ensureGitPaths();\n\t\tthis.setupGitWatcher();\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.ensureGitPaths();\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap<string, string> {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst restartGitWatcher = this.gitWatchersStarted;\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = undefined;\n\t\tif (restartGitWatcher) {\n\t\t\tthis.gitWatchersStarted = false;\n\t\t\tthis.startGitWatcher();\n\t\t}\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.gitWatchersStarted = false;\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate ensureGitPaths(): void {\n\t\tif (this.gitPaths !== undefined) return;\n\t\tthis.gitPaths = findGitPaths(this.cwd);\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise<string | null> {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath && this.reftableTablesListWatchFileListener) {\n\t\t\tunwatchFile(this.reftableTablesListPath, this.reftableTablesListWatchFileListener);\n\t\t}\n\t\tthis.reftableTablesListPath = null;\n\t\tthis.reftableTablesListFingerprint = null;\n\t\tthis.reftableTablesListWatchFileListener = null;\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\n\tprivate installHeadPollingFallback(): void {\n\t\tif (!this.gitPaths || this.headWatchFilePath || this.headWatchFileListener) {\n\t\t\treturn;\n\t\t}\n\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\tif (current.mtimeMs !== previous.mtimeMs || current.ctimeMs !== previous.ctimeMs || current.size !== previous.size) {\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t};\n\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t}\n\n\tprivate installReftableTablesListPolling(tablesListPath: string): void {\n\t\tif (this.reftableTablesListWatchFileListener) {\n\t\t\treturn;\n\t\t}\n\t\tthis.reftableTablesListWatchFileListener = (current, previous) => {\n\t\t\tif (\n\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\tcurrent.size !== previous.size\n\t\t\t) {\n\t\t\t\tthis.scheduleReftableRefresh();\n\t\t\t}\n\t\t};\n\t\twatchFile(tablesListPath, { interval: 250 }, this.reftableTablesListWatchFileListener);\n\t}\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || !this.gitWatchersStarted || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.ensureGitPaths();\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate readReftableTablesListFingerprint(): string | null {\n\t\tif (!this.reftableTablesListPath || !existsSync(this.reftableTablesListPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stat = statSync(this.reftableTablesListPath);\n\t\t\tconst content = readFileSync(this.reftableTablesListPath, \"utf8\");\n\t\t\treturn `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${content}`;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate scheduleReftableRefresh(): void {\n\t\tconst fingerprint = this.readReftableTablesListFingerprint();\n\t\tif (fingerprint !== null && fingerprint === this.reftableTablesListFingerprint) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.reftableTablesListFingerprint = fingerprint;\n\t\tthis.scheduleRefresh();\n\t}\n\n\tprivate handleReftableDirectoryEvent(filename: string | Buffer | null): void {\n\t\tif (filename === \"tables.list\") {\n\t\t\tthis.scheduleReftableRefresh();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleRefresh();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.ensureGitPaths();\n\t\tif (!this.gitPaths) return;\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (isSafeFsWatchPathError(error)) {\n\t\t\t\t\tthis.installHeadPollingFallback();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.handleGitWatcherError();\n\t\t\t},\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.installHeadPollingFallback();\n\t\t}\n\t\tif (!this.headWatcher && !this.headWatchFileListener) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableTablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tthis.reftableTablesListFingerprint = this.readReftableTablesListFingerprint();\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t(_eventType, filename) => {\n\t\t\t\t\tthis.handleReftableDirectoryEvent(filename);\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tif (isSafeFsWatchPathError(error)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.handleGitWatcherError();\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tconst tablesListPath = this.reftableTablesListPath;\n\t\t\tif (tablesListPath && existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleReftableRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t(error) => {\n\t\t\t\t\t\tif (isSafeFsWatchPathError(error)) {\n\t\t\t\t\t\t\tthis.installReftableTablesListPolling(tablesListPath);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.handleGitWatcherError();\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tthis.installReftableTablesListPolling(tablesListPath);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\"\n>;\n"]}
|