@firstpick/pi-package-webui 0.6.2 → 0.6.3

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/README.md CHANGED
@@ -126,6 +126,8 @@ Environment variables:
126
126
  - `PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT=/path/to/package-root` overrides the npm prefix used for optional companion installs.
127
127
  - `PI_WEBUI_FAST_PICKS_FILE=/path/to/paths.json` overrides saved cwd fast-pick storage.
128
128
  - `PI_WEBUI_NPM_BIN=/path/to/npm` selects the npm executable used by optional feature install/update actions.
129
+ - `PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY=1` lets optional bang-command autocomplete include local fish/bash/zsh history executables.
130
+ - `PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH=/path/to/runtime.json` overrides the runtime store shared with `@firstpick/pi-extension-bang-command-autocomplete`.
129
131
 
130
132
  Optional Natural Conversation server-side voice fallback variables:
131
133
 
@@ -144,7 +146,7 @@ Optional Natural Conversation server-side voice fallback variables:
144
146
  - Automatic tab naming from the first prompt, with `--name <name>` still available for an explicit initial tab name.
145
147
  - Streaming chat transcript with Markdown, copy buttons for fenced code blocks, rendered Mermaid diagrams from fenced `mermaid`/`mmd` code blocks, thinking output, tool/bash cards, queue and compaction events, edit-and-retry from user prompts, transcript search, copy buttons, and guarded abort controls that require holding Esc or the Abort button for 3 seconds.
146
148
  - Prompt composer with uploads, drag/drop/paste, inline image support, generated text attachments for long input or clipboard text, editable text attachments, slash-command autocomplete, and `@` file/path references with live suggestions.
147
- - Leading `!` and `!!` user-bash commands from the composer, serialized per tab; `!` keeps output in the next model context and `!!` excludes it.
149
+ - Leading `!` and `!!` user-bash commands from the composer, serialized per tab; `!` keeps output in the next model context and `!!` excludes it. When the optional `@firstpick/pi-extension-bang-command-autocomplete` companion is loaded, the browser composer also suggests `!`/`!!` shell commands through `GET /api/bang-suggestions?tab=<tabId>&query=<command>`. When the optional `@firstpick/pi-extension-fish-user-bash` companion is loaded, Web UI user-bash execution emits the Pi `user_bash` event so the companion can provide the selected shell backend.
148
150
  - 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.
149
151
  - 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.
150
152
  - Browser-native Pi dialogs for `/model`, `/settings`, `/theme`, `/fork`, `/clone`, `/name`, `/resume`, `/tree`, `/login`, `/logout`, `/scoped-models`, `/tools`, and `/skills`, plus native-command adapter output for `/copy`, `/session`, `/new`, `/compact`, `/reload`, and `/export`.
@@ -320,6 +322,7 @@ Useful browser endpoints exposed by the local server include:
320
322
  - `POST /api/prompt`, `POST /api/follow-up`, `POST /api/steer`, `POST /api/bash`, `POST /api/abort`, and `POST /api/abort-bash` for tab-scoped Pi interaction.
321
323
  - `POST /api/attachments` for uploaded/generated prompt attachments and inline images.
322
324
  - `GET /api/path-suggestions?tab=<tabId>&query=<path>` for `@` file/path references with live suggestions.
325
+ - `GET /api/bang-suggestions?tab=<tabId>&query=<command>` for optional `@firstpick/pi-extension-bang-command-autocomplete` `!`/`!!` command suggestions.
323
326
  - `GET /api/path-fast-picks` and `POST /api/path-fast-picks` for server-persisted cwd fast picks.
324
327
  - `GET /api/native-parity` for the packaged native TUI/Web UI parity matrix.
325
328
  - `GET /api/settings`, `POST /api/settings`, `GET /api/tools`, `POST /api/tools`, `GET /api/skills`, and `POST /api/skills` for browser-native Pi settings/tool/skill selectors.
@@ -353,6 +356,8 @@ When the standalone global `pi-webui` launcher is used, optional companion insta
353
356
  Optional companions:
354
357
 
355
358
  - `@firstpick/pi-package-natural-conversation` — standalone `/talk` Natural Conversation Mode package. Web UI does not import or load it directly; it detects the package through RPC-visible `/talk`, `/voice`, or `/conversation` commands and renders the optional shell only for tabs where those commands are available.
359
+ - `@firstpick/pi-extension-bang-command-autocomplete` — `!`/`!!` shell-command autocomplete. Native Pi TUI autocomplete still uses the companion provider; Web UI uses its own browser endpoint because RPC autocomplete providers do not reach the browser composer.
360
+ - `@firstpick/pi-extension-fish-user-bash` — fish/user-shell backend for `!`/`!!` user bash. Web UI emits Pi `user_bash` from the RPC helper so the companion can supply shell operations before default bash execution.
356
361
  - `@firstpick/pi-extension-btw` — ephemeral `/btw` side-question command with a TUI overlay, Web UI live output widget, and Transfer Context action.
357
362
  - `@firstpick/pi-prompts-git-pr` — guided Git commit/push workflow.
358
363
  - `@firstpick/pi-extension-release-npm` — NPM publish menu and release widgets.
package/bin/pi-webui.mjs CHANGED
@@ -5,7 +5,7 @@ import { createReadStream } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
7
  import { access, copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
8
- import { homedir, networkInterfaces, tmpdir } from "node:os";
8
+ import { homedir, networkInterfaces, platform, tmpdir } from "node:os";
9
9
  import path from "node:path";
10
10
  import { StringDecoder } from "node:string_decoder";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -88,6 +88,10 @@ const CODEX_USAGE_TIMEOUT_MS = 15 * 1000;
88
88
  const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
89
89
  const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
90
90
  const OPENAI_CODEX_USAGE_ENDPOINT = process.env.PI_WEBUI_CODEX_USAGE_URL || "https://chatgpt.com/backend-api/wham/usage";
91
+ const CLAUDE_USAGE_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_WEBUI_CLAUDE_USAGE_TIMEOUT_MS || "30000", 10) || 30000);
92
+ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
93
+ const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
94
+ const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
91
95
  const BODY_LIMIT_BYTES = 1024 * 1024;
92
96
  const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
93
97
  const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
@@ -129,6 +133,8 @@ const EXTENSION_UI_BLOCKING_METHODS = new Set(["select", "confirm", "input", "ed
129
133
  const STATUS_RPC_TIMEOUT_MS = 1_800;
130
134
  const FAST_PICK_LIMIT = 30;
131
135
  const PATH_SUGGESTION_LIMIT = 20;
136
+ const BANG_SUGGESTION_LIMIT = 24;
137
+ const BANG_SUGGESTION_QUERY_LIMIT = 512;
132
138
  const PATH_SUGGESTION_QUERY_LIMIT = 512;
133
139
  const PATH_SUGGESTION_SCAN_LIMIT = 5000;
134
140
  const PATH_SUGGESTION_MAX_OUTPUT_LENGTH = 300000;
@@ -244,6 +250,8 @@ function parseSlashCommand(message) {
244
250
  }
245
251
  const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
246
252
  const OPTIONAL_FEATURE_PACKAGES = new Map([
253
+ ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete"],
254
+ ["fishUserBash", "@firstpick/pi-extension-fish-user-bash"],
247
255
  ["btwCommand", "@firstpick/pi-extension-btw"],
248
256
  ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
249
257
  ["releaseNpm", "@firstpick/pi-extension-release-npm"],
@@ -3129,6 +3137,238 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
3129
3137
  };
3130
3138
  }
3131
3139
 
3140
+ const CLAUDE_USAGE_MONTHS = new Map([
3141
+ ["jan", 1], ["january", 1], ["feb", 2], ["february", 2],
3142
+ ["mar", 3], ["march", 3], ["apr", 4], ["april", 4], ["may", 5],
3143
+ ["jun", 6], ["june", 6], ["jul", 7], ["july", 7], ["aug", 8], ["august", 8],
3144
+ ["sep", 9], ["sept", 9], ["september", 9], ["oct", 10], ["october", 10],
3145
+ ["nov", 11], ["november", 11], ["dec", 12], ["december", 12],
3146
+ ]);
3147
+ const CLAUDE_USAGE_WEEKDAYS = new Map([
3148
+ ["sun", 0], ["sunday", 0], ["mon", 1], ["monday", 1],
3149
+ ["tue", 2], ["tues", 2], ["tuesday", 2], ["wed", 3], ["wednesday", 3],
3150
+ ["thu", 4], ["thur", 4], ["thurs", 4], ["thursday", 4],
3151
+ ["fri", 5], ["friday", 5], ["sat", 6], ["saturday", 6],
3152
+ ]);
3153
+
3154
+ function normalizedTimeZone(value) {
3155
+ const timeZone = String(value || "").trim();
3156
+ if (!timeZone) return "";
3157
+ try {
3158
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(new Date());
3159
+ return timeZone;
3160
+ } catch {
3161
+ return "";
3162
+ }
3163
+ }
3164
+
3165
+ function datePartsInTimeZone(date, timeZone) {
3166
+ const parts = {};
3167
+ const formatter = new Intl.DateTimeFormat("en-US", {
3168
+ timeZone,
3169
+ year: "numeric",
3170
+ month: "numeric",
3171
+ day: "numeric",
3172
+ hour: "numeric",
3173
+ minute: "numeric",
3174
+ second: "numeric",
3175
+ hourCycle: "h23",
3176
+ });
3177
+ for (const part of formatter.formatToParts(date)) {
3178
+ if (part.type !== "literal") parts[part.type] = Number(part.value);
3179
+ }
3180
+ if (parts.hour === 24) parts.hour = 0;
3181
+ return {
3182
+ year: parts.year,
3183
+ month: parts.month,
3184
+ day: parts.day,
3185
+ hour: parts.hour || 0,
3186
+ minute: parts.minute || 0,
3187
+ second: parts.second || 0,
3188
+ };
3189
+ }
3190
+
3191
+ function zonedDateTimeToUtc(parts, timeZone) {
3192
+ const targetWallTime = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour || 0, parts.minute || 0, parts.second || 0);
3193
+ let guess = targetWallTime;
3194
+ for (let index = 0; index < 4; index++) {
3195
+ const actual = datePartsInTimeZone(new Date(guess), timeZone);
3196
+ const actualWallTime = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour || 0, actual.minute || 0, actual.second || 0);
3197
+ const delta = targetWallTime - actualWallTime;
3198
+ if (delta === 0) break;
3199
+ guess += delta;
3200
+ }
3201
+ return new Date(guess);
3202
+ }
3203
+
3204
+ function parseClaudeUsageClock(hourValue, minuteValue, meridiemValue) {
3205
+ let hour = Number(hourValue);
3206
+ const minute = minuteValue === undefined || minuteValue === "" ? 0 : Number(minuteValue);
3207
+ if (!Number.isInteger(hour) || !Number.isInteger(minute) || minute < 0 || minute > 59) return null;
3208
+ const meridiem = String(meridiemValue || "").replace(/\./g, "").toLowerCase();
3209
+ if (meridiem) {
3210
+ if (hour < 1 || hour > 12) return null;
3211
+ if (meridiem === "pm" && hour !== 12) hour += 12;
3212
+ if (meridiem === "am" && hour === 12) hour = 0;
3213
+ } else if (hour < 0 || hour > 23) return null;
3214
+ return { hour, minute };
3215
+ }
3216
+
3217
+ function parseClaudeUsageMonthReset(dateText, timeZone, now) {
3218
+ const match = String(dateText || "").trim().match(/^([A-Za-z]{3,9})\s+(\d{1,2}),\s*(\d{1,2})(?::(\d{2}))?\s*([ap]\.?m\.?)?$/i);
3219
+ if (!match) return null;
3220
+ const month = CLAUDE_USAGE_MONTHS.get(match[1].toLowerCase());
3221
+ const day = Number(match[2]);
3222
+ const clock = parseClaudeUsageClock(match[3], match[4], match[5]);
3223
+ if (!month || !Number.isInteger(day) || day < 1 || day > 31 || !clock) return null;
3224
+ const nowParts = datePartsInTimeZone(now, timeZone);
3225
+ let resetDate = zonedDateTimeToUtc({ year: nowParts.year, month, day, ...clock }, timeZone);
3226
+ if (resetDate.getTime() < now.getTime() - 60_000) resetDate = zonedDateTimeToUtc({ year: nowParts.year + 1, month, day, ...clock }, timeZone);
3227
+ return Number.isFinite(resetDate.getTime()) ? resetDate : null;
3228
+ }
3229
+
3230
+ function parseClaudeUsageWeekdayReset(dateText, timeZone, now) {
3231
+ const match = String(dateText || "").trim().match(/^([A-Za-z]{3,9})\s+(\d{1,2})(?::(\d{2}))?\s*([ap]\.?m\.?)?$/i);
3232
+ if (!match) return null;
3233
+ const weekday = CLAUDE_USAGE_WEEKDAYS.get(match[1].toLowerCase());
3234
+ const clock = parseClaudeUsageClock(match[2], match[3], match[4]);
3235
+ if (weekday === undefined || !clock) return null;
3236
+ const nowParts = datePartsInTimeZone(now, timeZone);
3237
+ const currentWeekday = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day)).getUTCDay();
3238
+ let deltaDays = (weekday - currentWeekday + 7) % 7;
3239
+ let date = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day + deltaDays));
3240
+ let resetDate = zonedDateTimeToUtc({ year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate(), ...clock }, timeZone);
3241
+ if (resetDate.getTime() < now.getTime() - 60_000) {
3242
+ deltaDays += 7;
3243
+ date = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day + deltaDays));
3244
+ resetDate = zonedDateTimeToUtc({ year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate(), ...clock }, timeZone);
3245
+ }
3246
+ return Number.isFinite(resetDate.getTime()) ? resetDate : null;
3247
+ }
3248
+
3249
+ function parseClaudeUsageReset(resetText, now = new Date()) {
3250
+ const text = String(resetText || "").trim();
3251
+ if (!text) return { resetText: "" };
3252
+ const rawTimeZone = text.match(/\(([^)]+)\)\s*$/)?.[1] || "";
3253
+ const timeZone = normalizedTimeZone(rawTimeZone) || normalizedTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone);
3254
+ const dateText = text.replace(/\s*\([^)]+\)\s*$/, "").trim();
3255
+ if (!timeZone) return { resetText: text, timeZone: rawTimeZone || null };
3256
+ const resetDate = parseClaudeUsageMonthReset(dateText, timeZone, now) || parseClaudeUsageWeekdayReset(dateText, timeZone, now);
3257
+ if (!resetDate) return { resetText: text, timeZone };
3258
+ return {
3259
+ resetText: text,
3260
+ timeZone,
3261
+ resetsAt: resetDate.toISOString(),
3262
+ resetAfterSeconds: Math.max(0, Math.round((resetDate.getTime() - now.getTime()) / 1000)),
3263
+ };
3264
+ }
3265
+
3266
+ function parseClaudeUsageWindowLine(line, now) {
3267
+ const match = String(line || "").trim().match(/^(.+?):\s+(\d+(?:\.\d+)?)%\s+used\s+[·-]\s+resets\s+(.+)$/i);
3268
+ if (!match) return null;
3269
+ return {
3270
+ label: match[1].trim(),
3271
+ usedPercent: Number(match[2]),
3272
+ ...parseClaudeUsageReset(match[3], now),
3273
+ };
3274
+ }
3275
+
3276
+ function parseClaudeUsageActivityHeader(line) {
3277
+ const match = String(line || "").trim().match(/^(.+?)\s+[·-]\s+(\d+)\s+requests?\s+[·-]\s+(\d+)\s+sessions?$/i);
3278
+ if (!match) return null;
3279
+ return { label: match[1].trim(), requests: Number(match[2]), sessions: Number(match[3]), details: [] };
3280
+ }
3281
+
3282
+ function parseClaudeUsageActivityDetail(line) {
3283
+ const text = String(line || "").trim();
3284
+ const percentMatch = text.match(/^(\d+(?:\.\d+)?)%\s+(.+)$/);
3285
+ if (percentMatch) return { text, percent: Number(percentMatch[1]), description: percentMatch[2] };
3286
+ return { text };
3287
+ }
3288
+
3289
+ function parseClaudeUsageText(text, now = new Date()) {
3290
+ const summary = [];
3291
+ const notes = [];
3292
+ const windows = [];
3293
+ const activity = [];
3294
+ let activityTitle = "";
3295
+ let currentActivity = null;
3296
+ for (const rawLine of stripAnsi(text).replace(/\r/g, "").split("\n")) {
3297
+ const line = rawLine.trim();
3298
+ if (!line) continue;
3299
+ const window = parseClaudeUsageWindowLine(line, now);
3300
+ if (window) {
3301
+ windows.push(window);
3302
+ currentActivity = null;
3303
+ continue;
3304
+ }
3305
+ const activityHeader = parseClaudeUsageActivityHeader(line);
3306
+ if (activityHeader) {
3307
+ activity.push(activityHeader);
3308
+ currentActivity = activityHeader;
3309
+ continue;
3310
+ }
3311
+ if (currentActivity && /^\s+/.test(rawLine)) {
3312
+ currentActivity.details.push(parseClaudeUsageActivityDetail(line));
3313
+ continue;
3314
+ }
3315
+ if (/^what'?s contributing/i.test(line)) {
3316
+ activityTitle = line;
3317
+ currentActivity = null;
3318
+ continue;
3319
+ }
3320
+ if (summary.length === 0 && /using your subscription|claude code usage/i.test(line)) summary.push(line);
3321
+ else notes.push(line);
3322
+ }
3323
+ return { summary: summary[0] || "", windows, activityTitle, activity, notes };
3324
+ }
3325
+
3326
+ async function getClaudeCodeUsageStatus() {
3327
+ const result = await runCommand(CLAUDE_USAGE_COMMAND, CLAUDE_USAGE_ARGS, {
3328
+ cwd: options.cwd,
3329
+ timeoutMs: CLAUDE_USAGE_TIMEOUT_MS,
3330
+ maxOutputLength: CLAUDE_USAGE_OUTPUT_MAX_CHARS,
3331
+ });
3332
+ const command = formatCommandForDisplay(CLAUDE_USAGE_COMMAND, CLAUDE_USAGE_ARGS);
3333
+ if (result.timedOut) throw makeHttpError(504, `Claude usage command timed out: ${command}`);
3334
+ if (result.error && result.exitCode === undefined) throw makeHttpError(502, `Claude usage command failed: ${result.error}`);
3335
+ if (result.exitCode !== 0) {
3336
+ const detail = truncateLongText(stripAnsi(result.stderr || result.stdout || ""), 2000).trim();
3337
+ throw makeHttpError(502, `Claude usage command exited ${result.exitCode}${detail ? `: ${detail}` : ""}`);
3338
+ }
3339
+ const stdout = stripAnsi(result.stdout || "").trim();
3340
+ if (!stdout) throw makeHttpError(502, "Claude usage command returned no output");
3341
+ let usageText = stdout;
3342
+ let outputFormat = "text";
3343
+ let sessionId = null;
3344
+ let durationMs = undefined;
3345
+ if (stdout.startsWith("{")) {
3346
+ let parsed;
3347
+ try {
3348
+ parsed = JSON.parse(stdout);
3349
+ } catch {
3350
+ throw makeHttpError(502, "Claude usage command returned invalid JSON");
3351
+ }
3352
+ outputFormat = "json";
3353
+ sessionId = typeof parsed.session_id === "string" ? parsed.session_id : null;
3354
+ durationMs = numericValue(parsed.duration_ms);
3355
+ if (parsed.is_error) throw makeHttpError(502, parsed.result || "Claude usage command returned an error");
3356
+ if (typeof parsed.result === "string") usageText = parsed.result;
3357
+ }
3358
+ const fetchedAt = new Date();
3359
+ return {
3360
+ available: true,
3361
+ providerId: "claude-code",
3362
+ source: "claude-code-cli",
3363
+ command,
3364
+ outputFormat,
3365
+ fetchedAt: fetchedAt.toISOString(),
3366
+ durationMs,
3367
+ sessionId,
3368
+ ...parseClaudeUsageText(usageText, fetchedAt),
3369
+ };
3370
+ }
3371
+
3132
3372
  async function configuredScopedModelPatterns(cwd = options.cwd) {
3133
3373
  const cliPatterns = parseCliScopedModelPatterns();
3134
3374
  if (cliPatterns !== undefined) return { patterns: cliPatterns, source: "cli" };
@@ -3295,6 +3535,209 @@ function cleanPathSuggestionQuery(value) {
3295
3535
  return normalizeSuggestionPath(value).replace(/\0/g, "").slice(0, PATH_SUGGESTION_QUERY_LIMIT);
3296
3536
  }
3297
3537
 
3538
+ const BANG_COMMON_COMMANDS_BASE = [
3539
+ "ls", "la", "ll", "cd", "pwd", "cat", "less", "bat", "rg", "fd", "find", "grep", "sed", "awk", "jq",
3540
+ "git", "gh", "g", "pnpm", "bun", "npm", "node", "python", "python3", "uv", "cargo", "rustc", "make", "just",
3541
+ "docker", "docker-compose", "curl", "wget", "ssh", "scp", "rsync", "tmux", "htop", "btop",
3542
+ ];
3543
+ const BANG_COMMON_COMMANDS_UNIX = ["systemctl", "journalctl"];
3544
+ const BANG_COMMON_COMMANDS_LINUX = ["pacman", "yay"];
3545
+
3546
+ function bangCommonCommands() {
3547
+ const commands = [...BANG_COMMON_COMMANDS_BASE];
3548
+ const currentPlatform = platform();
3549
+ if (currentPlatform !== "win32") commands.push(...BANG_COMMON_COMMANDS_UNIX);
3550
+ if (currentPlatform === "linux") commands.push(...BANG_COMMON_COMMANDS_LINUX);
3551
+ return commands;
3552
+ }
3553
+
3554
+ function cleanBangSuggestionQuery(value) {
3555
+ return String(value || "").replace(/\0/g, "").replace(/^!+/, "").slice(0, BANG_SUGGESTION_QUERY_LIMIT);
3556
+ }
3557
+
3558
+ function parseBangCommandLine(commandLine) {
3559
+ const trimmed = String(commandLine || "").trim();
3560
+ if (!trimmed || trimmed.startsWith("#")) return { flags: [] };
3561
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
3562
+ let startIndex = 0;
3563
+ let executable = tokens[startIndex] || "";
3564
+ if (executable === "sudo") {
3565
+ startIndex += 1;
3566
+ executable = tokens[startIndex] || "";
3567
+ }
3568
+ executable = executable.replace(/^!+/, "");
3569
+ if (!executable) return { flags: [] };
3570
+ const flags = tokens.slice(startIndex + 1).filter((token) => token.startsWith("-") && token !== "-");
3571
+ return { executable, flags };
3572
+ }
3573
+
3574
+ function bangExecutable(commandLine) {
3575
+ return parseBangCommandLine(commandLine).executable;
3576
+ }
3577
+
3578
+ async function readTextFileIfExists(filePath) {
3579
+ try {
3580
+ return await readFile(filePath, "utf8");
3581
+ } catch {
3582
+ return "";
3583
+ }
3584
+ }
3585
+
3586
+ async function readFishHistoryExecutables() {
3587
+ const fishDataHome = process.env.XDG_DATA_HOME?.trim() || path.join(homedir(), ".local", "share");
3588
+ const content = await readTextFileIfExists(path.join(fishDataHome, "fish", "fish_history"));
3589
+ const commands = [];
3590
+ for (const line of content.split(/\r?\n/)) {
3591
+ const match = line.match(/^\s*-\s*cmd:\s*(.*)$/);
3592
+ const executable = match ? bangExecutable(match[1]) : "";
3593
+ if (executable) commands.push(executable);
3594
+ }
3595
+ return commands;
3596
+ }
3597
+
3598
+ async function readBashHistoryExecutables() {
3599
+ const content = await readTextFileIfExists(path.join(homedir(), ".bash_history"));
3600
+ return content.split(/\r?\n/).map((line) => bangExecutable(line)).filter(Boolean);
3601
+ }
3602
+
3603
+ async function readZshHistoryExecutables() {
3604
+ const content = await readTextFileIfExists(path.join(homedir(), ".zsh_history"));
3605
+ return content
3606
+ .split(/\r?\n/)
3607
+ .map((line) => bangExecutable(line.includes(";") ? line.slice(line.indexOf(";") + 1) : line))
3608
+ .filter(Boolean);
3609
+ }
3610
+
3611
+ function bangRuntimeStorePath() {
3612
+ const configured = process.env.PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH?.trim();
3613
+ return configured ? path.resolve(expandUserPath(configured)) : path.join(agentDir, "state", "bang-command-autocomplete-runtime.json");
3614
+ }
3615
+
3616
+ async function readBangRuntimeData() {
3617
+ const empty = { commands: new Set(), flagsByCommand: new Map(), lines: new Set() };
3618
+ const parsed = await readJsonFileIfExists(bangRuntimeStorePath());
3619
+ if (Array.isArray(parsed)) {
3620
+ for (const item of parsed) {
3621
+ const line = String(item || "").trim();
3622
+ if (!line) continue;
3623
+ const executable = bangExecutable(line);
3624
+ if (executable) empty.commands.add(executable);
3625
+ empty.lines.add(line.replace(/^!+/, ""));
3626
+ }
3627
+ return empty;
3628
+ }
3629
+ if (!parsed || typeof parsed !== "object") return empty;
3630
+ for (const item of Array.isArray(parsed.commands) ? parsed.commands : []) {
3631
+ const command = String(item || "").trim();
3632
+ if (command) empty.commands.add(command);
3633
+ }
3634
+ if (parsed.flags && typeof parsed.flags === "object") {
3635
+ for (const [command, flags] of Object.entries(parsed.flags)) {
3636
+ const normalizedCommand = String(command || "").trim();
3637
+ if (!normalizedCommand || !Array.isArray(flags)) continue;
3638
+ const normalizedFlags = flags.map((flag) => String(flag || "").trim()).filter(Boolean);
3639
+ if (normalizedFlags.length) empty.flagsByCommand.set(normalizedCommand, new Set(normalizedFlags));
3640
+ }
3641
+ }
3642
+ for (const item of Array.isArray(parsed.lines) ? parsed.lines : []) {
3643
+ const line = String(item || "").trim().replace(/^!+/, "");
3644
+ if (line) empty.lines.add(line);
3645
+ }
3646
+ return empty;
3647
+ }
3648
+
3649
+ async function buildBangCommandIndex(includeHistory, runtimeData) {
3650
+ const merged = new Map();
3651
+ for (const command of bangCommonCommands()) merged.set(command, "common");
3652
+ if (includeHistory) {
3653
+ const historyExecutables = [
3654
+ ...await readFishHistoryExecutables(),
3655
+ ...await readBashHistoryExecutables(),
3656
+ ...await readZshHistoryExecutables(),
3657
+ ];
3658
+ for (let index = historyExecutables.length - 1; index >= 0; index--) {
3659
+ const command = historyExecutables[index];
3660
+ if (command && (!merged.has(command) || merged.get(command) === "common")) merged.set(command, "history");
3661
+ }
3662
+ }
3663
+ for (const command of runtimeData.commands) merged.set(command, "runtime");
3664
+ return Array.from(merged.entries()).map(([command, source]) => ({ command, source }));
3665
+ }
3666
+
3667
+ function rankBangValues(values, query) {
3668
+ const q = String(query || "").toLowerCase();
3669
+ const startsWith = [];
3670
+ const includes = [];
3671
+ for (const value of values) {
3672
+ const text = typeof value === "string" ? value : value.command;
3673
+ const lower = String(text || "").toLowerCase();
3674
+ if (!q || lower.startsWith(q)) startsWith.push(value);
3675
+ else if (lower.includes(q)) includes.push(value);
3676
+ }
3677
+ return [...startsWith, ...includes].slice(0, BANG_SUGGESTION_LIMIT);
3678
+ }
3679
+
3680
+ function bangSuggestion(insertText, label, description, kind = "command") {
3681
+ return { insertText, label, description, kind };
3682
+ }
3683
+
3684
+ function bangSourceLabel(source) {
3685
+ if (source === "history") return "shell history";
3686
+ if (source === "runtime") return "current session";
3687
+ return "common command";
3688
+ }
3689
+
3690
+ async function getBangSuggestionData(tab, rawQuery) {
3691
+ const query = cleanBangSuggestionQuery(rawQuery);
3692
+ const includeHistory = isTruthyEnv(process.env.PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY);
3693
+ const runtimeData = await readBangRuntimeData();
3694
+ const commandIndex = await buildBangCommandIndex(includeHistory, runtimeData);
3695
+ const suggestions = [];
3696
+ const flagMatch = query.match(/^(\S+)\s+(\S*)$/);
3697
+
3698
+ if (flagMatch && (!flagMatch[2] || flagMatch[2].startsWith("-"))) {
3699
+ const command = flagMatch[1];
3700
+ const partialFlag = flagMatch[2] || "";
3701
+ for (const flag of rankBangValues(Array.from(runtimeData.flagsByCommand.get(command) || []), partialFlag)) {
3702
+ suggestions.push(bangSuggestion(`${command} ${flag}`, `!${command} ${flag}`, `learned for ${command}`, "flag"));
3703
+ }
3704
+ }
3705
+
3706
+ if (query.includes(" ")) {
3707
+ for (const lineCandidate of rankBangValues(Array.from(runtimeData.lines), query)) {
3708
+ suggestions.push(bangSuggestion(lineCandidate, `!${lineCandidate}`, "learned full line", "line"));
3709
+ }
3710
+ }
3711
+
3712
+ if (!query.includes(" ")) {
3713
+ const ranked = rankBangValues(commandIndex, query);
3714
+ for (const entry of ranked) {
3715
+ suggestions.push(bangSuggestion(entry.command, `!${entry.command}`, bangSourceLabel(entry.source), "command"));
3716
+ }
3717
+ for (const entry of ranked) {
3718
+ for (const flag of Array.from(runtimeData.flagsByCommand.get(entry.command) || []).slice(0, 3)) {
3719
+ suggestions.push(bangSuggestion(`${entry.command} ${flag}`, `!${entry.command} ${flag}`, "learned command + flag", "flag"));
3720
+ }
3721
+ }
3722
+ for (const lineCandidate of rankBangValues(Array.from(runtimeData.lines), query)) {
3723
+ if (lineCandidate.startsWith(query)) suggestions.push(bangSuggestion(lineCandidate, `!${lineCandidate}`, "learned full line", "line"));
3724
+ }
3725
+ }
3726
+
3727
+ const seen = new Set();
3728
+ return {
3729
+ cwd: tab.cwd,
3730
+ displayCwd: displayPath(tab.cwd),
3731
+ query,
3732
+ suggestions: suggestions.filter((item) => {
3733
+ const key = item.insertText;
3734
+ if (!key || seen.has(key)) return false;
3735
+ seen.add(key);
3736
+ return true;
3737
+ }).slice(0, BANG_SUGGESTION_LIMIT),
3738
+ };
3739
+ }
3740
+
3298
3741
  function splitSuggestionPathQuery(query) {
3299
3742
  const normalized = normalizeSuggestionPath(query);
3300
3743
  if (normalized === "~") return { displayBase: "~", prefix: "" };
@@ -8810,6 +9253,15 @@ const server = createServer(async (req, res) => {
8810
9253
  return;
8811
9254
  }
8812
9255
 
9256
+ if (url.pathname === "/api/claude-usage" && req.method === "GET") {
9257
+ try {
9258
+ sendJson(res, 200, { ok: true, data: await getClaudeCodeUsageStatus() });
9259
+ } catch (error) {
9260
+ sendJson(res, error?.statusCode || 500, { ok: false, error: error?.message || "Failed to read Claude usage" });
9261
+ }
9262
+ return;
9263
+ }
9264
+
8813
9265
  if (url.pathname === "/api/network" && req.method === "GET") {
8814
9266
  sendJson(res, 200, { ok: true, data: networkStatus({ includeAuthPin: isLocalRequest(req) }) });
8815
9267
  return;
@@ -8983,6 +9435,12 @@ const server = createServer(async (req, res) => {
8983
9435
  return;
8984
9436
  }
8985
9437
 
9438
+ if (url.pathname === "/api/bang-suggestions" && req.method === "GET") {
9439
+ const tab = getRequestedTab(req, url);
9440
+ sendJson(res, 200, { ok: true, data: await getBangSuggestionData(tab, url.searchParams.get("query")) });
9441
+ return;
9442
+ }
9443
+
8986
9444
  if (url.pathname === "/api/path-fast-picks" && req.method === "GET") {
8987
9445
  sendJson(res, 200, { ok: true, data: { picks: await readPathFastPicks() } });
8988
9446
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
@@ -23,6 +23,8 @@
23
23
  "image": "https://raw.githubusercontent.com/Firstp1ck/npm-packages/main/pi-package-webui/images/Webui_MainWindow_v0.4.8.png",
24
24
  "extensions": [
25
25
  "./index.ts",
26
+ "node_modules/@firstpick/pi-extension-bang-command-autocomplete/index.ts",
27
+ "node_modules/@firstpick/pi-extension-fish-user-bash/index.ts",
26
28
  "node_modules/@firstpick/pi-extension-btw/index.ts",
27
29
  "node_modules/@firstpick/pi-extension-git-footer-status/index.ts",
28
30
  "node_modules/@firstpick/pi-extension-release-aur/index.ts",
@@ -57,17 +59,19 @@
57
59
  "mermaid": "^11.15.0"
58
60
  },
59
61
  "optionalDependencies": {
60
- "@firstpick/pi-extension-btw": "^0.1.1",
61
- "@firstpick/pi-extension-git-footer-status": "^0.3.5",
62
- "@firstpick/pi-extension-release-aur": "^0.1.6",
62
+ "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
63
+ "@firstpick/pi-extension-btw": "^0.1.2",
64
+ "@firstpick/pi-extension-fish-user-bash": "^0.2.0",
65
+ "@firstpick/pi-extension-git-footer-status": "^0.3.6",
66
+ "@firstpick/pi-extension-release-aur": "^0.1.7",
63
67
  "@firstpick/pi-extension-release-npm": "^0.4.0",
64
68
  "@firstpick/pi-extension-safety-guard": "^0.2.3",
65
69
  "@firstpick/pi-extension-setup-skills": "^0.1.8",
66
- "@firstpick/pi-extension-stats": "^0.2.7",
70
+ "@firstpick/pi-extension-stats": "^0.2.8",
67
71
  "@firstpick/pi-extension-todo-progress": "^0.2.7",
68
72
  "@firstpick/pi-extension-tools": "^0.1.6",
69
- "@firstpick/pi-extension-workflows": "^0.1.1",
70
- "@firstpick/pi-package-remote-webui": "^0.1.4",
73
+ "@firstpick/pi-extension-workflows": "^0.1.2",
74
+ "@firstpick/pi-package-remote-webui": "^0.1.5",
71
75
  "@firstpick/pi-prompts-git-pr": "^0.1.2",
72
76
  "@firstpick/pi-themes-bundle": "^0.1.4"
73
77
  },