flyspace-cli 0.1.51 → 0.1.52

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.
@@ -17964,7 +17964,7 @@ function loadConfig() {
17964
17964
  claudeCwd: process.env["CLAUDE_CWD"] ?? process.cwd(),
17965
17965
  claudeConfigDir: process.env["CLAUDE_CONFIG_DIR"] || void 0,
17966
17966
  claudeCodeOauthToken: process.env["CLAUDE_CODE_OAUTH_TOKEN"] || void 0,
17967
- botName: process.env["BOT_NAME"] ?? "Custie",
17967
+ botName: process.env["BOT_NAME"] ?? "Bot",
17968
17968
  allowedUserIds,
17969
17969
  maxTurns: parseInt(process.env["MAX_TURNS"] ?? "10", 10),
17970
17970
  model: process.env["CUSTIE_MODEL"]?.trim() || "sonnet",
@@ -19619,11 +19619,10 @@ function extractUsage(result) {
19619
19619
  outputTokens: usage.output_tokens ?? 0,
19620
19620
  cacheReadTokens: usage.cache_read_input_tokens ?? 0,
19621
19621
  cacheCreationTokens: usage.cache_creation_input_tokens ?? 0,
19622
- costUsd: result.total_cost_usd ?? 0,
19623
- // Flagged as the provider's own figure so the store keeps it instead of
19624
- // re-pricing the tokens itself. A run that reports no cost at all is left
19625
- // unflagged and gets priced from its rate card.
19626
- ...result.total_cost_usd != null ? { costSource: "reported" } : {},
19622
+ // Not `total_cost_usd`: on a resumed session it is the running total for
19623
+ // the whole session, so recording it per run counted earlier runs again
19624
+ // (a $13 thread showed $72). The store prices this run's tokens instead.
19625
+ costUsd: 0,
19627
19626
  ...primaryModel(result.modelUsage) ? { model: primaryModel(result.modelUsage) } : {},
19628
19627
  ...result.duration_ms != null ? { durationMs: result.duration_ms } : {},
19629
19628
  ...result.num_turns != null ? { numTurns: result.num_turns } : {}
@@ -19728,14 +19727,20 @@ function loadSystemPrompt() {
19728
19727
  const filePath = existsSync7(customPath) ? customPath : defaultPath;
19729
19728
  return readFileSync2(filePath, "utf-8").trim();
19730
19729
  }
19731
- function loadCapabilities() {
19732
- const capabilitiesPath = resolve4(paths.PACKAGE_ROOT, "system.capabilities.md");
19733
- if (!existsSync7(capabilitiesPath)) return "";
19734
- return readFileSync2(capabilitiesPath, "utf-8").trim();
19730
+ function loadPackagePrompt(file) {
19731
+ const filePath = resolve4(paths.PACKAGE_ROOT, file);
19732
+ if (!existsSync7(filePath)) return "";
19733
+ return readFileSync2(filePath, "utf-8").trim();
19734
+ }
19735
+ function loadCapabilities(slackBound) {
19736
+ return [
19737
+ loadPackagePrompt("system.capabilities.md"),
19738
+ slackBound ? loadPackagePrompt("system.slack.md") : ""
19739
+ ].filter(Boolean).join("\n\n");
19735
19740
  }
19736
- function buildSystemPrompt(botName, agentPersona, channelPrompt, outputStyle) {
19741
+ function buildSystemPrompt(botName, agentPersona, channelPrompt, outputStyle, slackBound = true) {
19737
19742
  const prompt = loadSystemPrompt().replaceAll("{{botName}}", botName);
19738
- const capabilities = loadCapabilities();
19743
+ const capabilities = loadCapabilities(slackBound);
19739
19744
  const withCapabilities = capabilities ? `${prompt}
19740
19745
 
19741
19746
  ${capabilities}` : prompt;
@@ -19828,7 +19833,8 @@ function buildArgs(prompt, botName, options, resumeSessionId, isolatedStyle) {
19828
19833
  options.channelPrompt,
19829
19834
  // Host runs: the CLI applies settings.json's style itself. An isolated run
19830
19835
  // cannot see that file, so a custom style's body is injected here instead.
19831
- isolatedStyle?.builtIn ? void 0 : isolatedStyle?.body
19836
+ isolatedStyle?.builtIn ? void 0 : isolatedStyle?.body,
19837
+ options.slackBound
19832
19838
  ),
19833
19839
  options.memoryPrompt,
19834
19840
  docsAccessPromptNote(options.docsAccess, options.docsAccessUnverified)
@@ -20193,6 +20199,11 @@ var featureFlags = {
20193
20199
  description: "Shows admins what the agent has spent: a Cost section in a channel's AI overview and a per-thread cost in the thread menu. Estimated at API list rates, so on a Claude subscription it will not match your bill.",
20194
20200
  stage: "beta"
20195
20201
  },
20202
+ "session-retro": {
20203
+ title: "Session retro",
20204
+ description: "Once a thread costs more than $15, admins get a Retro button in its header: an AI review of where the spend went and what to do differently next time. The thread transcript and run usage are sent to an AI model.",
20205
+ stage: "beta"
20206
+ },
20196
20207
  "read-aloud": {
20197
20208
  title: "Read aloud",
20198
20209
  description: "Listen to messages, threads and docs as audio. Still rough in places, and each playback uses text-to-speech.",
@@ -23836,7 +23847,7 @@ async function summariseThreadTranscript(transcript, opts, deps = {}) {
23836
23847
  }
23837
23848
 
23838
23849
  // src/dashboard/chat-agent.ts
23839
- import { homedir as homedir6 } from "os";
23850
+ import { homedir as homedir8 } from "os";
23840
23851
 
23841
23852
  // src/mcp/config.ts
23842
23853
  import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
@@ -24551,7 +24562,7 @@ async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
24551
24562
 
24552
24563
  // ../api/src/version.ts
24553
24564
  import { readFileSync as readFileSync7 } from "fs";
24554
- var CLI_VERSION = true ? "0.1.51" : devVersion();
24565
+ var CLI_VERSION = true ? "0.1.52" : devVersion();
24555
24566
  function isOlderVersion(a, b) {
24556
24567
  const parse = (v) => v.replace(/^v/, "").split("-")[0].split(".").map(Number);
24557
24568
  const [pa, pb] = [parse(a), parse(b)];
@@ -24856,218 +24867,575 @@ function readAgentPersona(configDir, cwd, name) {
24856
24867
  }
24857
24868
  }
24858
24869
 
24859
- // src/store/session-store.ts
24860
- import Database2 from "better-sqlite3";
24861
- var SessionStore = class {
24862
- db;
24863
- constructor(dbPath) {
24864
- this.db = new Database2(dbPath);
24865
- this.db.pragma("journal_mode = WAL");
24866
- this.init();
24867
- }
24868
- init() {
24869
- this.db.exec(`
24870
- CREATE TABLE IF NOT EXISTS sessions (
24871
- channel_id TEXT NOT NULL,
24872
- thread_ts TEXT NOT NULL,
24873
- session_id TEXT NOT NULL,
24874
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
24875
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
24876
- PRIMARY KEY (channel_id, thread_ts)
24877
- )
24878
- `);
24879
- const sessionColumns = this.db.prepare("PRAGMA table_info(sessions)").all();
24880
- if (!sessionColumns.some((c) => c.name === "runner")) {
24881
- this.db.exec(`ALTER TABLE sessions ADD COLUMN runner TEXT NOT NULL DEFAULT 'claude'`);
24882
- }
24883
- this.db.exec(`DELETE FROM sessions WHERE runner = 'opencode'`);
24884
- this.db.exec(`
24885
- CREATE TABLE IF NOT EXISTS model_overrides (
24886
- channel_id TEXT NOT NULL,
24887
- thread_ts TEXT NOT NULL,
24888
- model TEXT NOT NULL,
24889
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
24890
- PRIMARY KEY (channel_id, thread_ts)
24891
- )
24892
- `);
24893
- this.db.exec(`
24894
- CREATE TABLE IF NOT EXISTS effort_overrides (
24895
- channel_id TEXT NOT NULL,
24896
- thread_ts TEXT NOT NULL,
24897
- effort TEXT NOT NULL,
24898
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
24899
- PRIMARY KEY (channel_id, thread_ts)
24900
- )
24901
- `);
24902
- }
24903
- getSession(channelId, threadTs) {
24904
- const row = this.db.prepare("SELECT * FROM sessions WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
24905
- if (!row) return void 0;
24906
- return {
24907
- channelId: row.channel_id,
24908
- threadTs: row.thread_ts,
24909
- sessionId: row.session_id,
24910
- runner: row.runner === "codex" ? "codex" : "claude",
24911
- createdAt: row.created_at,
24912
- updatedAt: row.updated_at
24913
- };
24914
- }
24915
- saveSession(channelId, threadTs, sessionId, runner = "claude") {
24916
- this.db.prepare(
24917
- `INSERT INTO sessions (channel_id, thread_ts, session_id, runner)
24918
- VALUES (?, ?, ?, ?)
24919
- ON CONFLICT (channel_id, thread_ts)
24920
- DO UPDATE SET session_id = excluded.session_id, runner = excluded.runner, updated_at = datetime('now')`
24921
- ).run(channelId, threadTs, sessionId, runner);
24922
- }
24923
- /** All sessions, newest activity first. Read-only listing for the dashboard. */
24924
- listSessions() {
24925
- const rows2 = this.db.prepare("SELECT * FROM sessions ORDER BY updated_at DESC").all();
24926
- return rows2.map((row) => ({
24927
- channelId: row.channel_id,
24928
- threadTs: row.thread_ts,
24929
- sessionId: row.session_id,
24930
- runner: row.runner === "codex" ? "codex" : "claude",
24931
- createdAt: row.created_at,
24932
- updatedAt: row.updated_at
24933
- }));
24934
- }
24935
- deleteSession(channelId, threadTs) {
24936
- this.db.prepare("DELETE FROM sessions WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
24937
- }
24938
- /**
24939
- * Drop every session in a channel. Used when the channel's execution runtime
24940
- * changes (`channels.runtime`, 0035): the session ids here point at Claude
24941
- * session files stored under whichever runtime wrote them — the host's
24942
- * CLAUDE_CONFIG_DIR, or the container's own per-channel home — so after a
24943
- * switch every one of them resolves to a file the new runtime cannot see.
24944
- * Left in place, the next turn in each thread would `--resume` an id that
24945
- * does not exist there and lose the conversation in a confusing way; dropping
24946
- * them makes the next turn cleanly start fresh instead.
24947
- *
24948
- * Returns how many were removed, so the caller can log something meaningful.
24949
- */
24950
- deleteSessionsForChannel(channelId) {
24951
- const result = this.db.prepare("DELETE FROM sessions WHERE channel_id = ?").run(channelId);
24952
- return result.changes;
24953
- }
24954
- /**
24955
- * Re-key a single thread's rows onto a different channel. `sessions`,
24956
- * `model_overrides` and `effort_overrides` are all keyed by (channel_id,
24957
- * thread_ts), so moving a thread in the dashboard without this leaves the
24958
- * agent unable to find its own session: the next turn would start from
24959
- * scratch and lose the conversation, and any `!model`/`!effort` override on
24960
- * the thread would silently revert.
24961
- *
24962
- * A row already sitting on the destination key wins — that means the thread
24963
- * has been moved back and forth and the destination row is the newer state,
24964
- * so the stale source row is dropped rather than overwriting it.
24965
- *
24966
- * Returns how many rows were re-keyed in each table.
24967
- */
24968
- moveThread(fromChannelId, toChannelId, threadTs) {
24969
- const move = this.db.transaction(() => {
24970
- const counts = { sessions: 0, modelOverrides: 0, effortOverrides: 0 };
24971
- for (const table of ["sessions", "model_overrides", "effort_overrides"]) {
24972
- const updated = this.db.prepare(
24973
- `UPDATE OR IGNORE ${table} SET channel_id = ?
24974
- WHERE channel_id = ? AND thread_ts = ?`
24975
- ).run(toChannelId, fromChannelId, threadTs);
24976
- this.db.prepare(`DELETE FROM ${table} WHERE channel_id = ? AND thread_ts = ?`).run(fromChannelId, threadTs);
24977
- if (table === "sessions") counts.sessions = updated.changes;
24978
- else if (table === "model_overrides") counts.modelOverrides = updated.changes;
24979
- else counts.effortOverrides = updated.changes;
24980
- }
24981
- return counts;
24982
- });
24983
- return move();
24984
- }
24985
- getModelOverride(channelId, threadTs) {
24986
- const row = this.db.prepare("SELECT model FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
24987
- return row?.model;
24988
- }
24989
- setModelOverride(channelId, threadTs, model) {
24990
- this.db.prepare(
24991
- `INSERT INTO model_overrides (channel_id, thread_ts, model)
24992
- VALUES (?, ?, ?)
24993
- ON CONFLICT (channel_id, thread_ts)
24994
- DO UPDATE SET model = excluded.model, updated_at = datetime('now')`
24995
- ).run(channelId, threadTs, model);
24996
- }
24997
- clearModelOverride(channelId, threadTs) {
24998
- this.db.prepare("DELETE FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
24999
- }
25000
- getEffortOverride(channelId, threadTs) {
25001
- const row = this.db.prepare("SELECT effort FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
25002
- return row?.effort && isEffort(row.effort) ? row.effort : void 0;
25003
- }
25004
- setEffortOverride(channelId, threadTs, effort) {
25005
- this.db.prepare(
25006
- `INSERT INTO effort_overrides (channel_id, thread_ts, effort)
25007
- VALUES (?, ?, ?)
25008
- ON CONFLICT (channel_id, thread_ts)
25009
- DO UPDATE SET effort = excluded.effort, updated_at = datetime('now')`
25010
- ).run(channelId, threadTs, effort);
25011
- }
25012
- clearEffortOverride(channelId, threadTs) {
25013
- this.db.prepare("DELETE FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
25014
- }
25015
- close() {
25016
- this.db.close();
25017
- }
25018
- };
25019
-
25020
- // src/dashboard/memory-extraction-runner.ts
25021
- import { spawn as spawn4 } from "child_process";
25022
- import { existsSync as existsSync13, mkdtempSync as mkdtempSync3, readFileSync as readFileSync10, rmSync as rmSync6 } from "fs";
25023
- import { tmpdir as tmpdir3 } from "os";
25024
- import { join as join12 } from "path";
24870
+ // ../api/src/claude/skills.ts
24871
+ import { existsSync as existsSync14, readdirSync as readdirSync4, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
24872
+ import { homedir as homedir6 } from "os";
24873
+ import { basename as basename3, dirname as dirname2, join as join12 } from "path";
24874
+ import yaml3 from "js-yaml";
25025
24875
 
25026
- // ../api/src/dashboard/profile-config.ts
24876
+ // ../api/src/claude/skill-files.ts
24877
+ import {
24878
+ existsSync as existsSync13,
24879
+ mkdirSync as mkdirSync9,
24880
+ readFileSync as readFileSync10,
24881
+ readdirSync as readdirSync3,
24882
+ rmSync as rmSync6,
24883
+ statSync as statSync5,
24884
+ writeFileSync as writeFileSync6
24885
+ } from "fs";
25027
24886
  import { homedir as homedir5 } from "os";
25028
- import { join as join11 } from "path";
25029
-
25030
- // ../api/src/dashboard/profile-config-cache.ts
25031
- var cache2 = /* @__PURE__ */ new Map();
25032
- function setProfileConfigCache(configs) {
25033
- cache2.clear();
25034
- for (const [profile, config] of Object.entries(configs)) cache2.set(profile, config);
24887
+ import { join as join11, resolve as resolve6, sep as sep3 } from "path";
24888
+ import yaml2 from "js-yaml";
24889
+ var MAX_SKILL_BYTES = 2 * 1024 * 1024;
24890
+ var SKILL_NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
24891
+ function expandHome2(p) {
24892
+ if (p === "~") return homedir5();
24893
+ if (p.startsWith("~/")) return join11(homedir5(), p.slice(2));
24894
+ return p;
25035
24895
  }
25036
- function cachedProfileConfig(profile = getProfile()) {
25037
- return cache2.get(profile);
24896
+ function workspaceSkillsDir(configDir) {
24897
+ return join11(configDir ? expandHome2(configDir) : join11(homedir5(), ".claude"), "skills");
25038
24898
  }
25039
-
25040
- // ../api/src/dashboard/profile-config.ts
25041
- function profileEnv(key) {
25042
- return cachedProfileConfig()?.env[key] || process.env[key] || void 0;
24899
+ function channelSkillsDir(cwd) {
24900
+ return join11(cwd, ".claude", "skills");
25043
24901
  }
25044
- function profileClaudeConfigDir() {
25045
- const config = cachedProfileConfig();
25046
- if (!config) return process.env["CLAUDE_CONFIG_DIR"] || void 0;
25047
- return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join11(homedir5(), ".claude");
24902
+ function isValidSkillName(name) {
24903
+ return SKILL_NAME.test(name);
25048
24904
  }
25049
- function profileOauthToken() {
25050
- const env = cachedProfileConfig()?.env ?? {};
25051
- if (env["CLAUDE_CODE_OAUTH_TOKEN"]) return env["CLAUDE_CODE_OAUTH_TOKEN"];
25052
- if (env["CLAUDE_CONFIG_DIR"]) return void 0;
25053
- return process.env["CLAUDE_CODE_OAUTH_TOKEN"] || void 0;
24905
+ function resolveSkillPath(dir, name) {
24906
+ if (!isValidSkillName(name)) return null;
24907
+ const abs = resolve6(dir, name, "SKILL.md");
24908
+ if (!abs.startsWith(resolve6(dir) + sep3)) return null;
24909
+ return abs;
25054
24910
  }
25055
- function defaultClaudeCwd() {
25056
- return profileEnv("CLAUDE_CWD") ?? process.cwd();
24911
+ function splitFrontmatter(raw) {
24912
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
24913
+ if (!match) return { fm: {}, body: raw };
24914
+ let fm = {};
24915
+ try {
24916
+ fm = yaml2.load(match[1]) ?? {};
24917
+ } catch {
24918
+ fm = {};
24919
+ }
24920
+ return { fm, body: raw.slice(match[0].length) };
25057
24921
  }
25058
- function defaultModel() {
25059
- return cachedProfileConfig()?.agentModel || profileEnv("CUSTIE_MODEL")?.trim() || "sonnet";
24922
+ function buildSkillFile(fm, body) {
24923
+ const { name, description, ...rest } = fm;
24924
+ const ordered = { name, description, ...rest };
24925
+ const front = yaml2.dump(ordered, { lineWidth: -1 }).trimEnd();
24926
+ return `---
24927
+ ${front}
24928
+ ---
24929
+
24930
+ ${body.replace(/^\n+/, "").trimEnd()}
24931
+ `;
25060
24932
  }
25061
- function defaultEffort() {
25062
- const raw = profileEnv("CUSTIE_EFFORT")?.trim().toLowerCase();
25063
- return raw && isEffort(raw) ? raw : void 0;
24933
+ function readMeta(abs) {
24934
+ try {
24935
+ const { fm } = splitFrontmatter(readFileSync10(abs, "utf-8"));
24936
+ return {
24937
+ name: typeof fm["name"] === "string" ? fm["name"] : void 0,
24938
+ description: typeof fm["description"] === "string" ? fm["description"] : void 0
24939
+ };
24940
+ } catch {
24941
+ return {};
24942
+ }
25064
24943
  }
25065
- function resolveChannelConfig(channelId) {
25066
- const channel = findChannel(channelId);
25067
- return {
25068
- cwd: channel?.cwd ?? defaultClaudeCwd(),
25069
- model: channel?.model?.trim() || defaultModel(),
25070
- effort: channel?.effort ?? defaultEffort(),
24944
+ function listSkillFiles(dir) {
24945
+ if (!existsSync13(dir)) return [];
24946
+ let entries2;
24947
+ try {
24948
+ entries2 = readdirSync3(dir);
24949
+ } catch {
24950
+ return [];
24951
+ }
24952
+ const rows2 = [];
24953
+ for (const entry of entries2) {
24954
+ if (!isValidSkillName(entry)) continue;
24955
+ const abs = join11(dir, entry, "SKILL.md");
24956
+ let stat;
24957
+ try {
24958
+ stat = statSync5(abs);
24959
+ } catch {
24960
+ continue;
24961
+ }
24962
+ if (!stat.isFile()) continue;
24963
+ const meta = readMeta(abs);
24964
+ rows2.push({
24965
+ // The directory name is the identifier the CLI resolves by, so it wins
24966
+ // over a frontmatter `name` that has drifted away from it.
24967
+ name: entry,
24968
+ description: (meta.description ?? "").trim(),
24969
+ mtime: stat.mtime.toISOString()
24970
+ });
24971
+ }
24972
+ return rows2.sort((a, b) => a.name.localeCompare(b.name));
24973
+ }
24974
+ function readSkillFile(dir, name) {
24975
+ const abs = resolveSkillPath(dir, name);
24976
+ if (!abs) return null;
24977
+ let stat;
24978
+ try {
24979
+ stat = statSync5(abs);
24980
+ } catch {
24981
+ return null;
24982
+ }
24983
+ if (!stat.isFile() || stat.size > MAX_SKILL_BYTES) return null;
24984
+ const { fm, body } = splitFrontmatter(readFileSync10(abs, "utf-8"));
24985
+ return {
24986
+ name,
24987
+ description: typeof fm["description"] === "string" ? fm["description"].trim() : "",
24988
+ body,
24989
+ mtime: stat.mtime.toISOString(),
24990
+ path: abs
24991
+ };
24992
+ }
24993
+ function writeSkillFile(dir, name, patch, baseMtime) {
24994
+ const abs = resolveSkillPath(dir, name);
24995
+ if (!abs) return { status: "not-found" };
24996
+ let stat;
24997
+ try {
24998
+ stat = statSync5(abs);
24999
+ } catch {
25000
+ return { status: "not-found" };
25001
+ }
25002
+ if (!stat.isFile()) return { status: "not-found" };
25003
+ if (baseMtime && stat.mtime.toISOString() !== baseMtime) {
25004
+ return { status: "conflict", mtime: stat.mtime.toISOString() };
25005
+ }
25006
+ const { fm } = splitFrontmatter(readFileSync10(abs, "utf-8"));
25007
+ const content = buildSkillFile({ ...fm, name, description: patch.description }, patch.body);
25008
+ if (Buffer.byteLength(content, "utf8") > MAX_SKILL_BYTES) return { status: "too-large" };
25009
+ writeFileSync6(abs, content, "utf8");
25010
+ return { status: "ok", mtime: statSync5(abs).mtime.toISOString() };
25011
+ }
25012
+ function createSkillFile(dir, name, description) {
25013
+ const abs = resolveSkillPath(dir, name);
25014
+ if (!abs) return { status: "bad-name" };
25015
+ if (existsSync13(abs)) return { status: "exists" };
25016
+ mkdirSync9(join11(dir, name), { recursive: true });
25017
+ writeFileSync6(
25018
+ abs,
25019
+ buildSkillFile(
25020
+ { name, description },
25021
+ `# ${name}
25022
+
25023
+ Describe what this skill does and when to use it.
25024
+ `
25025
+ ),
25026
+ "utf8"
25027
+ );
25028
+ const detail = readSkillFile(dir, name);
25029
+ return detail ? { status: "ok", skill: detail } : { status: "bad-name" };
25030
+ }
25031
+ function deleteSkillFile(dir, name) {
25032
+ const abs = resolveSkillPath(dir, name);
25033
+ if (!abs || !existsSync13(abs)) return { status: "not-found" };
25034
+ rmSync6(join11(dir, name), { recursive: true, force: true });
25035
+ return { status: "ok" };
25036
+ }
25037
+
25038
+ // ../api/src/claude/skills.ts
25039
+ function defaultConfigDir2() {
25040
+ return join12(homedir6(), ".claude");
25041
+ }
25042
+ function expandHome3(p) {
25043
+ if (p === "~") return homedir6();
25044
+ if (p.startsWith("~/")) return join12(homedir6(), p.slice(2));
25045
+ return p;
25046
+ }
25047
+ function parseFrontmatter2(file) {
25048
+ let content;
25049
+ try {
25050
+ content = readFileSync11(file, "utf-8");
25051
+ } catch {
25052
+ return {};
25053
+ }
25054
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
25055
+ if (!match) return {};
25056
+ try {
25057
+ const fm = yaml3.load(match[1]);
25058
+ const name = typeof fm?.["name"] === "string" ? fm["name"] : void 0;
25059
+ const description = typeof fm?.["description"] === "string" ? fm["description"] : void 0;
25060
+ return { name, description };
25061
+ } catch {
25062
+ return {};
25063
+ }
25064
+ }
25065
+ function isSymlinkedDir(root, entry) {
25066
+ if (!entry.isSymbolicLink()) return false;
25067
+ try {
25068
+ return statSync6(join12(root, entry.name)).isDirectory();
25069
+ } catch {
25070
+ return false;
25071
+ }
25072
+ }
25073
+ function findSkillFiles(root, maxDepth, out) {
25074
+ if (maxDepth < 0 || !existsSync14(root)) return;
25075
+ let entries2;
25076
+ try {
25077
+ entries2 = readdirSync4(root, { withFileTypes: true });
25078
+ } catch {
25079
+ return;
25080
+ }
25081
+ for (const entry of entries2) {
25082
+ if (entry.isFile()) {
25083
+ if (entry.name === "SKILL.md") out.push(join12(root, entry.name));
25084
+ } else if (entry.isDirectory() || isSymlinkedDir(root, entry)) {
25085
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
25086
+ findSkillFiles(join12(root, entry.name), maxDepth - 1, out);
25087
+ }
25088
+ }
25089
+ }
25090
+ function pluginNameFor(file, root) {
25091
+ let dir = dirname2(file);
25092
+ while (dir.startsWith(root) && dir !== dirname2(dir)) {
25093
+ try {
25094
+ const manifest = JSON.parse(
25095
+ readFileSync11(join12(dir, ".claude-plugin", "plugin.json"), "utf-8")
25096
+ );
25097
+ if (typeof manifest.name === "string" && manifest.name.trim()) return manifest.name.trim();
25098
+ } catch {
25099
+ }
25100
+ dir = dirname2(dir);
25101
+ }
25102
+ return void 0;
25103
+ }
25104
+ function collectFrom2(root, source, maxDepth, namePrefix) {
25105
+ const files = [];
25106
+ findSkillFiles(root, maxDepth, files);
25107
+ return files.map((file) => {
25108
+ const fm = parseFrontmatter2(file);
25109
+ const name = fm.name?.trim() || basename3(dirname2(file));
25110
+ const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25111
+ const prefix = namePrefix ?? plugin;
25112
+ return {
25113
+ name: prefix ? `${prefix}:${name}` : name,
25114
+ description: (fm.description ?? "").trim(),
25115
+ source,
25116
+ ...plugin && { plugin },
25117
+ // Only read by `listPluginSkillDetails`; `listSkills` strips it.
25118
+ file
25119
+ };
25120
+ });
25121
+ }
25122
+ function collectAll(configDir, cwd) {
25123
+ const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
25124
+ const collected = [
25125
+ ...collectFrom2(join12(cwd, ".claude", "skills"), "project", 2),
25126
+ ...nestedProjectRoots(cwd).flatMap(({ dir, prefix }) => collectFrom2(dir, "project", 2, prefix)),
25127
+ ...collectFrom2(join12(base, "skills"), "user", 2),
25128
+ ...collectFrom2(join12(base, "plugins"), "plugin", 8)
25129
+ ];
25130
+ const byName = /* @__PURE__ */ new Map();
25131
+ for (const skill of collected) {
25132
+ if (skill.name && !byName.has(skill.name)) byName.set(skill.name, skill);
25133
+ }
25134
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
25135
+ }
25136
+ function nestedProjectRoots(cwd) {
25137
+ let entries2;
25138
+ try {
25139
+ entries2 = readdirSync4(cwd, { withFileTypes: true });
25140
+ } catch {
25141
+ return [];
25142
+ }
25143
+ const roots = [];
25144
+ for (const entry of entries2) {
25145
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
25146
+ if (!entry.isDirectory() && !isSymlinkedDir(cwd, entry)) continue;
25147
+ const skillsDir = join12(cwd, entry.name, ".claude", "skills");
25148
+ if (existsSync14(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
25149
+ }
25150
+ return roots;
25151
+ }
25152
+ function listSkills(configDir, cwd) {
25153
+ return collectAll(configDir, cwd).map(({ file: _file, ...skill }) => skill);
25154
+ }
25155
+ function listPluginSkillDetails(configDir, cwd) {
25156
+ const details = [];
25157
+ for (const { file, ...skill } of collectAll(configDir, cwd)) {
25158
+ if (skill.source !== "plugin") continue;
25159
+ try {
25160
+ const { body } = splitFrontmatter(readFileSync11(file, "utf-8"));
25161
+ details.push({ ...skill, body, path: file, mtime: statSync6(file).mtime.toISOString() });
25162
+ } catch {
25163
+ }
25164
+ }
25165
+ return details;
25166
+ }
25167
+ function findSkillDetail(configDir, cwd, name, sources) {
25168
+ const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
25169
+ const roots = [
25170
+ [join12(cwd, ".claude", "skills"), "project", 2],
25171
+ ...nestedProjectRoots(cwd).map(({ dir, prefix }) => [
25172
+ dir,
25173
+ "project",
25174
+ 2,
25175
+ prefix
25176
+ ]),
25177
+ [join12(base, "skills"), "user", 2],
25178
+ [join12(base, "plugins"), "plugin", 8]
25179
+ ];
25180
+ for (const [root, source, maxDepth, namePrefix] of roots) {
25181
+ if (!sources.includes(source)) continue;
25182
+ const files = [];
25183
+ findSkillFiles(root, maxDepth, files);
25184
+ for (const file of files) {
25185
+ const fm = parseFrontmatter2(file);
25186
+ const rawName = fm.name?.trim() || basename3(dirname2(file));
25187
+ const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25188
+ const prefix = namePrefix ?? plugin;
25189
+ const skillName = prefix ? `${prefix}:${rawName}` : rawName;
25190
+ if (skillName !== name) continue;
25191
+ let raw;
25192
+ let mtime;
25193
+ try {
25194
+ raw = readFileSync11(file, "utf-8");
25195
+ mtime = statSync6(file).mtime.toISOString();
25196
+ } catch {
25197
+ continue;
25198
+ }
25199
+ const { body } = splitFrontmatter(raw);
25200
+ return {
25201
+ name: skillName,
25202
+ description: (fm.description ?? "").trim(),
25203
+ source,
25204
+ ...plugin && { plugin },
25205
+ body,
25206
+ path: file,
25207
+ mtime
25208
+ };
25209
+ }
25210
+ }
25211
+ return null;
25212
+ }
25213
+ function expandSkillCommand(configDir, cwd, text) {
25214
+ const match = text.trimStart().match(/^\/([\w.:-]+)(?:\s+([\s\S]*))?$/);
25215
+ if (!match) return null;
25216
+ const skill = findSkillDetail(configDir, cwd, match[1], ["project", "user", "plugin"]);
25217
+ if (!skill) return null;
25218
+ const args = match[2]?.trim() ?? "";
25219
+ const body = skill.body.includes("$ARGUMENTS") ? skill.body.replaceAll("$ARGUMENTS", args) : skill.body + (args ? `
25220
+
25221
+ ARGUMENTS: ${args}` : "");
25222
+ return `[the user ran the /${skill.name} skill; its instructions follow. Base directory for this skill: ${dirname2(skill.path)}]
25223
+
25224
+ ${body.trim()}`;
25225
+ }
25226
+
25227
+ // src/store/session-store.ts
25228
+ import Database2 from "better-sqlite3";
25229
+ var SessionStore = class {
25230
+ db;
25231
+ constructor(dbPath) {
25232
+ this.db = new Database2(dbPath);
25233
+ this.db.pragma("journal_mode = WAL");
25234
+ this.init();
25235
+ }
25236
+ init() {
25237
+ this.db.exec(`
25238
+ CREATE TABLE IF NOT EXISTS sessions (
25239
+ channel_id TEXT NOT NULL,
25240
+ thread_ts TEXT NOT NULL,
25241
+ session_id TEXT NOT NULL,
25242
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
25243
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
25244
+ PRIMARY KEY (channel_id, thread_ts)
25245
+ )
25246
+ `);
25247
+ const sessionColumns = this.db.prepare("PRAGMA table_info(sessions)").all();
25248
+ if (!sessionColumns.some((c) => c.name === "runner")) {
25249
+ this.db.exec(`ALTER TABLE sessions ADD COLUMN runner TEXT NOT NULL DEFAULT 'claude'`);
25250
+ }
25251
+ this.db.exec(`DELETE FROM sessions WHERE runner = 'opencode'`);
25252
+ this.db.exec(`
25253
+ CREATE TABLE IF NOT EXISTS model_overrides (
25254
+ channel_id TEXT NOT NULL,
25255
+ thread_ts TEXT NOT NULL,
25256
+ model TEXT NOT NULL,
25257
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
25258
+ PRIMARY KEY (channel_id, thread_ts)
25259
+ )
25260
+ `);
25261
+ this.db.exec(`
25262
+ CREATE TABLE IF NOT EXISTS effort_overrides (
25263
+ channel_id TEXT NOT NULL,
25264
+ thread_ts TEXT NOT NULL,
25265
+ effort TEXT NOT NULL,
25266
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
25267
+ PRIMARY KEY (channel_id, thread_ts)
25268
+ )
25269
+ `);
25270
+ }
25271
+ getSession(channelId, threadTs) {
25272
+ const row = this.db.prepare("SELECT * FROM sessions WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
25273
+ if (!row) return void 0;
25274
+ return {
25275
+ channelId: row.channel_id,
25276
+ threadTs: row.thread_ts,
25277
+ sessionId: row.session_id,
25278
+ runner: row.runner === "codex" ? "codex" : "claude",
25279
+ createdAt: row.created_at,
25280
+ updatedAt: row.updated_at
25281
+ };
25282
+ }
25283
+ saveSession(channelId, threadTs, sessionId, runner = "claude") {
25284
+ this.db.prepare(
25285
+ `INSERT INTO sessions (channel_id, thread_ts, session_id, runner)
25286
+ VALUES (?, ?, ?, ?)
25287
+ ON CONFLICT (channel_id, thread_ts)
25288
+ DO UPDATE SET session_id = excluded.session_id, runner = excluded.runner, updated_at = datetime('now')`
25289
+ ).run(channelId, threadTs, sessionId, runner);
25290
+ }
25291
+ /** All sessions, newest activity first. Read-only listing for the dashboard. */
25292
+ listSessions() {
25293
+ const rows2 = this.db.prepare("SELECT * FROM sessions ORDER BY updated_at DESC").all();
25294
+ return rows2.map((row) => ({
25295
+ channelId: row.channel_id,
25296
+ threadTs: row.thread_ts,
25297
+ sessionId: row.session_id,
25298
+ runner: row.runner === "codex" ? "codex" : "claude",
25299
+ createdAt: row.created_at,
25300
+ updatedAt: row.updated_at
25301
+ }));
25302
+ }
25303
+ deleteSession(channelId, threadTs) {
25304
+ this.db.prepare("DELETE FROM sessions WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
25305
+ }
25306
+ /**
25307
+ * Drop every session in a channel. Used when the channel's execution runtime
25308
+ * changes (`channels.runtime`, 0035): the session ids here point at Claude
25309
+ * session files stored under whichever runtime wrote them — the host's
25310
+ * CLAUDE_CONFIG_DIR, or the container's own per-channel home — so after a
25311
+ * switch every one of them resolves to a file the new runtime cannot see.
25312
+ * Left in place, the next turn in each thread would `--resume` an id that
25313
+ * does not exist there and lose the conversation in a confusing way; dropping
25314
+ * them makes the next turn cleanly start fresh instead.
25315
+ *
25316
+ * Returns how many were removed, so the caller can log something meaningful.
25317
+ */
25318
+ deleteSessionsForChannel(channelId) {
25319
+ const result = this.db.prepare("DELETE FROM sessions WHERE channel_id = ?").run(channelId);
25320
+ return result.changes;
25321
+ }
25322
+ /**
25323
+ * Re-key a single thread's rows onto a different channel. `sessions`,
25324
+ * `model_overrides` and `effort_overrides` are all keyed by (channel_id,
25325
+ * thread_ts), so moving a thread in the dashboard without this leaves the
25326
+ * agent unable to find its own session: the next turn would start from
25327
+ * scratch and lose the conversation, and any `!model`/`!effort` override on
25328
+ * the thread would silently revert.
25329
+ *
25330
+ * A row already sitting on the destination key wins — that means the thread
25331
+ * has been moved back and forth and the destination row is the newer state,
25332
+ * so the stale source row is dropped rather than overwriting it.
25333
+ *
25334
+ * Returns how many rows were re-keyed in each table.
25335
+ */
25336
+ moveThread(fromChannelId, toChannelId, threadTs) {
25337
+ const move = this.db.transaction(() => {
25338
+ const counts = { sessions: 0, modelOverrides: 0, effortOverrides: 0 };
25339
+ for (const table of ["sessions", "model_overrides", "effort_overrides"]) {
25340
+ const updated = this.db.prepare(
25341
+ `UPDATE OR IGNORE ${table} SET channel_id = ?
25342
+ WHERE channel_id = ? AND thread_ts = ?`
25343
+ ).run(toChannelId, fromChannelId, threadTs);
25344
+ this.db.prepare(`DELETE FROM ${table} WHERE channel_id = ? AND thread_ts = ?`).run(fromChannelId, threadTs);
25345
+ if (table === "sessions") counts.sessions = updated.changes;
25346
+ else if (table === "model_overrides") counts.modelOverrides = updated.changes;
25347
+ else counts.effortOverrides = updated.changes;
25348
+ }
25349
+ return counts;
25350
+ });
25351
+ return move();
25352
+ }
25353
+ getModelOverride(channelId, threadTs) {
25354
+ const row = this.db.prepare("SELECT model FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
25355
+ return row?.model;
25356
+ }
25357
+ setModelOverride(channelId, threadTs, model) {
25358
+ this.db.prepare(
25359
+ `INSERT INTO model_overrides (channel_id, thread_ts, model)
25360
+ VALUES (?, ?, ?)
25361
+ ON CONFLICT (channel_id, thread_ts)
25362
+ DO UPDATE SET model = excluded.model, updated_at = datetime('now')`
25363
+ ).run(channelId, threadTs, model);
25364
+ }
25365
+ clearModelOverride(channelId, threadTs) {
25366
+ this.db.prepare("DELETE FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
25367
+ }
25368
+ getEffortOverride(channelId, threadTs) {
25369
+ const row = this.db.prepare("SELECT effort FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
25370
+ return row?.effort && isEffort(row.effort) ? row.effort : void 0;
25371
+ }
25372
+ setEffortOverride(channelId, threadTs, effort) {
25373
+ this.db.prepare(
25374
+ `INSERT INTO effort_overrides (channel_id, thread_ts, effort)
25375
+ VALUES (?, ?, ?)
25376
+ ON CONFLICT (channel_id, thread_ts)
25377
+ DO UPDATE SET effort = excluded.effort, updated_at = datetime('now')`
25378
+ ).run(channelId, threadTs, effort);
25379
+ }
25380
+ clearEffortOverride(channelId, threadTs) {
25381
+ this.db.prepare("DELETE FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
25382
+ }
25383
+ close() {
25384
+ this.db.close();
25385
+ }
25386
+ };
25387
+
25388
+ // src/dashboard/memory-extraction-runner.ts
25389
+ import { spawn as spawn4 } from "child_process";
25390
+ import { existsSync as existsSync15, mkdtempSync as mkdtempSync3, readFileSync as readFileSync12, rmSync as rmSync7 } from "fs";
25391
+ import { tmpdir as tmpdir3 } from "os";
25392
+ import { join as join14 } from "path";
25393
+
25394
+ // ../api/src/dashboard/profile-config.ts
25395
+ import { homedir as homedir7 } from "os";
25396
+ import { join as join13 } from "path";
25397
+
25398
+ // ../api/src/dashboard/profile-config-cache.ts
25399
+ var cache2 = /* @__PURE__ */ new Map();
25400
+ function setProfileConfigCache(configs) {
25401
+ cache2.clear();
25402
+ for (const [profile, config] of Object.entries(configs)) cache2.set(profile, config);
25403
+ }
25404
+ function cachedProfileConfig(profile = getProfile()) {
25405
+ return cache2.get(profile);
25406
+ }
25407
+
25408
+ // ../api/src/dashboard/profile-config.ts
25409
+ function profileEnv(key) {
25410
+ return cachedProfileConfig()?.env[key] || process.env[key] || void 0;
25411
+ }
25412
+ function profileClaudeConfigDir() {
25413
+ const config = cachedProfileConfig();
25414
+ if (!config) return process.env["CLAUDE_CONFIG_DIR"] || void 0;
25415
+ return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join13(homedir7(), ".claude");
25416
+ }
25417
+ function profileOauthToken() {
25418
+ const env = cachedProfileConfig()?.env ?? {};
25419
+ if (env["CLAUDE_CODE_OAUTH_TOKEN"]) return env["CLAUDE_CODE_OAUTH_TOKEN"];
25420
+ if (env["CLAUDE_CONFIG_DIR"]) return void 0;
25421
+ return process.env["CLAUDE_CODE_OAUTH_TOKEN"] || void 0;
25422
+ }
25423
+ function defaultClaudeCwd() {
25424
+ return profileEnv("CLAUDE_CWD") ?? process.cwd();
25425
+ }
25426
+ function defaultModel() {
25427
+ return cachedProfileConfig()?.agentModel || profileEnv("CUSTIE_MODEL")?.trim() || "sonnet";
25428
+ }
25429
+ function defaultEffort() {
25430
+ const raw = profileEnv("CUSTIE_EFFORT")?.trim().toLowerCase();
25431
+ return raw && isEffort(raw) ? raw : void 0;
25432
+ }
25433
+ function resolveChannelConfig(channelId) {
25434
+ const channel = findChannel(channelId);
25435
+ return {
25436
+ cwd: channel?.cwd ?? defaultClaudeCwd(),
25437
+ model: channel?.model?.trim() || defaultModel(),
25438
+ effort: channel?.effort ?? defaultEffort(),
25071
25439
  runtime: channel?.runtime ?? "host",
25072
25440
  mounts: channel?.mounts ?? [],
25073
25441
  permissionMode: resolveChannelPermissionMode(channelId),
@@ -25087,13 +25455,15 @@ function findOwningProfile(channelId) {
25087
25455
  // src/dashboard/memory-extraction-runner.ts
25088
25456
  var CLAUDE_MODEL = "sonnet";
25089
25457
  var CODEX_MODEL = "gpt-6-astra";
25458
+ var CHEAP_CLAUDE_MODEL = "haiku";
25459
+ var CHEAP_CODEX_MODEL = "gpt-5.6-luna";
25090
25460
  var CODEX_EFFORT2 = "low";
25091
25461
  var TIMEOUT_MS2 = 15e4;
25092
25462
  var SUGGEST_TOOLS = "Read,Glob,Grep";
25093
25463
  function buildInvocation(runner, req, dir, auth, baseEnv = process.env, tools = "") {
25094
25464
  const env = { ...baseEnv, CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" };
25095
25465
  if (runner === "codex") {
25096
- const outputFile = join12(dir, "last-message.txt");
25466
+ const outputFile = join14(dir, "last-message.txt");
25097
25467
  return {
25098
25468
  command: "codex",
25099
25469
  args: [
@@ -25106,7 +25476,7 @@ function buildInvocation(runner, req, dir, auth, baseEnv = process.env, tools =
25106
25476
  "-s",
25107
25477
  "read-only",
25108
25478
  "-m",
25109
- CODEX_MODEL,
25479
+ req.tier === "cheap" ? CHEAP_CODEX_MODEL : CODEX_MODEL,
25110
25480
  "-c",
25111
25481
  `model_reasoning_effort=${CODEX_EFFORT2}`,
25112
25482
  "--output-last-message",
@@ -25128,12 +25498,12 @@ ${req.user}`,
25128
25498
  else delete env["CLAUDE_CONFIG_DIR"];
25129
25499
  if (auth.claudeCodeOauthToken) env["CLAUDE_CODE_OAUTH_TOKEN"] = auth.claudeCodeOauthToken;
25130
25500
  else delete env["CLAUDE_CODE_OAUTH_TOKEN"];
25501
+ const model = req.tier === "cheap" ? CHEAP_CLAUDE_MODEL : CLAUDE_MODEL;
25131
25502
  return {
25132
25503
  command: "claude",
25133
25504
  args: [
25134
25505
  "-p",
25135
- "--model",
25136
- CLAUDE_MODEL,
25506
+ ...isModelForGateway(model, baseEnv["ANTHROPIC_MODEL"]) ? ["--model", model] : [],
25137
25507
  "--no-session-persistence",
25138
25508
  "--tools",
25139
25509
  tools,
@@ -25149,7 +25519,7 @@ ${req.user}`,
25149
25519
  }
25150
25520
  function run(inv, cwd) {
25151
25521
  return new Promise((resolve8) => {
25152
- if (!existsSync13(cwd)) {
25522
+ if (!existsSync15(cwd)) {
25153
25523
  resolve8({ ok: false, error: `the channel folder ${cwd} does not exist on this Host` });
25154
25524
  return;
25155
25525
  }
@@ -25182,7 +25552,7 @@ function run(inv, cwd) {
25182
25552
  let raw = stdout;
25183
25553
  if (inv.outputFile) {
25184
25554
  try {
25185
- raw = readFileSync10(inv.outputFile, "utf-8");
25555
+ raw = readFileSync12(inv.outputFile, "utf-8");
25186
25556
  } catch {
25187
25557
  raw = "";
25188
25558
  }
@@ -25195,7 +25565,7 @@ function run(inv, cwd) {
25195
25565
  async function complete(req, tools = "", cwd) {
25196
25566
  const runner = runnerForModel(loadDashboardSettings().agent);
25197
25567
  const config = resolveChannelConfig(req.channelId);
25198
- const dir = mkdtempSync3(join12(tmpdir3(), "flyspace-memory-"));
25568
+ const dir = mkdtempSync3(join14(tmpdir3(), "flyspace-memory-"));
25199
25569
  try {
25200
25570
  const inv = buildInvocation(
25201
25571
  runner,
@@ -25210,7 +25580,7 @@ async function complete(req, tools = "", cwd) {
25210
25580
  );
25211
25581
  return await run(inv, cwd ?? dir);
25212
25582
  } finally {
25213
- rmSync6(dir, { recursive: true, force: true });
25583
+ rmSync7(dir, { recursive: true, force: true });
25214
25584
  }
25215
25585
  }
25216
25586
  function completeMemoryExtraction(req) {
@@ -25360,6 +25730,31 @@ var RATE_CARDS = [
25360
25730
  cacheReadPer1M: 0.02,
25361
25731
  cacheWritePer1M: 0.2,
25362
25732
  effectiveFrom: EPOCH
25733
+ },
25734
+ {
25735
+ // Groq's models page, checked 2026-10-30. Our own spend (titles, translation,
25736
+ // autocomplete, retros), priced so we can account for it. Groq does not
25737
+ // publish a cache-hit rate here, so cache reads are priced at full input.
25738
+ id: "groq:gpt-oss-120b@1030",
25739
+ provider: "groq",
25740
+ model: "GPT OSS 120B",
25741
+ matches: ["openai/gpt-oss-120b", "gpt-oss-120b"],
25742
+ inputPer1M: 0.15,
25743
+ outputPer1M: 0.6,
25744
+ cacheReadPer1M: 0.15,
25745
+ cacheWritePer1M: 0.15,
25746
+ effectiveFrom: EPOCH
25747
+ },
25748
+ {
25749
+ id: "groq:gpt-oss-20b@1030",
25750
+ provider: "groq",
25751
+ model: "GPT OSS 20B",
25752
+ matches: ["openai/gpt-oss-20b", "gpt-oss-20b"],
25753
+ inputPer1M: 0.075,
25754
+ outputPer1M: 0.3,
25755
+ cacheReadPer1M: 0.075,
25756
+ cacheWritePer1M: 0.075,
25757
+ effectiveFrom: EPOCH
25363
25758
  }
25364
25759
  ];
25365
25760
  var BY_ID = new Map(RATE_CARDS.map((c) => [c.id, c]));
@@ -25375,6 +25770,7 @@ function providerFor(model) {
25375
25770
  if (id.startsWith("claude") || /^(opus|sonnet|haiku|fable|mythos)/.test(id)) return "anthropic";
25376
25771
  if (id.startsWith("deepseek")) return "deepseek";
25377
25772
  if (id.startsWith("kimi") || id.startsWith("moonshot") || id === "k3") return "moonshot";
25773
+ if (id.startsWith("openai/gpt-oss") || id.startsWith("gpt-oss") || id.startsWith("whisper")) return "groq";
25378
25774
  if (id.startsWith("gpt")) return "openai";
25379
25775
  return "unknown";
25380
25776
  }
@@ -25884,9 +26280,9 @@ var UsageStore = class {
25884
26280
 
25885
26281
  // src/dashboard/rollover-summary.ts
25886
26282
  import { spawn as spawn5 } from "child_process";
25887
- import { existsSync as existsSync14, mkdtempSync as mkdtempSync4, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
26283
+ import { existsSync as existsSync16, mkdtempSync as mkdtempSync4, readFileSync as readFileSync13, rmSync as rmSync8 } from "fs";
25888
26284
  import { tmpdir as tmpdir4 } from "os";
25889
- import { join as join13 } from "path";
26285
+ import { join as join15 } from "path";
25890
26286
  var HAIKU_MODEL = "haiku";
25891
26287
  var CJK_PATTERN = /[ -〿぀-ヿ㐀-䶿一-鿿豈-﫿＀-￯]/;
25892
26288
  function estimateTokens(text) {
@@ -25949,8 +26345,8 @@ function runSummaryPrint(input, options) {
25949
26345
  return runPrint("claude", args, env).then((out) => out.trim());
25950
26346
  }
25951
26347
  async function runCodexSummary(input) {
25952
- const dir = mkdtempSync4(join13(tmpdir4(), "rollover-"));
25953
- const lastMessageFile = join13(dir, "last-message.txt");
26348
+ const dir = mkdtempSync4(join15(tmpdir4(), "rollover-"));
26349
+ const lastMessageFile = join15(dir, "last-message.txt");
25954
26350
  try {
25955
26351
  await runPrint(
25956
26352
  "codex",
@@ -25973,9 +26369,9 @@ ${input}`
25973
26369
  ],
25974
26370
  { ...process.env }
25975
26371
  );
25976
- return existsSync14(lastMessageFile) ? readFileSync11(lastMessageFile, "utf8").trim() : "";
26372
+ return existsSync16(lastMessageFile) ? readFileSync13(lastMessageFile, "utf8").trim() : "";
25977
26373
  } finally {
25978
- rmSync7(dir, { recursive: true, force: true });
26374
+ rmSync8(dir, { recursive: true, force: true });
25979
26375
  }
25980
26376
  }
25981
26377
  function runPrint(command, args, env) {
@@ -26197,6 +26593,7 @@ import { execFile } from "child_process";
26197
26593
  import { promisify } from "util";
26198
26594
  var execFileAsync = promisify(execFile);
26199
26595
  var WAKE_THREAD_RE = /chat wake\b.*?--thread[ =]['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/;
26596
+ var ABOUT_RE = /chat wake\b.*?--about[ =](?:"([^"]*)"|'([^']*)'|(\S+))/;
26200
26597
  function parseEtime(etime) {
26201
26598
  const [days, rest] = etime.includes("-") ? etime.split("-") : ["0", etime];
26202
26599
  const parts = rest.split(":").map(Number);
@@ -26205,23 +26602,41 @@ function parseEtime(etime) {
26205
26602
  return Number(days) * 86400 + h * 3600 + m * 60 + s;
26206
26603
  }
26207
26604
  function parseBackgroundTasks(psOutput, now = Date.now()) {
26605
+ const rows2 = psOutput.split("\n").flatMap((line) => {
26606
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
26607
+ return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), age: parseEtime(m[3]), command: m[4] }] : [];
26608
+ });
26609
+ const children = /* @__PURE__ */ new Map();
26610
+ for (const row of rows2) children.set(row.ppid, [...children.get(row.ppid) ?? [], row]);
26611
+ const isJob = (command) => !/^\S*node\b/.test(command) && WAKE_THREAD_RE.test(command);
26612
+ const jobPids = new Set(rows2.filter((r) => isJob(r.command)).map((r) => r.pid));
26208
26613
  const byThread = /* @__PURE__ */ new Map();
26209
- for (const line of psOutput.split("\n")) {
26210
- const m = /^\s*(\d+)\s+(\S+)\s+(.*)$/.exec(line);
26211
- if (!m) continue;
26212
- const [, pid, etime, command] = m;
26213
- if (/^\S*node\b/.test(command)) continue;
26214
- const threadId = WAKE_THREAD_RE.exec(command)?.[1];
26215
- if (!threadId) continue;
26614
+ for (const row of rows2) {
26615
+ if (!jobPids.has(row.pid) || jobPids.has(row.ppid)) continue;
26616
+ const threadId = WAKE_THREAD_RE.exec(row.command)[1];
26617
+ let current;
26618
+ const stack = [...children.get(row.pid) ?? []];
26619
+ while (stack.length) {
26620
+ const child = stack.pop();
26621
+ stack.push(...children.get(child.pid) ?? []);
26622
+ if (!jobPids.has(child.pid) && (!current || child.age < current.age)) current = child;
26623
+ }
26624
+ const about = ABOUT_RE.exec(row.command);
26216
26625
  const list = byThread.get(threadId) ?? [];
26217
- list.push({ pid: Number(pid), startedAt: now - parseEtime(etime) * 1e3 });
26626
+ list.push({
26627
+ pid: row.pid,
26628
+ startedAt: now - row.age * 1e3,
26629
+ command: row.command,
26630
+ ...about && { about: (about[1] ?? about[2] ?? about[3]).trim() },
26631
+ ...current && { current: current.command }
26632
+ });
26218
26633
  byThread.set(threadId, list);
26219
26634
  }
26220
26635
  return byThread;
26221
26636
  }
26222
26637
  async function scanBackgroundTasks() {
26223
26638
  try {
26224
- const { stdout } = await execFileAsync("ps", ["-axo", "pid=,etime=,command="], {
26639
+ const { stdout } = await execFileAsync("ps", ["-axo", "pid=,ppid=,etime=,command="], {
26225
26640
  maxBuffer: 16 * 1024 * 1024
26226
26641
  });
26227
26642
  return parseBackgroundTasks(stdout);
@@ -26232,7 +26647,7 @@ async function scanBackgroundTasks() {
26232
26647
 
26233
26648
  // src/dashboard/attachment-downloader.ts
26234
26649
  import { writeFile as writeFile2 } from "fs/promises";
26235
- import { join as join14 } from "path";
26650
+ import { join as join16 } from "path";
26236
26651
  import { GetObjectCommand } from "@aws-sdk/client-s3";
26237
26652
  var debug4 = process.env["DEBUG"] === "true";
26238
26653
  var ATTACHMENT_LINK = /\]\((?:https:\/\/[a-z0-9-]+\.flyspace\.ai)?\/api\/attachments\/([^)?\s]+)(?:\?[^)\s]*)?\)/g;
@@ -26299,7 +26714,7 @@ async function downloadOne2(key) {
26299
26714
  if (bytes.length > sizeLimit) {
26300
26715
  return { kind: "skip", skipped: { name, mimetype, reason: "too_large" } };
26301
26716
  }
26302
- const localPath = join14(paths.UPLOADS_DIR, lastSegment);
26717
+ const localPath = join16(paths.UPLOADS_DIR, lastSegment);
26303
26718
  await writeFile2(localPath, bytes);
26304
26719
  if (debug4)
26305
26720
  console.log(`[attachment-downloader] saved ${key} -> ${localPath} (${bytes.length} bytes)`);
@@ -26324,27 +26739,27 @@ async function downloadChatAttachments(body) {
26324
26739
  }
26325
26740
 
26326
26741
  // src/dashboard/doc-mention-guard.ts
26327
- import { existsSync as existsSync19, statSync as statSync7 } from "fs";
26742
+ import { existsSync as existsSync21, statSync as statSync9 } from "fs";
26328
26743
 
26329
26744
  // src/dashboard/docs-routes.ts
26330
26745
  import {
26331
26746
  closeSync,
26332
26747
  createReadStream,
26333
- existsSync as existsSync18,
26748
+ existsSync as existsSync20,
26334
26749
  lstatSync as lstatSync2,
26335
- mkdirSync as mkdirSync9,
26750
+ mkdirSync as mkdirSync10,
26336
26751
  openSync,
26337
26752
  readSync,
26338
- readdirSync as readdirSync3,
26339
- readFileSync as readFileSync15,
26753
+ readdirSync as readdirSync5,
26754
+ readFileSync as readFileSync17,
26340
26755
  realpathSync as realpathSync2,
26341
26756
  renameSync as renameSync2,
26342
- rmSync as rmSync8,
26343
- statSync as statSync6,
26344
- writeFileSync as writeFileSync6
26757
+ rmSync as rmSync9,
26758
+ statSync as statSync8,
26759
+ writeFileSync as writeFileSync7
26345
26760
  } from "fs";
26346
26761
  import { Readable } from "stream";
26347
- import { basename as basename4, dirname as dirname2, extname as extname2, join as join18, relative as relative2, resolve as resolve6, sep as sep3 } from "path";
26762
+ import { basename as basename5, dirname as dirname3, extname as extname2, join as join20, relative as relative2, resolve as resolve7, sep as sep4 } from "path";
26348
26763
  import { Hono as Hono4 } from "hono";
26349
26764
  import { streamSSE } from "hono/streaming";
26350
26765
 
@@ -26456,8 +26871,8 @@ var requireDocsAccess = async (c, next) => {
26456
26871
  };
26457
26872
 
26458
26873
  // src/dashboard/docs-watcher.ts
26459
- import { existsSync as existsSync15, watch } from "fs";
26460
- import { basename as basename3, join as join15 } from "path";
26874
+ import { existsSync as existsSync17, watch } from "fs";
26875
+ import { basename as basename4, join as join17 } from "path";
26461
26876
  var DEBOUNCE_MS = 200;
26462
26877
  var MAX_PENDING = 200;
26463
26878
  var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
@@ -26493,12 +26908,12 @@ function flush(cwd) {
26493
26908
  function watchDocs(cwd, listener) {
26494
26909
  let entry = entries.get(cwd);
26495
26910
  if (!entry) {
26496
- const root = basename3(cwd);
26911
+ const root = basename4(cwd);
26497
26912
  const watcher = watch(cwd, { recursive: true, persistent: false }, (_event, filename) => {
26498
26913
  const current = entries.get(cwd);
26499
26914
  if (!current || filename === null) return;
26500
26915
  const rel = filename.split("\\").join("/");
26501
- if (rel === root && !existsSync15(join15(cwd, rel))) return;
26916
+ if (rel === root && !existsSync17(join17(cwd, rel))) return;
26502
26917
  if (isIgnoredDocPath(rel)) return;
26503
26918
  if (current.pending.size < MAX_PENDING) current.pending.add(rel);
26504
26919
  if (current.timer === null) current.timer = setTimeout(() => flush(cwd), DEBOUNCE_MS);
@@ -27831,8 +28246,8 @@ function createFeatureFlagsRouter() {
27831
28246
  }
27832
28247
 
27833
28248
  // ../api/src/dashboard/public-share-routes.ts
27834
- import { existsSync as existsSync17, readFileSync as readFileSync13, statSync as statSync5 } from "fs";
27835
- import { join as join17 } from "path";
28249
+ import { existsSync as existsSync19, readFileSync as readFileSync15, statSync as statSync7 } from "fs";
28250
+ import { join as join19 } from "path";
27836
28251
  import { Hono as Hono3 } from "hono";
27837
28252
  import { GetObjectCommand as GetObjectCommand3 } from "@aws-sdk/client-s3";
27838
28253
  import { getSignedUrl as getSignedUrl2 } from "@aws-sdk/s3-request-presigner";
@@ -28039,13 +28454,13 @@ function injectShareHead(html, head) {
28039
28454
 
28040
28455
  // ../api/src/dashboard/app-icon.ts
28041
28456
  import { createHash as createHash6 } from "crypto";
28042
- import { existsSync as existsSync16, readFileSync as readFileSync12 } from "fs";
28043
- import { join as join16 } from "path";
28457
+ import { existsSync as existsSync18, readFileSync as readFileSync14 } from "fs";
28458
+ import { join as join18 } from "path";
28044
28459
  import sharp2 from "sharp";
28045
28460
  var PLATE = "#0A0A0F";
28046
- var BRAND_DIR = existsSync16(join16(paths.WEB_ROOT, "public")) ? join16(paths.WEB_ROOT, "public") : join16(paths.PACKAGE_ROOT, "dist", "brand");
28047
- var MARK_FILE = join16(BRAND_DIR, "icons", "icon-512.png");
28048
- var MARK_SVG_FILE = join16(BRAND_DIR, "favicon.svg");
28461
+ var BRAND_DIR = existsSync18(join18(paths.WEB_ROOT, "public")) ? join18(paths.WEB_ROOT, "public") : join18(paths.PACKAGE_ROOT, "dist", "brand");
28462
+ var MARK_FILE = join18(BRAND_DIR, "icons", "icon-512.png");
28463
+ var MARK_SVG_FILE = join18(BRAND_DIR, "favicon.svg");
28049
28464
  var LAYOUT = {
28050
28465
  standard: { logo: 0.7, logoCx: 0.5, logoCy: 0.48, badge: 0.27, badgeCx: 0.22, badgeCy: 0.76 },
28051
28466
  maskable: { logo: 0.56, logoCx: 0.5, logoCy: 0.48, badge: 0.23, badgeCx: 0.33, badgeCy: 0.66 }
@@ -28068,7 +28483,7 @@ function roundedPlate(size, fill = PLATE) {
28068
28483
  }
28069
28484
  async function renderBadge(box) {
28070
28485
  const transparent = { r: 0, g: 0, b: 0, alpha: 0 };
28071
- const raster = await sharp2(readFileSync12(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
28486
+ const raster = await sharp2(readFileSync14(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
28072
28487
  return sharp2(raster).trim().resize(box, box, { fit: "contain", background: transparent }).png().toBuffer();
28073
28488
  }
28074
28489
  async function sampleBackground(logo) {
@@ -28123,7 +28538,7 @@ async function renderAppIcon({
28123
28538
  if (hit) return hit;
28124
28539
  const out = logo && await composeIcon(logo, size, maskable, plain).catch(() => null) || // No workspace logo to lead with — the stock mark is still the best icon,
28125
28540
  // either on its usual dark plate or, for a favicon, trimmed and bare.
28126
- (transparent ? await renderBadge(size) : await sharp2(readFileSync12(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
28541
+ (transparent ? await renderBadge(size) : await sharp2(readFileSync14(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
28127
28542
  cache4.set(key, out);
28128
28543
  return out;
28129
28544
  }
@@ -28146,38 +28561,6 @@ async function composeIcon(logo, size, maskable, plain) {
28146
28561
  ]).png().toBuffer();
28147
28562
  return sharp2(composed).composite([{ input: roundedPlate(size), blend: "dest-in" }]).png().toBuffer();
28148
28563
  }
28149
- function buildManifest(profile, displayName2) {
28150
- const workspace = displayName2?.trim() || profile;
28151
- const icon = (file) => `/icons/app/${profile}/${file}`;
28152
- return {
28153
- id: `/?workspace=${profile}`,
28154
- name: workspace === "Flyspace" ? "Flyspace" : `${workspace} \xB7 Flyspace`,
28155
- short_name: workspace,
28156
- description: "The AI native workspace",
28157
- start_url: `/?workspace=${profile}`,
28158
- scope: "/",
28159
- display: "standalone",
28160
- background_color: PLATE,
28161
- theme_color: PLATE,
28162
- icons: [
28163
- { src: icon("icon-192.png"), sizes: "192x192", type: "image/png" },
28164
- { src: icon("icon-512.png"), sizes: "512x512", type: "image/png" },
28165
- {
28166
- src: icon("icon-512-maskable.png"),
28167
- sizes: "512x512",
28168
- type: "image/png",
28169
- purpose: "maskable"
28170
- }
28171
- ],
28172
- shortcuts: [
28173
- {
28174
- name: "New post",
28175
- url: `/?workspace=${profile}&compose=1`,
28176
- icons: [{ src: icon("icon-192.png"), sizes: "192x192", type: "image/png" }]
28177
- }
28178
- ]
28179
- };
28180
- }
28181
28564
 
28182
28565
  // ../api/src/dashboard/share-og.ts
28183
28566
  import { createHash as createHash7 } from "crypto";
@@ -28692,9 +29075,9 @@ function createPublicShareApiRouter() {
28692
29075
  var BUILD_PREFIX = "/share/_assets";
28693
29076
  var shellCache = null;
28694
29077
  function readShell(path) {
28695
- const { mtimeMs } = statSync5(path);
29078
+ const { mtimeMs } = statSync7(path);
28696
29079
  if (shellCache?.mtimeMs === mtimeMs) return shellCache.html;
28697
- const html = readFileSync13(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
29080
+ const html = readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
28698
29081
  shellCache = { mtimeMs, html };
28699
29082
  return html;
28700
29083
  }
@@ -28714,17 +29097,17 @@ function serveBuildFile(c, webDist, dir, name) {
28714
29097
  if (!type || !/^[A-Za-z0-9._-]+$/.test(name) || name.includes("..")) {
28715
29098
  return c.text("not found", 404);
28716
29099
  }
28717
- const path = join17(webDist, dir, name);
28718
- if (!existsSync17(path)) return c.text("not found", 404);
29100
+ const path = join19(webDist, dir, name);
29101
+ if (!existsSync19(path)) return c.text("not found", 404);
28719
29102
  c.header("Content-Type", type);
28720
29103
  c.header("Cache-Control", "public, max-age=31536000, immutable");
28721
29104
  if (ext === ".css") {
28722
- return c.body(readFileSync13(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
29105
+ return c.body(readFileSync15(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
28723
29106
  }
28724
29107
  if (ext === ".js") {
28725
- return c.body(readFileSync13(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
29108
+ return c.body(readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
28726
29109
  }
28727
- return c.body(new Uint8Array(readFileSync13(path)));
29110
+ return c.body(new Uint8Array(readFileSync15(path)));
28728
29111
  }
28729
29112
  var HTML_SHARE_CSP = "sandbox allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox";
28730
29113
  function servePublishedHtml(c, share) {
@@ -28860,8 +29243,8 @@ ${analytics}` : head);
28860
29243
  const requested = c.req.param("lang");
28861
29244
  const lang = canonicalLanguage(requested);
28862
29245
  if (!isTranslatableLanguage(lang)) return next();
28863
- const shell = join17(webDist, "index.html");
28864
- if (!existsSync17(shell)) return next();
29246
+ const shell = join19(webDist, "index.html");
29247
+ if (!existsSync19(shell)) return next();
28865
29248
  const share = await getDocShare(c.req.param("id"));
28866
29249
  if (!share) return next();
28867
29250
  if (requested !== lang) return c.redirect(`/share/${share.id}/${lang}`, 302);
@@ -28896,8 +29279,8 @@ ${analytics}` : head);
28896
29279
  const share = await getDocShare(c.req.param("id"));
28897
29280
  if (!share) return next();
28898
29281
  if (share.kind === "html") return servePublishedHtml(c, share);
28899
- const shell = join17(webDist, "index.html");
28900
- if (!existsSync17(shell)) return next();
29282
+ const shell = join19(webDist, "index.html");
29283
+ if (!existsSync19(shell)) return next();
28901
29284
  return readerPage(
28902
29285
  c,
28903
29286
  share,
@@ -28922,7 +29305,7 @@ ${analytics}` : head);
28922
29305
  }
28923
29306
 
28924
29307
  // src/dashboard/artifact-export.ts
28925
- import { readFileSync as readFileSync14 } from "fs";
29308
+ import { readFileSync as readFileSync16 } from "fs";
28926
29309
  async function exportDocAsArtifact(channelId, docPath) {
28927
29310
  const owningProfile = findOwningProfile(channelId);
28928
29311
  const channelConfig = await runWithProfile(
@@ -28931,7 +29314,7 @@ async function exportDocAsArtifact(channelId, docPath) {
28931
29314
  );
28932
29315
  const abs = resolveDocPath(channelConfig.cwd, docPath);
28933
29316
  if (!abs) throw new Error(`doc not found: ${docPath}`);
28934
- const content = readFileSync14(abs, "utf8");
29317
+ const content = readFileSync16(abs, "utf8");
28935
29318
  const title = extractTitle(abs, "md");
28936
29319
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
28937
29320
  const prompt = `Publish the document at \`${docPath}\` (already read below) as a Claude Artifact, then record the result as a stub file under this channel's \`docs/artifacts/\` folder (create the folder if it doesn't exist).
@@ -29092,7 +29475,7 @@ function entryKind(entry, abs) {
29092
29475
  if (entry.isFile()) return "file";
29093
29476
  if (!entry.isSymbolicLink()) return null;
29094
29477
  try {
29095
- const target = statSync6(abs);
29478
+ const target = statSync8(abs);
29096
29479
  return target.isDirectory() ? "dir" : target.isFile() ? "file" : null;
29097
29480
  } catch {
29098
29481
  return null;
@@ -29105,11 +29488,11 @@ function fileNode(root, abs, name) {
29105
29488
  const lang = CODE_EXTENSIONS[ext];
29106
29489
  let stat;
29107
29490
  try {
29108
- stat = statSync6(abs);
29491
+ stat = statSync8(abs);
29109
29492
  } catch {
29110
29493
  return null;
29111
29494
  }
29112
- const path = relative2(root, abs).split(sep3).join("/");
29495
+ const path = relative2(root, abs).split(sep4).join("/");
29113
29496
  const mtime = stat.mtime.toISOString();
29114
29497
  if (kind) {
29115
29498
  return {
@@ -29148,9 +29531,9 @@ function readHead(absPath) {
29148
29531
  }
29149
29532
  }
29150
29533
  function extractTitle(absPath, kind) {
29151
- if (kind === "url" || kind === "excalidraw") return basename4(absPath);
29534
+ if (kind === "url" || kind === "excalidraw") return basename5(absPath);
29152
29535
  const head = readHead(absPath);
29153
- if (!head) return basename4(absPath);
29536
+ if (!head) return basename5(absPath);
29154
29537
  if (kind === "md") {
29155
29538
  const m = head.match(/^#{1,3}\s+(.+?)\s*$/m);
29156
29539
  if (m) return m[1].replace(/[*_`]/g, "").trim();
@@ -29158,12 +29541,12 @@ function extractTitle(absPath, kind) {
29158
29541
  const t = head.match(/<title[^>]*>([^<]+)<\/title>/i) ?? head.match(/<h1[^>]*>([^<]+)<\/h1>/i);
29159
29542
  if (t) return t[1].trim();
29160
29543
  }
29161
- return basename4(absPath);
29544
+ return basename5(absPath);
29162
29545
  }
29163
29546
  function resolveDirPath(root, rel) {
29164
29547
  if (rel.includes("\0")) return null;
29165
- const abs = resolve6(root, rel);
29166
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
29548
+ const abs = resolve7(root, rel);
29549
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
29167
29550
  return abs;
29168
29551
  }
29169
29552
  function isListableFile(name) {
@@ -29179,7 +29562,7 @@ function probeDir(absDir, showHidden) {
29179
29562
  if (depth > MAX_SEARCH_DEPTH) return false;
29180
29563
  let entries2;
29181
29564
  try {
29182
- entries2 = readdirSync3(dir, { withFileTypes: true });
29565
+ entries2 = readdirSync5(dir, { withFileTypes: true });
29183
29566
  } catch {
29184
29567
  return false;
29185
29568
  }
@@ -29190,7 +29573,7 @@ function probeDir(absDir, showHidden) {
29190
29573
  return false;
29191
29574
  }
29192
29575
  if (!showHidden && entry.name.startsWith(".")) continue;
29193
- const abs = join18(dir, entry.name);
29576
+ const abs = join20(dir, entry.name);
29194
29577
  const kind = entryKind(entry, abs);
29195
29578
  if (kind === "dir") {
29196
29579
  if (SKIP_DIRS.has(entry.name)) hasOther = true;
@@ -29210,14 +29593,14 @@ function probeDir(absDir, showHidden) {
29210
29593
  }
29211
29594
  function readGitBranch(dir) {
29212
29595
  try {
29213
- let gitDir = join18(dir, ".git");
29214
- if (statSync6(gitDir).isFile()) {
29215
- const pointer = readFileSync15(gitDir, "utf8").trim();
29596
+ let gitDir = join20(dir, ".git");
29597
+ if (statSync8(gitDir).isFile()) {
29598
+ const pointer = readFileSync17(gitDir, "utf8").trim();
29216
29599
  const match = pointer.match(/^gitdir:\s*(.+)$/);
29217
29600
  if (!match) return void 0;
29218
- gitDir = resolve6(dir, match[1]);
29601
+ gitDir = resolve7(dir, match[1]);
29219
29602
  }
29220
- const head = readFileSync15(join18(gitDir, "HEAD"), "utf8").trim();
29603
+ const head = readFileSync17(join20(gitDir, "HEAD"), "utf8").trim();
29221
29604
  const branchMatch = head.match(/^ref:\s*refs\/heads\/(.+)$/);
29222
29605
  if (branchMatch) return branchMatch[1];
29223
29606
  return /^[0-9a-f]{7,40}$/i.test(head) ? head.slice(0, 7) : void 0;
@@ -29230,7 +29613,7 @@ function listDocLevel(root, relDir = "", sort = "newest", showHidden = false) {
29230
29613
  if (absDir === null) return [];
29231
29614
  let entries2;
29232
29615
  try {
29233
- entries2 = readdirSync3(absDir, { withFileTypes: true });
29616
+ entries2 = readdirSync5(absDir, { withFileTypes: true });
29234
29617
  } catch {
29235
29618
  return [];
29236
29619
  }
@@ -29239,14 +29622,14 @@ function listDocLevel(root, relDir = "", sort = "newest", showHidden = false) {
29239
29622
  for (const entry of entries2) {
29240
29623
  if (dirs.length + docs.length >= MAX_ENTRIES) break;
29241
29624
  if (!showHidden && entry.name.startsWith(".")) continue;
29242
- const abs = join18(absDir, entry.name);
29243
- const path = relative2(root, abs).split(sep3).join("/");
29625
+ const abs = join20(absDir, entry.name);
29626
+ const path = relative2(root, abs).split(sep4).join("/");
29244
29627
  const kind = entryKind(entry, abs);
29245
29628
  if (kind === "dir") {
29246
29629
  if (SKIP_DIRS.has(entry.name)) continue;
29247
29630
  const probe = probeDir(abs, showHidden);
29248
29631
  if (!probe.hasDocs && probe.hasOther) continue;
29249
- const isRepo = existsSync18(join18(abs, ".git"));
29632
+ const isRepo = existsSync20(join20(abs, ".git"));
29250
29633
  dirs.push({
29251
29634
  path,
29252
29635
  name: entry.name,
@@ -29275,14 +29658,14 @@ function flatDocs(root, {
29275
29658
  if (depth > MAX_SEARCH_DEPTH || hits.length >= MAX_FLAT_DOCS) return;
29276
29659
  let entries2;
29277
29660
  try {
29278
- entries2 = readdirSync3(dir, { withFileTypes: true });
29661
+ entries2 = readdirSync5(dir, { withFileTypes: true });
29279
29662
  } catch {
29280
29663
  return;
29281
29664
  }
29282
29665
  for (const entry of entries2) {
29283
29666
  if (hits.length >= MAX_FLAT_DOCS) return;
29284
29667
  if (!showHidden && entry.name.startsWith(".")) continue;
29285
- const abs = join18(dir, entry.name);
29668
+ const abs = join20(dir, entry.name);
29286
29669
  const kind = entryKind(entry, abs);
29287
29670
  if (kind === "dir") {
29288
29671
  if (!SKIP_DIRS.has(entry.name)) walk(abs, depth + 1);
@@ -29302,8 +29685,8 @@ function flatDocs(root, {
29302
29685
  }
29303
29686
  function resolveDocPath(root, rel) {
29304
29687
  if (!rel || rel.includes("\0")) return null;
29305
- const abs = resolve6(root, rel);
29306
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
29688
+ const abs = resolve7(root, rel);
29689
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
29307
29690
  const ext = extname2(abs).toLowerCase();
29308
29691
  if (!(ext in DOC_EXTENSIONS) && !(ext in CODE_EXTENSIONS)) return null;
29309
29692
  return abs;
@@ -29313,7 +29696,7 @@ function writeDocContent(root, rel, content, baseMtime) {
29313
29696
  if (!abs) return { status: "not-found" };
29314
29697
  let stat;
29315
29698
  try {
29316
- stat = statSync6(abs);
29699
+ stat = statSync8(abs);
29317
29700
  } catch {
29318
29701
  return { status: "not-found" };
29319
29702
  }
@@ -29324,29 +29707,29 @@ function writeDocContent(root, rel, content, baseMtime) {
29324
29707
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) {
29325
29708
  return { status: "too-large" };
29326
29709
  }
29327
- writeFileSync6(abs, content, "utf8");
29328
- return { status: "ok", mtime: statSync6(abs).mtime.toISOString() };
29710
+ writeFileSync7(abs, content, "utf8");
29711
+ return { status: "ok", mtime: statSync8(abs).mtime.toISOString() };
29329
29712
  }
29330
29713
  function resolveRawPath(root, rel) {
29331
29714
  if (!rel || rel.includes("\0")) return null;
29332
- const abs = resolve6(root, rel);
29333
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
29715
+ const abs = resolve7(root, rel);
29716
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
29334
29717
  const contentType = MEDIA_EXTENSIONS[extname2(abs).toLowerCase()];
29335
29718
  if (!contentType) return null;
29336
29719
  return { abs, contentType };
29337
29720
  }
29338
29721
  function resolveHtmlPath(root, rel) {
29339
29722
  if (!rel || rel.includes("\0")) return null;
29340
- const abs = resolve6(root, rel);
29341
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
29723
+ const abs = resolve7(root, rel);
29724
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
29342
29725
  if (DOC_EXTENSIONS[extname2(abs).toLowerCase()] !== "html") return null;
29343
29726
  return abs;
29344
29727
  }
29345
29728
  function resolveDownloadPath(root, rel) {
29346
29729
  if (!rel || rel.includes("\0")) return null;
29347
- const abs = resolve6(root, rel);
29348
- if (abs !== root && !abs.startsWith(root + sep3)) return null;
29349
- if (!isListableFile(basename4(abs))) return null;
29730
+ const abs = resolve7(root, rel);
29731
+ if (abs !== root && !abs.startsWith(root + sep4)) return null;
29732
+ if (!isListableFile(basename5(abs))) return null;
29350
29733
  const contentType = MEDIA_EXTENSIONS[extname2(abs).toLowerCase()] ?? "application/octet-stream";
29351
29734
  return { abs, contentType };
29352
29735
  }
@@ -29362,7 +29745,7 @@ function uniqueName(absDir, name) {
29362
29745
  let candidate = name;
29363
29746
  for (let n = 1; n < 1e3; n++) {
29364
29747
  try {
29365
- statSync6(join18(absDir, candidate));
29748
+ statSync8(join20(absDir, candidate));
29366
29749
  } catch {
29367
29750
  return candidate;
29368
29751
  }
@@ -29374,7 +29757,7 @@ function saveUploadedFile(root, relDir, name, data) {
29374
29757
  const absDir = resolveDirPath(root, relDir);
29375
29758
  if (absDir === null) return { status: "no-dir" };
29376
29759
  try {
29377
- if (!statSync6(absDir).isDirectory()) return { status: "no-dir" };
29760
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
29378
29761
  } catch {
29379
29762
  return { status: "no-dir" };
29380
29763
  }
@@ -29384,34 +29767,34 @@ function saveUploadedFile(root, relDir, name, data) {
29384
29767
  if (!(ext in DOC_EXTENSIONS) && !ASSET_LIST_EXTENSIONS.has(ext)) return { status: "bad-type" };
29385
29768
  if (data.byteLength > MAX_UPLOAD_BYTES) return { status: "too-large" };
29386
29769
  const final = uniqueName(absDir, safe);
29387
- const abs = join18(absDir, final);
29388
- writeFileSync6(abs, data);
29389
- return { status: "ok", path: relative2(root, abs).split(sep3).join("/"), name: final };
29770
+ const abs = join20(absDir, final);
29771
+ writeFileSync7(abs, data);
29772
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: final };
29390
29773
  }
29391
29774
  function createDocFolder(root, relDir, name) {
29392
29775
  const absDir = resolveDirPath(root, relDir);
29393
29776
  if (absDir === null) return { status: "no-dir" };
29394
29777
  try {
29395
- if (!statSync6(absDir).isDirectory()) return { status: "no-dir" };
29778
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
29396
29779
  } catch {
29397
29780
  return { status: "no-dir" };
29398
29781
  }
29399
29782
  const safe = sanitizeUploadName(name);
29400
29783
  if (!safe) return { status: "bad-name" };
29401
- const abs = join18(absDir, safe);
29784
+ const abs = join20(absDir, safe);
29402
29785
  try {
29403
- statSync6(abs);
29786
+ statSync8(abs);
29404
29787
  return { status: "exists" };
29405
29788
  } catch {
29406
29789
  }
29407
- mkdirSync9(abs);
29408
- return { status: "ok", path: relative2(root, abs).split(sep3).join("/"), name: safe };
29790
+ mkdirSync10(abs);
29791
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: safe };
29409
29792
  }
29410
29793
  function createDocFile(root, relDir, name, content) {
29411
29794
  const absDir = resolveDirPath(root, relDir);
29412
29795
  if (absDir === null) return { status: "no-dir" };
29413
29796
  try {
29414
- if (!statSync6(absDir).isDirectory()) return { status: "no-dir" };
29797
+ if (!statSync8(absDir).isDirectory()) return { status: "no-dir" };
29415
29798
  } catch {
29416
29799
  return { status: "no-dir" };
29417
29800
  }
@@ -29421,30 +29804,30 @@ function createDocFile(root, relDir, name, content) {
29421
29804
  if (!(ext in DOC_EXTENSIONS) && !(ext in CODE_EXTENSIONS)) return { status: "bad-name" };
29422
29805
  if (SKIP_FILES.has(safe)) return { status: "bad-name" };
29423
29806
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) return { status: "too-large" };
29424
- const abs = join18(absDir, safe);
29807
+ const abs = join20(absDir, safe);
29425
29808
  try {
29426
- writeFileSync6(abs, content, { encoding: "utf8", flag: "wx" });
29809
+ writeFileSync7(abs, content, { encoding: "utf8", flag: "wx" });
29427
29810
  } catch (err) {
29428
29811
  if (err.code === "EEXIST") return { status: "exists" };
29429
29812
  throw err;
29430
29813
  }
29431
- return { status: "ok", path: relative2(root, abs).split(sep3).join("/"), name: safe };
29814
+ return { status: "ok", path: relative2(root, abs).split(sep4).join("/"), name: safe };
29432
29815
  }
29433
29816
  function moveDocEntry(root, from, to) {
29434
29817
  if (!from || !to || from.includes("\0") || to.includes("\0")) return { status: "not-found" };
29435
- const absFrom = resolve6(root, from);
29436
- if (!absFrom.startsWith(root + sep3)) return { status: "not-found" };
29818
+ const absFrom = resolve7(root, from);
29819
+ if (!absFrom.startsWith(root + sep4)) return { status: "not-found" };
29437
29820
  let stat;
29438
29821
  try {
29439
- stat = statSync6(absFrom);
29822
+ stat = statSync8(absFrom);
29440
29823
  } catch {
29441
29824
  return { status: "not-found" };
29442
29825
  }
29443
29826
  const isDir = stat.isDirectory();
29444
29827
  if (!isDir && !stat.isFile()) return { status: "not-found" };
29445
- const absTo = resolve6(root, to);
29446
- if (!absTo.startsWith(root + sep3)) return { status: "bad-target" };
29447
- const name = sanitizeUploadName(basename4(absTo));
29828
+ const absTo = resolve7(root, to);
29829
+ if (!absTo.startsWith(root + sep4)) return { status: "bad-target" };
29830
+ const name = sanitizeUploadName(basename5(absTo));
29448
29831
  if (!name) return { status: "bad-target" };
29449
29832
  if (!isDir) {
29450
29833
  const ext = extname2(name).toLowerCase();
@@ -29452,15 +29835,15 @@ function moveDocEntry(root, from, to) {
29452
29835
  return { status: "bad-target" };
29453
29836
  }
29454
29837
  }
29455
- const absToDir = dirname2(absTo);
29838
+ const absToDir = dirname3(absTo);
29456
29839
  if (resolveDirPath(root, relative2(root, absToDir)) === null) return { status: "bad-target" };
29457
29840
  try {
29458
- if (!statSync6(absToDir).isDirectory()) return { status: "bad-target" };
29841
+ if (!statSync8(absToDir).isDirectory()) return { status: "bad-target" };
29459
29842
  } catch {
29460
29843
  return { status: "bad-target" };
29461
29844
  }
29462
- const finalAbs = join18(absToDir, name);
29463
- if (isDir && (finalAbs === absFrom || finalAbs.startsWith(absFrom + sep3))) {
29845
+ const finalAbs = join20(absToDir, name);
29846
+ if (isDir && (finalAbs === absFrom || finalAbs.startsWith(absFrom + sep4))) {
29464
29847
  return { status: "into-self" };
29465
29848
  }
29466
29849
  try {
@@ -29468,12 +29851,12 @@ function moveDocEntry(root, from, to) {
29468
29851
  } catch {
29469
29852
  }
29470
29853
  renameSync2(absFrom, finalAbs);
29471
- return { status: "ok", path: relative2(root, finalAbs).split(sep3).join("/"), name };
29854
+ return { status: "ok", path: relative2(root, finalAbs).split(sep4).join("/"), name };
29472
29855
  }
29473
29856
  function deleteDocEntry(root, path) {
29474
29857
  if (!path || path.includes("\0")) return { status: "not-found" };
29475
- const abs = resolve6(root, path);
29476
- if (!abs.startsWith(root + sep3)) return { status: "not-found" };
29858
+ const abs = resolve7(root, path);
29859
+ if (!abs.startsWith(root + sep4)) return { status: "not-found" };
29477
29860
  let stat;
29478
29861
  try {
29479
29862
  stat = lstatSync2(abs);
@@ -29482,10 +29865,10 @@ function deleteDocEntry(root, path) {
29482
29865
  }
29483
29866
  const isDir = stat.isDirectory();
29484
29867
  if (!isDir && !stat.isFile() && !stat.isSymbolicLink()) return { status: "not-found" };
29485
- rmSync8(abs, { recursive: isDir });
29868
+ rmSync9(abs, { recursive: isDir });
29486
29869
  return {
29487
29870
  status: "ok",
29488
- path: relative2(root, abs).split(sep3).join("/"),
29871
+ path: relative2(root, abs).split(sep4).join("/"),
29489
29872
  type: isDir ? "dir" : "file"
29490
29873
  };
29491
29874
  }
@@ -29515,13 +29898,13 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29515
29898
  if (!resolved) return c.json({ error: "not found" }, 404);
29516
29899
  let stat;
29517
29900
  try {
29518
- stat = statSync6(resolved.abs);
29901
+ stat = statSync8(resolved.abs);
29519
29902
  } catch {
29520
29903
  return c.json({ error: "not found" }, 404);
29521
29904
  }
29522
29905
  if (!stat.isFile()) return c.json({ error: "not found" }, 404);
29523
29906
  if (stat.size > MAX_RAW_BYTES) return c.json({ error: "file too large" }, 413);
29524
- const name = basename4(resolved.abs);
29907
+ const name = basename5(resolved.abs);
29525
29908
  const asciiName = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
29526
29909
  const disposition = download ? "attachment" : "inline";
29527
29910
  const stream = Readable.toWeb(createReadStream(resolved.abs));
@@ -29537,13 +29920,13 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29537
29920
  if (!abs) return c.json({ error: "not found" }, 404);
29538
29921
  let stat;
29539
29922
  try {
29540
- stat = statSync6(abs);
29923
+ stat = statSync8(abs);
29541
29924
  } catch {
29542
29925
  return c.json({ error: "not found" }, 404);
29543
29926
  }
29544
29927
  if (!stat.isFile()) return c.json({ error: "not found" }, 404);
29545
29928
  if (stat.size > MAX_RAW_BYTES) return c.json({ error: "file too large" }, 413);
29546
- return c.body(withDocLinkBridge(readFileSync15(abs, "utf8")), 200, {
29929
+ return c.body(withDocLinkBridge(readFileSync17(abs, "utf8")), 200, {
29547
29930
  "Content-Type": "text/html; charset=utf-8",
29548
29931
  "Content-Security-Policy": HTML_SHARE_CSP,
29549
29932
  "X-Content-Type-Options": "nosniff",
@@ -29661,7 +30044,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29661
30044
  if (!abs) return c.json({ error: "not found" }, 404);
29662
30045
  let stat;
29663
30046
  try {
29664
- stat = statSync6(abs);
30047
+ stat = statSync8(abs);
29665
30048
  } catch {
29666
30049
  return c.json({ error: "not found" }, 404);
29667
30050
  }
@@ -29710,7 +30093,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29710
30093
  if (!abs) return c.json({ error: "not found" }, 404);
29711
30094
  let stat;
29712
30095
  try {
29713
- stat = statSync6(abs);
30096
+ stat = statSync8(abs);
29714
30097
  } catch {
29715
30098
  return c.json({ error: "not found" }, 404);
29716
30099
  }
@@ -29725,10 +30108,10 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29725
30108
  // by; only docs get a parsed title.
29726
30109
  kind: kind ?? "code",
29727
30110
  lang: kind ? void 0 : CODE_EXTENSIONS[ext],
29728
- title: kind ? extractTitle(abs, kind) : basename4(abs),
30111
+ title: kind ? extractTitle(abs, kind) : basename5(abs),
29729
30112
  mtime: stat.mtime.toISOString(),
29730
30113
  tooLarge: tooLarge || void 0,
29731
- content: tooLarge ? "" : readFileSync15(abs, "utf8")
30114
+ content: tooLarge ? "" : readFileSync17(abs, "utf8")
29732
30115
  });
29733
30116
  });
29734
30117
  app.put("/:id/docs/content", async (c) => {
@@ -29761,7 +30144,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29761
30144
  }
29762
30145
  let stat;
29763
30146
  try {
29764
- stat = statSync6(abs);
30147
+ stat = statSync8(abs);
29765
30148
  } catch {
29766
30149
  return { error: c.json({ error: "not found" }, 404) };
29767
30150
  }
@@ -29771,7 +30154,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29771
30154
  channel,
29772
30155
  rel,
29773
30156
  title: extractTitle(abs, "md"),
29774
- content: readFileSync15(abs, "utf8")
30157
+ content: readFileSync17(abs, "utf8")
29775
30158
  };
29776
30159
  };
29777
30160
  app.get("/:id/docs/translation/:lang", async (c) => {
@@ -29829,9 +30212,9 @@ function withDocLinkBridge(html) {
29829
30212
  var DOC_MENTION_RE = /(?<![\w@/`])@((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]{1,6})(?::(\d+))?(?![\w-])/g;
29830
30213
  function isRealDoc(root, rel) {
29831
30214
  const abs = resolveDocPath(root, rel);
29832
- if (!abs || !existsSync19(abs)) return false;
30215
+ if (!abs || !existsSync21(abs)) return false;
29833
30216
  try {
29834
- return statSync7(abs).isFile();
30217
+ return statSync9(abs).isFile();
29835
30218
  } catch {
29836
30219
  return false;
29837
30220
  }
@@ -30250,7 +30633,7 @@ function loadChatAgentConfig() {
30250
30633
  maxBudgetUsd = Number.isFinite(n) && n > 0 ? n : void 0;
30251
30634
  }
30252
30635
  return {
30253
- botName: process.env["BOT_NAME"] ?? "Custie",
30636
+ botName: process.env["BOT_NAME"] ?? "Bot",
30254
30637
  maxBudgetUsd,
30255
30638
  sessionCompactThresholdTokens: parseTokenCount(
30256
30639
  process.env["SESSION_COMPACT_THRESHOLD_TOKENS"],
@@ -30265,10 +30648,11 @@ function loadChatAgentConfig() {
30265
30648
  var RETRY_DELAY_MS = 3e3;
30266
30649
  var MAX_CONSECUTIVE_WAKES = 5;
30267
30650
  var BACKGROUND_SWEEP_MS = 6e4;
30651
+ var BACKGROUND_CHECK_IN_MS = 30 * 6e4;
30268
30652
  var MISSED_MESSAGE_WINDOW_MS = 24 * 60 * 60 * 1e3;
30269
30653
  var MISSED_MESSAGE_THREAD_LIMIT = 100;
30270
30654
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
30271
- function stripPathPrefixes(label, roots, home = homedir6()) {
30655
+ function stripPathPrefixes(label, roots, home = homedir8()) {
30272
30656
  let out = label;
30273
30657
  for (const root of roots) {
30274
30658
  if (root) out = out.replaceAll(`${root.replace(/\/+$/, "")}/`, "");
@@ -30506,6 +30890,16 @@ var ChatAgent = class {
30506
30890
  if (tasks?.length) {
30507
30891
  watched.tasks = tasks;
30508
30892
  this.channelActivityNotifier()("background", { channelId: watched.channelId, threadId, on: true });
30893
+ const oldest = Math.min(...tasks.map((t) => t.startedAt));
30894
+ if (!watched.checkedIn && Date.now() - oldest >= BACKGROUND_CHECK_IN_MS) {
30895
+ watched.checkedIn = true;
30896
+ const pids = tasks.map((t) => t.about ? `${t.pid}: ${t.about}` : t.pid).join(", ");
30897
+ const text2 = `Background task (PID ${pids}) is still running after ${Math.round((Date.now() - oldest) / 6e4)} min. Check its log: if it is stuck, kill it and retry or report; if it is genuinely progressing, say how long is left.`;
30898
+ await runWithProfile(watched.profile, async () => {
30899
+ const { replyId } = await postToDashboardChannel({ threadId, text: text2 });
30900
+ await this.wake(threadId, replyId, text2);
30901
+ }).catch((err) => console.error("[chat-agent] background check-in failed:", err.message));
30902
+ }
30509
30903
  continue;
30510
30904
  }
30511
30905
  this.watchedTasks.delete(threadId);
@@ -30826,7 +31220,7 @@ var ChatAgent = class {
30826
31220
  return this.queue.drain(timeoutMs);
30827
31221
  }
30828
31222
  async run(msg) {
30829
- const { data: thread, error } = await this.supabase().from("threads").select("id, channel_id, title").eq("id", msg.threadId).single();
31223
+ const { data: thread, error } = await this.supabase().from("threads").select("id, channel_id, title, channels(external_channel_id)").eq("id", msg.threadId).single();
30830
31224
  if (error || !thread) {
30831
31225
  console.error(`[chat-agent] thread ${msg.threadId} not found:`, error?.message);
30832
31226
  return;
@@ -30906,7 +31300,9 @@ var ChatAgent = class {
30906
31300
  if (memory.enabled) channelConfig = { ...channelConfig, disableAutoMemory: true };
30907
31301
  channelConfig = {
30908
31302
  ...channelConfig,
30909
- permissionThread: { threadId: msg.threadId, channelId: thread.channel_id }
31303
+ permissionThread: { threadId: msg.threadId, channelId: thread.channel_id },
31304
+ // Typed as an array, but a many-to-one embed returns a single row.
31305
+ slackBound: !![thread.channels].flat()[0]?.external_channel_id
30910
31306
  };
30911
31307
  if (memory.memoryPrompt) channelConfig = { ...channelConfig, memoryPrompt: memory.memoryPrompt };
30912
31308
  const store = this.openSessionStore();
@@ -30932,7 +31328,7 @@ var ChatAgent = class {
30932
31328
  ${msg.body}` : msg.woken ? `[background task finished]
30933
31329
  [note: nobody sent a new message. A background task you launched earlier in this thread has finished and reported the result below (it is already posted in the thread, so do not repeat it). Carry on with whatever was meant to happen next, then report. If nothing is left to do, say so in one line.]
30934
31330
 
30935
- ${msg.body}` : msg.body;
31331
+ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.cwd, msg.body) ?? msg.body;
30936
31332
  const barePrompt = header + interruptionNote + recoveryNote + body + buildFilesPromptSection(attachments);
30937
31333
  let resumableSessionId = session?.runner === activeRunner ? session.sessionId : void 0;
30938
31334
  let prompt = barePrompt;
@@ -31359,6 +31755,7 @@ ${msg.body}` : msg.body;
31359
31755
  maxBudgetUsd: this.config.maxBudgetUsd,
31360
31756
  agentPersona,
31361
31757
  channelPrompt: channelConfig.prompt,
31758
+ slackBound: channelConfig.slackBound,
31362
31759
  onActivity,
31363
31760
  signal,
31364
31761
  mcpConfigPath,
@@ -31403,7 +31800,8 @@ ${msg.body}` : msg.body;
31403
31800
  this.config.botName,
31404
31801
  agentPersona,
31405
31802
  channelConfig.prompt,
31406
- resolveSelectedOutputStyle(channelConfig.claudeConfigDir)?.body
31803
+ resolveSelectedOutputStyle(channelConfig.claudeConfigDir)?.body,
31804
+ channelConfig.slackBound
31407
31805
  ),
31408
31806
  channelConfig.memoryPrompt,
31409
31807
  docsAccessPromptNote(channelConfig.docsAccess, channelConfig.docsAccessUnverified)
@@ -31577,436 +31975,92 @@ ${msg.body}` : msg.body;
31577
31975
  await this.postReply(msg.threadId, "\u23F9 Stopped by user.", activities);
31578
31976
  }
31579
31977
  return true;
31580
- }
31581
- if (response.sessionId)
31582
- store.saveSession(channelKey, msg.threadId, response.sessionId, "claude");
31583
- await this.postReply(msg.threadId, response.text || "No response", activities);
31584
- return true;
31585
- }
31586
- /**
31587
- * A thread's messages in order, for anything that needs the raw
31588
- * author/body pairs rather than `fetchThreadContext`'s formatted block —
31589
- * currently just the rollover sliding-window seed. Shares the same query
31590
- * (and the same archived-replies exclusion) so the two callers never drift.
31591
- */
31592
- async fetchThreadMessages(threadId, excludeReplyId) {
31593
- const { data, error } = await this.supabase().from("thread_replies").select("id, author, body").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: true });
31594
- if (error || !data) return [];
31595
- const prior = excludeReplyId ? data.filter((r) => r.id !== excludeReplyId) : data;
31596
- return prior.map((r) => ({ author: r.author, body: r.body }));
31597
- }
31598
- /**
31599
- * Thread history before the triggering message, formatted like the Slack
31600
- * listener's thread context block. Empty string when the trigger is the
31601
- * only message (nothing to seed).
31602
- */
31603
- async fetchThreadContext(threadId, excludeReplyId) {
31604
- const prior = await this.fetchThreadMessages(threadId, excludeReplyId);
31605
- if (prior.length === 0) return "";
31606
- const lines = prior.map((r) => `${r.author}: ${r.body}`).join("\n");
31607
- return `[thread context: messages before this one]
31608
- ${lines}
31609
- [end thread context]
31610
-
31611
- `;
31612
- }
31613
- /**
31614
- * Last recorded run's replayed context for a thread; see `contextTokensOf`.
31615
- */
31616
- lastRunContextTokens(threadTs) {
31617
- return contextTokensOf(this.openUsageStore().recent(1, { threadTs })[0]);
31618
- }
31619
- /**
31620
- * Builds the rollover handoff seed for a thread past the compact
31621
- * threshold — see docs/session-auto-compact.md and rollover-summary.ts.
31622
- * `undefined` on anything that stops rollover from being safe to do
31623
- * (nothing to summarize, or the Haiku call itself failed); the caller
31624
- * treats that as "skip rollover, resume the old session as normal".
31625
- */
31626
- async buildRolloverSeed(threadId, excludeReplyId, auth) {
31627
- const messages = await this.fetchThreadMessages(threadId, excludeReplyId);
31628
- if (messages.length === 0) return void 0;
31629
- const recentVerbatimTokens = this.config.recentVerbatimTokens ?? DEFAULT_RECENT_VERBATIM_TOKENS;
31630
- return this.summarizeForRollover(messages, recentVerbatimTokens, auth);
31631
- }
31632
- /** Programmatic check for `@path` doc mentions: the model's paths are
31633
- * never trusted, only ones that resolve to a real file in the channel
31634
- * folder stay as mentions. */
31635
- async guardDocMentionsFor(threadId, body) {
31636
- if (!body.includes("@")) return body;
31637
- try {
31638
- const { data: thread } = await this.supabase().from("threads").select("channel_id").eq("id", threadId).single();
31639
- if (!thread?.channel_id) return body;
31640
- const cwd = runWithProfile(
31641
- findOwningProfile(thread.channel_id),
31642
- () => resolveChannelConfig(thread.channel_id).cwd
31643
- );
31644
- return guardDocMentions(body, cwd);
31645
- } catch {
31646
- return body;
31647
- }
31648
- }
31649
- async postReply(threadId, body, activities) {
31650
- const row = {
31651
- thread_id: threadId,
31652
- author: AGENT_AUTHOR,
31653
- body: await this.guardDocMentionsFor(threadId, await uploadLocalImages(body))
31654
- };
31655
- if (activities && activities.length > 0) row["activities"] = activities;
31656
- let { error } = await this.supabase().from("thread_replies").insert(row);
31657
- if (error && row["activities"]) {
31658
- delete row["activities"];
31659
- ({ error } = await this.supabase().from("thread_replies").insert(row));
31660
- }
31661
- if (error) {
31662
- console.error(`[chat-agent] failed to post reply to ${threadId}:`, error.message);
31663
- }
31664
- }
31665
- };
31666
-
31667
- // ../api/src/claude/skills.ts
31668
- import { existsSync as existsSync21, readdirSync as readdirSync5, readFileSync as readFileSync17, statSync as statSync9 } from "fs";
31669
- import { homedir as homedir8 } from "os";
31670
- import { basename as basename5, dirname as dirname3, join as join20 } from "path";
31671
- import yaml3 from "js-yaml";
31672
-
31673
- // ../api/src/claude/skill-files.ts
31674
- import {
31675
- existsSync as existsSync20,
31676
- mkdirSync as mkdirSync10,
31677
- readFileSync as readFileSync16,
31678
- readdirSync as readdirSync4,
31679
- rmSync as rmSync9,
31680
- statSync as statSync8,
31681
- writeFileSync as writeFileSync7
31682
- } from "fs";
31683
- import { homedir as homedir7 } from "os";
31684
- import { join as join19, resolve as resolve7, sep as sep4 } from "path";
31685
- import yaml2 from "js-yaml";
31686
- var MAX_SKILL_BYTES = 2 * 1024 * 1024;
31687
- var SKILL_NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
31688
- function expandHome2(p) {
31689
- if (p === "~") return homedir7();
31690
- if (p.startsWith("~/")) return join19(homedir7(), p.slice(2));
31691
- return p;
31692
- }
31693
- function workspaceSkillsDir(configDir) {
31694
- return join19(configDir ? expandHome2(configDir) : join19(homedir7(), ".claude"), "skills");
31695
- }
31696
- function channelSkillsDir(cwd) {
31697
- return join19(cwd, ".claude", "skills");
31698
- }
31699
- function isValidSkillName(name) {
31700
- return SKILL_NAME.test(name);
31701
- }
31702
- function resolveSkillPath(dir, name) {
31703
- if (!isValidSkillName(name)) return null;
31704
- const abs = resolve7(dir, name, "SKILL.md");
31705
- if (!abs.startsWith(resolve7(dir) + sep4)) return null;
31706
- return abs;
31707
- }
31708
- function splitFrontmatter(raw) {
31709
- const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
31710
- if (!match) return { fm: {}, body: raw };
31711
- let fm = {};
31712
- try {
31713
- fm = yaml2.load(match[1]) ?? {};
31714
- } catch {
31715
- fm = {};
31716
- }
31717
- return { fm, body: raw.slice(match[0].length) };
31718
- }
31719
- function buildSkillFile(fm, body) {
31720
- const { name, description, ...rest } = fm;
31721
- const ordered = { name, description, ...rest };
31722
- const front = yaml2.dump(ordered, { lineWidth: -1 }).trimEnd();
31723
- return `---
31724
- ${front}
31725
- ---
31726
-
31727
- ${body.replace(/^\n+/, "").trimEnd()}
31728
- `;
31729
- }
31730
- function readMeta(abs) {
31731
- try {
31732
- const { fm } = splitFrontmatter(readFileSync16(abs, "utf-8"));
31733
- return {
31734
- name: typeof fm["name"] === "string" ? fm["name"] : void 0,
31735
- description: typeof fm["description"] === "string" ? fm["description"] : void 0
31736
- };
31737
- } catch {
31738
- return {};
31739
- }
31740
- }
31741
- function listSkillFiles(dir) {
31742
- if (!existsSync20(dir)) return [];
31743
- let entries2;
31744
- try {
31745
- entries2 = readdirSync4(dir);
31746
- } catch {
31747
- return [];
31748
- }
31749
- const rows2 = [];
31750
- for (const entry of entries2) {
31751
- if (!isValidSkillName(entry)) continue;
31752
- const abs = join19(dir, entry, "SKILL.md");
31753
- let stat;
31754
- try {
31755
- stat = statSync8(abs);
31756
- } catch {
31757
- continue;
31758
- }
31759
- if (!stat.isFile()) continue;
31760
- const meta = readMeta(abs);
31761
- rows2.push({
31762
- // The directory name is the identifier the CLI resolves by, so it wins
31763
- // over a frontmatter `name` that has drifted away from it.
31764
- name: entry,
31765
- description: (meta.description ?? "").trim(),
31766
- mtime: stat.mtime.toISOString()
31767
- });
31768
- }
31769
- return rows2.sort((a, b) => a.name.localeCompare(b.name));
31770
- }
31771
- function readSkillFile(dir, name) {
31772
- const abs = resolveSkillPath(dir, name);
31773
- if (!abs) return null;
31774
- let stat;
31775
- try {
31776
- stat = statSync8(abs);
31777
- } catch {
31778
- return null;
31779
- }
31780
- if (!stat.isFile() || stat.size > MAX_SKILL_BYTES) return null;
31781
- const { fm, body } = splitFrontmatter(readFileSync16(abs, "utf-8"));
31782
- return {
31783
- name,
31784
- description: typeof fm["description"] === "string" ? fm["description"].trim() : "",
31785
- body,
31786
- mtime: stat.mtime.toISOString(),
31787
- path: abs
31788
- };
31789
- }
31790
- function writeSkillFile(dir, name, patch, baseMtime) {
31791
- const abs = resolveSkillPath(dir, name);
31792
- if (!abs) return { status: "not-found" };
31793
- let stat;
31794
- try {
31795
- stat = statSync8(abs);
31796
- } catch {
31797
- return { status: "not-found" };
31978
+ }
31979
+ if (response.sessionId)
31980
+ store.saveSession(channelKey, msg.threadId, response.sessionId, "claude");
31981
+ await this.postReply(msg.threadId, response.text || "No response", activities);
31982
+ return true;
31798
31983
  }
31799
- if (!stat.isFile()) return { status: "not-found" };
31800
- if (baseMtime && stat.mtime.toISOString() !== baseMtime) {
31801
- return { status: "conflict", mtime: stat.mtime.toISOString() };
31984
+ /**
31985
+ * A thread's messages in order, for anything that needs the raw
31986
+ * author/body pairs rather than `fetchThreadContext`'s formatted block —
31987
+ * currently just the rollover sliding-window seed. Shares the same query
31988
+ * (and the same archived-replies exclusion) so the two callers never drift.
31989
+ */
31990
+ async fetchThreadMessages(threadId, excludeReplyId) {
31991
+ const { data, error } = await this.supabase().from("thread_replies").select("id, author, body").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: true });
31992
+ if (error || !data) return [];
31993
+ const prior = excludeReplyId ? data.filter((r) => r.id !== excludeReplyId) : data;
31994
+ return prior.map((r) => ({ author: r.author, body: r.body }));
31802
31995
  }
31803
- const { fm } = splitFrontmatter(readFileSync16(abs, "utf-8"));
31804
- const content = buildSkillFile({ ...fm, name, description: patch.description }, patch.body);
31805
- if (Buffer.byteLength(content, "utf8") > MAX_SKILL_BYTES) return { status: "too-large" };
31806
- writeFileSync7(abs, content, "utf8");
31807
- return { status: "ok", mtime: statSync8(abs).mtime.toISOString() };
31808
- }
31809
- function createSkillFile(dir, name, description) {
31810
- const abs = resolveSkillPath(dir, name);
31811
- if (!abs) return { status: "bad-name" };
31812
- if (existsSync20(abs)) return { status: "exists" };
31813
- mkdirSync10(join19(dir, name), { recursive: true });
31814
- writeFileSync7(
31815
- abs,
31816
- buildSkillFile(
31817
- { name, description },
31818
- `# ${name}
31819
-
31820
- Describe what this skill does and when to use it.
31821
- `
31822
- ),
31823
- "utf8"
31824
- );
31825
- const detail = readSkillFile(dir, name);
31826
- return detail ? { status: "ok", skill: detail } : { status: "bad-name" };
31827
- }
31828
- function deleteSkillFile(dir, name) {
31829
- const abs = resolveSkillPath(dir, name);
31830
- if (!abs || !existsSync20(abs)) return { status: "not-found" };
31831
- rmSync9(join19(dir, name), { recursive: true, force: true });
31832
- return { status: "ok" };
31833
- }
31996
+ /**
31997
+ * Thread history before the triggering message, formatted like the Slack
31998
+ * listener's thread context block. Empty string when the trigger is the
31999
+ * only message (nothing to seed).
32000
+ */
32001
+ async fetchThreadContext(threadId, excludeReplyId) {
32002
+ const prior = await this.fetchThreadMessages(threadId, excludeReplyId);
32003
+ if (prior.length === 0) return "";
32004
+ const lines = prior.map((r) => `${r.author}: ${r.body}`).join("\n");
32005
+ return `[thread context: messages before this one]
32006
+ ${lines}
32007
+ [end thread context]
31834
32008
 
31835
- // ../api/src/claude/skills.ts
31836
- function defaultConfigDir2() {
31837
- return join20(homedir8(), ".claude");
31838
- }
31839
- function expandHome3(p) {
31840
- if (p === "~") return homedir8();
31841
- if (p.startsWith("~/")) return join20(homedir8(), p.slice(2));
31842
- return p;
31843
- }
31844
- function parseFrontmatter2(file) {
31845
- let content;
31846
- try {
31847
- content = readFileSync17(file, "utf-8");
31848
- } catch {
31849
- return {};
31850
- }
31851
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
31852
- if (!match) return {};
31853
- try {
31854
- const fm = yaml3.load(match[1]);
31855
- const name = typeof fm?.["name"] === "string" ? fm["name"] : void 0;
31856
- const description = typeof fm?.["description"] === "string" ? fm["description"] : void 0;
31857
- return { name, description };
31858
- } catch {
31859
- return {};
31860
- }
31861
- }
31862
- function isSymlinkedDir(root, entry) {
31863
- if (!entry.isSymbolicLink()) return false;
31864
- try {
31865
- return statSync9(join20(root, entry.name)).isDirectory();
31866
- } catch {
31867
- return false;
32009
+ `;
31868
32010
  }
31869
- }
31870
- function findSkillFiles(root, maxDepth, out) {
31871
- if (maxDepth < 0 || !existsSync21(root)) return;
31872
- let entries2;
31873
- try {
31874
- entries2 = readdirSync5(root, { withFileTypes: true });
31875
- } catch {
31876
- return;
32011
+ /**
32012
+ * Last recorded run's replayed context for a thread; see `contextTokensOf`.
32013
+ */
32014
+ lastRunContextTokens(threadTs) {
32015
+ return contextTokensOf(this.openUsageStore().recent(1, { threadTs })[0]);
31877
32016
  }
31878
- for (const entry of entries2) {
31879
- if (entry.isFile()) {
31880
- if (entry.name === "SKILL.md") out.push(join20(root, entry.name));
31881
- } else if (entry.isDirectory() || isSymlinkedDir(root, entry)) {
31882
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
31883
- findSkillFiles(join20(root, entry.name), maxDepth - 1, out);
31884
- }
32017
+ /**
32018
+ * Builds the rollover handoff seed for a thread past the compact
32019
+ * threshold — see docs/session-auto-compact.md and rollover-summary.ts.
32020
+ * `undefined` on anything that stops rollover from being safe to do
32021
+ * (nothing to summarize, or the Haiku call itself failed); the caller
32022
+ * treats that as "skip rollover, resume the old session as normal".
32023
+ */
32024
+ async buildRolloverSeed(threadId, excludeReplyId, auth) {
32025
+ const messages = await this.fetchThreadMessages(threadId, excludeReplyId);
32026
+ if (messages.length === 0) return void 0;
32027
+ const recentVerbatimTokens = this.config.recentVerbatimTokens ?? DEFAULT_RECENT_VERBATIM_TOKENS;
32028
+ return this.summarizeForRollover(messages, recentVerbatimTokens, auth);
31885
32029
  }
31886
- }
31887
- function pluginNameFor(file, root) {
31888
- let dir = dirname3(file);
31889
- while (dir.startsWith(root) && dir !== dirname3(dir)) {
32030
+ /** Programmatic check for `@path` doc mentions: the model's paths are
32031
+ * never trusted, only ones that resolve to a real file in the channel
32032
+ * folder stay as mentions. */
32033
+ async guardDocMentionsFor(threadId, body) {
32034
+ if (!body.includes("@")) return body;
31890
32035
  try {
31891
- const manifest = JSON.parse(
31892
- readFileSync17(join20(dir, ".claude-plugin", "plugin.json"), "utf-8")
32036
+ const { data: thread } = await this.supabase().from("threads").select("channel_id").eq("id", threadId).single();
32037
+ if (!thread?.channel_id) return body;
32038
+ const cwd = runWithProfile(
32039
+ findOwningProfile(thread.channel_id),
32040
+ () => resolveChannelConfig(thread.channel_id).cwd
31893
32041
  );
31894
- if (typeof manifest.name === "string" && manifest.name.trim()) return manifest.name.trim();
32042
+ return guardDocMentions(body, cwd);
31895
32043
  } catch {
32044
+ return body;
31896
32045
  }
31897
- dir = dirname3(dir);
31898
32046
  }
31899
- return void 0;
31900
- }
31901
- function collectFrom2(root, source, maxDepth, namePrefix) {
31902
- const files = [];
31903
- findSkillFiles(root, maxDepth, files);
31904
- return files.map((file) => {
31905
- const fm = parseFrontmatter2(file);
31906
- const name = fm.name?.trim() || basename5(dirname3(file));
31907
- const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
31908
- const prefix = namePrefix ?? plugin;
31909
- return {
31910
- name: prefix ? `${prefix}:${name}` : name,
31911
- description: (fm.description ?? "").trim(),
31912
- source,
31913
- ...plugin && { plugin },
31914
- // Only read by `listPluginSkillDetails`; `listSkills` strips it.
31915
- file
32047
+ async postReply(threadId, body, activities) {
32048
+ const row = {
32049
+ thread_id: threadId,
32050
+ author: AGENT_AUTHOR,
32051
+ body: await this.guardDocMentionsFor(threadId, await uploadLocalImages(body))
31916
32052
  };
31917
- });
31918
- }
31919
- function collectAll(configDir, cwd) {
31920
- const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
31921
- const collected = [
31922
- ...collectFrom2(join20(cwd, ".claude", "skills"), "project", 2),
31923
- ...nestedProjectRoots(cwd).flatMap(({ dir, prefix }) => collectFrom2(dir, "project", 2, prefix)),
31924
- ...collectFrom2(join20(base, "skills"), "user", 2),
31925
- ...collectFrom2(join20(base, "plugins"), "plugin", 8)
31926
- ];
31927
- const byName = /* @__PURE__ */ new Map();
31928
- for (const skill of collected) {
31929
- if (skill.name && !byName.has(skill.name)) byName.set(skill.name, skill);
31930
- }
31931
- return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
31932
- }
31933
- function nestedProjectRoots(cwd) {
31934
- let entries2;
31935
- try {
31936
- entries2 = readdirSync5(cwd, { withFileTypes: true });
31937
- } catch {
31938
- return [];
31939
- }
31940
- const roots = [];
31941
- for (const entry of entries2) {
31942
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
31943
- if (!entry.isDirectory() && !isSymlinkedDir(cwd, entry)) continue;
31944
- const skillsDir = join20(cwd, entry.name, ".claude", "skills");
31945
- if (existsSync21(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
31946
- }
31947
- return roots;
31948
- }
31949
- function listSkills(configDir, cwd) {
31950
- return collectAll(configDir, cwd).map(({ file: _file, ...skill }) => skill);
31951
- }
31952
- function listPluginSkillDetails(configDir, cwd) {
31953
- const details = [];
31954
- for (const { file, ...skill } of collectAll(configDir, cwd)) {
31955
- if (skill.source !== "plugin") continue;
31956
- try {
31957
- const { body } = splitFrontmatter(readFileSync17(file, "utf-8"));
31958
- details.push({ ...skill, body, path: file, mtime: statSync9(file).mtime.toISOString() });
31959
- } catch {
32053
+ if (activities && activities.length > 0) row["activities"] = activities;
32054
+ let { error } = await this.supabase().from("thread_replies").insert(row);
32055
+ if (error && row["activities"]) {
32056
+ delete row["activities"];
32057
+ ({ error } = await this.supabase().from("thread_replies").insert(row));
31960
32058
  }
31961
- }
31962
- return details;
31963
- }
31964
- function findSkillDetail(configDir, cwd, name, sources) {
31965
- const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
31966
- const roots = [
31967
- [join20(cwd, ".claude", "skills"), "project", 2],
31968
- ...nestedProjectRoots(cwd).map(({ dir, prefix }) => [
31969
- dir,
31970
- "project",
31971
- 2,
31972
- prefix
31973
- ]),
31974
- [join20(base, "skills"), "user", 2],
31975
- [join20(base, "plugins"), "plugin", 8]
31976
- ];
31977
- for (const [root, source, maxDepth, namePrefix] of roots) {
31978
- if (!sources.includes(source)) continue;
31979
- const files = [];
31980
- findSkillFiles(root, maxDepth, files);
31981
- for (const file of files) {
31982
- const fm = parseFrontmatter2(file);
31983
- const rawName = fm.name?.trim() || basename5(dirname3(file));
31984
- const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
31985
- const prefix = namePrefix ?? plugin;
31986
- const skillName = prefix ? `${prefix}:${rawName}` : rawName;
31987
- if (skillName !== name) continue;
31988
- let raw;
31989
- let mtime;
31990
- try {
31991
- raw = readFileSync17(file, "utf-8");
31992
- mtime = statSync9(file).mtime.toISOString();
31993
- } catch {
31994
- continue;
31995
- }
31996
- const { body } = splitFrontmatter(raw);
31997
- return {
31998
- name: skillName,
31999
- description: (fm.description ?? "").trim(),
32000
- source,
32001
- ...plugin && { plugin },
32002
- body,
32003
- path: file,
32004
- mtime
32005
- };
32059
+ if (error) {
32060
+ console.error(`[chat-agent] failed to post reply to ${threadId}:`, error.message);
32006
32061
  }
32007
32062
  }
32008
- return null;
32009
- }
32063
+ };
32010
32064
 
32011
32065
  // src/slack/commands.ts
32012
32066
  var SKILL_SELECT_ACTION_ID = "custie_skill_select";
@@ -34177,6 +34231,8 @@ export {
34177
34231
  listMemberChannels,
34178
34232
  refreshCache,
34179
34233
  resolveChannelId,
34234
+ resolveRateCard,
34235
+ explainCost,
34180
34236
  UsageStore,
34181
34237
  listActiveUsers,
34182
34238
  displayNameFor,
@@ -34360,6 +34416,17 @@ export {
34360
34416
  LOCAL_DB_PATH,
34361
34417
  createHostDbClient,
34362
34418
  listAgents,
34419
+ workspaceSkillsDir,
34420
+ channelSkillsDir,
34421
+ isValidSkillName,
34422
+ listSkillFiles,
34423
+ readSkillFile,
34424
+ writeSkillFile,
34425
+ createSkillFile,
34426
+ deleteSkillFile,
34427
+ listSkills,
34428
+ listPluginSkillDetails,
34429
+ findSkillDetail,
34363
34430
  SessionStore,
34364
34431
  setProfileConfigCache,
34365
34432
  cachedProfileConfig,
@@ -34414,7 +34481,6 @@ export {
34414
34481
  createFeatureFlagsRouter,
34415
34482
  PLATE,
34416
34483
  renderAppIcon,
34417
- buildManifest,
34418
34484
  clientKey,
34419
34485
  createPublicShareApiRouter,
34420
34486
  createPublicShareAssetRouter,
@@ -34430,17 +34496,6 @@ export {
34430
34496
  syncSupportReply,
34431
34497
  loadChatAgentConfig,
34432
34498
  ChatAgent,
34433
- workspaceSkillsDir,
34434
- channelSkillsDir,
34435
- isValidSkillName,
34436
- listSkillFiles,
34437
- readSkillFile,
34438
- writeSkillFile,
34439
- createSkillFile,
34440
- deleteSkillFile,
34441
- listSkills,
34442
- listPluginSkillDetails,
34443
- findSkillDetail,
34444
34499
  recentRunsForWorkspace,
34445
34500
  lastRunsForWorkspace,
34446
34501
  installUsageRecording,