@firstpick/pi-package-webui 0.6.2 → 0.6.4

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/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,8 +88,20 @@ 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;
97
+ const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
98
+ const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
99
+ const FILE_TREE_MAX_ENTRIES = 1200;
100
+ const FILE_TREE_ENTRY_STAT_CONCURRENCY = 32;
101
+ const FILE_SEARCH_MAX_RESULTS = 200;
102
+ const FILE_SEARCH_MAX_SCANNED = 12_000;
103
+ const FILE_SEARCH_MAX_DEPTH = 8;
104
+ const FILE_SEARCH_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
93
105
  const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
94
106
  const VOICE_AUDIO_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
95
107
  const VOICE_AUDIO_JSON_BODY_LIMIT_BYTES = Math.ceil(VOICE_AUDIO_BODY_LIMIT_BYTES * 1.4) + 1024 * 1024;
@@ -129,6 +141,8 @@ const EXTENSION_UI_BLOCKING_METHODS = new Set(["select", "confirm", "input", "ed
129
141
  const STATUS_RPC_TIMEOUT_MS = 1_800;
130
142
  const FAST_PICK_LIMIT = 30;
131
143
  const PATH_SUGGESTION_LIMIT = 20;
144
+ const BANG_SUGGESTION_LIMIT = 24;
145
+ const BANG_SUGGESTION_QUERY_LIMIT = 512;
132
146
  const PATH_SUGGESTION_QUERY_LIMIT = 512;
133
147
  const PATH_SUGGESTION_SCAN_LIMIT = 5000;
134
148
  const PATH_SUGGESTION_MAX_OUTPUT_LENGTH = 300000;
@@ -244,6 +258,8 @@ function parseSlashCommand(message) {
244
258
  }
245
259
  const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
246
260
  const OPTIONAL_FEATURE_PACKAGES = new Map([
261
+ ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete"],
262
+ ["fishUserBash", "@firstpick/pi-extension-fish-user-bash"],
247
263
  ["btwCommand", "@firstpick/pi-extension-btw"],
248
264
  ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
249
265
  ["releaseNpm", "@firstpick/pi-extension-release-npm"],
@@ -3129,6 +3145,238 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
3129
3145
  };
3130
3146
  }
3131
3147
 
3148
+ const CLAUDE_USAGE_MONTHS = new Map([
3149
+ ["jan", 1], ["january", 1], ["feb", 2], ["february", 2],
3150
+ ["mar", 3], ["march", 3], ["apr", 4], ["april", 4], ["may", 5],
3151
+ ["jun", 6], ["june", 6], ["jul", 7], ["july", 7], ["aug", 8], ["august", 8],
3152
+ ["sep", 9], ["sept", 9], ["september", 9], ["oct", 10], ["october", 10],
3153
+ ["nov", 11], ["november", 11], ["dec", 12], ["december", 12],
3154
+ ]);
3155
+ const CLAUDE_USAGE_WEEKDAYS = new Map([
3156
+ ["sun", 0], ["sunday", 0], ["mon", 1], ["monday", 1],
3157
+ ["tue", 2], ["tues", 2], ["tuesday", 2], ["wed", 3], ["wednesday", 3],
3158
+ ["thu", 4], ["thur", 4], ["thurs", 4], ["thursday", 4],
3159
+ ["fri", 5], ["friday", 5], ["sat", 6], ["saturday", 6],
3160
+ ]);
3161
+
3162
+ function normalizedTimeZone(value) {
3163
+ const timeZone = String(value || "").trim();
3164
+ if (!timeZone) return "";
3165
+ try {
3166
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(new Date());
3167
+ return timeZone;
3168
+ } catch {
3169
+ return "";
3170
+ }
3171
+ }
3172
+
3173
+ function datePartsInTimeZone(date, timeZone) {
3174
+ const parts = {};
3175
+ const formatter = new Intl.DateTimeFormat("en-US", {
3176
+ timeZone,
3177
+ year: "numeric",
3178
+ month: "numeric",
3179
+ day: "numeric",
3180
+ hour: "numeric",
3181
+ minute: "numeric",
3182
+ second: "numeric",
3183
+ hourCycle: "h23",
3184
+ });
3185
+ for (const part of formatter.formatToParts(date)) {
3186
+ if (part.type !== "literal") parts[part.type] = Number(part.value);
3187
+ }
3188
+ if (parts.hour === 24) parts.hour = 0;
3189
+ return {
3190
+ year: parts.year,
3191
+ month: parts.month,
3192
+ day: parts.day,
3193
+ hour: parts.hour || 0,
3194
+ minute: parts.minute || 0,
3195
+ second: parts.second || 0,
3196
+ };
3197
+ }
3198
+
3199
+ function zonedDateTimeToUtc(parts, timeZone) {
3200
+ const targetWallTime = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour || 0, parts.minute || 0, parts.second || 0);
3201
+ let guess = targetWallTime;
3202
+ for (let index = 0; index < 4; index++) {
3203
+ const actual = datePartsInTimeZone(new Date(guess), timeZone);
3204
+ const actualWallTime = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour || 0, actual.minute || 0, actual.second || 0);
3205
+ const delta = targetWallTime - actualWallTime;
3206
+ if (delta === 0) break;
3207
+ guess += delta;
3208
+ }
3209
+ return new Date(guess);
3210
+ }
3211
+
3212
+ function parseClaudeUsageClock(hourValue, minuteValue, meridiemValue) {
3213
+ let hour = Number(hourValue);
3214
+ const minute = minuteValue === undefined || minuteValue === "" ? 0 : Number(minuteValue);
3215
+ if (!Number.isInteger(hour) || !Number.isInteger(minute) || minute < 0 || minute > 59) return null;
3216
+ const meridiem = String(meridiemValue || "").replace(/\./g, "").toLowerCase();
3217
+ if (meridiem) {
3218
+ if (hour < 1 || hour > 12) return null;
3219
+ if (meridiem === "pm" && hour !== 12) hour += 12;
3220
+ if (meridiem === "am" && hour === 12) hour = 0;
3221
+ } else if (hour < 0 || hour > 23) return null;
3222
+ return { hour, minute };
3223
+ }
3224
+
3225
+ function parseClaudeUsageMonthReset(dateText, timeZone, now) {
3226
+ 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);
3227
+ if (!match) return null;
3228
+ const month = CLAUDE_USAGE_MONTHS.get(match[1].toLowerCase());
3229
+ const day = Number(match[2]);
3230
+ const clock = parseClaudeUsageClock(match[3], match[4], match[5]);
3231
+ if (!month || !Number.isInteger(day) || day < 1 || day > 31 || !clock) return null;
3232
+ const nowParts = datePartsInTimeZone(now, timeZone);
3233
+ let resetDate = zonedDateTimeToUtc({ year: nowParts.year, month, day, ...clock }, timeZone);
3234
+ if (resetDate.getTime() < now.getTime() - 60_000) resetDate = zonedDateTimeToUtc({ year: nowParts.year + 1, month, day, ...clock }, timeZone);
3235
+ return Number.isFinite(resetDate.getTime()) ? resetDate : null;
3236
+ }
3237
+
3238
+ function parseClaudeUsageWeekdayReset(dateText, timeZone, now) {
3239
+ const match = String(dateText || "").trim().match(/^([A-Za-z]{3,9})\s+(\d{1,2})(?::(\d{2}))?\s*([ap]\.?m\.?)?$/i);
3240
+ if (!match) return null;
3241
+ const weekday = CLAUDE_USAGE_WEEKDAYS.get(match[1].toLowerCase());
3242
+ const clock = parseClaudeUsageClock(match[2], match[3], match[4]);
3243
+ if (weekday === undefined || !clock) return null;
3244
+ const nowParts = datePartsInTimeZone(now, timeZone);
3245
+ const currentWeekday = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day)).getUTCDay();
3246
+ let deltaDays = (weekday - currentWeekday + 7) % 7;
3247
+ let date = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day + deltaDays));
3248
+ let resetDate = zonedDateTimeToUtc({ year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate(), ...clock }, timeZone);
3249
+ if (resetDate.getTime() < now.getTime() - 60_000) {
3250
+ deltaDays += 7;
3251
+ date = new Date(Date.UTC(nowParts.year, nowParts.month - 1, nowParts.day + deltaDays));
3252
+ resetDate = zonedDateTimeToUtc({ year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate(), ...clock }, timeZone);
3253
+ }
3254
+ return Number.isFinite(resetDate.getTime()) ? resetDate : null;
3255
+ }
3256
+
3257
+ function parseClaudeUsageReset(resetText, now = new Date()) {
3258
+ const text = String(resetText || "").trim();
3259
+ if (!text) return { resetText: "" };
3260
+ const rawTimeZone = text.match(/\(([^)]+)\)\s*$/)?.[1] || "";
3261
+ const timeZone = normalizedTimeZone(rawTimeZone) || normalizedTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone);
3262
+ const dateText = text.replace(/\s*\([^)]+\)\s*$/, "").trim();
3263
+ if (!timeZone) return { resetText: text, timeZone: rawTimeZone || null };
3264
+ const resetDate = parseClaudeUsageMonthReset(dateText, timeZone, now) || parseClaudeUsageWeekdayReset(dateText, timeZone, now);
3265
+ if (!resetDate) return { resetText: text, timeZone };
3266
+ return {
3267
+ resetText: text,
3268
+ timeZone,
3269
+ resetsAt: resetDate.toISOString(),
3270
+ resetAfterSeconds: Math.max(0, Math.round((resetDate.getTime() - now.getTime()) / 1000)),
3271
+ };
3272
+ }
3273
+
3274
+ function parseClaudeUsageWindowLine(line, now) {
3275
+ const match = String(line || "").trim().match(/^(.+?):\s+(\d+(?:\.\d+)?)%\s+used\s+[·-]\s+resets\s+(.+)$/i);
3276
+ if (!match) return null;
3277
+ return {
3278
+ label: match[1].trim(),
3279
+ usedPercent: Number(match[2]),
3280
+ ...parseClaudeUsageReset(match[3], now),
3281
+ };
3282
+ }
3283
+
3284
+ function parseClaudeUsageActivityHeader(line) {
3285
+ const match = String(line || "").trim().match(/^(.+?)\s+[·-]\s+(\d+)\s+requests?\s+[·-]\s+(\d+)\s+sessions?$/i);
3286
+ if (!match) return null;
3287
+ return { label: match[1].trim(), requests: Number(match[2]), sessions: Number(match[3]), details: [] };
3288
+ }
3289
+
3290
+ function parseClaudeUsageActivityDetail(line) {
3291
+ const text = String(line || "").trim();
3292
+ const percentMatch = text.match(/^(\d+(?:\.\d+)?)%\s+(.+)$/);
3293
+ if (percentMatch) return { text, percent: Number(percentMatch[1]), description: percentMatch[2] };
3294
+ return { text };
3295
+ }
3296
+
3297
+ function parseClaudeUsageText(text, now = new Date()) {
3298
+ const summary = [];
3299
+ const notes = [];
3300
+ const windows = [];
3301
+ const activity = [];
3302
+ let activityTitle = "";
3303
+ let currentActivity = null;
3304
+ for (const rawLine of stripAnsi(text).replace(/\r/g, "").split("\n")) {
3305
+ const line = rawLine.trim();
3306
+ if (!line) continue;
3307
+ const window = parseClaudeUsageWindowLine(line, now);
3308
+ if (window) {
3309
+ windows.push(window);
3310
+ currentActivity = null;
3311
+ continue;
3312
+ }
3313
+ const activityHeader = parseClaudeUsageActivityHeader(line);
3314
+ if (activityHeader) {
3315
+ activity.push(activityHeader);
3316
+ currentActivity = activityHeader;
3317
+ continue;
3318
+ }
3319
+ if (currentActivity && /^\s+/.test(rawLine)) {
3320
+ currentActivity.details.push(parseClaudeUsageActivityDetail(line));
3321
+ continue;
3322
+ }
3323
+ if (/^what'?s contributing/i.test(line)) {
3324
+ activityTitle = line;
3325
+ currentActivity = null;
3326
+ continue;
3327
+ }
3328
+ if (summary.length === 0 && /using your subscription|claude code usage/i.test(line)) summary.push(line);
3329
+ else notes.push(line);
3330
+ }
3331
+ return { summary: summary[0] || "", windows, activityTitle, activity, notes };
3332
+ }
3333
+
3334
+ async function getClaudeCodeUsageStatus() {
3335
+ const result = await runCommand(CLAUDE_USAGE_COMMAND, CLAUDE_USAGE_ARGS, {
3336
+ cwd: options.cwd,
3337
+ timeoutMs: CLAUDE_USAGE_TIMEOUT_MS,
3338
+ maxOutputLength: CLAUDE_USAGE_OUTPUT_MAX_CHARS,
3339
+ });
3340
+ const command = formatCommandForDisplay(CLAUDE_USAGE_COMMAND, CLAUDE_USAGE_ARGS);
3341
+ if (result.timedOut) throw makeHttpError(504, `Claude usage command timed out: ${command}`);
3342
+ if (result.error && result.exitCode === undefined) throw makeHttpError(502, `Claude usage command failed: ${result.error}`);
3343
+ if (result.exitCode !== 0) {
3344
+ const detail = truncateLongText(stripAnsi(result.stderr || result.stdout || ""), 2000).trim();
3345
+ throw makeHttpError(502, `Claude usage command exited ${result.exitCode}${detail ? `: ${detail}` : ""}`);
3346
+ }
3347
+ const stdout = stripAnsi(result.stdout || "").trim();
3348
+ if (!stdout) throw makeHttpError(502, "Claude usage command returned no output");
3349
+ let usageText = stdout;
3350
+ let outputFormat = "text";
3351
+ let sessionId = null;
3352
+ let durationMs = undefined;
3353
+ if (stdout.startsWith("{")) {
3354
+ let parsed;
3355
+ try {
3356
+ parsed = JSON.parse(stdout);
3357
+ } catch {
3358
+ throw makeHttpError(502, "Claude usage command returned invalid JSON");
3359
+ }
3360
+ outputFormat = "json";
3361
+ sessionId = typeof parsed.session_id === "string" ? parsed.session_id : null;
3362
+ durationMs = numericValue(parsed.duration_ms);
3363
+ if (parsed.is_error) throw makeHttpError(502, parsed.result || "Claude usage command returned an error");
3364
+ if (typeof parsed.result === "string") usageText = parsed.result;
3365
+ }
3366
+ const fetchedAt = new Date();
3367
+ return {
3368
+ available: true,
3369
+ providerId: "claude-code",
3370
+ source: "claude-code-cli",
3371
+ command,
3372
+ outputFormat,
3373
+ fetchedAt: fetchedAt.toISOString(),
3374
+ durationMs,
3375
+ sessionId,
3376
+ ...parseClaudeUsageText(usageText, fetchedAt),
3377
+ };
3378
+ }
3379
+
3132
3380
  async function configuredScopedModelPatterns(cwd = options.cwd) {
3133
3381
  const cliPatterns = parseCliScopedModelPatterns();
3134
3382
  if (cliPatterns !== undefined) return { patterns: cliPatterns, source: "cli" };
@@ -3295,6 +3543,209 @@ function cleanPathSuggestionQuery(value) {
3295
3543
  return normalizeSuggestionPath(value).replace(/\0/g, "").slice(0, PATH_SUGGESTION_QUERY_LIMIT);
3296
3544
  }
3297
3545
 
3546
+ const BANG_COMMON_COMMANDS_BASE = [
3547
+ "ls", "la", "ll", "cd", "pwd", "cat", "less", "bat", "rg", "fd", "find", "grep", "sed", "awk", "jq",
3548
+ "git", "gh", "g", "pnpm", "bun", "npm", "node", "python", "python3", "uv", "cargo", "rustc", "make", "just",
3549
+ "docker", "docker-compose", "curl", "wget", "ssh", "scp", "rsync", "tmux", "htop", "btop",
3550
+ ];
3551
+ const BANG_COMMON_COMMANDS_UNIX = ["systemctl", "journalctl"];
3552
+ const BANG_COMMON_COMMANDS_LINUX = ["pacman", "yay"];
3553
+
3554
+ function bangCommonCommands() {
3555
+ const commands = [...BANG_COMMON_COMMANDS_BASE];
3556
+ const currentPlatform = platform();
3557
+ if (currentPlatform !== "win32") commands.push(...BANG_COMMON_COMMANDS_UNIX);
3558
+ if (currentPlatform === "linux") commands.push(...BANG_COMMON_COMMANDS_LINUX);
3559
+ return commands;
3560
+ }
3561
+
3562
+ function cleanBangSuggestionQuery(value) {
3563
+ return String(value || "").replace(/\0/g, "").replace(/^!+/, "").slice(0, BANG_SUGGESTION_QUERY_LIMIT);
3564
+ }
3565
+
3566
+ function parseBangCommandLine(commandLine) {
3567
+ const trimmed = String(commandLine || "").trim();
3568
+ if (!trimmed || trimmed.startsWith("#")) return { flags: [] };
3569
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
3570
+ let startIndex = 0;
3571
+ let executable = tokens[startIndex] || "";
3572
+ if (executable === "sudo") {
3573
+ startIndex += 1;
3574
+ executable = tokens[startIndex] || "";
3575
+ }
3576
+ executable = executable.replace(/^!+/, "");
3577
+ if (!executable) return { flags: [] };
3578
+ const flags = tokens.slice(startIndex + 1).filter((token) => token.startsWith("-") && token !== "-");
3579
+ return { executable, flags };
3580
+ }
3581
+
3582
+ function bangExecutable(commandLine) {
3583
+ return parseBangCommandLine(commandLine).executable;
3584
+ }
3585
+
3586
+ async function readTextFileIfExists(filePath) {
3587
+ try {
3588
+ return await readFile(filePath, "utf8");
3589
+ } catch {
3590
+ return "";
3591
+ }
3592
+ }
3593
+
3594
+ async function readFishHistoryExecutables() {
3595
+ const fishDataHome = process.env.XDG_DATA_HOME?.trim() || path.join(homedir(), ".local", "share");
3596
+ const content = await readTextFileIfExists(path.join(fishDataHome, "fish", "fish_history"));
3597
+ const commands = [];
3598
+ for (const line of content.split(/\r?\n/)) {
3599
+ const match = line.match(/^\s*-\s*cmd:\s*(.*)$/);
3600
+ const executable = match ? bangExecutable(match[1]) : "";
3601
+ if (executable) commands.push(executable);
3602
+ }
3603
+ return commands;
3604
+ }
3605
+
3606
+ async function readBashHistoryExecutables() {
3607
+ const content = await readTextFileIfExists(path.join(homedir(), ".bash_history"));
3608
+ return content.split(/\r?\n/).map((line) => bangExecutable(line)).filter(Boolean);
3609
+ }
3610
+
3611
+ async function readZshHistoryExecutables() {
3612
+ const content = await readTextFileIfExists(path.join(homedir(), ".zsh_history"));
3613
+ return content
3614
+ .split(/\r?\n/)
3615
+ .map((line) => bangExecutable(line.includes(";") ? line.slice(line.indexOf(";") + 1) : line))
3616
+ .filter(Boolean);
3617
+ }
3618
+
3619
+ function bangRuntimeStorePath() {
3620
+ const configured = process.env.PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH?.trim();
3621
+ return configured ? path.resolve(expandUserPath(configured)) : path.join(agentDir, "state", "bang-command-autocomplete-runtime.json");
3622
+ }
3623
+
3624
+ async function readBangRuntimeData() {
3625
+ const empty = { commands: new Set(), flagsByCommand: new Map(), lines: new Set() };
3626
+ const parsed = await readJsonFileIfExists(bangRuntimeStorePath());
3627
+ if (Array.isArray(parsed)) {
3628
+ for (const item of parsed) {
3629
+ const line = String(item || "").trim();
3630
+ if (!line) continue;
3631
+ const executable = bangExecutable(line);
3632
+ if (executable) empty.commands.add(executable);
3633
+ empty.lines.add(line.replace(/^!+/, ""));
3634
+ }
3635
+ return empty;
3636
+ }
3637
+ if (!parsed || typeof parsed !== "object") return empty;
3638
+ for (const item of Array.isArray(parsed.commands) ? parsed.commands : []) {
3639
+ const command = String(item || "").trim();
3640
+ if (command) empty.commands.add(command);
3641
+ }
3642
+ if (parsed.flags && typeof parsed.flags === "object") {
3643
+ for (const [command, flags] of Object.entries(parsed.flags)) {
3644
+ const normalizedCommand = String(command || "").trim();
3645
+ if (!normalizedCommand || !Array.isArray(flags)) continue;
3646
+ const normalizedFlags = flags.map((flag) => String(flag || "").trim()).filter(Boolean);
3647
+ if (normalizedFlags.length) empty.flagsByCommand.set(normalizedCommand, new Set(normalizedFlags));
3648
+ }
3649
+ }
3650
+ for (const item of Array.isArray(parsed.lines) ? parsed.lines : []) {
3651
+ const line = String(item || "").trim().replace(/^!+/, "");
3652
+ if (line) empty.lines.add(line);
3653
+ }
3654
+ return empty;
3655
+ }
3656
+
3657
+ async function buildBangCommandIndex(includeHistory, runtimeData) {
3658
+ const merged = new Map();
3659
+ for (const command of bangCommonCommands()) merged.set(command, "common");
3660
+ if (includeHistory) {
3661
+ const historyExecutables = [
3662
+ ...await readFishHistoryExecutables(),
3663
+ ...await readBashHistoryExecutables(),
3664
+ ...await readZshHistoryExecutables(),
3665
+ ];
3666
+ for (let index = historyExecutables.length - 1; index >= 0; index--) {
3667
+ const command = historyExecutables[index];
3668
+ if (command && (!merged.has(command) || merged.get(command) === "common")) merged.set(command, "history");
3669
+ }
3670
+ }
3671
+ for (const command of runtimeData.commands) merged.set(command, "runtime");
3672
+ return Array.from(merged.entries()).map(([command, source]) => ({ command, source }));
3673
+ }
3674
+
3675
+ function rankBangValues(values, query) {
3676
+ const q = String(query || "").toLowerCase();
3677
+ const startsWith = [];
3678
+ const includes = [];
3679
+ for (const value of values) {
3680
+ const text = typeof value === "string" ? value : value.command;
3681
+ const lower = String(text || "").toLowerCase();
3682
+ if (!q || lower.startsWith(q)) startsWith.push(value);
3683
+ else if (lower.includes(q)) includes.push(value);
3684
+ }
3685
+ return [...startsWith, ...includes].slice(0, BANG_SUGGESTION_LIMIT);
3686
+ }
3687
+
3688
+ function bangSuggestion(insertText, label, description, kind = "command") {
3689
+ return { insertText, label, description, kind };
3690
+ }
3691
+
3692
+ function bangSourceLabel(source) {
3693
+ if (source === "history") return "shell history";
3694
+ if (source === "runtime") return "current session";
3695
+ return "common command";
3696
+ }
3697
+
3698
+ async function getBangSuggestionData(tab, rawQuery) {
3699
+ const query = cleanBangSuggestionQuery(rawQuery);
3700
+ const includeHistory = isTruthyEnv(process.env.PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY);
3701
+ const runtimeData = await readBangRuntimeData();
3702
+ const commandIndex = await buildBangCommandIndex(includeHistory, runtimeData);
3703
+ const suggestions = [];
3704
+ const flagMatch = query.match(/^(\S+)\s+(\S*)$/);
3705
+
3706
+ if (flagMatch && (!flagMatch[2] || flagMatch[2].startsWith("-"))) {
3707
+ const command = flagMatch[1];
3708
+ const partialFlag = flagMatch[2] || "";
3709
+ for (const flag of rankBangValues(Array.from(runtimeData.flagsByCommand.get(command) || []), partialFlag)) {
3710
+ suggestions.push(bangSuggestion(`${command} ${flag}`, `!${command} ${flag}`, `learned for ${command}`, "flag"));
3711
+ }
3712
+ }
3713
+
3714
+ if (query.includes(" ")) {
3715
+ for (const lineCandidate of rankBangValues(Array.from(runtimeData.lines), query)) {
3716
+ suggestions.push(bangSuggestion(lineCandidate, `!${lineCandidate}`, "learned full line", "line"));
3717
+ }
3718
+ }
3719
+
3720
+ if (!query.includes(" ")) {
3721
+ const ranked = rankBangValues(commandIndex, query);
3722
+ for (const entry of ranked) {
3723
+ suggestions.push(bangSuggestion(entry.command, `!${entry.command}`, bangSourceLabel(entry.source), "command"));
3724
+ }
3725
+ for (const entry of ranked) {
3726
+ for (const flag of Array.from(runtimeData.flagsByCommand.get(entry.command) || []).slice(0, 3)) {
3727
+ suggestions.push(bangSuggestion(`${entry.command} ${flag}`, `!${entry.command} ${flag}`, "learned command + flag", "flag"));
3728
+ }
3729
+ }
3730
+ for (const lineCandidate of rankBangValues(Array.from(runtimeData.lines), query)) {
3731
+ if (lineCandidate.startsWith(query)) suggestions.push(bangSuggestion(lineCandidate, `!${lineCandidate}`, "learned full line", "line"));
3732
+ }
3733
+ }
3734
+
3735
+ const seen = new Set();
3736
+ return {
3737
+ cwd: tab.cwd,
3738
+ displayCwd: displayPath(tab.cwd),
3739
+ query,
3740
+ suggestions: suggestions.filter((item) => {
3741
+ const key = item.insertText;
3742
+ if (!key || seen.has(key)) return false;
3743
+ seen.add(key);
3744
+ return true;
3745
+ }).slice(0, BANG_SUGGESTION_LIMIT),
3746
+ };
3747
+ }
3748
+
3298
3749
  function splitSuggestionPathQuery(query) {
3299
3750
  const normalized = normalizeSuggestionPath(query);
3300
3751
  if (normalized === "~") return { displayBase: "~", prefix: "" };
@@ -4741,6 +5192,7 @@ async function serveStatic(req, res, url) {
4741
5192
 
4742
5193
  function requestBodyLimitForPath(pathname) {
4743
5194
  if (pathname === "/api/attachments") return UPLOAD_BODY_LIMIT_BYTES;
5195
+ if (pathname === "/api/files/content") return FILE_VIEWER_BODY_LIMIT_BYTES;
4744
5196
  if (["/api/prompt", "/api/steer", "/api/follow-up"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
4745
5197
  return BODY_LIMIT_BYTES;
4746
5198
  }
@@ -7651,6 +8103,292 @@ function resolveTabPath(tab, value) {
7651
8103
  return path.isAbsolute(text) ? text : path.resolve(tab?.cwd || options.cwd, text);
7652
8104
  }
7653
8105
 
8106
+ async function workspaceRoot(tab) {
8107
+ const root = path.resolve(tab?.cwd || options.cwd);
8108
+ return { root, realRoot: await realpath(root).catch(() => root) };
8109
+ }
8110
+
8111
+ async function resolveWorkspacePath(tab, value = "", { mustExist = true } = {}) {
8112
+ const { root, realRoot } = await workspaceRoot(tab);
8113
+ const text = String(value || "").trim();
8114
+ if (text.includes("\0")) throw makeHttpError(400, "Path cannot contain null bytes");
8115
+ const targetPath = text ? (path.isAbsolute(text) ? path.resolve(text) : path.resolve(root, text)) : root;
8116
+ if (targetPath !== root && !pathInside(root, targetPath)) throw makeHttpError(403, "Path must stay inside the active tab working directory");
8117
+ let info = null;
8118
+ let realTarget = targetPath;
8119
+ try {
8120
+ info = await stat(targetPath);
8121
+ realTarget = await realpath(targetPath).catch(() => targetPath);
8122
+ } catch (error) {
8123
+ if (mustExist) throw makeHttpError(error?.code === "ENOENT" ? 404 : 400, `Path not found: ${displayPath(targetPath)}`);
8124
+ }
8125
+ if (realTarget !== realRoot && !pathInside(realRoot, realTarget)) throw makeHttpError(403, "Resolved path escapes the active tab working directory");
8126
+ const relative = path.relative(root, targetPath).split(path.sep).join("/");
8127
+ return { root, realRoot, targetPath, realTarget, relative, info };
8128
+ }
8129
+
8130
+ function fileViewerLanguage(filePath) {
8131
+ const ext = path.extname(String(filePath || "")).toLowerCase();
8132
+ if (ext === ".md" || ext === ".markdown") return "markdown";
8133
+ return "text";
8134
+ }
8135
+
8136
+ function fileTreeEntryType(dirent, info) {
8137
+ if (info?.isDirectory?.() || dirent?.isDirectory?.()) return "directory";
8138
+ if (info?.isFile?.() || dirent?.isFile?.()) return "file";
8139
+ return dirent?.isSymbolicLink?.() ? "symlink" : "other";
8140
+ }
8141
+
8142
+ async function statFileTreeEntries(dirPath, dirents, root, realRoot) {
8143
+ const ordered = [...dirents].sort((a, b) => {
8144
+ const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
8145
+ const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
8146
+ return aRank - bRank || a.name.localeCompare(b.name);
8147
+ });
8148
+ const selected = ordered.slice(0, FILE_TREE_MAX_ENTRIES);
8149
+ const entries = [];
8150
+ let cursor = 0;
8151
+ async function worker() {
8152
+ while (cursor < selected.length) {
8153
+ const dirent = selected[cursor++];
8154
+ const targetPath = path.join(dirPath, dirent.name);
8155
+ const relative = path.relative(root, targetPath).split(path.sep).join("/");
8156
+ try {
8157
+ const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
8158
+ const outsideRoot = realTarget !== realRoot && !pathInside(realRoot, realTarget);
8159
+ const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
8160
+ entries.push({
8161
+ name: dirent.name,
8162
+ path: relative,
8163
+ type,
8164
+ directory: type === "directory",
8165
+ file: type === "file",
8166
+ symlink: dirent.isSymbolicLink(),
8167
+ outsideRoot,
8168
+ size: info.size,
8169
+ mtimeMs: info.mtimeMs,
8170
+ extension: path.extname(dirent.name).toLowerCase(),
8171
+ canOpenInWebui: type === "file",
8172
+ });
8173
+ } catch (error) {
8174
+ entries.push({ name: dirent.name, path: relative, type: "error", directory: false, file: false, error: sanitizeError(error), canOpenInWebui: false });
8175
+ }
8176
+ }
8177
+ }
8178
+ const workers = Array.from({ length: Math.min(FILE_TREE_ENTRY_STAT_CONCURRENCY, selected.length) }, () => worker());
8179
+ await Promise.all(workers);
8180
+ entries.sort((a, b) => {
8181
+ const aRank = a.type === "directory" ? 0 : a.type === "file" ? 1 : 2;
8182
+ const bRank = b.type === "directory" ? 0 : b.type === "file" ? 1 : 2;
8183
+ return aRank - bRank || a.name.localeCompare(b.name);
8184
+ });
8185
+ return { entries, truncated: ordered.length > selected.length, total: ordered.length };
8186
+ }
8187
+
8188
+ async function getFileTreeData(tab, requestedPath = "") {
8189
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
8190
+ if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Path is not a directory");
8191
+ const dirents = await readdir(resolved.targetPath, { withFileTypes: true });
8192
+ const listed = await statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot);
8193
+ return {
8194
+ root: resolved.root,
8195
+ displayRoot: displayPath(resolved.root),
8196
+ path: resolved.relative,
8197
+ displayPath: displayPath(resolved.targetPath),
8198
+ entries: listed.entries,
8199
+ truncated: listed.truncated,
8200
+ total: listed.total,
8201
+ };
8202
+ }
8203
+
8204
+ function normalizeFileSearchQuery(value = "") {
8205
+ const query = String(value || "").trim().replace(/\s+/g, " ");
8206
+ if (query.includes("\0")) throw makeHttpError(400, "Search query cannot contain null bytes");
8207
+ if (query.length > 160) throw makeHttpError(400, "Search query is too long");
8208
+ return query;
8209
+ }
8210
+
8211
+ function fileSearchMatches(entry, queryLower) {
8212
+ const name = String(entry.name || "").toLowerCase();
8213
+ const filePath = String(entry.path || "").toLowerCase();
8214
+ return name.includes(queryLower) || filePath.includes(queryLower);
8215
+ }
8216
+
8217
+ async function getFileSearchData(tab, rawQuery = "") {
8218
+ const query = normalizeFileSearchQuery(rawQuery);
8219
+ if (!query) {
8220
+ const root = path.resolve(tab?.cwd || options.cwd);
8221
+ return { root, displayRoot: displayPath(root), query, entries: [], truncated: false, total: 0, scanned: 0, maxDepth: FILE_SEARCH_MAX_DEPTH };
8222
+ }
8223
+ const resolved = await resolveWorkspacePath(tab, "");
8224
+ if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Workspace root is not a directory");
8225
+ const queryLower = query.toLowerCase();
8226
+ const entries = [];
8227
+ const queue = [{ dirPath: resolved.root, relative: "", depth: 0 }];
8228
+ const visitedRealDirs = new Set([resolved.realRoot]);
8229
+ let scanned = 0;
8230
+ let truncated = false;
8231
+
8232
+ while (queue.length && scanned < FILE_SEARCH_MAX_SCANNED && entries.length < FILE_SEARCH_MAX_RESULTS) {
8233
+ const current = queue.shift();
8234
+ let dirents = [];
8235
+ try {
8236
+ dirents = await readdir(current.dirPath, { withFileTypes: true });
8237
+ } catch {
8238
+ continue;
8239
+ }
8240
+ dirents.sort((a, b) => {
8241
+ const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
8242
+ const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
8243
+ return aRank - bRank || a.name.localeCompare(b.name);
8244
+ });
8245
+
8246
+ for (const dirent of dirents) {
8247
+ if (scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS) break;
8248
+ scanned += 1;
8249
+ const targetPath = path.join(current.dirPath, dirent.name);
8250
+ const relative = (current.relative ? `${current.relative}/${dirent.name}` : dirent.name).split(path.sep).join("/");
8251
+ const depth = current.depth + 1;
8252
+ try {
8253
+ const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
8254
+ const outsideRoot = realTarget !== resolved.realRoot && !pathInside(resolved.realRoot, realTarget);
8255
+ const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
8256
+ const entry = {
8257
+ name: dirent.name,
8258
+ path: relative,
8259
+ type,
8260
+ directory: type === "directory",
8261
+ file: type === "file",
8262
+ symlink: dirent.isSymbolicLink(),
8263
+ outsideRoot,
8264
+ size: info.size,
8265
+ mtimeMs: info.mtimeMs,
8266
+ extension: path.extname(dirent.name).toLowerCase(),
8267
+ depth,
8268
+ canOpenInWebui: type === "file",
8269
+ };
8270
+ if (fileSearchMatches(entry, queryLower)) entries.push(entry);
8271
+ if (depth < FILE_SEARCH_MAX_DEPTH && type === "directory" && !FILE_SEARCH_EXCLUDED_DIRS.has(dirent.name) && !visitedRealDirs.has(realTarget)) {
8272
+ visitedRealDirs.add(realTarget);
8273
+ queue.push({ dirPath: targetPath, relative, depth });
8274
+ }
8275
+ } catch (error) {
8276
+ const entry = { name: dirent.name, path: relative, type: "error", directory: false, file: false, depth, error: sanitizeError(error), canOpenInWebui: false };
8277
+ if (fileSearchMatches(entry, queryLower)) entries.push(entry);
8278
+ }
8279
+ }
8280
+ }
8281
+ truncated = queue.length > 0 || scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS;
8282
+ return {
8283
+ root: resolved.root,
8284
+ displayRoot: displayPath(resolved.root),
8285
+ query,
8286
+ entries,
8287
+ truncated,
8288
+ total: entries.length,
8289
+ scanned,
8290
+ maxDepth: FILE_SEARCH_MAX_DEPTH,
8291
+ excludedDirs: [...FILE_SEARCH_EXCLUDED_DIRS],
8292
+ };
8293
+ }
8294
+
8295
+ function assertTextFileBuffer(buffer) {
8296
+ if (isLikelyBinaryBuffer(buffer)) throw makeHttpError(415, "File appears to be binary; only text files can be opened in WebUI");
8297
+ }
8298
+
8299
+ async function getFileContentData(tab, requestedPath = "") {
8300
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
8301
+ if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
8302
+ if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
8303
+ const buffer = await readFile(resolved.targetPath);
8304
+ assertTextFileBuffer(buffer);
8305
+ return {
8306
+ root: resolved.root,
8307
+ path: resolved.relative,
8308
+ name: path.basename(resolved.targetPath),
8309
+ content: buffer.toString("utf8"),
8310
+ size: resolved.info.size,
8311
+ mtimeMs: resolved.info.mtimeMs,
8312
+ extension: path.extname(resolved.targetPath).toLowerCase(),
8313
+ language: fileViewerLanguage(resolved.targetPath),
8314
+ };
8315
+ }
8316
+
8317
+ async function saveFileContentData(tab, body = {}) {
8318
+ if (typeof body.content !== "string") throw makeHttpError(400, "File content must be a string");
8319
+ if (body.content.includes("\0")) throw makeHttpError(400, "File content cannot contain null bytes");
8320
+ if (Buffer.byteLength(body.content, "utf8") > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
8321
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
8322
+ if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
8323
+ if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
8324
+ assertTextFileBuffer(await readFile(resolved.targetPath));
8325
+ const expectedMtimeMs = Number(body.mtimeMs);
8326
+ if (Number.isFinite(expectedMtimeMs) && Math.abs(resolved.info.mtimeMs - expectedMtimeMs) > 5) {
8327
+ throw makeHttpError(409, "File changed on disk after it was opened. Reopen it before saving.");
8328
+ }
8329
+ const tmpFile = `${resolved.targetPath}.${process.pid}.${Date.now()}.tmp`;
8330
+ try {
8331
+ await writeFile(tmpFile, body.content, { encoding: "utf8", mode: resolved.info.mode & 0o777 });
8332
+ await rename(tmpFile, resolved.targetPath);
8333
+ } catch (error) {
8334
+ await rm(tmpFile, { force: true }).catch(() => {});
8335
+ throw error;
8336
+ }
8337
+ const nextStats = await stat(resolved.targetPath);
8338
+ return {
8339
+ path: resolved.relative,
8340
+ name: path.basename(resolved.targetPath),
8341
+ size: nextStats.size,
8342
+ mtimeMs: nextStats.mtimeMs,
8343
+ extension: path.extname(resolved.targetPath).toLowerCase(),
8344
+ language: fileViewerLanguage(resolved.targetPath),
8345
+ };
8346
+ }
8347
+
8348
+ function defaultEditorCommand(targetPath) {
8349
+ if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
8350
+ if (platform() === "darwin") return { command: "open", args: [targetPath] };
8351
+ return { command: process.env.PI_WEBUI_OPEN_COMMAND || "xdg-open", args: [targetPath] };
8352
+ }
8353
+
8354
+ function firstCommandOutputLine(value = "") {
8355
+ return String(value || "").split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";
8356
+ }
8357
+
8358
+ async function queryXdgMime(args = [], cwd = options.cwd) {
8359
+ const result = await runCommand("xdg-mime", args, { cwd, timeoutMs: 1500, maxOutputLength: 4096 });
8360
+ if (result.exitCode !== 0) return "";
8361
+ return firstCommandOutputLine(result.stdout);
8362
+ }
8363
+
8364
+ async function linuxDefaultEditorCommand(targetPath, { cwd = options.cwd, isFile = true } = {}) {
8365
+ if (process.env.PI_WEBUI_OPEN_COMMAND) return defaultEditorCommand(targetPath);
8366
+ if (!isFile) return defaultEditorCommand(targetPath);
8367
+ const fileMime = await queryXdgMime(["query", "filetype", targetPath], cwd);
8368
+ const fileDefaultDesktop = fileMime ? await queryXdgMime(["query", "default", fileMime], cwd) : "";
8369
+ if (fileDefaultDesktop) return { command: "xdg-open", args: [targetPath], mime: fileMime, desktopFile: fileDefaultDesktop, fallbackToTextEditor: false };
8370
+ const textDefaultDesktop = await queryXdgMime(["query", "default", "text/plain"], cwd);
8371
+ if (textDefaultDesktop) {
8372
+ return { command: "gio", args: ["launch", textDefaultDesktop, targetPath], mime: fileMime, desktopFile: textDefaultDesktop, fallbackToTextEditor: true };
8373
+ }
8374
+ return { ...defaultEditorCommand(targetPath), mime: fileMime, fallbackToTextEditor: false };
8375
+ }
8376
+
8377
+ async function defaultEditorCommandForPath(targetPath, options = {}) {
8378
+ if (platform() === "linux") return linuxDefaultEditorCommand(targetPath, options);
8379
+ return defaultEditorCommand(targetPath);
8380
+ }
8381
+
8382
+ async function openPathInDefaultEditor(tab, requestedPath = "") {
8383
+ if (!String(requestedPath || "").trim()) throw makeHttpError(400, "Path to open is required");
8384
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
8385
+ const { command, args, mime, desktopFile, fallbackToTextEditor } = await defaultEditorCommandForPath(resolved.targetPath, { cwd: resolved.root, isFile: !!resolved.info?.isFile?.() });
8386
+ const child = spawn(command, args, { cwd: resolved.root, stdio: "ignore", detached: true, windowsHide: true });
8387
+ child.on("error", () => {});
8388
+ child.unref?.();
8389
+ return { path: resolved.relative, command: [command, ...args].join(" "), mime, desktopFile, fallbackToTextEditor: !!fallbackToTextEditor };
8390
+ }
8391
+
7654
8392
  function configuredSessionDir() {
7655
8393
  for (let index = 0; index < options.piArgs.length; index++) {
7656
8394
  const arg = options.piArgs[index];
@@ -7726,7 +8464,7 @@ function extractSessionTextContent(content) {
7726
8464
  .map((part) => {
7727
8465
  if (typeof part === "string") return part;
7728
8466
  if (part?.type === "text" && typeof part.text === "string") return part.text;
7729
- if (part?.type === "toolCall") return `[tool call: ${part.toolName || "tool"}]`;
8467
+ if (part?.type === "toolCall") return `[tool call: ${part.toolName || part.name || "tool"}]`;
7730
8468
  if (part?.type === "thinking") return "[thinking]";
7731
8469
  if (part?.type === "image") return "[image]";
7732
8470
  return "";
@@ -7735,6 +8473,104 @@ function extractSessionTextContent(content) {
7735
8473
  .join(" ");
7736
8474
  }
7737
8475
 
8476
+ function generatedSessionEntryId(usedIds) {
8477
+ let id = "";
8478
+ do {
8479
+ id = randomUUID().replace(/-/g, "").slice(0, 8);
8480
+ } while (usedIds.has(id));
8481
+ usedIds.add(id);
8482
+ return id;
8483
+ }
8484
+
8485
+ async function writeForkedSessionFromEntries({ entries, targetLeafId, cwd, parentSession }) {
8486
+ const manager = SessionManager.create(cwd, configuredSessionDir(), { parentSession });
8487
+ const header = manager.getHeader();
8488
+ const sessionFile = manager.getSessionFile();
8489
+ if (!header || !sessionFile) throw new Error("Failed to create forked session metadata");
8490
+
8491
+ const outputEntries = [header];
8492
+ if (targetLeafId) {
8493
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
8494
+ const pathEntries = [];
8495
+ let current = byId.get(targetLeafId);
8496
+ while (current) {
8497
+ pathEntries.push(current);
8498
+ current = current.parentId ? byId.get(current.parentId) : undefined;
8499
+ }
8500
+ pathEntries.reverse();
8501
+ if (!pathEntries.length) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetLeafId}`);
8502
+
8503
+ const pathWithoutLabels = [];
8504
+ let pathParentId = null;
8505
+ for (const entry of pathEntries) {
8506
+ if (entry.type === "label") continue;
8507
+ pathWithoutLabels.push({ ...entry, parentId: pathParentId });
8508
+ pathParentId = entry.id;
8509
+ }
8510
+ outputEntries.push(...pathWithoutLabels);
8511
+
8512
+ const pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));
8513
+ const labelsByTarget = new Map();
8514
+ const labelTimestampsByTarget = new Map();
8515
+ for (const entry of entries) {
8516
+ if (entry?.type !== "label" || !pathEntryIds.has(entry.targetId)) continue;
8517
+ if (entry.label) {
8518
+ labelsByTarget.set(entry.targetId, entry.label);
8519
+ labelTimestampsByTarget.set(entry.targetId, entry.timestamp);
8520
+ } else {
8521
+ labelsByTarget.delete(entry.targetId);
8522
+ labelTimestampsByTarget.delete(entry.targetId);
8523
+ }
8524
+ }
8525
+
8526
+ let labelParentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
8527
+ const usedIds = new Set([...pathEntryIds, header.id]);
8528
+ for (const [targetId, label] of labelsByTarget) {
8529
+ const labelEntry = {
8530
+ type: "label",
8531
+ id: generatedSessionEntryId(usedIds),
8532
+ parentId: labelParentId,
8533
+ timestamp: labelTimestampsByTarget.get(targetId) || new Date().toISOString(),
8534
+ targetId,
8535
+ label,
8536
+ };
8537
+ outputEntries.push(labelEntry);
8538
+ labelParentId = labelEntry.id;
8539
+ }
8540
+ }
8541
+
8542
+ await writeFile(sessionFile, `${outputEntries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, { flag: "wx" });
8543
+ return sessionFile;
8544
+ }
8545
+
8546
+ async function createForkedSessionFile(tab, entryId) {
8547
+ requirePersistentSessions();
8548
+ const targetEntryId = String(entryId || "").trim();
8549
+ if (!targetEntryId) throw makeHttpError(400, "entryId is required");
8550
+
8551
+ const state = await currentSessionState(tab).catch(() => tab.lastState || {});
8552
+ if (state.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before forking the session.");
8553
+ const parentSession = state.sessionFile || tabRestorableSessionFile(tab);
8554
+
8555
+ const entriesResponse = await safeRpcResponse(tab, { type: "get_entries" }, REQUEST_TIMEOUT_MS);
8556
+ if (entriesResponse.success === false) throw makeHttpError(400, entriesResponse.error || "failed to load session entries");
8557
+ const entries = Array.isArray(entriesResponse.data?.entries) ? entriesResponse.data.entries : [];
8558
+ const selectedEntry = entries.find((entry) => entry?.id === targetEntryId);
8559
+ if (!selectedEntry) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetEntryId}`);
8560
+ if (selectedEntry.type !== "message" || selectedEntry.message?.role !== "user") {
8561
+ throw makeHttpError(400, "Fork point must be a user message");
8562
+ }
8563
+
8564
+ const text = extractSessionTextContent(selectedEntry.message.content).trim();
8565
+ const sessionFile = await writeForkedSessionFromEntries({
8566
+ entries,
8567
+ targetLeafId: selectedEntry.parentId || null,
8568
+ cwd: tab.cwd,
8569
+ parentSession,
8570
+ });
8571
+ return { sessionFile, text, parentSession, targetEntryId };
8572
+ }
8573
+
7738
8574
  function sessionTreeEntryLabel(entry) {
7739
8575
  if (!entry || typeof entry !== "object") return "entry";
7740
8576
  if (entry.type === "message") return entry.message?.role || "message";
@@ -7806,18 +8642,26 @@ async function requireIdleForSessionAction(tab, actionLabel) {
7806
8642
  }
7807
8643
 
7808
8644
  async function runForkCommand(tab, entryId) {
7809
- await requireIdleForSessionAction(tab, "forking the session");
7810
- const targetEntryId = String(entryId || "").trim();
7811
- if (!targetEntryId) throw makeHttpError(400, "entryId is required");
7812
- const response = await tab.rpc.send({ type: "fork", entryId: targetEntryId });
7813
- if (response.success === false) return response;
7814
- const state = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
7815
- if (state.ok) rememberTabState(tab, state.data);
8645
+ const fork = await createForkedSessionFile(tab, entryId);
8646
+ const title = uniqueTabTitle(generatedTabTitleFromPrompt(fork.text) || `${tab.title || "Session"} fork`, null);
8647
+ const forkTab = await createTab({
8648
+ title,
8649
+ titleSource: title ? "auto" : undefined,
8650
+ conversationStarted: true,
8651
+ cwd: tab.cwd,
8652
+ sessionFile: fork.sessionFile,
8653
+ gitWorkspace: tab.gitWorkspace,
8654
+ });
8655
+ const forkTabMeta = tabMeta(forkTab);
7816
8656
  return rpcSuccess("fork", {
7817
- message: response.data?.cancelled ? "Fork cancelled." : "Forked the current session.",
7818
- text: response.data?.text || "",
7819
- result: response.data,
7820
- tab: tabMeta(tab),
8657
+ message: "Forked the current session in a new terminal tab.",
8658
+ text: fork.text || "",
8659
+ result: { cancelled: false, text: fork.text || "", sessionFile: fork.sessionFile, targetEntryId: fork.targetEntryId },
8660
+ sessionFile: fork.sessionFile,
8661
+ parentSession: fork.parentSession,
8662
+ tab: forkTabMeta,
8663
+ tabs: listTabs(),
8664
+ sourceTab: tabMeta(tab),
7821
8665
  });
7822
8666
  }
7823
8667
 
@@ -8810,6 +9654,15 @@ const server = createServer(async (req, res) => {
8810
9654
  return;
8811
9655
  }
8812
9656
 
9657
+ if (url.pathname === "/api/claude-usage" && req.method === "GET") {
9658
+ try {
9659
+ sendJson(res, 200, { ok: true, data: await getClaudeCodeUsageStatus() });
9660
+ } catch (error) {
9661
+ sendJson(res, error?.statusCode || 500, { ok: false, error: error?.message || "Failed to read Claude usage" });
9662
+ }
9663
+ return;
9664
+ }
9665
+
8813
9666
  if (url.pathname === "/api/network" && req.method === "GET") {
8814
9667
  sendJson(res, 200, { ok: true, data: networkStatus({ includeAuthPin: isLocalRequest(req) }) });
8815
9668
  return;
@@ -8983,6 +9836,12 @@ const server = createServer(async (req, res) => {
8983
9836
  return;
8984
9837
  }
8985
9838
 
9839
+ if (url.pathname === "/api/bang-suggestions" && req.method === "GET") {
9840
+ const tab = getRequestedTab(req, url);
9841
+ sendJson(res, 200, { ok: true, data: await getBangSuggestionData(tab, url.searchParams.get("query")) });
9842
+ return;
9843
+ }
9844
+
8986
9845
  if (url.pathname === "/api/path-fast-picks" && req.method === "GET") {
8987
9846
  sendJson(res, 200, { ok: true, data: { picks: await readPathFastPicks() } });
8988
9847
  return;
@@ -8997,6 +9856,41 @@ const server = createServer(async (req, res) => {
8997
9856
  return;
8998
9857
  }
8999
9858
 
9859
+ if (url.pathname === "/api/files" && req.method === "GET") {
9860
+ const tab = getRequestedTab(req, url);
9861
+ sendJson(res, 200, { ok: true, data: await getFileTreeData(tab, url.searchParams.get("path") || "") });
9862
+ return;
9863
+ }
9864
+
9865
+ if (url.pathname === "/api/files/search" && req.method === "GET") {
9866
+ const tab = getRequestedTab(req, url);
9867
+ sendJson(res, 200, { ok: true, data: await getFileSearchData(tab, url.searchParams.get("q") || url.searchParams.get("query") || "") });
9868
+ return;
9869
+ }
9870
+
9871
+ if (url.pathname === "/api/files/content" && req.method === "GET") {
9872
+ const tab = getRequestedTab(req, url);
9873
+ sendJson(res, 200, { ok: true, data: await getFileContentData(tab, url.searchParams.get("path") || "") });
9874
+ return;
9875
+ }
9876
+
9877
+ if (url.pathname === "/api/files/content" && req.method === "POST") {
9878
+ requireLocalhostRoute(req, url.pathname);
9879
+ const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
9880
+ const tab = getRequestedTab(req, url, body);
9881
+ if (isNaturalConversationActive(tab)) throw makeHttpError(409, "file edits are blocked");
9882
+ sendJson(res, 200, { ok: true, data: await saveFileContentData(tab, body) });
9883
+ return;
9884
+ }
9885
+
9886
+ if (url.pathname === "/api/files/open-default" && req.method === "POST") {
9887
+ requireLocalhostRoute(req, url.pathname);
9888
+ const body = await readJsonBody(req);
9889
+ const tab = getRequestedTab(req, url, body);
9890
+ sendJson(res, 200, { ok: true, data: await openPathInDefaultEditor(tab, body.path || body.filePath || "") });
9891
+ return;
9892
+ }
9893
+
9000
9894
  if (url.pathname === "/api/attachments" && req.method === "POST") {
9001
9895
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
9002
9896
  const tab = getRequestedTab(req, url, body);
@@ -9043,7 +9937,7 @@ const server = createServer(async (req, res) => {
9043
9937
  const tab = getRequestedTab(req, url, body);
9044
9938
  ensureNaturalConversationRouteAllowed(tab, "session fork actions are blocked");
9045
9939
  const response = await runForkCommand(tab, body.entryId);
9046
- sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
9940
+ sendJson(res, response.success === false ? 400 : 200, response);
9047
9941
  return;
9048
9942
  }
9049
9943