@firstpick/pi-package-webui 0.10.1 → 0.10.2

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/DEVELOPMENT.md CHANGED
@@ -4,19 +4,13 @@ Contributor-only implementation, API, architecture, testing, and maintenance inf
4
4
 
5
5
  [Back to README](README.md) · [Advanced user technical reference](TECHNICAL.md)
6
6
 
7
- ## TUI tool and skill selector
7
+ ## Tool and skill command ownership
8
8
 
9
- `index.ts` keeps resource scope resolution and persistence in `registerTuiResourceController`. After the user chooses Session, Global, or Model scope, `lib/tui-resource-selector.mjs` owns the shared searchable list used by both `/tools` and `/skills`. Its interaction follows Pi's `/scoped-models` selector: arrows navigate, Enter toggles, the `app.models.enableAll`, `app.models.clearAll`, and `app.models.save` bindings perform bulk actions and save, and Escape or Ctrl+C cancels. Bulk actions affect only filtered resources while search is active.
10
-
11
- For Model scope, `lib/tui-model-profile-selector.mjs` searches provider, exact ID, and display name. It returns the selected model object directly rather than reconstructing a model from its rendered label. The picker opens at the active model when possible and marks models with a resource-specific profile.
9
+ WebUI does not register TUI `/tools` or `/skills` commands. The standalone `@firstpick/pi-extension-tools` and `@firstpick/pi-extension-setup-skills` packages own those commands and their Session, Global, and Model selector flow. Shared profile resolution, locking, and TUI selector components live in `@firstpick/pi-utils`. Browser-native tool and skill controls continue through `webui-rpc-helper.mjs` and the WebUI HTTP routes against the same saved state.
12
10
 
13
11
  Focused contributor validation:
14
12
 
15
13
  ```bash
16
- node --check lib/tui-resource-selector.mjs
17
- node --check lib/tui-model-profile-selector.mjs
18
- node tests/tui-resource-selector.test.mjs
19
- node tests/tui-model-profile-selector.test.mjs
20
14
  node tests/resource-tui-extension.test.mjs
21
15
  ```
22
16
 
@@ -279,7 +273,7 @@ Compact mode keeps live output lightweight, coalesces sustained live DOM/scroll
279
273
  - Optional Natural Conversation Mode shell for the standalone `@firstpick/pi-package-natural-conversation` package: when `/talk` (or `/voice`/`/conversation`) is loaded in the active Pi tab, Web UI shows per-tab Start/End controls, a read-only voice-mode chip, and backend guards that keep thinking `off` while blocking unsafe Web UI actions.
280
274
  - Browser voice loop for Natural Conversation Mode (`public/voice-conversation.mjs`): while the mode is active in a tab, the browser's Web Speech APIs listen for speech, send final transcripts as normal prompts, and speak Pi's final answers. The microphone pauses while answers are spoken (echo prevention), speech during final-output streaming becomes a steering interruption, speech during tool execution is queued until the tool phase ends, and silence after a spoken question sends a single structured silence event. Remote (non-localhost) sessions keep the microphone off until the per-tab `Allow remote microphone streaming` consent is granted; only text transcripts ever reach the Pi host on the browser-default path. Opt-in server-side fallback routes are available for local/Groq/OpenAI STT and local/OpenAI TTS when configured with server-side env vars; remote/LAN raw-audio STT fallback uploads require explicit per-request consent.
281
275
  - Browser-native Pi dialogs for `/model`, `/settings`, `/summary-setup`, `/safety-guard-setup`, `/git-workflow-setup`, `/theme`, `/fork`, `/clone`, `/name`, `/resume`, `/tree`, `/login`, `/logout`, `/scoped-models`, `/tools`, and `/skills`, plus an on-demand `/summary` Markdown overlay and native-command adapter output for `/copy`, `/session`, `/new`, `/compact`, `/reload`, and `/export`. Safety Guard Setup includes the opt-in auto-review toggle and active-tab authenticated model/supported-thinking selectors; auto-review remains off by default, and enabled saves reject unavailable selections.
282
- - Runtime `/tools` and `/skills` selectors backed by the hidden Web UI RPC helper, with explicit **Session only**, **Global default**, and exact **Model default** scopes. Session choices persist on the current branch and take precedence; global defaults are inherited by future sessions without rewriting existing branches. Disabled skills are removed from the system prompt, and tracked `SKILL.md` files can be opened/edited from skill tags. Responsive fitting keeps visible and hidden tag sets disjoint; the `+X` disclosure renders the hidden set in an upward, bounded popup and preserves selection, outside-dismissal, `Escape`, and focus-return behavior.
276
+ - Browser-native tool and skill selectors backed by the hidden Web UI RPC helper, with explicit **Session only**, **Global default**, and exact **Model default** scopes. Session choices persist on the current branch and take precedence; global defaults are inherited by future sessions without rewriting existing branches. Disabled skills are removed from the system prompt, and tracked `SKILL.md` files can be opened/edited from skill tags. Responsive fitting keeps visible and hidden tag sets disjoint; the `+X` disclosure renders the hidden set in an upward, bounded popup and preserves selection, outside-dismissal, `Escape`, and focus-return behavior.
283
277
  - Session resume into a newly created terminal tab, metadata rename, and localhost-only safe delete with active/open-tab/session-directory guards.
284
278
  - Model, thinking, session, workspace, theme, optional-feature, Codex usage, optional Remote WebUI, update/restart/stop, event, notification, thinking-visibility, terminal-tab-layout, and custom-background controls in collapsible side-panel sections.
285
279
  - A side-panel **Git** section mirrors the repositories represented by every open terminal tab/group. Repository cards are shown directly—without session-name parent disclosures—and always use the Git-root or cwd basename as their title. One repository can be expanded at a time. First/stale expansion refreshes local status after a five-minute cache window, while live filesystem updates use a debounced server watcher and SSE invalidation to refresh visible repositories without periodic Git polling or an automatic network `git fetch`. Its compact Changes tree groups conflicted, staged, modified, and untracked paths with additions/deletions; right-click a repository, folder, or file (or press Shift+F10/the Context Menu key) for View Diff, refresh, stage/unstage, and confirmed discard/delete actions. History lists the latest 30 commits and opens bounded read-only commit diffs.
@@ -660,17 +654,17 @@ Product screenshots are maintained in the [user-facing README](README.md#feature
660
654
 
661
655
  ### Tools setup
662
656
 
663
- - **What it is:** Browser and native TUI `/tools` selectors for active and available Pi tools.
657
+ - **What it is:** A browser selector for active and available Pi tools. The standalone tools extension owns the TUI `/tools` command.
664
658
  - **What you can do:** Search or toggle tools, pin the current session branch, save a global default, configure an exact provider/model profile, or return a scope to inherited behavior. A successful model change immediately recomputes unpinned tools.
665
659
 
666
660
  ### Skills setup
667
661
 
668
- - **What it is:** Browser and native TUI `/skills` selectors for skills discovered in the active Pi session.
662
+ - **What it is:** A browser selector for skills discovered in the active Pi session. The standalone skills extension owns the TUI `/skills` command.
669
663
  - **What you can do:** Find skills by name or description, pin the current session branch, save a global default, configure an exact provider/model profile, or return a scope to inherited behavior. A successful model change immediately recomputes unpinned skills while preserving `disableModelInvocation` filtering and explicit disabled-skill blocking.
670
664
 
671
665
  Session-specific tool and skill choices are independent and always win when their branch is resumed or selected in `/tree`. Exact model profiles are keyed by case-sensitive provider/model ID pairs and are stored as an array under settings-envelope version 8. Each profile contains nullable tool and skill selections: `null` inherits, while an empty array explicitly enables none. Legacy branch entries remain explicit pins; version-2 branch entries add `explicit` and `inherit` modes. Global and exact-model defaults are stored in the private Pi Web UI settings file (normally `~/.pi/webui/settings.json`) and do not mutate an explicit current session.
672
666
 
673
- `index.ts` owns resource lifecycle only in TUI mode, while `webui-rpc-helper.mjs` owns it in RPC mode. Both capture or resolve an immutable runtime fallback, recompute on session/tree/model events, and fence asynchronous model changes before applying them. HTTP model-profile writes validate the exact authenticated model and update the latest locked settings snapshot so concurrent writers and temporarily unavailable names are preserved.
667
+ `webui-rpc-helper.mjs` owns the browser session's resource lifecycle in RPC mode. It captures or resolves an immutable runtime fallback, recomputes on session/tree/model events, and fences asynchronous model changes before applying them. HTTP model-profile writes validate the exact authenticated model and update the latest locked settings snapshot so concurrent writers and temporarily unavailable names are preserved.
674
668
 
675
669
  `@firstpick/pi-package-qt-webui` consumes this package as the canonical tool/skill state owner. Its backend imports `webuiSettingsFile()`, `readWebuiSettings()`, `updateWebuiSettings()`, and the resource-selection helpers rather than copying the settings schema or lock protocol. Qt global and exact-model writes therefore merge into the same `resourceDefaults`, and its Pi helper uses the same `webui-tools-config` and `webui-skills-config` version-2 branch entries for session explicit/inherit state. Qt-only sampling remains outside this contract. Each Qt resource-state request reads the latest shared settings; there is no direct process-to-process synchronization.
676
670
 
@@ -758,9 +752,9 @@ Optional companions:
758
752
  - `@firstpick/pi-extension-workflows` — `/workflow` runtime with non-blocking Web UI subprocess-output widgets.
759
753
  - `@firstpick/pi-extension-feature-system-prompt` — feature-request classification and routing, with lightweight/complex decisions shown in the Web UI composer.
760
754
  - `@firstpick/pi-extension-safety-guard` — configurable guardrails for dangerous bash commands and protected file edits, with native `/safety-guard-setup` controls.
761
- - `@firstpick/pi-extension-setup-skills` — TUI `/skills` setup command alongside WebUI-native skill toggles.
755
+ - `@firstpick/pi-extension-setup-skills` — sole owner of the TUI `/skills` setup command; WebUI keeps separate browser-native skill controls.
762
756
  - `@firstpick/pi-extension-todo-progress` — todo-progress rendering.
763
- - `@firstpick/pi-extension-tools` — TUI `/tools` active-tool manager alongside WebUI-native tool toggles.
757
+ - `@firstpick/pi-extension-tools` — sole owner of the TUI `/tools` active-tool manager; WebUI keeps separate browser-native tool controls.
764
758
  - `@firstpick/pi-package-remote-webui` — `/remote` trusted-LAN QR helper plus the optional browser controls for opening/closing LAN access and Remote PIN auth.
765
759
  - `@firstpick/pi-extension-git-footer-status` — richer extension-owned git/footer status, including the structured Web UI footer payload. The Claude Usage panel consumes its live Anthropic response-header snapshot when available and keeps the standalone Claude CLI endpoint as an explicit/fallback refresh path.
766
760
  - `@firstpick/pi-extension-stats` — stats commands and status data.
@@ -791,7 +785,7 @@ For an existing repository, the workflow can:
791
785
  1. Show staged, unstaged, untracked, and fetched incoming changes.
792
786
  2. Fast-forward pull fetched incoming commits when the repository is safely behind.
793
787
  3. Review/select files, preserve a non-empty staged set, or explicitly opt into `git add .`.
794
- 4. Generate `/git-staged-msg` with the configured model, supported reasoning effort, language, and scope policy, then restore the tab's prior model/effort. Each request is correlated to its originating tab and a before-generation snapshot of both message files; the browser advances only when both non-empty files are fresh and stable for that exact generation.
788
+ 4. Generate `/git-staged-msg` with the configured model, supported reasoning effort, language, and scope policy without changing the tab's active model or effort. Each request is correlated to its originating tab and a before-generation snapshot of both message files; the browser advances only when both non-empty files are fresh and stable for that exact generation.
795
789
  5. Use the preferred generated short/long message, a generated single-file default such as `updated file.txt`, or a manual **Commit input** message.
796
790
  6. Show an optional pre-commit verification reminder, then require explicit confirmation before push and PR delivery actions.
797
791
 
@@ -805,13 +799,13 @@ The saved setup includes:
805
799
  - ask/current-branch/PR-worktree delivery highlighting; and
806
800
  - optional pre-commit verification reminders.
807
801
 
808
- If a configured model or effort is unavailable, setup saving fails closed. During generation, the server selects the configured profile and invokes the native extension command. The accepted RPC response confirms only that Pi handled the command. The server treats a correlated `extension_error` event as the native command's terminal failure and checks for a fresh correlated artifact only when the command did not report one. If the artifact check fails immediately after the accepted response, the server allows a bounded 500 ms grace period for a separately delivered correlated `extension_error` before reporting the artifact failure. Only the native command's internal direct model/provider-generation failure classification may start the explicitly configured fallback profile once. Invalid generated output, a missing or stale artifact after a command with no reported error, and all non-provider failures remain terminal. It never chooses an unconfigured model. The original tab model and effort are restored after a successful native artifact verification or terminal failure. Request validation, staged-content checks, cancellation, Git failures, and Pi process exit/error do not trigger fallback; a dead Pi process cannot run another attempt. Footer and Guided Git pushes send the active tab's current `HEAD` to the same-named branch on the preferred remote and set that branch as the upstream instead of retaining a potentially mismatched upstream. Guided Git never force-pushes automatically. Git hooks and signing configuration continue to run normally.
802
+ If a configured model or effort is unavailable, setup saving fails closed. During generation, the server encodes the configured profile in a private base64url extension-command argument and invokes the native extension command. The extension validates and resolves that profile, then calls its provider independently without changing the parent tab's active model or reasoning effort. The accepted RPC response confirms only that Pi handled the command. The server treats a correlated `extension_error` event as the native command's terminal failure and checks for a fresh correlated artifact only when the command did not report one. If the artifact check fails immediately after the accepted response, the server allows a bounded 500 ms grace period for a separately delivered correlated `extension_error` before reporting the artifact failure. Only the native command's internal direct model/provider-generation failure classification may start the explicitly configured fallback profile once. Invalid generated output, a missing or stale artifact after a command with no reported error, and all non-provider failures remain terminal. It never chooses an unconfigured model. Request validation, staged-content checks, cancellation, Git failures, and Pi process exit/error do not trigger fallback; a dead Pi process cannot run another attempt. Footer and Guided Git pushes send the active tab's current `HEAD` to the same-named branch on the preferred remote and set that branch as the upstream instead of retaining a potentially mismatched upstream. Guided Git never force-pushes automatically. Git hooks and signing configuration continue to run normally.
809
803
 
810
804
  After the message is generated, **Create PR** invokes the native branch command to generate `dev/COMMIT/staged-branch-name.txt`, lets you confirm or edit the `type/feature-name` branch, then switches with `git switch -c` before committing. In PR mode, choose **Commit short**, **Commit long**, or type a message and use **Commit input**, then **Push and Create PR** pushes the branch, invokes `/pr`, shows the generated `dev/PR/<encodeURIComponent(current-branch)>.md` description for editing/confirmation, and creates the pull request with `gh pr create`. Use **Manual branch** to skip model branch-name generation and type the branch directly.
811
805
 
812
806
  Use the workflow process buttons to jump directly to **Initialize**, **Stage**, **Message**, **Commit**, **Push**, or PR steps when earlier work was already completed manually. Selecting **Message** lets you either run `/git-staged-msg` or type a commit message and use **Commit input** directly. Selecting **Commit** loads the current generated files from `dev/COMMIT/` before enabling the commit choices. Manual preview remains available for existing files, while an active generation uses bounded single-flight polling and the exact server generation ID so duplicate timers and reconnects cannot surface a stale artifact. A yellow dot means that process was selected or is available but its action has not completed in this workflow; green means the process action completed.
813
807
 
814
- All three generation commands come from `@firstpick/pi-extension-git-guided-workflow` and call the active selected model directly. Creating the PR also requires an authenticated GitHub CLI (`gh`). Review the generated commit message, branch name, remote URL, and PR description before committing, pushing, or creating a PR.
808
+ All three generation commands come from `@firstpick/pi-extension-git-guided-workflow`. Direct invocations call the active Pi model; WebUI invocations call the configured Guided Git model independently. Creating the PR also requires an authenticated GitHub CLI (`gh`). Review the generated commit message, branch name, remote URL, and PR description before committing, pushing, or creating a PR.
815
809
 
816
810
  ### Extension activation contract
817
811
 
@@ -845,9 +839,9 @@ npx playwright test --project=chromium tests/browser/guided-git-extension-comman
845
839
 
846
840
  The persisted `generation.fallback` object always contains `provider`, `modelId`, and `thinkingLevel`; an empty provider/model pair disables fallback. The Guided Git setup client sends the nested fallback object on every save, filters the selected primary out of fallback choices, and sends empty provider/model fields when **No fallback** is selected. Server-side validation remains authoritative for availability, profile equality, and supported effort.
847
841
 
848
- `POST /api/git-workflow/generate` keeps `generation` as the effective profile and allocates one server generation ID for commit, branch, or PR text. The server resolves an RPC command with `source: "extension"`, selects the configured profile, sends the exact native slash command, and waits for that synchronous command response. The attempt succeeds only when the command also produces a fresh artifact relative to the captured baseline. If artifact verification fails, a bounded grace period gives the native `extension_error` event precedence when RPC stdout delivers it after the accepted command response. Only the native extension's stable internal direct model/provider-failure classification may start the configured fallback and return `fallbackUsed: true` with `primaryGeneration`; a successful RPC response without either a fresh artifact or correlated native error is terminal. Terminal dispatch errors include bounded correlation metadata.
842
+ `POST /api/git-workflow/generate` keeps `generation` as the effective profile and allocates one server generation ID for commit, branch, or PR text. The server resolves an RPC command with `source: "extension"`, selects the configured profile, encodes it with the public generation arguments in a private base64url command argument, sends the exact native slash command, and waits for that synchronous command response. The server does not send `set_model` or `set_thinking_level` RPC requests. The attempt succeeds only when the command also produces a fresh artifact relative to the captured baseline. If artifact verification fails, a bounded grace period gives the native `extension_error` event precedence when RPC stdout delivers it after the accepted command response. Only the native extension's stable internal direct model/provider-failure classification may start the configured fallback and return `fallbackUsed: true` with `primaryGeneration`; a successful RPC response without either a fresh artifact or correlated native error is terminal. Terminal dispatch errors include bounded correlation metadata.
849
843
 
850
- Fallback lifecycle events start with `webui_git_workflow_generation_fallback_started` and carry the effective `generation`, `primaryGeneration`, `kind`, `tabId`, and `generationId`, plus a curated bounded `reason` or `error`; full provider diagnostics remain server-side. The server retains at most the start and terminal fallback events per tab and replays them on EventSource reconnect. One correlation ID and pre-primary artifact baseline remain authoritative across both attempts. Commit, branch, and PR reads require successful terminal artifact verification, so failed-primary output cannot become ready while fallback runs. The server owns reservation, cancellation state, the two-attempt ceiling, and restoration of the original model/effort after success or terminal failure; the browser observes lifecycle state and never sends a retry. Validation failures, user aborts, Git command failures, and Pi process exit/error remain ordinary failures and never enter fallback dispatch.
844
+ Fallback lifecycle events start with `webui_git_workflow_generation_fallback_started` and carry the effective `generation`, `primaryGeneration`, `kind`, `tabId`, and `generationId`, plus a curated bounded `reason` or `error`; full provider diagnostics remain server-side. The server retains at most the start and terminal fallback events per tab and replays them on EventSource reconnect. One correlation ID and pre-primary artifact baseline remain authoritative across both attempts. Commit, branch, and PR reads require successful terminal artifact verification, so failed-primary output cannot become ready while fallback runs. The server owns reservation, cancellation state, and the two-attempt ceiling; the browser observes lifecycle state and never sends a retry. Primary and fallback requests leave the parent session's active model and effort unchanged. Validation failures, user aborts, Git command failures, and Pi process exit/error remain ordinary failures and never enter fallback dispatch.
851
845
 
852
846
  ## Open Issue bot
853
847
 
package/README.md CHANGED
@@ -162,7 +162,7 @@ For a long scoped-model list, right-click the Git footer **Model** box and choos
162
162
 
163
163
  **Optional feature needed:** None — the browser tools setup is included in Pi Web UI core.
164
164
 
165
- Enable tools for the current session, save a global default, or configure an exact model profile. In Pi's TUI, `/tools` uses the same searchable keyboard workflow as `/scoped-models`: arrow keys move, `Enter` toggles, `Ctrl+A` enables matching entries, `Ctrl+X` clears them, and `Ctrl+S` saves. **Model default** opens a searchable exact-model picker that marks the active model and existing tool profiles without switching the active model. Selecting a configured model automatically applies its tool profile unless the session has its own tool selection.
165
+ Enable tools for the current session, save a global default, or configure an exact model profile. Selecting a configured model automatically applies its tool profile unless the session has its own tool selection. Pi's TUI `/tools` command belongs to the optional `@firstpick/pi-extension-tools` companion and uses the same Session, Global, and Model scopes; WebUI does not register a competing command.
166
166
 
167
167
  #### Skills setup
168
168
 
@@ -170,7 +170,7 @@ Enable tools for the current session, save a global default, or configure an exa
170
170
 
171
171
  **Optional feature needed:** None — the browser skills setup is included in Pi Web UI core.
172
172
 
173
- Find installed skills and manage session, global, or exact-model activation. In Pi's TUI, `/skills` uses the same searchable keyboard workflow as `/scoped-models`, including the exact-model picker used by `/tools`. Selecting a configured model automatically applies its skill profile unless the session has its own skill selection.
173
+ Find installed skills and manage session, global, or exact-model activation. Selecting a configured model automatically applies its skill profile unless the session has its own skill selection. Pi's TUI `/skills` command belongs to the optional `@firstpick/pi-extension-setup-skills` companion and uses the same Session, Global, and Model scopes; WebUI does not register a competing command.
174
174
 
175
175
  ### Project automation and Git
176
176
 
@@ -192,7 +192,7 @@ Run `/git-guided-workflow` in the browser composer or use the **Guided Git workf
192
192
 
193
193
  Move through review, staging, commit-message generation, commit, push, and pull-request steps with explicit confirmations. If a repository has no remote, choose **Public** or **Private** from the visibility dropdown and confirm publication. Guided Git uses the local Git root directory name, runs the authenticated system `gh` command, adds `origin`, and pushes the current branch.
194
194
 
195
- In **Guided Git Setup**, you can optionally choose a fallback model and its own reasoning effort. If the primary model reaches a final generation failure, Guided Git tries the fallback once, reports the change in the workflow, and restores the tab’s prior model and effort afterward. Large staged diffs use multiple model requests; a fallback attempt sends the complete staged evidence again to the configured fallback provider and can nearly double the request count and cost. Validation failures, cancellation, Git command failures, and a stopped Pi process do not trigger fallback.
195
+ In **Guided Git Setup**, choose the model and reasoning effort used for generated Git text. Guided Git calls that model independently without changing the parent tab’s active model or effort. You can optionally choose a fallback model and its own reasoning effort; after a final primary generation failure, Guided Git tries the fallback once and reports the change in the workflow. Large staged diffs use multiple model requests; a fallback attempt sends the complete staged evidence again to the configured fallback provider and can nearly double the request count and cost. Validation failures, cancellation, Git command failures, and a stopped Pi process do not trigger fallback.
196
196
 
197
197
  #### Git branch picker
198
198
 
package/TECHNICAL.md CHANGED
@@ -194,7 +194,7 @@ The flat-or-advanced choice is a browser-local display preference. It persists a
194
194
 
195
195
  ## Tool and skill scopes
196
196
 
197
- The browser-native tool and skill selectors, and the TUI `/tools` and `/skills` commands, offer **Session only**, **Global default**, and **Model default** scopes. In the TUI resource list, type to search, use the arrow keys to move, press `Enter` to toggle, `Ctrl+A` to enable matching entries, `Ctrl+X` to clear matching entries, and `Ctrl+S` to save. `Escape` cancels; `Ctrl+C` clears a non-empty search before cancelling. These shortcuts match `/scoped-models`, including custom Pi bindings for the shared model-selection actions. **Model default** uses a separate searchable provider, ID, and display-name picker. It opens at the active model when available, marks existing profiles, and returns the exact provider/model pair without changing the active model. Tools and skills resolve independently: a session choice wins over an exact case-sensitive provider/model profile, which wins over the global default and then Pi's runtime default.
197
+ The browser-native tool and skill selectors offer **Session only**, **Global default**, and **Model default** scopes. The extension-owned TUI `/tools` and `/skills` commands use the same scopes and saved state. Tools and skills resolve independently: a session choice wins over an exact case-sensitive provider/model profile, which wins over the global default and then Pi's runtime default. WebUI does not register either TUI command; they belong to `@firstpick/pi-extension-tools` and `@firstpick/pi-extension-setup-skills`.
198
198
 
199
199
  After Pi successfully selects a model, its exact tool and skill profiles apply immediately for resource types that are not pinned by the current session; no reload or selector reopening is needed. A model with no profile falls back through the global and runtime defaults. Choosing a model inside a profile editor selects the profile to edit—it does not switch the active Pi model.
200
200
 
@@ -331,7 +331,7 @@ The launcher refuses immediately while the originating tab is running, compactin
331
331
 
332
332
  Open **Common Pi Options → Guided Git Setup** or run `/git-workflow-setup` before using generated commit messages, branch names, or pull-request text. Choose the required primary model and its reasoning effort. You may also choose a different fallback model and a separate supported effort, or leave **No fallback** selected. The effort lists follow the capabilities reported for each selected model. Before enabling fallback, account for its privacy and cost impact: large commit diffs use multiple model requests, and a fallback attempt sends the complete staged evidence again to the configured fallback provider.
333
333
 
334
- A configured fallback is a strict one-retry policy: Guided Git lets Pi finish the primary model’s own retry lifecycle, then makes at most one fallback attempt after a final primary model-generation failure. The workflow output identifies the primary and configured fallback at startup and reports when generation continues with the fallback. For a commit diff at the extension’s 16 MiB ceiling, one attempt can use up to 35 requests; chunk-summary formatting does not trigger retries. Fallback can repeat the full attempt, for up to 70 requests across both providers. Fallback status is restored when you return to the tab or its live event connection reconnects. Generated commit, branch, or PR text is treated as ready only after the correlated attempt finishes successfully. After successful generation or terminal failure, the tab’s model and reasoning effort are restored to the values it had before Guided Git generation began.
334
+ A configured fallback is a strict one-retry policy: Guided Git lets the primary model finish its own retry lifecycle, then makes at most one fallback attempt after a final primary model-generation failure. The workflow output identifies the primary and configured fallback at startup and reports when generation continues with the fallback. For a commit diff at the extension’s 16 MiB ceiling, one attempt can use up to 35 requests; chunk-summary formatting does not trigger retries. Fallback can repeat the full attempt, for up to 70 requests across both providers. Fallback status is restored when you return to the tab or its live event connection reconnects. Generated commit, branch, or PR text is treated as ready only after the correlated attempt finishes successfully. Primary and fallback requests run independently of the parent Pi session, whose active model and reasoning effort remain unchanged throughout.
335
335
 
336
336
  Fallback applies only to model generation. Request validation failures, staged-content checks, busy-state rejection, user cancellation, Git command failures, and a stopped or failed Pi process do not trigger it. A dead Pi process cannot run the fallback; restart or reload the tab and start a new generation request after addressing the failure.
337
337
 
package/bin/pi-webui.mjs CHANGED
@@ -3124,14 +3124,25 @@ async function triggerSessionSummary(tab, { refresh = false } = {}) {
3124
3124
  }
3125
3125
  }
3126
3126
 
3127
- function gitWorkflowGenerationPrompt(kind, preferences, commandName) {
3127
+ function gitWorkflowGenerationProfileArgument(profile) {
3128
+ const payload = Buffer.from(JSON.stringify({
3129
+ version: 1,
3130
+ provider: profile.provider,
3131
+ modelId: profile.modelId,
3132
+ thinkingLevel: profile.thinkingLevel,
3133
+ }), "utf8").toString("base64url");
3134
+ return `--firstpick-webui-generation-profile=${payload}`;
3135
+ }
3136
+
3137
+ function gitWorkflowGenerationPrompt(kind, preferences, commandName, profile) {
3138
+ const generationProfile = gitWorkflowGenerationProfileArgument(profile);
3128
3139
  switch (kind) {
3129
3140
  case "commit":
3130
- return `/${commandName} ${preferences.commit.language} ${preferences.commit.scope}`;
3141
+ return `/${commandName} ${preferences.commit.language} ${preferences.commit.scope} ${generationProfile}`;
3131
3142
  case "branch":
3132
- return `/${commandName}`;
3143
+ return `/${commandName} ${generationProfile}`;
3133
3144
  case "pr":
3134
- return `/${commandName} ${preferences.commit.language}`;
3145
+ return `/${commandName} ${preferences.commit.language} ${generationProfile}`;
3135
3146
  default:
3136
3147
  throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3137
3148
  }
@@ -3212,37 +3223,6 @@ function publicGitWorkflowGenerationProfile(profile) {
3212
3223
  };
3213
3224
  }
3214
3225
 
3215
- async function restoreGitWorkflowGenerationProfile(tab, expectedRecord = tab?.gitWorkflowGeneration) {
3216
- const record = expectedRecord && tab?.gitWorkflowGeneration === expectedRecord ? expectedRecord : null;
3217
- const restore = record?.restore || tab?.gitWorkflowGenerationRestore;
3218
- if (!restore) return;
3219
- if (record?.restorePromise) return record.restorePromise;
3220
- const operation = (async () => {
3221
- try {
3222
- if (!tab.rpc?.isRunning?.()) return;
3223
- if (restore.model?.provider && restore.model?.id) {
3224
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3225
- if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3226
- }
3227
- if (restore.thinkingLevel) {
3228
- const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3229
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
3230
- }
3231
- recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3232
- } catch (error) {
3233
- console.error(`[guided-git] failed to restore generation profile for ${record?.generationId || tab.id}: ${sanitizeError(error)}`);
3234
- recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: boundedGitWorkflowGenerationError("Guided Git could not restore the previous model profile.") });
3235
- } finally {
3236
- if (!record || tab.gitWorkflowGeneration === record) {
3237
- tab.gitWorkflowGeneration = null;
3238
- tab.gitWorkflowGenerationRestore = null;
3239
- }
3240
- }
3241
- })();
3242
- if (record) record.restorePromise = operation;
3243
- return operation;
3244
- }
3245
-
3246
3226
  async function createGitWorkflowArtifactGeneration(tab, generationId, kind) {
3247
3227
  const createdAt = Date.now();
3248
3228
  if (kind === "commit") {
@@ -3325,7 +3305,7 @@ async function finishGitWorkflowGeneration(tab, record, { successful }) {
3325
3305
  tab.gitWorkflowMessageGeneration = record.previousMessageGeneration;
3326
3306
  }
3327
3307
  markTabIdle(tab);
3328
- await restoreGitWorkflowGenerationProfile(tab, record);
3308
+ if (tab.gitWorkflowGeneration === record) tab.gitWorkflowGeneration = null;
3329
3309
  }
3330
3310
 
3331
3311
  async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attempt) {
@@ -3341,15 +3321,7 @@ async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attemp
3341
3321
  record.promptAccepted = false;
3342
3322
  record.pendingSettlement = null;
3343
3323
  record.nativeCommandError = null;
3344
- if (record.currentModelKey !== `${profile.provider}/${profile.modelId}`) {
3345
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: profile.provider, modelId: profile.modelId });
3346
- assertGitWorkflowGenerationOwnership(tab, record);
3347
- if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${profile.provider}/${profile.modelId}`);
3348
- record.currentModelKey = `${profile.provider}/${profile.modelId}`;
3349
- }
3350
- const thinkingResponse = await setThinkingLevelForTab(tab, profile.thinkingLevel, { allowPending: false });
3351
- assertGitWorkflowGenerationOwnership(tab, record);
3352
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${profile.thinkingLevel}`);
3324
+ record.message = gitWorkflowGenerationPrompt(record.kind, record.preferences, record.nativeCommandName, profile);
3353
3325
 
3354
3326
  assertGitWorkflowGenerationOwnership(tab, record);
3355
3327
  markTabWorking(tab);
@@ -3452,7 +3424,7 @@ function consumeGitWorkflowGenerationEvent(tab, event, { finalError = false } =
3452
3424
  }
3453
3425
 
3454
3426
  async function startGitWorkflowGeneration(tab, body = {}) {
3455
- if (tab.gitWorkflowGeneration || tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3427
+ if (tab.gitWorkflowGeneration) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3456
3428
  const kind = String(body.kind || "").trim();
3457
3429
  if (!new Set(["commit", "branch", "pr"]).has(kind)) throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3458
3430
 
@@ -3462,7 +3434,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3462
3434
  generationId: randomUUID(),
3463
3435
  kind,
3464
3436
  message: "",
3465
- restore: null,
3437
+ preferences: null,
3466
3438
  previousMessageGeneration: tab.gitWorkflowMessageGeneration || null,
3467
3439
  messageGeneration: null,
3468
3440
  artifactGeneration: null,
@@ -3475,7 +3447,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3475
3447
  attemptRunStarted: false,
3476
3448
  promptAccepted: false,
3477
3449
  pendingSettlement: null,
3478
- currentModelKey: "",
3479
3450
  nativeCommandName: "",
3480
3451
  nativeCommandError: null,
3481
3452
  nativeGeneration: true,
@@ -3491,10 +3462,10 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3491
3462
  const preferences = await readGitWorkflowPreferences();
3492
3463
  assertGitWorkflowGenerationOwnership(tab, record);
3493
3464
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
3465
+ record.preferences = preferences;
3494
3466
  const nativeCommandName = await resolveGuidedGitNativeCommand(tab, kind);
3495
3467
  assertGitWorkflowGenerationOwnership(tab, record);
3496
3468
  record.nativeCommandName = nativeCommandName;
3497
- record.message = gitWorkflowGenerationPrompt(kind, preferences, nativeCommandName);
3498
3469
 
3499
3470
  const state = await currentSessionState(tab);
3500
3471
  assertGitWorkflowGenerationOwnership(tab, record);
@@ -3520,9 +3491,6 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3520
3491
  )
3521
3492
  : null;
3522
3493
 
3523
- record.restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3524
- record.currentModelKey = gitWorkflowModelKey(state.model);
3525
- tab.gitWorkflowGenerationRestore = record.restore;
3526
3494
  record.artifactGeneration = await createGitWorkflowArtifactGeneration(tab, record.generationId, kind);
3527
3495
  record.messageGeneration = kind === "commit" ? record.artifactGeneration : null;
3528
3496
  assertGitWorkflowGenerationOwnership(tab, record);
@@ -3546,8 +3514,7 @@ async function startGitWorkflowGeneration(tab, body = {}) {
3546
3514
  }
3547
3515
  } catch (error) {
3548
3516
  if (tab.gitWorkflowGeneration === record && !record.finishing) {
3549
- if (record.restore) await finishGitWorkflowGeneration(tab, record, { successful: false });
3550
- else tab.gitWorkflowGeneration = null;
3517
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3551
3518
  }
3552
3519
  throw error;
3553
3520
  }
@@ -11524,7 +11491,6 @@ function attachRpcToTab(tab, rpc) {
11524
11491
  tab.gitWorkflowArtifactGeneration.successful = false;
11525
11492
  }
11526
11493
  tab.gitWorkflowGeneration = null;
11527
- tab.gitWorkflowGenerationRestore = null;
11528
11494
  tab.gitWorkflowMessageGeneration = null;
11529
11495
  clearPendingExtensionUiRequests(tab);
11530
11496
  clearExtensionStatuses(tab);
@@ -11563,7 +11529,6 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11563
11529
  pendingThinkingLevel: undefined,
11564
11530
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
11565
11531
  gitWorkflowGeneration: null,
11566
- gitWorkflowGenerationRestore: null,
11567
11532
  gitWorkflowMessageGeneration: null,
11568
11533
  gitWorkflowArtifactGeneration: null,
11569
11534
  gitWorkflowFallbackLifecycle: null,
package/index.ts CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { homedir } from "node:os";
4
4
  import type { Readable } from "node:stream";
5
5
  import { fileURLToPath } from "node:url";
6
- import { formatSkillsForPrompt, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
7
  import { delay, takeValue, tokenizeArgs } from "@firstpick/pi-utils";
8
8
  import { detachChildProcess as releaseStartedChild, isProcessRunning, terminateChildProcess as terminateFailedChild } from "@firstpick/pi-utils/process";
9
9
  import { fetchJsonWithTimeout as fetchJsonWithTimeoutBase } from "@firstpick/pi-utils/http";
@@ -12,21 +12,9 @@ import { createRestoreFile } from "./lib/update/supervisor.mjs";
12
12
  import {
13
13
  gitWorkflowPreferencesSummary,
14
14
  readGitWorkflowPreferences,
15
- readWebuiSettings,
16
15
  supportedGitWorkflowThinkingLevels,
17
- updateWebuiSettings,
18
16
  writeGitWorkflowPreferences,
19
17
  } from "./lib/git-workflow-preferences.mjs";
20
- import {
21
- branchResourceDirective,
22
- exactModelProfile,
23
- normalizeResourceNameList,
24
- preserveUnavailableResourceNames,
25
- resolveResourceSelection,
26
- setExactModelProfile,
27
- } from "./lib/resource-selection.mjs";
28
- import { selectTuiModelProfile } from "./lib/tui-model-profile-selector.mjs";
29
- import { selectTuiResources } from "./lib/tui-resource-selector.mjs";
30
18
 
31
19
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
20
  const packageRoot = __dirname;
@@ -881,250 +869,7 @@ async function runGitWorkflowSetup(ctx: ExtensionCommandContext): Promise<void>
881
869
  }
882
870
  }
883
871
 
884
- function lastResourceBranchConfig(ctx: ExtensionCommandContext, customType: string): any {
885
- let found: any;
886
- for (const entry of ctx.sessionManager.getBranch()) {
887
- if ((entry as any)?.type === "custom" && (entry as any).customType === customType) found = (entry as any).data;
888
- }
889
- return found;
890
- }
891
-
892
- function registerTuiResourceController(pi: ExtensionAPI): void {
893
- let runtimeToolBaseline: string[] | undefined;
894
- let enabledTools = new Set<string>();
895
- let enabledSkills: Set<string> | null = null;
896
- let legacyDisabledSkills = new Set<string>();
897
- let toolsPinned = false;
898
- let skillsPinned = false;
899
- let tuiActive = false;
900
- let generation = 0;
901
-
902
- const modelKey = (model: any): string => model?.provider && model?.id ? `${model.provider}\0${model.id}` : "";
903
- const runtimeTools = (): string[] => runtimeToolBaseline ??= normalizeResourceNameList(pi.getActiveTools()) || [];
904
- const toolNames = (): string[] => pi.getAllTools().map((tool: any) => tool.name);
905
- const skills = (ctx: ExtensionCommandContext): any[] => {
906
- const options = (ctx as any).getSystemPromptOptions?.();
907
- return Array.isArray(options?.skills) ? options.skills : [];
908
- };
909
- const isSkillEnabled = (name: string): boolean => enabledSkills instanceof Set ? enabledSkills.has(name) : !legacyDisabledSkills.has(name);
910
-
911
- function applyResolvedState(ctx: ExtensionCommandContext, defaults: any, model: any): void {
912
- const toolDirective = branchResourceDirective(lastResourceBranchConfig(ctx, "webui-tools-config"), "tools");
913
- toolsPinned = toolDirective.pinned;
914
- const baseline = runtimeTools();
915
- const resolvedTools = toolDirective.pinned
916
- ? { names: toolDirective.names || [], source: "session" }
917
- : resolveResourceSelection(defaults, "tools", model?.provider, model?.id, baseline);
918
- enabledTools = new Set(resolvedTools.names || baseline);
919
- const existingTools = new Set(toolNames());
920
- pi.setActiveTools([...enabledTools].filter((name) => existingTools.has(name)));
921
-
922
- const skillDirective = branchResourceDirective(lastResourceBranchConfig(ctx, "webui-skills-config"), "skills");
923
- skillsPinned = skillDirective.pinned;
924
- legacyDisabledSkills = new Set();
925
- if (skillDirective.pinned && skillDirective.legacyDisabledNames !== null) {
926
- enabledSkills = null;
927
- legacyDisabledSkills = new Set(skillDirective.legacyDisabledNames);
928
- } else {
929
- const resolvedSkills = skillDirective.pinned
930
- ? { names: skillDirective.names || [], source: "session" }
931
- : resolveResourceSelection(defaults, "skills", model?.provider, model?.id, null);
932
- enabledSkills = resolvedSkills.names === null ? null : new Set(resolvedSkills.names);
933
- }
934
- }
935
-
936
- async function recompute(ctx: ExtensionCommandContext, requestedModel: any = ctx.model): Promise<boolean> {
937
- if (ctx.mode !== "tui") return false;
938
- const requestedKey = modelKey(requestedModel);
939
- const currentGeneration = ++generation;
940
- let defaults;
941
- try {
942
- defaults = (await readWebuiSettings()).resourceDefaults;
943
- } catch (error) {
944
- ctx.ui.notify(`Resource defaults could not be read: ${error instanceof Error ? error.message : String(error)}`, "error");
945
- return false;
946
- }
947
- if (currentGeneration !== generation || modelKey(ctx.model) !== requestedKey) return false;
948
- applyResolvedState(ctx, defaults, requestedModel);
949
- return true;
950
- }
951
-
952
- function availableModels(ctx: ExtensionCommandContext): any[] {
953
- return ctx.modelRegistry.getAvailable()
954
- .filter((model: any) => model?.provider && model?.id)
955
- .sort((left: any, right: any) => `${left.provider}/${left.id}`.localeCompare(`${right.provider}/${right.id}`));
956
- }
957
-
958
- async function runSelector(resourceType: "tools" | "skills", ctx: ExtensionCommandContext): Promise<void> {
959
- if (ctx.mode !== "tui") {
960
- ctx.ui.notify(`/${resourceType} is available in interactive TUI mode only.`, "warning");
961
- return;
962
- }
963
- const resourceLabel = resourceType === "tools" ? "Tools" : "Skills";
964
- const scope = await ctx.ui.select(`${resourceLabel} setup`, ["Session only", "Global default", "Model default"]);
965
- if (!scope) return;
966
- const settings = await readWebuiSettings();
967
- const visibleNames = resourceType === "tools" ? toolNames() : skills(ctx).map((skill: any) => skill.name);
968
- const selectionKey = resourceType === "tools" ? "enabledTools" : "enabledSkills";
969
- let previousNames: string[] | null = null;
970
- let provider = "";
971
- let modelId = "";
972
-
973
- if (scope === "Session only") {
974
- const action = await ctx.ui.select(`${resourceLabel} for this session`, ["Edit selection", "Use inherited defaults"]);
975
- if (!action) return;
976
- if (action === "Use inherited defaults") {
977
- pi.appendEntry(resourceType === "tools" ? "webui-tools-config" : "webui-skills-config", { version: 2, mode: "inherit" });
978
- await recompute(ctx);
979
- ctx.ui.notify(`${resourceLabel} now use inherited defaults.`, "info");
980
- return;
981
- }
982
- previousNames = resourceType === "tools"
983
- ? [...enabledTools]
984
- : enabledSkills instanceof Set ? [...enabledSkills] : visibleNames.filter((name) => !legacyDisabledSkills.has(name));
985
- } else if (scope === "Global default") {
986
- const action = await ctx.ui.select(`Global ${resourceLabel.toLowerCase()} default`, ["Edit selection", "Use Pi runtime default"]);
987
- if (!action) return;
988
- if (action === "Use Pi runtime default") {
989
- await updateWebuiSettings(() => ({ resourceDefaults: { [resourceType]: { [selectionKey]: null } } }));
990
- await recompute(ctx);
991
- ctx.ui.notify(`Global ${resourceLabel.toLowerCase()} default now inherits Pi runtime behavior.`, "info");
992
- return;
993
- }
994
- previousNames = settings.resourceDefaults?.[resourceType]?.[selectionKey];
995
- if (previousNames === null) previousNames = resolveResourceSelection(settings.resourceDefaults, resourceType, "", "", resourceType === "tools" ? runtimeTools() : null).names;
996
- } else {
997
- const models = availableModels(ctx);
998
- if (!models.length) {
999
- ctx.ui.notify("No authenticated Pi models are available.", "warning");
1000
- return;
1001
- }
1002
- const configuredModelKeys = (Array.isArray(settings.resourceDefaults?.modelProfiles)
1003
- ? settings.resourceDefaults.modelProfiles
1004
- : [])
1005
- .filter((profile: any) => Array.isArray(profile?.[resourceType]?.[selectionKey]))
1006
- .map((profile: any) => `${profile.provider}\0${profile.modelId}`);
1007
- const model = await selectTuiModelProfile(ctx, {
1008
- title: `${resourceLabel} Model Profile`,
1009
- subtitle: "Choose a profile to edit. This does not switch the active model.",
1010
- models,
1011
- activeModelKey: modelKey(ctx.model),
1012
- configuredModelKeys,
1013
- });
1014
- if (!model) return;
1015
- provider = model.provider;
1016
- modelId = model.id;
1017
- const action = await ctx.ui.select(`${resourceLabel} for ${provider}/${modelId}`, ["Edit selection", "Use inherited defaults"]);
1018
- if (!action) return;
1019
- const profile = exactModelProfile(settings.resourceDefaults, provider, modelId);
1020
- previousNames = profile?.[resourceType]?.[selectionKey] ?? null;
1021
- if (action === "Use inherited defaults") {
1022
- await updateWebuiSettings((current: any) => ({
1023
- resourceDefaults: {
1024
- modelProfiles: setExactModelProfile(current.resourceDefaults, provider, modelId, resourceType, null),
1025
- },
1026
- }));
1027
- await recompute(ctx);
1028
- ctx.ui.notify(`${resourceLabel} for ${provider}/${modelId} now use inherited defaults.`, "info");
1029
- return;
1030
- }
1031
- if (previousNames === null) {
1032
- previousNames = resolveResourceSelection(settings.resourceDefaults, resourceType, provider, modelId, resourceType === "tools" ? runtimeTools() : null).names;
1033
- }
1034
- }
1035
-
1036
- const selectionTarget = scope === "Model default" ? `${provider}/${modelId} model profile` : scope;
1037
- const selected = await selectTuiResources(ctx, {
1038
- title: `${resourceLabel} Configuration`,
1039
- subtitle: `${selectionTarget}. Changes apply only after Ctrl+S.`,
1040
- resources: visibleNames,
1041
- enabledResourceNames: previousNames || [],
1042
- });
1043
- if (!selected) return;
1044
- if (scope === "Session only") {
1045
- const preserved = preserveUnavailableResourceNames(previousNames, visibleNames, selected);
1046
- pi.appendEntry(resourceType === "tools" ? "webui-tools-config" : "webui-skills-config", {
1047
- version: 2,
1048
- mode: "explicit",
1049
- [selectionKey]: preserved,
1050
- });
1051
- } else if (scope === "Global default") {
1052
- await updateWebuiSettings((current: any) => ({
1053
- resourceDefaults: {
1054
- [resourceType]: {
1055
- [selectionKey]: preserveUnavailableResourceNames(current.resourceDefaults?.[resourceType]?.[selectionKey], visibleNames, selected),
1056
- },
1057
- },
1058
- }));
1059
- } else {
1060
- await updateWebuiSettings((current: any) => {
1061
- const currentNames = exactModelProfile(current.resourceDefaults, provider, modelId)?.[resourceType]?.[selectionKey];
1062
- const preserved = preserveUnavailableResourceNames(currentNames, visibleNames, selected);
1063
- return {
1064
- resourceDefaults: {
1065
- modelProfiles: setExactModelProfile(current.resourceDefaults, provider, modelId, resourceType, preserved),
1066
- },
1067
- };
1068
- });
1069
- }
1070
- await recompute(ctx);
1071
- ctx.ui.notify(`${resourceLabel} ${selectionTarget.toLowerCase()} saved.`, "info");
1072
- }
1073
-
1074
- pi.registerCommand("tools", {
1075
- description: "Choose session, global, or exact-model tools",
1076
- handler: async (_args, ctx) => runSelector("tools", ctx),
1077
- });
1078
- pi.registerCommand("skills", {
1079
- description: "Choose session, global, or exact-model skills",
1080
- handler: async (_args, ctx) => runSelector("skills", ctx),
1081
- });
1082
- pi.on("session_start", async (_event, ctx) => {
1083
- tuiActive = ctx.mode === "tui";
1084
- if (tuiActive) {
1085
- if (runtimeToolBaseline === undefined) enabledTools = new Set(runtimeTools());
1086
- await recompute(ctx);
1087
- }
1088
- });
1089
- pi.on("session_tree", async (_event, ctx) => {
1090
- tuiActive = ctx.mode === "tui";
1091
- if (tuiActive) await recompute(ctx);
1092
- });
1093
- pi.on("model_select", async (event, ctx) => {
1094
- if (ctx.mode === "tui") await recompute(ctx, event.model);
1095
- });
1096
- pi.on("session_shutdown", () => {
1097
- tuiActive = false;
1098
- generation += 1;
1099
- });
1100
- pi.on("input", async (event, ctx) => {
1101
- if (!tuiActive || ctx.mode !== "tui") return { action: "continue" };
1102
- const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
1103
- if (!match || isSkillEnabled(match[1])) return { action: "continue" };
1104
- ctx.ui.notify(`Skill /skill:${match[1]} is disabled by /skills.`, "warning");
1105
- return { action: "handled" };
1106
- });
1107
- pi.on("before_agent_start", async (event) => {
1108
- if (!tuiActive || (enabledSkills === null && legacyDisabledSkills.size === 0)) return undefined;
1109
- const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
1110
- const disabledNames = allSkills.filter((skill: any) => !isSkillEnabled(skill.name)).map((skill: any) => skill.name);
1111
- const filtered = allSkills.filter((skill: any) => isSkillEnabled(skill.name) && skill.disableModelInvocation !== true);
1112
- if (filtered.length === allSkills.length) return undefined;
1113
- let nextPrompt = event.systemPrompt;
1114
- const nextSection = formatSkillsForPrompt(filtered);
1115
- if (nextPrompt.includes("<available_skills>")) {
1116
- nextPrompt = nextPrompt.replace(/\n?The following skills provide[\s\S]*?<\/available_skills>\n?/m, nextSection ? `\n${nextSection}\n` : "\n");
1117
- }
1118
- for (const name of disabledNames) {
1119
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1120
- nextPrompt = nextPrompt.replace(new RegExp(`\\n? <skill>\\n <name>${escaped}<\\/name>[\\s\\S]*? <\\/skill>`, "g"), "");
1121
- }
1122
- return { systemPrompt: nextPrompt };
1123
- });
1124
- }
1125
-
1126
872
  export default function (pi: ExtensionAPI) {
1127
- registerTuiResourceController(pi);
1128
873
  const subagentGate = registerSubagentGate(pi);
1129
874
  pi.on("session_shutdown", () => subagentGate.dispose());
1130
875