flyspace-cli 0.1.57 → 0.1.59

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.
@@ -25,6 +25,7 @@ import {
25
25
  getR2Bucket,
26
26
  getR2Client,
27
27
  getSupabaseClient,
28
+ hasSupabaseCredentials,
28
29
  isChannelAccessAllowed,
29
30
  isEffort,
30
31
  isHumanAuthor,
@@ -44,6 +45,7 @@ import {
44
45
  resolveModel,
45
46
  resolveOwnPersona,
46
47
  runWithProfile,
48
+ setSupabaseClient,
47
49
  setSupabaseClientFactory,
48
50
  startChannelRegistryPolling,
49
51
  sweepScratchDir,
@@ -9284,7 +9286,7 @@ var require_sign = __commonJS({
9284
9286
  "../../node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js"(exports, module) {
9285
9287
  "use strict";
9286
9288
  var $isNaN = require_isNaN();
9287
- module.exports = function sign(number) {
9289
+ module.exports = function sign2(number) {
9288
9290
  if ($isNaN(number) || number === 0) {
9289
9291
  return number;
9290
9292
  }
@@ -9648,7 +9650,7 @@ var require_get_intrinsic = __commonJS({
9648
9650
  var min = require_min();
9649
9651
  var pow = require_pow();
9650
9652
  var round = require_round();
9651
- var sign = require_sign();
9653
+ var sign2 = require_sign();
9652
9654
  var $Function = Function;
9653
9655
  var getEvalledConstructor = function(expressionSyntax) {
9654
9656
  try {
@@ -9762,7 +9764,7 @@ var require_get_intrinsic = __commonJS({
9762
9764
  "%Math.min%": min,
9763
9765
  "%Math.pow%": pow,
9764
9766
  "%Math.round%": round,
9765
- "%Math.sign%": sign,
9767
+ "%Math.sign%": sign2,
9766
9768
  "%Reflect.getPrototypeOf%": $ReflectGPO
9767
9769
  };
9768
9770
  if (getProto) {
@@ -10952,7 +10954,7 @@ var require_supports_color = __commonJS({
10952
10954
  return 1;
10953
10955
  }
10954
10956
  if ("CI" in env) {
10955
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
10957
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") {
10956
10958
  return 1;
10957
10959
  }
10958
10960
  return min;
@@ -19184,6 +19186,111 @@ Nothing was run. Channels on the \`host\` runtime are unaffected.`
19184
19186
  };
19185
19187
  }
19186
19188
 
19189
+ // src/claude/plugin-ui.ts
19190
+ var SURFACE = "desktop";
19191
+ var CLIENT_ID = "flyspace";
19192
+ var RENDER_TIMEOUT_MS = 5e3;
19193
+ var SETTLE_TIMEOUT_MS = 2e3;
19194
+ var PluginUiSession = class {
19195
+ constructor(stdin) {
19196
+ this.stdin = stdin;
19197
+ }
19198
+ panes = [];
19199
+ status = {};
19200
+ pending = /* @__PURE__ */ new Map();
19201
+ seq = 0;
19202
+ onInvalidate;
19203
+ write(obj) {
19204
+ if (this.stdin.writable) this.stdin.write(`${JSON.stringify(obj)}
19205
+ `);
19206
+ }
19207
+ /** Attach as a surface, then send the user's prompt. */
19208
+ start(prompt) {
19209
+ this.write({
19210
+ type: "control_request",
19211
+ request_id: "flyspace-ui-attach",
19212
+ request: { subtype: "ui_attach", surface: SURFACE, client_id: CLIENT_ID }
19213
+ });
19214
+ this.write({ type: "user", message: { role: "user", content: prompt } });
19215
+ }
19216
+ /** Feed every parsed stdout event through here. */
19217
+ onEvent(event) {
19218
+ if (event.type === "control_response") {
19219
+ const res = event.response;
19220
+ const resolve8 = res?.request_id ? this.pending.get(res.request_id) : void 0;
19221
+ if (!resolve8 || !res?.request_id) return;
19222
+ this.pending.delete(res.request_id);
19223
+ resolve8(res.subtype === "success" ? res.response?.tree : void 0);
19224
+ return;
19225
+ }
19226
+ const e = event;
19227
+ if (e.type !== "system") return;
19228
+ if (e.subtype === "ui_invalidate") this.onInvalidate?.();
19229
+ if (e.subtype === "ui_panes" && Array.isArray(e.panes)) {
19230
+ this.panes = e.panes.filter((p) => typeof p?.id === "string").map((p) => ({
19231
+ id: p.id,
19232
+ title: p.title ?? p.id,
19233
+ ...p.plugin ? { plugin: p.plugin } : {}
19234
+ }));
19235
+ } else if (e.subtype === "ui_status" && e.plugin) {
19236
+ if (e.text) this.status[e.plugin] = e.text;
19237
+ else delete this.status[e.plugin];
19238
+ }
19239
+ }
19240
+ render(instanceId) {
19241
+ const requestId = `flyspace-ui-render-${++this.seq}`;
19242
+ return new Promise((resolve8) => {
19243
+ this.pending.set(requestId, resolve8);
19244
+ this.write({
19245
+ type: "control_request",
19246
+ request_id: requestId,
19247
+ request: {
19248
+ subtype: "ui_render",
19249
+ surface: SURFACE,
19250
+ client_id: CLIENT_ID,
19251
+ component: "Pane",
19252
+ instance_id: instanceId,
19253
+ props: {}
19254
+ }
19255
+ });
19256
+ });
19257
+ }
19258
+ /**
19259
+ * Render every open pane, then close stdin so the CLI exits. Resolves with
19260
+ * the snapshot; panes whose render failed or timed out keep no tree.
19261
+ */
19262
+ async finish() {
19263
+ if (this.panes.length) {
19264
+ await new Promise((resolve8) => {
19265
+ const timer2 = setTimeout(resolve8, SETTLE_TIMEOUT_MS);
19266
+ this.onInvalidate = () => {
19267
+ clearTimeout(timer2);
19268
+ resolve8();
19269
+ };
19270
+ });
19271
+ this.onInvalidate = void 0;
19272
+ }
19273
+ const renders = Promise.all(
19274
+ this.panes.map(async (p) => ({ ...p, tree: await this.render(p.id) }))
19275
+ );
19276
+ let timer;
19277
+ const timeout = new Promise((resolve8) => {
19278
+ timer = setTimeout(() => resolve8(void 0), RENDER_TIMEOUT_MS);
19279
+ });
19280
+ const rendered = await Promise.race([renders, timeout]);
19281
+ clearTimeout(timer);
19282
+ this.pending.clear();
19283
+ this.close();
19284
+ return {
19285
+ panes: rendered ?? this.panes,
19286
+ ...Object.keys(this.status).length ? { status: { ...this.status } } : {}
19287
+ };
19288
+ }
19289
+ close() {
19290
+ if (this.stdin.writable) this.stdin.end();
19291
+ }
19292
+ };
19293
+
19187
19294
  // src/claude/model-aliases.ts
19188
19295
  var MODEL_ALIASES = {
19189
19296
  fable: "claude-fable-5"
@@ -19672,7 +19779,9 @@ var KILLED_TOOL_RE = /exit code (137|143)\b|command timed out after/i;
19672
19779
  function hasKilledToolResult(event) {
19673
19780
  if (event.type !== "user") return false;
19674
19781
  return (event.message?.content ?? []).some(
19675
- (block) => block.type === "tool_result" && block.is_error === true && KILLED_TOOL_RE.test(typeof block.content === "string" ? block.content : JSON.stringify(block.content ?? ""))
19782
+ (block) => block.type === "tool_result" && block.is_error === true && KILLED_TOOL_RE.test(
19783
+ typeof block.content === "string" ? block.content : JSON.stringify(block.content ?? "")
19784
+ )
19676
19785
  );
19677
19786
  }
19678
19787
  function extractActivities(event) {
@@ -19957,6 +20066,9 @@ function isModelForGateway(model, pinned) {
19957
20066
  if (!pinned) return true;
19958
20067
  return model.split("-")[0].toLowerCase() === pinned.split("-")[0].toLowerCase();
19959
20068
  }
20069
+ function usesPluginUi(options) {
20070
+ return Boolean(options.onPluginUi && options.onActivity) && (options.runtime ?? "host") === "host";
20071
+ }
19960
20072
  function buildArgs(prompt, botName, options, resumeSessionId, isolatedStyle) {
19961
20073
  const args = [
19962
20074
  "--print",
@@ -19964,6 +20076,7 @@ function buildArgs(prompt, botName, options, resumeSessionId, isolatedStyle) {
19964
20076
  // activity); plain json emits one blob on completion. stream-json with
19965
20077
  // --print requires --verbose.
19966
20078
  ...options.onActivity ? ["--output-format", "stream-json", "--verbose"] : ["--output-format", "json"],
20079
+ ...usesPluginUi(options) ? ["--input-format", "stream-json"] : [],
19967
20080
  ...permissionArgs(options.permissionMode, options.permissionPromptTool),
19968
20081
  "--no-chrome",
19969
20082
  // `=` form: the flag is variadic and would otherwise swallow the next token.
@@ -20017,7 +20130,7 @@ function buildArgs(prompt, botName, options, resumeSessionId, isolatedStyle) {
20017
20130
  if (resumeSessionId) {
20018
20131
  args.push("--resume", resumeSessionId);
20019
20132
  }
20020
- args.push(prompt);
20133
+ if (!usesPluginUi(options)) args.push(prompt);
20021
20134
  return args;
20022
20135
  }
20023
20136
  function recordUsage2(response, options) {
@@ -20046,7 +20159,8 @@ function runCli(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId,
20046
20159
  );
20047
20160
  const env = resolveMiseEnv(cwd);
20048
20161
  env["FLYSPACE_SCRATCH_DIR"] = paths.SCRATCH_DIR;
20049
- if (options.permissionPromptTool && !env["MCP_TOOL_TIMEOUT"]) env["MCP_TOOL_TIMEOUT"] = "360000";
20162
+ if (options.permissionPromptTool && !env["MCP_TOOL_TIMEOUT"])
20163
+ env["MCP_TOOL_TIMEOUT"] = "360000";
20050
20164
  env["CLAUDE_CODE_ARTIFACT"] = "1";
20051
20165
  if (options.disableAutoMemory) env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1";
20052
20166
  else delete env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"];
@@ -20089,7 +20203,11 @@ function runCli(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId,
20089
20203
  env: plan.env,
20090
20204
  stdio: ["pipe", "pipe", "pipe"]
20091
20205
  });
20092
- child.stdin.end();
20206
+ const pluginUi = usesPluginUi(options) ? new PluginUiSession(child.stdin) : void 0;
20207
+ child.stdin.on("error", () => {
20208
+ });
20209
+ if (pluginUi) pluginUi.start(prompt);
20210
+ else child.stdin.end();
20093
20211
  let stdout = "";
20094
20212
  let stderr = "";
20095
20213
  let timedOut = false;
@@ -20159,6 +20277,17 @@ function runCli(prompt, cwd, botName, options, claudeConfigDir, resumeSessionId,
20159
20277
  }
20160
20278
  if (event.session_id) liveSessionId = event.session_id;
20161
20279
  if (event.type === "result") streamResultLine = line;
20280
+ if (pluginUi) {
20281
+ pluginUi.onEvent(event);
20282
+ if (event.type === "result") {
20283
+ void pluginUi.finish().then((state) => {
20284
+ try {
20285
+ options.onPluginUi?.(state);
20286
+ } catch {
20287
+ }
20288
+ });
20289
+ }
20290
+ }
20162
20291
  if (hasKilledToolResult(event)) killedTool = true;
20163
20292
  if (event.type === "assistant" && !event.parent_tool_use_id) {
20164
20293
  for (const block of event.message?.content ?? []) {
@@ -20926,6 +21055,575 @@ async function runCompanion(config, userId, slot) {
20926
21055
  }
20927
21056
  }
20928
21057
 
21058
+ // src/commands/persona.ts
21059
+ import { execFileSync as execFileSync5 } from "child_process";
21060
+ import { createHash as createHash3 } from "crypto";
21061
+ import { existsSync as existsSync9, mkdtempSync as mkdtempSync2, readdirSync as readdirSync2, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "fs";
21062
+ import { homedir as homedir3 } from "os";
21063
+ import { basename as basename2, join as join8 } from "path";
21064
+ import sharp from "sharp";
21065
+
21066
+ // src/auth/device-auth.ts
21067
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "crypto";
21068
+ import { existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
21069
+ import { dirname, join as join6 } from "path";
21070
+ var DEFAULT_API_URL = "https://app.flyspace.ai";
21071
+ var EXPIRY_SKEW_MS = 6e4;
21072
+ var AuthApiError = class extends Error {
21073
+ constructor(message, status) {
21074
+ super(message);
21075
+ this.status = status;
21076
+ this.name = "AuthApiError";
21077
+ }
21078
+ };
21079
+ function apiUrl() {
21080
+ return (process.env["FLYSPACE_API_URL"] || DEFAULT_API_URL).replace(/\/+$/, "");
21081
+ }
21082
+ function deviceKeyPath() {
21083
+ return join6(paths.BASE_CONFIG_DIR, "device.key");
21084
+ }
21085
+ function credentialsPath() {
21086
+ return join6(paths.BASE_CONFIG_DIR, "credentials.json");
21087
+ }
21088
+ function ensureDeviceKey(path = deviceKeyPath()) {
21089
+ let created = false;
21090
+ if (!existsSync8(path)) {
21091
+ const { privateKey: privateKey2 } = generateKeyPairSync("ed25519");
21092
+ mkdirSync5(dirname(path), { recursive: true });
21093
+ writeFileSync3(path, privateKey2.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
21094
+ created = true;
21095
+ }
21096
+ const privateKey = createPrivateKey(readFileSync4(path, "utf8"));
21097
+ const publicKeyBase64 = createPublicKey(privateKey).export({ type: "spki", format: "der" }).toString(
21098
+ "base64"
21099
+ );
21100
+ return { privateKey, publicKeyBase64, created };
21101
+ }
21102
+ function loadCredentials(path = credentialsPath()) {
21103
+ if (!existsSync8(path)) return null;
21104
+ try {
21105
+ return JSON.parse(readFileSync4(path, "utf8"));
21106
+ } catch {
21107
+ return null;
21108
+ }
21109
+ }
21110
+ function saveCredentials(creds, path = credentialsPath()) {
21111
+ mkdirSync5(dirname(path), { recursive: true });
21112
+ writeFileSync3(path, `${JSON.stringify(creds, null, 2)}
21113
+ `, { mode: 384 });
21114
+ }
21115
+ function clearLocalAuth() {
21116
+ rmSync3(credentialsPath(), { force: true });
21117
+ rmSync3(deviceKeyPath(), { force: true });
21118
+ }
21119
+ async function post(base, path, body, token) {
21120
+ return fetch(`${base}${path}`, {
21121
+ method: "POST",
21122
+ headers: {
21123
+ "content-type": "application/json",
21124
+ ...token ? { authorization: `Bearer ${token}` } : {}
21125
+ },
21126
+ body: JSON.stringify(body)
21127
+ });
21128
+ }
21129
+ async function readJson(res) {
21130
+ try {
21131
+ return await res.json();
21132
+ } catch {
21133
+ return {};
21134
+ }
21135
+ }
21136
+ async function expectOk(res, what) {
21137
+ const json = await readJson(res);
21138
+ if (!res.ok) {
21139
+ const reason = typeof json["error"] === "string" ? json["error"] : res.statusText;
21140
+ throw new AuthApiError(`${what} failed (${res.status}): ${reason}`, res.status);
21141
+ }
21142
+ return json;
21143
+ }
21144
+ function toSlugs(value) {
21145
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
21146
+ }
21147
+ function toGrant(json) {
21148
+ const user = json["user"] ?? {};
21149
+ return {
21150
+ accessToken: String(json["access_token"]),
21151
+ expiresIn: Number(json["expires_in"]),
21152
+ deviceId: String(json["device_id"]),
21153
+ userEmail: String(user["email"] ?? ""),
21154
+ workspaces: toSlugs(json["workspaces"])
21155
+ };
21156
+ }
21157
+ async function requestDeviceCode(base, input) {
21158
+ const res = await post(base, "/api/auth/device/code", {
21159
+ public_key: input.publicKey,
21160
+ name: input.name,
21161
+ platform: input.platform
21162
+ });
21163
+ const json = await expectOk(res, "Requesting a device code");
21164
+ return {
21165
+ deviceCode: String(json["device_code"]),
21166
+ userCode: String(json["user_code"]),
21167
+ verificationUri: String(json["verification_uri"]),
21168
+ expiresIn: Number(json["expires_in"]),
21169
+ interval: Number(json["interval"] ?? 5)
21170
+ };
21171
+ }
21172
+ async function pollDeviceToken(base, deviceCode) {
21173
+ const res = await post(base, "/api/auth/device/token", { device_code: deviceCode });
21174
+ const json = await readJson(res);
21175
+ if (res.ok) return { status: "approved", grant: toGrant(json) };
21176
+ switch (json["error"]) {
21177
+ case "authorization_pending":
21178
+ return { status: "pending" };
21179
+ case "slow_down":
21180
+ return { status: "slow_down" };
21181
+ case "access_denied":
21182
+ return { status: "denied" };
21183
+ case "expired_token":
21184
+ return { status: "expired" };
21185
+ default:
21186
+ throw new AuthApiError(`Polling for approval failed (${res.status}): ${String(json["error"] ?? res.statusText)}`, res.status);
21187
+ }
21188
+ }
21189
+ async function refreshAccessToken(creds, privateKey) {
21190
+ const challenge = await expectOk(
21191
+ await post(creds.apiUrl, "/api/auth/device/challenge", { device_id: creds.deviceId }),
21192
+ "Requesting a refresh challenge"
21193
+ );
21194
+ const nonce = String(challenge["nonce"]);
21195
+ const signature = sign(null, Buffer.from(nonce), privateKey).toString("base64");
21196
+ const json = await expectOk(
21197
+ await post(creds.apiUrl, "/api/auth/device/refresh", { device_id: creds.deviceId, nonce, signature }),
21198
+ "Refreshing the access token"
21199
+ );
21200
+ return {
21201
+ ...creds,
21202
+ accessToken: String(json["access_token"]),
21203
+ accessTokenExpiresAt: Date.now() + Number(json["expires_in"]) * 1e3
21204
+ };
21205
+ }
21206
+ async function fetchWhoAmI(base, token) {
21207
+ const res = await fetch(`${base}/api/auth/device/me`, { headers: { authorization: `Bearer ${token}` } });
21208
+ const json = await expectOk(res, "Checking the session");
21209
+ const user = json["user"] ?? {};
21210
+ const device = json["device"] ?? {};
21211
+ return {
21212
+ userEmail: String(user["email"] ?? ""),
21213
+ deviceId: String(device["id"] ?? ""),
21214
+ deviceName: String(device["name"] ?? ""),
21215
+ workspaces: toSlugs(json["workspaces"])
21216
+ };
21217
+ }
21218
+ async function boundWorkspaces() {
21219
+ const creds = loadCredentials();
21220
+ if (!creds) return null;
21221
+ try {
21222
+ const me = await fetchWhoAmI(creds.apiUrl, await getAccessToken());
21223
+ saveCredentials({ ...loadCredentials() ?? creds, workspaces: me.workspaces });
21224
+ return { workspaces: me.workspaces, fresh: true };
21225
+ } catch {
21226
+ return { workspaces: creds.workspaces ?? [], fresh: false };
21227
+ }
21228
+ }
21229
+ async function revokeDevice(base, token) {
21230
+ await expectOk(await post(base, "/api/auth/device/revoke", {}, token), "Revoking this device");
21231
+ }
21232
+ async function getAccessToken() {
21233
+ const fromEnv = process.env["FLYSPACE_TOKEN"];
21234
+ if (fromEnv) return fromEnv;
21235
+ const creds = loadCredentials();
21236
+ if (!creds) return null;
21237
+ if (creds.accessTokenExpiresAt - EXPIRY_SKEW_MS > Date.now()) return creds.accessToken;
21238
+ const { privateKey } = ensureDeviceKey();
21239
+ const refreshed = await refreshAccessToken(creds, privateKey);
21240
+ saveCredentials(refreshed);
21241
+ return refreshed.accessToken;
21242
+ }
21243
+
21244
+ // src/dashboard/host-db-client.ts
21245
+ import { createClient } from "@supabase/supabase-js";
21246
+ import { randomUUID as randomUUID2 } from "crypto";
21247
+
21248
+ // src/dashboard/host-lock.ts
21249
+ import { execFileSync as execFileSync4 } from "child_process";
21250
+ import { randomBytes } from "crypto";
21251
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
21252
+ import { join as join7 } from "path";
21253
+ function hostLockPath() {
21254
+ return join7(paths.BASE_DATA_DIR, "host.lock");
21255
+ }
21256
+ function isLiveFlyspace(pid) {
21257
+ try {
21258
+ process.kill(pid, 0);
21259
+ const command = execFileSync4("ps", ["-p", String(pid), "-o", "command="], {
21260
+ encoding: "utf8"
21261
+ });
21262
+ return command.includes("flyspace") || command.includes("host-server");
21263
+ } catch {
21264
+ return false;
21265
+ }
21266
+ }
21267
+ function readLockPid(path) {
21268
+ try {
21269
+ const pid = Number(JSON.parse(readFileSync5(path, "utf8")).pid);
21270
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
21271
+ } catch {
21272
+ return null;
21273
+ }
21274
+ }
21275
+ function acquireHostLock() {
21276
+ const path = hostLockPath();
21277
+ mkdirSync6(paths.BASE_DATA_DIR, { recursive: true });
21278
+ const body = JSON.stringify({
21279
+ pid: process.pid,
21280
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
21281
+ execPath: process.argv[1] ?? ""
21282
+ });
21283
+ for (let attempt = 0; attempt < 2; attempt++) {
21284
+ try {
21285
+ writeFileSync4(path, body, { flag: "wx", mode: 384 });
21286
+ const release = () => {
21287
+ if (readLockPid(path) === process.pid) rmSync4(path, { force: true });
21288
+ };
21289
+ process.once("exit", release);
21290
+ return release;
21291
+ } catch (err) {
21292
+ if (err.code !== "EEXIST") throw err;
21293
+ const holder = readLockPid(path);
21294
+ if (holder === process.pid) return () => {
21295
+ };
21296
+ if (holder && isLiveFlyspace(holder)) {
21297
+ throw new Error(
21298
+ `Another Flyspace Host is already running on this machine (pid ${holder}). Stop it first, or check for a second CLI install (\`which -a flyspace\`). Two Hosts overwrite each other's skill mirror.`
21299
+ );
21300
+ }
21301
+ rmSync4(path, { force: true });
21302
+ }
21303
+ }
21304
+ throw new Error(`Could not take the Host lock at ${path}`);
21305
+ }
21306
+ function publishHostEndpoint(port) {
21307
+ const path = hostLockPath();
21308
+ if (readLockPid(path) !== process.pid) return null;
21309
+ const token = randomBytes(32).toString("hex");
21310
+ const lock = JSON.parse(readFileSync5(path, "utf8"));
21311
+ writeFileSync4(path, JSON.stringify({ ...lock, port, token }), { mode: 384 });
21312
+ return token;
21313
+ }
21314
+ function readHostEndpoint() {
21315
+ try {
21316
+ const { pid, port, token } = JSON.parse(readFileSync5(hostLockPath(), "utf8"));
21317
+ if (pid === process.pid || !Number.isInteger(port) || typeof token !== "string") return null;
21318
+ return { port, token };
21319
+ } catch {
21320
+ return null;
21321
+ }
21322
+ }
21323
+
21324
+ // src/dashboard/host-db-client.ts
21325
+ var REQUEST_TIMEOUT_MS2 = 3e4;
21326
+ var pending = /* @__PURE__ */ new Map();
21327
+ var sender = null;
21328
+ var onSender = [];
21329
+ function setHostDbSender(fn) {
21330
+ sender = fn;
21331
+ if (!fn) return;
21332
+ const waiting = onSender;
21333
+ onSender = [];
21334
+ for (const wake of waiting) wake();
21335
+ }
21336
+ function sendAgentFailure(report) {
21337
+ sender?.({ type: "agent-failure", ...report });
21338
+ }
21339
+ function handleHostDbResult(id, res) {
21340
+ const p = pending.get(id);
21341
+ if (!p) return;
21342
+ pending.delete(id);
21343
+ clearTimeout(p.timer);
21344
+ p.resolve(res);
21345
+ }
21346
+ function whenConnected() {
21347
+ if (sender) return Promise.resolve(sender);
21348
+ return new Promise((resolve8, reject) => {
21349
+ const timer = setTimeout(() => {
21350
+ onSender = onSender.filter((w) => w !== wake);
21351
+ reject(new Error("Host is not connected to the Data API"));
21352
+ }, REQUEST_TIMEOUT_MS2);
21353
+ const wake = () => {
21354
+ clearTimeout(timer);
21355
+ resolve8(sender);
21356
+ };
21357
+ onSender.push(wake);
21358
+ });
21359
+ }
21360
+ async function requestHostDb(req) {
21361
+ const send = await whenConnected();
21362
+ const id = randomUUID2();
21363
+ return new Promise((resolve8, reject) => {
21364
+ const timer = setTimeout(() => {
21365
+ pending.delete(id);
21366
+ reject(new Error("Data API did not answer in time"));
21367
+ }, REQUEST_TIMEOUT_MS2);
21368
+ pending.set(id, { resolve: resolve8, reject, timer });
21369
+ send({ type: "db", id, req });
21370
+ });
21371
+ }
21372
+ var pendingUrls = /* @__PURE__ */ new Map();
21373
+ function handleAttachmentUrlResult(id, url) {
21374
+ pendingUrls.get(id)?.(url);
21375
+ pendingUrls.delete(id);
21376
+ }
21377
+ async function requestAttachmentUrl(key) {
21378
+ const send = await whenConnected();
21379
+ const id = randomUUID2();
21380
+ return new Promise((resolve8, reject) => {
21381
+ const timer = setTimeout(() => {
21382
+ pendingUrls.delete(id);
21383
+ reject(new Error("Data API did not answer in time"));
21384
+ }, REQUEST_TIMEOUT_MS2);
21385
+ pendingUrls.set(id, (url) => {
21386
+ clearTimeout(timer);
21387
+ resolve8(url);
21388
+ });
21389
+ send({ type: "attachment-url", id, key });
21390
+ });
21391
+ }
21392
+ var pendingSvgs = /* @__PURE__ */ new Map();
21393
+ function handlePluginSvgResult(id, url) {
21394
+ pendingSvgs.get(id)?.(url);
21395
+ pendingSvgs.delete(id);
21396
+ }
21397
+ async function requestPluginSvg(workspace, svg) {
21398
+ const send = await whenConnected();
21399
+ const id = randomUUID2();
21400
+ return new Promise((resolve8, reject) => {
21401
+ const timer = setTimeout(() => {
21402
+ pendingSvgs.delete(id);
21403
+ reject(new Error("Data API did not answer in time"));
21404
+ }, REQUEST_TIMEOUT_MS2);
21405
+ pendingSvgs.set(id, (url) => {
21406
+ clearTimeout(timer);
21407
+ resolve8(url);
21408
+ });
21409
+ send({ type: "plugin-svg", id, workspace, svg });
21410
+ });
21411
+ }
21412
+ var pendingRespond = /* @__PURE__ */ new Map();
21413
+ function handleShouldRespondResult(id, respond) {
21414
+ pendingRespond.get(id)?.(respond);
21415
+ pendingRespond.delete(id);
21416
+ }
21417
+ async function requestShouldRespond(transcript) {
21418
+ const send = await whenConnected().catch(() => null);
21419
+ if (!send) return false;
21420
+ const id = randomUUID2();
21421
+ return new Promise((resolve8) => {
21422
+ const timer = setTimeout(() => {
21423
+ pendingRespond.delete(id);
21424
+ resolve8(false);
21425
+ }, REQUEST_TIMEOUT_MS2);
21426
+ pendingRespond.set(id, (respond) => {
21427
+ clearTimeout(timer);
21428
+ resolve8(respond);
21429
+ });
21430
+ send({ type: "should-respond", id, transcript });
21431
+ });
21432
+ }
21433
+ var BODYLESS_STATUS = /* @__PURE__ */ new Set([101, 204, 205, 304]);
21434
+ function dbFetch(send) {
21435
+ return async (input, init) => {
21436
+ const req = new Request(input, init);
21437
+ const url = new URL(req.url);
21438
+ const method = req.method.toUpperCase();
21439
+ const res = await send({
21440
+ method,
21441
+ path: `${url.pathname}${url.search}`,
21442
+ headers: Object.fromEntries(req.headers.entries()),
21443
+ body: method === "GET" || method === "HEAD" ? void 0 : await req.text()
21444
+ });
21445
+ const noBody = method === "HEAD" || BODYLESS_STATUS.has(res.status);
21446
+ return new Response(noBody ? null : res.body, { status: res.status, headers: res.headers });
21447
+ };
21448
+ }
21449
+ var hostDbFetch = dbFetch(requestHostDb);
21450
+ var LOCAL_DB_PATH = "/internal/db";
21451
+ async function requestViaLocalHost(req) {
21452
+ const deadline = Date.now() + REQUEST_TIMEOUT_MS2;
21453
+ let endpoint = readHostEndpoint();
21454
+ while (!endpoint && Date.now() < deadline) {
21455
+ await new Promise((r) => setTimeout(r, 1e3));
21456
+ endpoint = readHostEndpoint();
21457
+ }
21458
+ if (!endpoint) throw new Error("No local Host to reach the Data API through");
21459
+ const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_DB_PATH}`, {
21460
+ method: "POST",
21461
+ headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
21462
+ body: JSON.stringify(req),
21463
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2 + 5e3)
21464
+ });
21465
+ if (!res.ok) throw new Error(`Local Host DB relay answered ${res.status}`);
21466
+ return await res.json();
21467
+ }
21468
+ function relayChannel(topic) {
21469
+ const channel = {
21470
+ on: () => channel,
21471
+ subscribe: (callback) => {
21472
+ queueMicrotask(() => callback?.("SUBSCRIBED"));
21473
+ return channel;
21474
+ },
21475
+ send: async (msg) => {
21476
+ if (msg.type !== "broadcast" || !sender) return "error";
21477
+ sender({ type: "db-broadcast", topic, event: msg.event, payload: msg.payload ?? {} });
21478
+ return "ok";
21479
+ },
21480
+ unsubscribe: async () => "ok"
21481
+ };
21482
+ return channel;
21483
+ }
21484
+ function createHostDbClient(via = "socket") {
21485
+ const client = createClient("https://host-db.invalid", "host-device", {
21486
+ auth: { persistSession: false, autoRefreshToken: false },
21487
+ global: { fetch: via === "socket" ? hostDbFetch : dbFetch(requestViaLocalHost) }
21488
+ });
21489
+ return new Proxy(client, {
21490
+ get(target, prop) {
21491
+ if (prop === "channel") return relayChannel;
21492
+ if (prop === "removeChannel") return async () => "ok";
21493
+ const value = Reflect.get(target, prop, target);
21494
+ return typeof value === "function" ? value.bind(target) : value;
21495
+ }
21496
+ });
21497
+ }
21498
+
21499
+ // src/commands/supabase-via-host.ts
21500
+ function useHostDbWithoutCredentials() {
21501
+ const viaHost = !!loadCredentials() && (!hasSupabaseCredentials() || !!readHostEndpoint());
21502
+ if (viaHost) setSupabaseClient(createHostDbClient("local-host"));
21503
+ return viaHost;
21504
+ }
21505
+
21506
+ // src/commands/persona.ts
21507
+ var USAGE = `
21508
+ Usage: flyspace persona avatars [--character <id>] [--clear]
21509
+
21510
+ Use a claudecafe persona-panel character's faces (claudecafe.dev) as the
21511
+ workspace bot's avatars: a reply ending in her mood marker shows the matching
21512
+ face, and "neutral" becomes the bot's default avatar.
21513
+
21514
+ --character <id> Character folder under ~/.config/claudecafe/characters
21515
+ (default: "character" in its config.json, else kotone)
21516
+ --clear Remove the per-expression avatars
21517
+ `;
21518
+ var AVATAR_SIZE = 96;
21519
+ var PACKS = {
21520
+ kotone: {
21521
+ version: "1.4.0",
21522
+ url: "https://github.com/minipai/claudecafe/releases/download/kotone-characters-v1.4.0/ClaudeCafe-Kotone-characters-v1.4.0.zip",
21523
+ sha256: "7a0d8d9b7e52104feaff94be2745ad4179367325b2eb69432b94fc689a29f041"
21524
+ },
21525
+ kurumi: {
21526
+ version: "1.4.0",
21527
+ url: "https://github.com/minipai/claudecafe/releases/download/kurumi-characters-v1.4.0/ClaudeCafe-Kurumi-characters-v1.4.0.zip",
21528
+ sha256: "1f028c4189a0e605517d85089a19f8662789c1f8068ccdb9dba6069b6b8aa17b"
21529
+ },
21530
+ kokona: {
21531
+ version: "1.4.0",
21532
+ url: "https://github.com/minipai/claudecafe/releases/download/kokona-characters-v1.4.0/ClaudeCafe-Kokona-characters-v1.4.0.zip",
21533
+ sha256: "2151f12a2c8569bdab5c8d4df86c91da200c40946318a75e7c1c883604dbb9fb"
21534
+ }
21535
+ };
21536
+ function pluginInstalled() {
21537
+ const claudeDir = process.env["CLAUDE_CONFIG_DIR"] || join8(homedir3(), ".claude");
21538
+ return existsSync9(join8(claudeDir, "plugins", "cache", "claudecafe", "persona-panel"));
21539
+ }
21540
+ function installPack(root, character) {
21541
+ const pack = PACKS[character];
21542
+ if (!pack) throw new Error(`No published pack for "${character}".`);
21543
+ const charactersDir = join8(root, "characters");
21544
+ execFileSync5("mkdir", ["-p", charactersDir]);
21545
+ const staging = mkdtempSync2(join8(charactersDir, `.${character}-`));
21546
+ try {
21547
+ const zip = join8(staging, "pack.zip");
21548
+ execFileSync5("curl", ["-fsSL", "--max-time", "60", "-o", zip, pack.url]);
21549
+ const digest = createHash3("sha256").update(readFileSync6(zip)).digest("hex");
21550
+ if (digest !== pack.sha256) throw new Error(`${character} pack SHA-256 mismatch`);
21551
+ execFileSync5("unzip", ["-q", zip, "-d", staging]);
21552
+ const folder = join8(charactersDir, character);
21553
+ if (existsSync9(folder)) renameSync2(folder, join8(staging, "previous"));
21554
+ renameSync2(join8(staging, character), folder);
21555
+ } finally {
21556
+ rmSync5(staging, { recursive: true, force: true });
21557
+ }
21558
+ }
21559
+ function cafeRoot() {
21560
+ return join8(process.env["XDG_CONFIG_HOME"] || join8(homedir3(), ".config"), "claudecafe");
21561
+ }
21562
+ function configuredCharacter(root) {
21563
+ try {
21564
+ const config = JSON.parse(readFileSync6(join8(root, "config.json"), "utf8"));
21565
+ if (config.character && config.character !== "none") return config.character;
21566
+ } catch {
21567
+ }
21568
+ return "kotone";
21569
+ }
21570
+ async function runPersonaCmd(args) {
21571
+ if (args[0] !== "avatars") {
21572
+ console.log(USAGE);
21573
+ return;
21574
+ }
21575
+ loadEnvFiles();
21576
+ useHostDbWithoutCredentials();
21577
+ const profile = getProfile();
21578
+ if (args.includes("--clear")) {
21579
+ await upsertWorkspaceBranding(profile, { botExpressionAvatars: null });
21580
+ console.log("Cleared the per-expression bot avatars.");
21581
+ return;
21582
+ }
21583
+ const idx = args.indexOf("--character");
21584
+ const { character, count } = await syncPersonaAvatars(profile, idx !== -1 && args[idx + 1] || void 0);
21585
+ console.log(`Saved ${count} ${character} avatars.`);
21586
+ }
21587
+ var DEFAULT_BOT_NAMES = /* @__PURE__ */ new Set(["Bot", "Workspace Agent"]);
21588
+ async function syncPersonaAvatars(profile, requested) {
21589
+ const root = cafeRoot();
21590
+ const character = requested || configuredCharacter(root);
21591
+ const dir = join8(root, "characters", character, "avatars");
21592
+ if (!existsSync9(dir)) installPack(root, character);
21593
+ const avatars = {};
21594
+ for (const file of readdirSync2(dir).filter((f) => f.endsWith(".webp"))) {
21595
+ const image = await sharp(join8(dir, file)).resize({ width: AVATAR_SIZE, height: AVATAR_SIZE, fit: "cover", position: "top" }).webp({ quality: 80 }).toBuffer();
21596
+ avatars[basename2(file, ".webp")] = `data:image/webp;base64,${image.toString("base64")}`;
21597
+ }
21598
+ if (!Object.keys(avatars).length) throw new Error(`No .webp avatars in ${dir}.`);
21599
+ const current = (await getWorkspaceBranding(profile))?.botName?.trim();
21600
+ const keepName = current && !DEFAULT_BOT_NAMES.has(current);
21601
+ await upsertWorkspaceBranding(profile, {
21602
+ botExpressionAvatars: avatars,
21603
+ ...keepName ? {} : { botName: character.charAt(0).toUpperCase() + character.slice(1) },
21604
+ ...avatars["neutral"] ? { botAvatar: avatars["neutral"] } : {}
21605
+ });
21606
+ return { character, count: Object.keys(avatars).length };
21607
+ }
21608
+ async function autoSyncPersonaAvatars(profile) {
21609
+ if (!pluginInstalled() || !resolveOwnPersona(void 0)) return;
21610
+ const root = cafeRoot();
21611
+ const character = configuredCharacter(root);
21612
+ const stamp = `${character}@${PACKS[character]?.version ?? "local"}`;
21613
+ const marker = join8(root, `.flyspace-avatars-${profile}`);
21614
+ try {
21615
+ if (readFileSync6(marker, "utf8") === stamp) return;
21616
+ } catch {
21617
+ }
21618
+ try {
21619
+ const { count } = await syncPersonaAvatars(profile, character);
21620
+ writeFileSync5(marker, stamp);
21621
+ console.log(`[persona] synced ${count} ${character} avatars`);
21622
+ } catch (err) {
21623
+ console.warn(`[persona] avatar sync skipped: ${err.message}`);
21624
+ }
21625
+ }
21626
+
20929
21627
  // ../api/src/feature-flags.ts
20930
21628
  var featureFlags = {
20931
21629
  "ai-cost": {
@@ -21392,8 +22090,8 @@ async function buildPrompt(profile, channelId, opts) {
21392
22090
  }
21393
22091
 
21394
22092
  // src/dashboard/settings-host.ts
21395
- import { writeFileSync as writeFileSync3, existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync4, rmSync as rmSync3 } from "fs";
21396
- import { dirname } from "path";
22093
+ import { writeFileSync as writeFileSync6, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync7, rmSync as rmSync6 } from "fs";
22094
+ import { dirname as dirname2 } from "path";
21397
22095
 
21398
22096
  // ../api/src/dashboard/auto-title.ts
21399
22097
  var GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions";
@@ -21554,9 +22252,9 @@ function parseAgentProfiles(raw) {
21554
22252
  return entries2.length > 0 ? Object.fromEntries(entries2) : void 0;
21555
22253
  }
21556
22254
  function loadDashboardSettings() {
21557
- if (!existsSync8(paths.DASHBOARD_SETTINGS_FILE)) return localDefaults();
22255
+ if (!existsSync10(paths.DASHBOARD_SETTINGS_FILE)) return localDefaults();
21558
22256
  try {
21559
- const raw = JSON.parse(readFileSync4(paths.DASHBOARD_SETTINGS_FILE, "utf-8"));
22257
+ const raw = JSON.parse(readFileSync7(paths.DASHBOARD_SETTINGS_FILE, "utf-8"));
21560
22258
  const providers = parseProviders(raw.providers, {
21561
22259
  agent: normalizeDefaultModel(raw.agent, localDefaults().agent),
21562
22260
  fallbackModel: typeof raw.fallbackModel === "string" && isAllowedModel(raw.fallbackModel) ? raw.fallbackModel : void 0
@@ -21583,9 +22281,9 @@ function withFallbackModel(providers, model) {
21583
22281
  return [cleared[0], { runner, model }, ...cleared.slice(1).filter((p) => p.runner !== runner)];
21584
22282
  }
21585
22283
  function writeSettings(next) {
21586
- mkdirSync5(dirname(paths.DASHBOARD_SETTINGS_FILE), { recursive: true });
22284
+ mkdirSync7(dirname2(paths.DASHBOARD_SETTINGS_FILE), { recursive: true });
21587
22285
  const merged = { ...readSettingsFile() ?? {}, ...next };
21588
- writeFileSync3(paths.DASHBOARD_SETTINGS_FILE, JSON.stringify(merged, null, 2), "utf-8");
22286
+ writeFileSync6(paths.DASHBOARD_SETTINGS_FILE, JSON.stringify(merged, null, 2), "utf-8");
21589
22287
  return next;
21590
22288
  }
21591
22289
  function saveDashboardSettings(patch) {
@@ -21619,13 +22317,13 @@ async function loadFullDashboardSettings(profile = getProfile()) {
21619
22317
  function saveWorkspacePrompt(prompt) {
21620
22318
  const trimmed = prompt.trim();
21621
22319
  if (!trimmed || trimmed === loadWorkspacePrompt().defaultPrompt) return resetWorkspacePrompt();
21622
- mkdirSync5(dirname(paths.PROMPT_FILE), { recursive: true });
21623
- writeFileSync3(paths.PROMPT_FILE, `${trimmed}
22320
+ mkdirSync7(dirname2(paths.PROMPT_FILE), { recursive: true });
22321
+ writeFileSync6(paths.PROMPT_FILE, `${trimmed}
21624
22322
  `, "utf-8");
21625
22323
  return loadWorkspacePrompt();
21626
22324
  }
21627
22325
  function resetWorkspacePrompt() {
21628
- rmSync3(paths.PROMPT_FILE, { force: true });
22326
+ rmSync6(paths.PROMPT_FILE, { force: true });
21629
22327
  return loadWorkspacePrompt();
21630
22328
  }
21631
22329
  function saveAgentProfile(name, patch) {
@@ -21650,9 +22348,9 @@ function saveAgentProfile(name, patch) {
21650
22348
 
21651
22349
  // ../api/src/codex/agent.ts
21652
22350
  import { spawn as spawn2 } from "child_process";
21653
- import { existsSync as existsSync9, mkdtempSync as mkdtempSync2, readFileSync as readFileSync5, rmSync as rmSync4, statSync as statSync3 } from "fs";
22351
+ import { existsSync as existsSync11, mkdtempSync as mkdtempSync3, readFileSync as readFileSync8, rmSync as rmSync7, statSync as statSync3 } from "fs";
21654
22352
  import { tmpdir as tmpdir2 } from "os";
21655
- import { join as join6 } from "path";
22353
+ import { join as join9 } from "path";
21656
22354
  var AUTH_ERROR_PATTERNS2 = [
21657
22355
  /401 unauthorized/i,
21658
22356
  /missing bearer or basic authentication/i,
@@ -21783,8 +22481,8 @@ function getMaxDurationMs2() {
21783
22481
  }
21784
22482
  function codexAuthAvailable(env = process.env) {
21785
22483
  if (env["OPENAI_API_KEY"]?.trim()) return true;
21786
- const home = env["CODEX_HOME"]?.trim() || join6(env["HOME"] ?? "", ".codex");
21787
- return existsSync9(join6(home, "auth.json"));
22484
+ const home = env["CODEX_HOME"]?.trim() || join9(env["HOME"] ?? "", ".codex");
22485
+ return existsSync11(join9(home, "auth.json"));
21788
22486
  }
21789
22487
  function applySystemPrompt(prompt, options, resumeSessionId) {
21790
22488
  if (resumeSessionId || !options.systemPrompt?.trim()) return prompt;
@@ -21838,8 +22536,8 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
21838
22536
  recordCodexUsage(response, options);
21839
22537
  resolve8(response);
21840
22538
  };
21841
- const scratch = mkdtempSync2(join6(tmpdir2(), "flyspace-codex-"));
21842
- const lastMessageFile = join6(scratch, "last-message.txt");
22539
+ const scratch = mkdtempSync3(join9(tmpdir2(), "flyspace-codex-"));
22540
+ const lastMessageFile = join9(scratch, "last-message.txt");
21843
22541
  const args = buildArgs2(prompt, options, lastMessageFile, resumeSessionId);
21844
22542
  console.log(`[codex] spawning codex CLI in ${cwd}`);
21845
22543
  console.log(`[codex] args: ${args.slice(0, -1).join(" ")}`);
@@ -21909,7 +22607,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
21909
22607
  const cleanup = () => {
21910
22608
  clearTimeout(timeoutHandle);
21911
22609
  if (signal) signal.removeEventListener("abort", onAbort);
21912
- rmSync4(scratch, { recursive: true, force: true });
22610
+ rmSync7(scratch, { recursive: true, force: true });
21913
22611
  };
21914
22612
  child.stdout.setEncoding("utf8");
21915
22613
  child.stderr.setEncoding("utf8");
@@ -21938,7 +22636,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
21938
22636
  child.on("close", (code, signal2) => {
21939
22637
  let lastMessage = "";
21940
22638
  try {
21941
- lastMessage = readFileSync5(lastMessageFile, "utf8").trim();
22639
+ lastMessage = readFileSync8(lastMessageFile, "utf8").trim();
21942
22640
  } catch {
21943
22641
  lastMessage = "";
21944
22642
  }
@@ -21992,7 +22690,7 @@ function runCodexCli(prompt, cwd, options, resumeSessionId) {
21992
22690
  });
21993
22691
  }
21994
22692
  async function askCodex(prompt, cwd, options = {}, resumeSessionId) {
21995
- if (!existsSync9(cwd) || !statSync3(cwd).isDirectory()) {
22693
+ if (!existsSync11(cwd) || !statSync3(cwd).isDirectory()) {
21996
22694
  console.error(`[codex] working directory does not exist: ${cwd}`);
21997
22695
  return {
21998
22696
  sessionId: resumeSessionId ?? "",
@@ -22445,7 +23143,7 @@ function renderAsciiTable(t) {
22445
23143
  }
22446
23144
 
22447
23145
  // src/store/channel-cache.ts
22448
- import { mkdirSync as mkdirSync6 } from "fs";
23146
+ import { mkdirSync as mkdirSync8 } from "fs";
22449
23147
 
22450
23148
  // src/store/sqlite.ts
22451
23149
  import Database from "better-sqlite3";
@@ -22469,7 +23167,7 @@ function getDb() {
22469
23167
  const file = paths.DB_FILE;
22470
23168
  const existing = dbs.get(file);
22471
23169
  if (existing) return existing;
22472
- mkdirSync6(paths.DATA_DIR, { recursive: true });
23170
+ mkdirSync8(paths.DATA_DIR, { recursive: true });
22473
23171
  const db = openLocalDatabase(file);
22474
23172
  if (!db) return null;
22475
23173
  db.exec(`
@@ -22985,17 +23683,17 @@ var TriggerEngine = class {
22985
23683
  };
22986
23684
 
22987
23685
  // src/store/user-cache.ts
22988
- import { existsSync as existsSync10, readFileSync as readFileSync6 } from "fs";
22989
- import { join as join7 } from "path";
23686
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
23687
+ import { join as join10 } from "path";
22990
23688
  function jsonUserCachePath() {
22991
- const file = join7(paths.CONFIG_DIR, "slack_users.json");
22992
- return existsSync10(file) ? file : void 0;
23689
+ const file = join10(paths.CONFIG_DIR, "slack_users.json");
23690
+ return existsSync12(file) ? file : void 0;
22993
23691
  }
22994
23692
  function readJsonUserCache() {
22995
23693
  const file = jsonUserCachePath();
22996
23694
  if (!file) return void 0;
22997
23695
  try {
22998
- const parsed = JSON.parse(readFileSync6(file, "utf8"));
23696
+ const parsed = JSON.parse(readFileSync9(file, "utf8"));
22999
23697
  return parsed.users;
23000
23698
  } catch {
23001
23699
  return void 0;
@@ -23402,7 +24100,7 @@ var MessageQueue = class {
23402
24100
 
23403
24101
  // src/slack/file-downloader.ts
23404
24102
  import { writeFile } from "fs/promises";
23405
- import { join as join8, extname } from "path";
24103
+ import { join as join11, extname } from "path";
23406
24104
  var debug3 = process.env["DEBUG"] === "true";
23407
24105
  var SUPPORTED_IMAGE_MIMETYPES = /* @__PURE__ */ new Set([
23408
24106
  "image/png",
@@ -23502,7 +24200,7 @@ async function downloadOne(file, botToken) {
23502
24200
  const ext = extname(originalName) || `.${file.filetype ?? "bin"}`;
23503
24201
  const safeName = sanitizeFilename(originalName.replace(ext, ""));
23504
24202
  const filename = `${Date.now()}-${file.id ?? "unnamed"}-${safeName}${ext}`;
23505
- const localPath = join8(paths.UPLOADS_DIR, filename);
24203
+ const localPath = join11(paths.UPLOADS_DIR, filename);
23506
24204
  await writeFile(localPath, buffer);
23507
24205
  if (debug3)
23508
24206
  console.log(`[file-downloader] saved ${file.id} -> ${localPath} (${buffer.length} bytes)`);
@@ -23672,9 +24370,9 @@ function identityHandleFor(slackUserId) {
23672
24370
  }
23673
24371
 
23674
24372
  // src/store/slack-avatar-sync.ts
23675
- import sharp from "sharp";
24373
+ import sharp2 from "sharp";
23676
24374
  import { PutObjectCommand } from "@aws-sdk/client-s3";
23677
- var AVATAR_SIZE = 192;
24375
+ var AVATAR_SIZE2 = 192;
23678
24376
  function r2Configured() {
23679
24377
  return Boolean(
23680
24378
  process.env["CLOUDFLARE_R2_ACCOUNT_ID"] && process.env["CLOUDFLARE_R2_ACCESS_KEY_ID"] && process.env["CLOUDFLARE_R2_SECRET_ACCESS_KEY"] && process.env["CLOUDFLARE_R2_BUCKET_NAME"]
@@ -23696,7 +24394,7 @@ async function syncSlackAvatars(ids) {
23696
24394
  const res = await fetch(row.image_url);
23697
24395
  if (!res.ok) throw new Error(`fetch ${res.status}`);
23698
24396
  const original = Buffer.from(await res.arrayBuffer());
23699
- const resized = await sharp(original).resize({ width: AVATAR_SIZE, height: AVATAR_SIZE, fit: "cover" }).png().toBuffer();
24397
+ const resized = await sharp2(original).resize({ width: AVATAR_SIZE2, height: AVATAR_SIZE2, fit: "cover" }).png().toBuffer();
23700
24398
  const key = `avatar/slack/${getProfile()}/${id}.png`;
23701
24399
  await getR2Client().send(
23702
24400
  new PutObjectCommand({
@@ -23950,16 +24648,16 @@ async function summariseThreadTranscript(transcript, opts, deps = {}) {
23950
24648
  }
23951
24649
 
23952
24650
  // src/dashboard/chat-agent.ts
23953
- import { homedir as homedir7 } from "os";
24651
+ import { homedir as homedir8 } from "os";
23954
24652
  import { stripVTControlCharacters } from "util";
23955
24653
 
23956
24654
  // src/mcp/config.ts
23957
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
24655
+ import { mkdtempSync as mkdtempSync4, rmSync as rmSync8, writeFileSync as writeFileSync7 } from "fs";
23958
24656
  import { tmpdir as tmpdir3 } from "os";
23959
- import { join as join9 } from "path";
24657
+ import { join as join12 } from "path";
23960
24658
 
23961
24659
  // ../api/src/mcp/crypto.ts
23962
- import { createCipheriv, createDecipheriv, randomBytes, timingSafeEqual } from "crypto";
24660
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
23963
24661
  var ALGORITHM = "aes-256-gcm";
23964
24662
  var KEY_BYTES = 32;
23965
24663
  var IV_BYTES = 12;
@@ -23992,7 +24690,7 @@ function currentKeyVersion() {
23992
24690
  );
23993
24691
  }
23994
24692
  function encrypt(key, purpose, plaintext) {
23995
- const iv = randomBytes(IV_BYTES);
24693
+ const iv = randomBytes2(IV_BYTES);
23996
24694
  const cipher = createCipheriv(ALGORITHM, key, iv);
23997
24695
  cipher.setAAD(Buffer.from(purpose, "utf8"));
23998
24696
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
@@ -24012,7 +24710,7 @@ function decrypt(key, purpose, blob) {
24012
24710
  }
24013
24711
  function createEnvelope() {
24014
24712
  const keyVersion = currentKeyVersion();
24015
- const key = randomBytes(KEY_BYTES);
24713
+ const key = randomBytes2(KEY_BYTES);
24016
24714
  const wrappedDek = encrypt(
24017
24715
  readMasterKey(keyVersion),
24018
24716
  purposeForDek(keyVersion),
@@ -24078,7 +24776,7 @@ function secretsMatch(a, b) {
24078
24776
  }
24079
24777
 
24080
24778
  // ../api/src/mcp/oauth.ts
24081
- import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
24779
+ import { createHash as createHash4, randomBytes as randomBytes3 } from "crypto";
24082
24780
  var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
24083
24781
  "client_id",
24084
24782
  "redirect_uri",
@@ -24092,11 +24790,11 @@ function base64url(buffer) {
24092
24790
  return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24093
24791
  }
24094
24792
  function createStateToken() {
24095
- return base64url(randomBytes2(32));
24793
+ return base64url(randomBytes3(32));
24096
24794
  }
24097
24795
  function createPkcePair() {
24098
- const verifier = base64url(randomBytes2(32));
24099
- const challenge = base64url(createHash3("sha256").update(verifier).digest());
24796
+ const verifier = base64url(randomBytes3(32));
24797
+ const challenge = base64url(createHash4("sha256").update(verifier).digest());
24100
24798
  return { verifier, challenge };
24101
24799
  }
24102
24800
  function clientEnvName(providerSlug, suffix) {
@@ -24216,7 +24914,7 @@ async function exchangeCode(params) {
24216
24914
  );
24217
24915
  return { ...tokens, scopes: tokens.scopes.length ? tokens.scopes : provider.defaultScopes };
24218
24916
  }
24219
- async function refreshAccessToken(params) {
24917
+ async function refreshAccessToken2(params) {
24220
24918
  const { provider, client, refreshToken } = params;
24221
24919
  return requestToken(
24222
24920
  provider,
@@ -24502,7 +25200,7 @@ async function renew(workspaceId, connection, provider, deps) {
24502
25200
  }
24503
25201
  let tokens;
24504
25202
  try {
24505
- tokens = await refreshAccessToken({
25203
+ tokens = await refreshAccessToken2({
24506
25204
  provider,
24507
25205
  client: readOAuthClient(provider.slug),
24508
25206
  refreshToken,
@@ -24642,12 +25340,12 @@ async function buildMcpConfig(profile, connectionIds) {
24642
25340
  return { config, skipped };
24643
25341
  }
24644
25342
  function writeMcpConfigFile(config) {
24645
- const dir = mkdtempSync3(join9(tmpdir3(), "flyspace-mcp-"));
24646
- const path = join9(dir, "mcp-config.json");
24647
- writeFileSync4(path, JSON.stringify(config), { mode: 384 });
25343
+ const dir = mkdtempSync4(join12(tmpdir3(), "flyspace-mcp-"));
25344
+ const path = join12(dir, "mcp-config.json");
25345
+ writeFileSync7(path, JSON.stringify(config), { mode: 384 });
24648
25346
  return {
24649
25347
  path,
24650
- cleanup: () => rmSync5(dir, { recursive: true, force: true })
25348
+ cleanup: () => rmSync8(dir, { recursive: true, force: true })
24651
25349
  };
24652
25350
  }
24653
25351
  async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
@@ -24665,8 +25363,8 @@ async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
24665
25363
  }
24666
25364
 
24667
25365
  // ../api/src/version.ts
24668
- import { readFileSync as readFileSync7 } from "fs";
24669
- var CLI_VERSION = true ? "0.1.57" : devVersion();
25366
+ import { readFileSync as readFileSync10 } from "fs";
25367
+ var CLI_VERSION = true ? "0.1.59" : devVersion();
24670
25368
  function isOlderVersion(a, b) {
24671
25369
  const parse2 = (v) => v.replace(/^v/, "").split("-")[0].split(".").map(Number);
24672
25370
  const [pa, pb] = [parse2(a), parse2(b)];
@@ -24688,278 +25386,43 @@ async function latestCliVersion() {
24688
25386
  return version;
24689
25387
  }
24690
25388
 
24691
- // src/dashboard/host-db-client.ts
24692
- import { createClient } from "@supabase/supabase-js";
24693
- import { randomUUID as randomUUID2 } from "crypto";
24694
-
24695
- // src/dashboard/host-lock.ts
24696
- import { execFileSync as execFileSync4 } from "child_process";
24697
- import { randomBytes as randomBytes3 } from "crypto";
24698
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync8, rmSync as rmSync6, writeFileSync as writeFileSync5 } from "fs";
24699
- import { join as join10 } from "path";
24700
- function hostLockPath() {
24701
- return join10(paths.BASE_DATA_DIR, "host.lock");
24702
- }
24703
- function isLiveFlyspace(pid) {
24704
- try {
24705
- process.kill(pid, 0);
24706
- const command = execFileSync4("ps", ["-p", String(pid), "-o", "command="], {
24707
- encoding: "utf8"
24708
- });
24709
- return command.includes("flyspace") || command.includes("host-server");
24710
- } catch {
24711
- return false;
24712
- }
24713
- }
24714
- function readLockPid(path) {
24715
- try {
24716
- const pid = Number(JSON.parse(readFileSync8(path, "utf8")).pid);
24717
- return Number.isInteger(pid) && pid > 0 ? pid : null;
24718
- } catch {
24719
- return null;
24720
- }
24721
- }
24722
- function acquireHostLock() {
24723
- const path = hostLockPath();
24724
- mkdirSync7(paths.BASE_DATA_DIR, { recursive: true });
24725
- const body = JSON.stringify({
24726
- pid: process.pid,
24727
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
24728
- execPath: process.argv[1] ?? ""
24729
- });
24730
- for (let attempt = 0; attempt < 2; attempt++) {
24731
- try {
24732
- writeFileSync5(path, body, { flag: "wx", mode: 384 });
24733
- const release = () => {
24734
- if (readLockPid(path) === process.pid) rmSync6(path, { force: true });
24735
- };
24736
- process.once("exit", release);
24737
- return release;
24738
- } catch (err) {
24739
- if (err.code !== "EEXIST") throw err;
24740
- const holder = readLockPid(path);
24741
- if (holder === process.pid) return () => {
24742
- };
24743
- if (holder && isLiveFlyspace(holder)) {
24744
- throw new Error(
24745
- `Another Flyspace Host is already running on this machine (pid ${holder}). Stop it first, or check for a second CLI install (\`which -a flyspace\`). Two Hosts overwrite each other's skill mirror.`
24746
- );
24747
- }
24748
- rmSync6(path, { force: true });
24749
- }
24750
- }
24751
- throw new Error(`Could not take the Host lock at ${path}`);
24752
- }
24753
- function publishHostEndpoint(port) {
24754
- const path = hostLockPath();
24755
- if (readLockPid(path) !== process.pid) return null;
24756
- const token = randomBytes3(32).toString("hex");
24757
- const lock = JSON.parse(readFileSync8(path, "utf8"));
24758
- writeFileSync5(path, JSON.stringify({ ...lock, port, token }), { mode: 384 });
24759
- return token;
24760
- }
24761
- function readHostEndpoint() {
24762
- try {
24763
- const { pid, port, token } = JSON.parse(readFileSync8(hostLockPath(), "utf8"));
24764
- if (pid === process.pid || !Number.isInteger(port) || typeof token !== "string") return null;
24765
- return { port, token };
24766
- } catch {
24767
- return null;
24768
- }
24769
- }
24770
-
24771
- // src/dashboard/host-db-client.ts
24772
- var REQUEST_TIMEOUT_MS2 = 3e4;
24773
- var pending = /* @__PURE__ */ new Map();
24774
- var sender = null;
24775
- var onSender = [];
24776
- function setHostDbSender(fn) {
24777
- sender = fn;
24778
- if (!fn) return;
24779
- const waiting = onSender;
24780
- onSender = [];
24781
- for (const wake of waiting) wake();
24782
- }
24783
- function sendAgentFailure(report) {
24784
- sender?.({ type: "agent-failure", ...report });
24785
- }
24786
- function handleHostDbResult(id, res) {
24787
- const p = pending.get(id);
24788
- if (!p) return;
24789
- pending.delete(id);
24790
- clearTimeout(p.timer);
24791
- p.resolve(res);
24792
- }
24793
- function whenConnected() {
24794
- if (sender) return Promise.resolve(sender);
24795
- return new Promise((resolve8, reject) => {
24796
- const timer = setTimeout(() => {
24797
- onSender = onSender.filter((w) => w !== wake);
24798
- reject(new Error("Host is not connected to the Data API"));
24799
- }, REQUEST_TIMEOUT_MS2);
24800
- const wake = () => {
24801
- clearTimeout(timer);
24802
- resolve8(sender);
24803
- };
24804
- onSender.push(wake);
24805
- });
24806
- }
24807
- async function requestHostDb(req) {
24808
- const send = await whenConnected();
24809
- const id = randomUUID2();
24810
- return new Promise((resolve8, reject) => {
24811
- const timer = setTimeout(() => {
24812
- pending.delete(id);
24813
- reject(new Error("Data API did not answer in time"));
24814
- }, REQUEST_TIMEOUT_MS2);
24815
- pending.set(id, { resolve: resolve8, reject, timer });
24816
- send({ type: "db", id, req });
24817
- });
24818
- }
24819
- var pendingUrls = /* @__PURE__ */ new Map();
24820
- function handleAttachmentUrlResult(id, url) {
24821
- pendingUrls.get(id)?.(url);
24822
- pendingUrls.delete(id);
24823
- }
24824
- async function requestAttachmentUrl(key) {
24825
- const send = await whenConnected();
24826
- const id = randomUUID2();
24827
- return new Promise((resolve8, reject) => {
24828
- const timer = setTimeout(() => {
24829
- pendingUrls.delete(id);
24830
- reject(new Error("Data API did not answer in time"));
24831
- }, REQUEST_TIMEOUT_MS2);
24832
- pendingUrls.set(id, (url) => {
24833
- clearTimeout(timer);
24834
- resolve8(url);
24835
- });
24836
- send({ type: "attachment-url", id, key });
24837
- });
24838
- }
24839
- var pendingRespond = /* @__PURE__ */ new Map();
24840
- function handleShouldRespondResult(id, respond) {
24841
- pendingRespond.get(id)?.(respond);
24842
- pendingRespond.delete(id);
24843
- }
24844
- async function requestShouldRespond(transcript) {
24845
- const send = await whenConnected().catch(() => null);
24846
- if (!send) return false;
24847
- const id = randomUUID2();
24848
- return new Promise((resolve8) => {
24849
- const timer = setTimeout(() => {
24850
- pendingRespond.delete(id);
24851
- resolve8(false);
24852
- }, REQUEST_TIMEOUT_MS2);
24853
- pendingRespond.set(id, (respond) => {
24854
- clearTimeout(timer);
24855
- resolve8(respond);
24856
- });
24857
- send({ type: "should-respond", id, transcript });
24858
- });
24859
- }
24860
- var BODYLESS_STATUS = /* @__PURE__ */ new Set([101, 204, 205, 304]);
24861
- function dbFetch(send) {
24862
- return async (input, init) => {
24863
- const req = new Request(input, init);
24864
- const url = new URL(req.url);
24865
- const method = req.method.toUpperCase();
24866
- const res = await send({
24867
- method,
24868
- path: `${url.pathname}${url.search}`,
24869
- headers: Object.fromEntries(req.headers.entries()),
24870
- body: method === "GET" || method === "HEAD" ? void 0 : await req.text()
24871
- });
24872
- const noBody = method === "HEAD" || BODYLESS_STATUS.has(res.status);
24873
- return new Response(noBody ? null : res.body, { status: res.status, headers: res.headers });
24874
- };
24875
- }
24876
- var hostDbFetch = dbFetch(requestHostDb);
24877
- var LOCAL_DB_PATH = "/internal/db";
24878
- async function requestViaLocalHost(req) {
24879
- const deadline = Date.now() + REQUEST_TIMEOUT_MS2;
24880
- let endpoint = readHostEndpoint();
24881
- while (!endpoint && Date.now() < deadline) {
24882
- await new Promise((r) => setTimeout(r, 1e3));
24883
- endpoint = readHostEndpoint();
24884
- }
24885
- if (!endpoint) throw new Error("No local Host to reach the Data API through");
24886
- const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_DB_PATH}`, {
24887
- method: "POST",
24888
- headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
24889
- body: JSON.stringify(req),
24890
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2 + 5e3)
24891
- });
24892
- if (!res.ok) throw new Error(`Local Host DB relay answered ${res.status}`);
24893
- return await res.json();
24894
- }
24895
- function relayChannel(topic) {
24896
- const channel = {
24897
- on: () => channel,
24898
- subscribe: (callback) => {
24899
- queueMicrotask(() => callback?.("SUBSCRIBED"));
24900
- return channel;
24901
- },
24902
- send: async (msg) => {
24903
- if (msg.type !== "broadcast" || !sender) return "error";
24904
- sender({ type: "db-broadcast", topic, event: msg.event, payload: msg.payload ?? {} });
24905
- return "ok";
24906
- },
24907
- unsubscribe: async () => "ok"
24908
- };
24909
- return channel;
24910
- }
24911
- function createHostDbClient(via = "socket") {
24912
- const client = createClient("https://host-db.invalid", "host-device", {
24913
- auth: { persistSession: false, autoRefreshToken: false },
24914
- global: { fetch: via === "socket" ? hostDbFetch : dbFetch(requestViaLocalHost) }
24915
- });
24916
- return new Proxy(client, {
24917
- get(target, prop) {
24918
- if (prop === "channel") return relayChannel;
24919
- if (prop === "removeChannel") return async () => "ok";
24920
- const value = Reflect.get(target, prop, target);
24921
- return typeof value === "function" ? value.bind(target) : value;
24922
- }
24923
- });
24924
- }
24925
-
24926
25389
  // src/claude/agents.ts
24927
- import { existsSync as existsSync13, readdirSync as readdirSync4, readFileSync as readFileSync11 } from "fs";
24928
- import { homedir as homedir5 } from "os";
24929
- import { basename as basename3, join as join13 } from "path";
25390
+ import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync13 } from "fs";
25391
+ import { homedir as homedir6 } from "os";
25392
+ import { basename as basename4, join as join15 } from "path";
24930
25393
  import yaml3 from "js-yaml";
24931
25394
 
24932
25395
  // ../api/src/claude/skills.ts
24933
- import { existsSync as existsSync12, readdirSync as readdirSync3, readFileSync as readFileSync10, statSync as statSync5 } from "fs";
24934
- import { homedir as homedir4 } from "os";
24935
- import { basename as basename2, dirname as dirname2, join as join12 } from "path";
25396
+ import { existsSync as existsSync14, readdirSync as readdirSync4, readFileSync as readFileSync12, statSync as statSync5 } from "fs";
25397
+ import { homedir as homedir5 } from "os";
25398
+ import { basename as basename3, dirname as dirname3, join as join14 } from "path";
24936
25399
  import yaml2 from "js-yaml";
24937
25400
 
24938
25401
  // ../api/src/claude/skill-files.ts
24939
25402
  import {
24940
- existsSync as existsSync11,
24941
- mkdirSync as mkdirSync8,
24942
- readFileSync as readFileSync9,
24943
- readdirSync as readdirSync2,
24944
- rmSync as rmSync7,
25403
+ existsSync as existsSync13,
25404
+ mkdirSync as mkdirSync9,
25405
+ readFileSync as readFileSync11,
25406
+ readdirSync as readdirSync3,
25407
+ rmSync as rmSync9,
24945
25408
  statSync as statSync4,
24946
- writeFileSync as writeFileSync6
25409
+ writeFileSync as writeFileSync8
24947
25410
  } from "fs";
24948
- import { homedir as homedir3 } from "os";
24949
- import { join as join11, resolve as resolve5, sep as sep2 } from "path";
25411
+ import { homedir as homedir4 } from "os";
25412
+ import { join as join13, resolve as resolve5, sep as sep2 } from "path";
24950
25413
  import yaml from "js-yaml";
24951
25414
  var MAX_SKILL_BYTES = 2 * 1024 * 1024;
24952
25415
  var SKILL_NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
24953
25416
  function expandHome(p) {
24954
- if (p === "~") return homedir3();
24955
- if (p.startsWith("~/")) return join11(homedir3(), p.slice(2));
25417
+ if (p === "~") return homedir4();
25418
+ if (p.startsWith("~/")) return join13(homedir4(), p.slice(2));
24956
25419
  return p;
24957
25420
  }
24958
25421
  function workspaceSkillsDir(configDir) {
24959
- return join11(configDir ? expandHome(configDir) : join11(homedir3(), ".claude"), "skills");
25422
+ return join13(configDir ? expandHome(configDir) : join13(homedir4(), ".claude"), "skills");
24960
25423
  }
24961
25424
  function channelSkillsDir(cwd) {
24962
- return join11(cwd, ".claude", "skills");
25425
+ return join13(cwd, ".claude", "skills");
24963
25426
  }
24964
25427
  function isValidSkillName(name) {
24965
25428
  return SKILL_NAME.test(name);
@@ -24994,7 +25457,7 @@ ${body.replace(/^\n+/, "").trimEnd()}
24994
25457
  }
24995
25458
  function readMeta(abs) {
24996
25459
  try {
24997
- const { fm } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25460
+ const { fm } = splitFrontmatter(readFileSync11(abs, "utf-8"));
24998
25461
  return {
24999
25462
  name: typeof fm["name"] === "string" ? fm["name"] : void 0,
25000
25463
  description: typeof fm["description"] === "string" ? fm["description"] : void 0
@@ -25004,17 +25467,17 @@ function readMeta(abs) {
25004
25467
  }
25005
25468
  }
25006
25469
  function listSkillFiles(dir) {
25007
- if (!existsSync11(dir)) return [];
25470
+ if (!existsSync13(dir)) return [];
25008
25471
  let entries2;
25009
25472
  try {
25010
- entries2 = readdirSync2(dir);
25473
+ entries2 = readdirSync3(dir);
25011
25474
  } catch {
25012
25475
  return [];
25013
25476
  }
25014
25477
  const rows2 = [];
25015
25478
  for (const entry of entries2) {
25016
25479
  if (!isValidSkillName(entry)) continue;
25017
- const abs = join11(dir, entry, "SKILL.md");
25480
+ const abs = join13(dir, entry, "SKILL.md");
25018
25481
  let stat;
25019
25482
  try {
25020
25483
  stat = statSync4(abs);
@@ -25043,7 +25506,7 @@ function readSkillFile(dir, name) {
25043
25506
  return null;
25044
25507
  }
25045
25508
  if (!stat.isFile() || stat.size > MAX_SKILL_BYTES) return null;
25046
- const { fm, body } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25509
+ const { fm, body } = splitFrontmatter(readFileSync11(abs, "utf-8"));
25047
25510
  return {
25048
25511
  name,
25049
25512
  description: typeof fm["description"] === "string" ? fm["description"].trim() : "",
@@ -25065,18 +25528,18 @@ function writeSkillFile(dir, name, patch, baseMtime) {
25065
25528
  if (baseMtime && stat.mtime.toISOString() !== baseMtime) {
25066
25529
  return { status: "conflict", mtime: stat.mtime.toISOString() };
25067
25530
  }
25068
- const { fm } = splitFrontmatter(readFileSync9(abs, "utf-8"));
25531
+ const { fm } = splitFrontmatter(readFileSync11(abs, "utf-8"));
25069
25532
  const content = buildSkillFile({ ...fm, name, description: patch.description }, patch.body);
25070
25533
  if (Buffer.byteLength(content, "utf8") > MAX_SKILL_BYTES) return { status: "too-large" };
25071
- writeFileSync6(abs, content, "utf8");
25534
+ writeFileSync8(abs, content, "utf8");
25072
25535
  return { status: "ok", mtime: statSync4(abs).mtime.toISOString() };
25073
25536
  }
25074
25537
  function createSkillFile(dir, name, description) {
25075
25538
  const abs = resolveSkillPath(dir, name);
25076
25539
  if (!abs) return { status: "bad-name" };
25077
- if (existsSync11(abs)) return { status: "exists" };
25078
- mkdirSync8(join11(dir, name), { recursive: true });
25079
- writeFileSync6(
25540
+ if (existsSync13(abs)) return { status: "exists" };
25541
+ mkdirSync9(join13(dir, name), { recursive: true });
25542
+ writeFileSync8(
25080
25543
  abs,
25081
25544
  buildSkillFile(
25082
25545
  { name, description },
@@ -25092,24 +25555,24 @@ Describe what this skill does and when to use it.
25092
25555
  }
25093
25556
  function deleteSkillFile(dir, name) {
25094
25557
  const abs = resolveSkillPath(dir, name);
25095
- if (!abs || !existsSync11(abs)) return { status: "not-found" };
25096
- rmSync7(join11(dir, name), { recursive: true, force: true });
25558
+ if (!abs || !existsSync13(abs)) return { status: "not-found" };
25559
+ rmSync9(join13(dir, name), { recursive: true, force: true });
25097
25560
  return { status: "ok" };
25098
25561
  }
25099
25562
 
25100
25563
  // ../api/src/claude/skills.ts
25101
25564
  function defaultConfigDir() {
25102
- return join12(homedir4(), ".claude");
25565
+ return join14(homedir5(), ".claude");
25103
25566
  }
25104
25567
  function expandHome2(p) {
25105
- if (p === "~") return homedir4();
25106
- if (p.startsWith("~/")) return join12(homedir4(), p.slice(2));
25568
+ if (p === "~") return homedir5();
25569
+ if (p.startsWith("~/")) return join14(homedir5(), p.slice(2));
25107
25570
  return p;
25108
25571
  }
25109
25572
  function parseFrontmatter(file) {
25110
25573
  let content;
25111
25574
  try {
25112
- content = readFileSync10(file, "utf-8");
25575
+ content = readFileSync12(file, "utf-8");
25113
25576
  } catch {
25114
25577
  return {};
25115
25578
  }
@@ -25127,39 +25590,39 @@ function parseFrontmatter(file) {
25127
25590
  function isSymlinkedDir(root, entry) {
25128
25591
  if (!entry.isSymbolicLink()) return false;
25129
25592
  try {
25130
- return statSync5(join12(root, entry.name)).isDirectory();
25593
+ return statSync5(join14(root, entry.name)).isDirectory();
25131
25594
  } catch {
25132
25595
  return false;
25133
25596
  }
25134
25597
  }
25135
25598
  function findSkillFiles(root, maxDepth, out) {
25136
- if (maxDepth < 0 || !existsSync12(root)) return;
25599
+ if (maxDepth < 0 || !existsSync14(root)) return;
25137
25600
  let entries2;
25138
25601
  try {
25139
- entries2 = readdirSync3(root, { withFileTypes: true });
25602
+ entries2 = readdirSync4(root, { withFileTypes: true });
25140
25603
  } catch {
25141
25604
  return;
25142
25605
  }
25143
25606
  for (const entry of entries2) {
25144
25607
  if (entry.isFile()) {
25145
- if (entry.name === "SKILL.md") out.push(join12(root, entry.name));
25608
+ if (entry.name === "SKILL.md") out.push(join14(root, entry.name));
25146
25609
  } else if (entry.isDirectory() || isSymlinkedDir(root, entry)) {
25147
25610
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
25148
- findSkillFiles(join12(root, entry.name), maxDepth - 1, out);
25611
+ findSkillFiles(join14(root, entry.name), maxDepth - 1, out);
25149
25612
  }
25150
25613
  }
25151
25614
  }
25152
25615
  function pluginNameFor(file, root) {
25153
- let dir = dirname2(file);
25154
- while (dir.startsWith(root) && dir !== dirname2(dir)) {
25616
+ let dir = dirname3(file);
25617
+ while (dir.startsWith(root) && dir !== dirname3(dir)) {
25155
25618
  try {
25156
25619
  const manifest = JSON.parse(
25157
- readFileSync10(join12(dir, ".claude-plugin", "plugin.json"), "utf-8")
25620
+ readFileSync12(join14(dir, ".claude-plugin", "plugin.json"), "utf-8")
25158
25621
  );
25159
25622
  if (typeof manifest.name === "string" && manifest.name.trim()) return manifest.name.trim();
25160
25623
  } catch {
25161
25624
  }
25162
- dir = dirname2(dir);
25625
+ dir = dirname3(dir);
25163
25626
  }
25164
25627
  return void 0;
25165
25628
  }
@@ -25169,29 +25632,29 @@ function findPluginMarkdown(pluginsRoot, dirName, maxDepth = 8) {
25169
25632
  if (depth < 0) return;
25170
25633
  let entries2;
25171
25634
  try {
25172
- entries2 = readdirSync3(dir, { withFileTypes: true });
25635
+ entries2 = readdirSync4(dir, { withFileTypes: true });
25173
25636
  } catch {
25174
25637
  return;
25175
25638
  }
25176
25639
  for (const entry of entries2) {
25177
25640
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
25178
25641
  if (!entry.isDirectory() && !isSymlinkedDir(dir, entry)) continue;
25179
- const child = join12(dir, entry.name);
25642
+ const child = join14(dir, entry.name);
25180
25643
  if (entry.name === dirName) {
25181
25644
  for (const f of readdirSafe(child)) {
25182
- if (f.endsWith(".md")) out.push({ file: join12(child, f), plugin: pluginNameFor(join12(child, f), pluginsRoot) });
25645
+ if (f.endsWith(".md")) out.push({ file: join14(child, f), plugin: pluginNameFor(join14(child, f), pluginsRoot) });
25183
25646
  }
25184
25647
  } else {
25185
25648
  walk(child, depth - 1);
25186
25649
  }
25187
25650
  }
25188
25651
  };
25189
- if (existsSync12(pluginsRoot)) walk(pluginsRoot, maxDepth);
25652
+ if (existsSync14(pluginsRoot)) walk(pluginsRoot, maxDepth);
25190
25653
  return out;
25191
25654
  }
25192
25655
  function readdirSafe(dir) {
25193
25656
  try {
25194
- return readdirSync3(dir);
25657
+ return readdirSync4(dir);
25195
25658
  } catch {
25196
25659
  return [];
25197
25660
  }
@@ -25199,16 +25662,16 @@ function readdirSafe(dir) {
25199
25662
  function listCommands(configDir, cwd) {
25200
25663
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25201
25664
  const local = (dir, source) => readdirSafe(dir).filter((f) => f.endsWith(".md")).map((f) => ({
25202
- name: basename2(f, ".md"),
25203
- description: (parseFrontmatter(join12(dir, f)).description ?? "").trim(),
25665
+ name: basename3(f, ".md"),
25666
+ description: (parseFrontmatter(join14(dir, f)).description ?? "").trim(),
25204
25667
  source,
25205
25668
  kind: "command"
25206
25669
  }));
25207
25670
  const collected = [
25208
- ...local(join12(cwd, ".claude", "commands"), "project"),
25209
- ...local(join12(base, "commands"), "user"),
25210
- ...findPluginMarkdown(join12(base, "plugins"), "commands").map(({ file, plugin }) => ({
25211
- name: plugin ? `${plugin}:${basename2(file, ".md")}` : basename2(file, ".md"),
25671
+ ...local(join14(cwd, ".claude", "commands"), "project"),
25672
+ ...local(join14(base, "commands"), "user"),
25673
+ ...findPluginMarkdown(join14(base, "plugins"), "commands").map(({ file, plugin }) => ({
25674
+ name: plugin ? `${plugin}:${basename3(file, ".md")}` : basename3(file, ".md"),
25212
25675
  description: (parseFrontmatter(file).description ?? "").trim(),
25213
25676
  source: "plugin",
25214
25677
  ...plugin && { plugin },
@@ -25229,7 +25692,7 @@ function collectFrom(root, source, maxDepth, namePrefix) {
25229
25692
  findSkillFiles(root, maxDepth, files);
25230
25693
  return files.map((file) => {
25231
25694
  const fm = parseFrontmatter(file);
25232
- const name = fm.name?.trim() || basename2(dirname2(file));
25695
+ const name = fm.name?.trim() || basename3(dirname3(file));
25233
25696
  const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25234
25697
  const prefix = namePrefix ?? plugin;
25235
25698
  return {
@@ -25245,10 +25708,10 @@ function collectFrom(root, source, maxDepth, namePrefix) {
25245
25708
  function collectAll(configDir, cwd) {
25246
25709
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25247
25710
  const collected = [
25248
- ...collectFrom(join12(cwd, ".claude", "skills"), "project", 2),
25711
+ ...collectFrom(join14(cwd, ".claude", "skills"), "project", 2),
25249
25712
  ...nestedProjectRoots(cwd).flatMap(({ dir, prefix }) => collectFrom(dir, "project", 2, prefix)),
25250
- ...collectFrom(join12(base, "skills"), "user", 2),
25251
- ...collectFrom(join12(base, "plugins"), "plugin", 8)
25713
+ ...collectFrom(join14(base, "skills"), "user", 2),
25714
+ ...collectFrom(join14(base, "plugins"), "plugin", 8)
25252
25715
  ];
25253
25716
  const byName = /* @__PURE__ */ new Map();
25254
25717
  for (const skill of collected) {
@@ -25259,7 +25722,7 @@ function collectAll(configDir, cwd) {
25259
25722
  function nestedProjectRoots(cwd) {
25260
25723
  let entries2;
25261
25724
  try {
25262
- entries2 = readdirSync3(cwd, { withFileTypes: true });
25725
+ entries2 = readdirSync4(cwd, { withFileTypes: true });
25263
25726
  } catch {
25264
25727
  return [];
25265
25728
  }
@@ -25267,8 +25730,8 @@ function nestedProjectRoots(cwd) {
25267
25730
  for (const entry of entries2) {
25268
25731
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
25269
25732
  if (!entry.isDirectory() && !isSymlinkedDir(cwd, entry)) continue;
25270
- const skillsDir = join12(cwd, entry.name, ".claude", "skills");
25271
- if (existsSync12(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
25733
+ const skillsDir = join14(cwd, entry.name, ".claude", "skills");
25734
+ if (existsSync14(skillsDir)) roots.push({ dir: skillsDir, prefix: entry.name });
25272
25735
  }
25273
25736
  return roots;
25274
25737
  }
@@ -25280,7 +25743,7 @@ function listPluginSkillDetails(configDir, cwd) {
25280
25743
  for (const { file, ...skill } of collectAll(configDir, cwd)) {
25281
25744
  if (skill.source !== "plugin") continue;
25282
25745
  try {
25283
- const { body } = splitFrontmatter(readFileSync10(file, "utf-8"));
25746
+ const { body } = splitFrontmatter(readFileSync12(file, "utf-8"));
25284
25747
  details.push({ ...skill, body, path: file, mtime: statSync5(file).mtime.toISOString() });
25285
25748
  } catch {
25286
25749
  }
@@ -25290,15 +25753,15 @@ function listPluginSkillDetails(configDir, cwd) {
25290
25753
  function findSkillDetail(configDir, cwd, name, sources) {
25291
25754
  const base = configDir ? expandHome2(configDir) : defaultConfigDir();
25292
25755
  const roots = [
25293
- [join12(cwd, ".claude", "skills"), "project", 2],
25756
+ [join14(cwd, ".claude", "skills"), "project", 2],
25294
25757
  ...nestedProjectRoots(cwd).map(({ dir, prefix }) => [
25295
25758
  dir,
25296
25759
  "project",
25297
25760
  2,
25298
25761
  prefix
25299
25762
  ]),
25300
- [join12(base, "skills"), "user", 2],
25301
- [join12(base, "plugins"), "plugin", 8]
25763
+ [join14(base, "skills"), "user", 2],
25764
+ [join14(base, "plugins"), "plugin", 8]
25302
25765
  ];
25303
25766
  for (const [root, source, maxDepth, namePrefix] of roots) {
25304
25767
  if (!sources.includes(source)) continue;
@@ -25306,7 +25769,7 @@ function findSkillDetail(configDir, cwd, name, sources) {
25306
25769
  findSkillFiles(root, maxDepth, files);
25307
25770
  for (const file of files) {
25308
25771
  const fm = parseFrontmatter(file);
25309
- const rawName = fm.name?.trim() || basename2(dirname2(file));
25772
+ const rawName = fm.name?.trim() || basename3(dirname3(file));
25310
25773
  const plugin = source === "plugin" ? pluginNameFor(file, root) : void 0;
25311
25774
  const prefix = namePrefix ?? plugin;
25312
25775
  const skillName = prefix ? `${prefix}:${rawName}` : rawName;
@@ -25314,7 +25777,7 @@ function findSkillDetail(configDir, cwd, name, sources) {
25314
25777
  let raw;
25315
25778
  let mtime;
25316
25779
  try {
25317
- raw = readFileSync10(file, "utf-8");
25780
+ raw = readFileSync12(file, "utf-8");
25318
25781
  mtime = statSync5(file).mtime.toISOString();
25319
25782
  } catch {
25320
25783
  continue;
@@ -25342,24 +25805,24 @@ function expandSkillCommand(configDir, cwd, text) {
25342
25805
  const body = skill.body.includes("$ARGUMENTS") ? skill.body.replaceAll("$ARGUMENTS", args) : skill.body + (args ? `
25343
25806
 
25344
25807
  ARGUMENTS: ${args}` : "");
25345
- return `[the user ran the /${skill.name} skill; its instructions follow. Base directory for this skill: ${dirname2(skill.path)}]
25808
+ return `[the user ran the /${skill.name} skill; its instructions follow. Base directory for this skill: ${dirname3(skill.path)}]
25346
25809
 
25347
25810
  ${body.trim()}`;
25348
25811
  }
25349
25812
 
25350
25813
  // src/claude/agents.ts
25351
25814
  function defaultConfigDir2() {
25352
- return join13(homedir5(), ".claude");
25815
+ return join15(homedir6(), ".claude");
25353
25816
  }
25354
25817
  function expandHome3(p) {
25355
- if (p === "~") return homedir5();
25356
- if (p.startsWith("~/")) return join13(homedir5(), p.slice(2));
25818
+ if (p === "~") return homedir6();
25819
+ if (p.startsWith("~/")) return join15(homedir6(), p.slice(2));
25357
25820
  return p;
25358
25821
  }
25359
25822
  function parseFrontmatter2(file) {
25360
25823
  let content;
25361
25824
  try {
25362
- content = readFileSync11(file, "utf-8");
25825
+ content = readFileSync13(file, "utf-8");
25363
25826
  } catch {
25364
25827
  return {};
25365
25828
  }
@@ -25375,29 +25838,29 @@ function parseFrontmatter2(file) {
25375
25838
  }
25376
25839
  }
25377
25840
  function collectFrom2(root, source) {
25378
- if (!existsSync13(root)) return [];
25841
+ if (!existsSync15(root)) return [];
25379
25842
  let entries2;
25380
25843
  try {
25381
- entries2 = readdirSync4(root).filter((f) => f.endsWith(".md"));
25844
+ entries2 = readdirSync5(root).filter((f) => f.endsWith(".md"));
25382
25845
  } catch {
25383
25846
  return [];
25384
25847
  }
25385
25848
  return entries2.map((file) => {
25386
- const path = join13(root, file);
25849
+ const path = join15(root, file);
25387
25850
  const fm = parseFrontmatter2(path);
25388
- const name = fm.name?.trim() || basename3(file, ".md");
25851
+ const name = fm.name?.trim() || basename4(file, ".md");
25389
25852
  return { name, description: (fm.description ?? "").trim(), source, path };
25390
25853
  });
25391
25854
  }
25392
25855
  function listAgents(configDir, cwd) {
25393
25856
  const base = configDir ? expandHome3(configDir) : defaultConfigDir2();
25394
25857
  const collected = [
25395
- ...collectFrom2(join13(cwd, ".claude", "agents"), "project"),
25396
- ...collectFrom2(join13(base, "agents"), "user"),
25858
+ ...collectFrom2(join15(cwd, ".claude", "agents"), "project"),
25859
+ ...collectFrom2(join15(base, "agents"), "user"),
25397
25860
  // Plugin agents, namespaced `plugin:agent` the way the CLI lists them.
25398
- ...findPluginMarkdown(join13(base, "plugins"), "agents").map(({ file, plugin }) => {
25861
+ ...findPluginMarkdown(join15(base, "plugins"), "agents").map(({ file, plugin }) => {
25399
25862
  const fm = parseFrontmatter2(file);
25400
- const name = fm.name?.trim() || basename3(file, ".md");
25863
+ const name = fm.name?.trim() || basename4(file, ".md");
25401
25864
  return {
25402
25865
  name: plugin ? `${plugin}:${name}` : name,
25403
25866
  description: (fm.description ?? "").trim(),
@@ -25416,7 +25879,7 @@ function readAgentPersona(configDir, cwd, name) {
25416
25879
  const agent = listAgents(configDir, cwd).find((a) => a.name === name);
25417
25880
  if (!agent) return void 0;
25418
25881
  try {
25419
- const content = readFileSync11(agent.path, "utf-8");
25882
+ const content = readFileSync13(agent.path, "utf-8");
25420
25883
  return content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim();
25421
25884
  } catch {
25422
25885
  return void 0;
@@ -25425,13 +25888,13 @@ function readAgentPersona(configDir, cwd, name) {
25425
25888
 
25426
25889
  // src/dashboard/memory-extraction-runner.ts
25427
25890
  import { spawn as spawn4 } from "child_process";
25428
- import { existsSync as existsSync14, mkdtempSync as mkdtempSync4, readFileSync as readFileSync12, rmSync as rmSync8 } from "fs";
25891
+ import { existsSync as existsSync16, mkdtempSync as mkdtempSync5, readFileSync as readFileSync14, rmSync as rmSync10 } from "fs";
25429
25892
  import { tmpdir as tmpdir4 } from "os";
25430
- import { join as join15 } from "path";
25893
+ import { join as join17 } from "path";
25431
25894
 
25432
25895
  // ../api/src/dashboard/profile-config.ts
25433
- import { homedir as homedir6 } from "os";
25434
- import { join as join14, parse, resolve as resolve6 } from "path";
25896
+ import { homedir as homedir7 } from "os";
25897
+ import { join as join16, parse, resolve as resolve6 } from "path";
25435
25898
 
25436
25899
  // ../api/src/dashboard/profile-config-cache.ts
25437
25900
  var cache3 = /* @__PURE__ */ new Map();
@@ -25450,7 +25913,7 @@ function profileEnv(key) {
25450
25913
  function profileClaudeConfigDir() {
25451
25914
  const config = cachedProfileConfig();
25452
25915
  if (!config) return process.env["CLAUDE_CONFIG_DIR"] || void 0;
25453
- return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join14(homedir6(), ".claude");
25916
+ return config.env["CLAUDE_CONFIG_DIR"]?.trim() || join16(homedir7(), ".claude");
25454
25917
  }
25455
25918
  function profileOauthToken() {
25456
25919
  const env = cachedProfileConfig()?.env ?? {};
@@ -25460,7 +25923,7 @@ function profileOauthToken() {
25460
25923
  }
25461
25924
  function isUnsafeCwd(cwd) {
25462
25925
  const p = resolve6(cwd);
25463
- return p === parse(p).root || p === resolve6(homedir6());
25926
+ return p === parse(p).root || p === resolve6(homedir7());
25464
25927
  }
25465
25928
  function defaultClaudeCwd() {
25466
25929
  return profileEnv("CLAUDE_CWD") ?? process.cwd();
@@ -25511,7 +25974,7 @@ var SUGGEST_TOOLS = "Read,Glob,Grep";
25511
25974
  function buildInvocation(runner, req, dir, auth, baseEnv = process.env, tools = "") {
25512
25975
  const env = { ...baseEnv, CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" };
25513
25976
  if (runner === "codex") {
25514
- const outputFile = join15(dir, "last-message.txt");
25977
+ const outputFile = join17(dir, "last-message.txt");
25515
25978
  return {
25516
25979
  command: "codex",
25517
25980
  args: [
@@ -25567,7 +26030,7 @@ ${req.user}`,
25567
26030
  }
25568
26031
  function run(inv, cwd) {
25569
26032
  return new Promise((resolve8) => {
25570
- if (!existsSync14(cwd)) {
26033
+ if (!existsSync16(cwd)) {
25571
26034
  resolve8({ ok: false, error: `the channel folder ${cwd} does not exist on this Host` });
25572
26035
  return;
25573
26036
  }
@@ -25600,7 +26063,7 @@ function run(inv, cwd) {
25600
26063
  let raw = stdout;
25601
26064
  if (inv.outputFile) {
25602
26065
  try {
25603
- raw = readFileSync12(inv.outputFile, "utf-8");
26066
+ raw = readFileSync14(inv.outputFile, "utf-8");
25604
26067
  } catch {
25605
26068
  raw = "";
25606
26069
  }
@@ -25613,7 +26076,7 @@ function run(inv, cwd) {
25613
26076
  async function complete(req, tools = "", cwd) {
25614
26077
  const runner = runnerForModel(loadDashboardSettings().agent);
25615
26078
  const config = resolveChannelConfig(req.channelId);
25616
- const dir = mkdtempSync4(join15(tmpdir4(), "flyspace-memory-"));
26079
+ const dir = mkdtempSync5(join17(tmpdir4(), "flyspace-memory-"));
25617
26080
  try {
25618
26081
  const inv = buildInvocation(
25619
26082
  runner,
@@ -25628,7 +26091,7 @@ async function complete(req, tools = "", cwd) {
25628
26091
  );
25629
26092
  return await run(inv, cwd ?? dir);
25630
26093
  } finally {
25631
- rmSync8(dir, { recursive: true, force: true });
26094
+ rmSync10(dir, { recursive: true, force: true });
25632
26095
  }
25633
26096
  }
25634
26097
  function completeMemoryExtraction(req) {
@@ -26328,9 +26791,9 @@ var UsageStore = class {
26328
26791
 
26329
26792
  // src/dashboard/rollover-summary.ts
26330
26793
  import { spawn as spawn5 } from "child_process";
26331
- import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync13, rmSync as rmSync9 } from "fs";
26794
+ import { existsSync as existsSync17, mkdtempSync as mkdtempSync6, readFileSync as readFileSync15, rmSync as rmSync11 } from "fs";
26332
26795
  import { tmpdir as tmpdir5 } from "os";
26333
- import { join as join16 } from "path";
26796
+ import { join as join18 } from "path";
26334
26797
  var HAIKU_MODEL = "haiku";
26335
26798
  var CJK_PATTERN = /[ -〿぀-ヿ㐀-䶿一-鿿豈-﫿＀-￯]/;
26336
26799
  function estimateTokens(text) {
@@ -26393,8 +26856,8 @@ function runSummaryPrint(input, options) {
26393
26856
  return runPrint("claude", args, env).then((out) => out.trim());
26394
26857
  }
26395
26858
  async function runCodexSummary(input) {
26396
- const dir = mkdtempSync5(join16(tmpdir5(), "rollover-"));
26397
- const lastMessageFile = join16(dir, "last-message.txt");
26859
+ const dir = mkdtempSync6(join18(tmpdir5(), "rollover-"));
26860
+ const lastMessageFile = join18(dir, "last-message.txt");
26398
26861
  try {
26399
26862
  await runPrint(
26400
26863
  "codex",
@@ -26417,9 +26880,9 @@ ${input}`
26417
26880
  ],
26418
26881
  { ...process.env }
26419
26882
  );
26420
- return existsSync15(lastMessageFile) ? readFileSync13(lastMessageFile, "utf8").trim() : "";
26883
+ return existsSync17(lastMessageFile) ? readFileSync15(lastMessageFile, "utf8").trim() : "";
26421
26884
  } finally {
26422
- rmSync9(dir, { recursive: true, force: true });
26885
+ rmSync11(dir, { recursive: true, force: true });
26423
26886
  }
26424
26887
  }
26425
26888
  function runPrint(command, args, env) {
@@ -26659,7 +27122,7 @@ async function scanBackgroundTasks() {
26659
27122
 
26660
27123
  // src/dashboard/attachment-downloader.ts
26661
27124
  import { writeFile as writeFile2 } from "fs/promises";
26662
- import { join as join17 } from "path";
27125
+ import { join as join19 } from "path";
26663
27126
  import { GetObjectCommand } from "@aws-sdk/client-s3";
26664
27127
  var debug4 = process.env["DEBUG"] === "true";
26665
27128
  var ATTACHMENT_LINK = /\]\((?:https:\/\/[a-z0-9-]+\.flyspace\.ai)?\/api\/attachments\/([^)?\s]+)(?:\?[^)\s]*)?\)/g;
@@ -26726,7 +27189,7 @@ async function downloadOne2(key) {
26726
27189
  if (bytes.length > sizeLimit) {
26727
27190
  return { kind: "skip", skipped: { name, mimetype, reason: "too_large" } };
26728
27191
  }
26729
- const localPath = join17(paths.UPLOADS_DIR, lastSegment);
27192
+ const localPath = join19(paths.UPLOADS_DIR, lastSegment);
26730
27193
  await writeFile2(localPath, bytes);
26731
27194
  if (debug4)
26732
27195
  console.log(`[attachment-downloader] saved ${key} -> ${localPath} (${bytes.length} bytes)`);
@@ -26750,28 +27213,63 @@ async function downloadChatAttachments(body) {
26750
27213
  return { succeeded, skipped };
26751
27214
  }
26752
27215
 
27216
+ // src/dashboard/plugin-ui-store.ts
27217
+ import { createHash as createHash5 } from "crypto";
27218
+ var INLINE_MAX = 2048;
27219
+ var uploaded = /* @__PURE__ */ new Map();
27220
+ var sha256 = (s) => createHash5("sha256").update(s).digest("hex");
27221
+ async function offloadSvg(workspace, source) {
27222
+ const cacheKey2 = `${workspace}:${sha256(source)}`;
27223
+ const cached = uploaded.get(cacheKey2);
27224
+ if (cached) return cached;
27225
+ const url = await requestPluginSvg(workspace, source);
27226
+ if (url) uploaded.set(cacheKey2, url);
27227
+ return url;
27228
+ }
27229
+ async function offloadNode(workspace, node) {
27230
+ const children = node.children ? await Promise.all(node.children.map((c) => typeof c === "string" ? c : offloadNode(workspace, c))) : void 0;
27231
+ const source = node.props?.["source"];
27232
+ if (node.type !== "Svg" || typeof source !== "string" || source.length <= INLINE_MAX) {
27233
+ return children ? { ...node, children } : node;
27234
+ }
27235
+ const src = await offloadSvg(workspace, source).catch((err) => {
27236
+ console.error(`[plugin-ui-store] SVG upload failed: ${err.message}`);
27237
+ return null;
27238
+ });
27239
+ if (!src) return children ? { ...node, children } : node;
27240
+ const { source: _, ...props } = node.props;
27241
+ return { ...node, props: { ...props, src }, ...children ? { children } : {} };
27242
+ }
27243
+ async function offloadPluginUi(workspace, state) {
27244
+ const panes = await Promise.all(
27245
+ state.panes.map(async (p) => p.tree ? { ...p, tree: await offloadNode(workspace, p.tree) } : p)
27246
+ );
27247
+ return { ...state, panes };
27248
+ }
27249
+ var pluginUiHash = (state) => sha256(JSON.stringify(state));
27250
+
26753
27251
  // src/dashboard/doc-mention-guard.ts
26754
- import { existsSync as existsSync20, statSync as statSync8 } from "fs";
27252
+ import { existsSync as existsSync22, statSync as statSync8 } from "fs";
26755
27253
 
26756
27254
  // src/dashboard/docs-routes.ts
26757
27255
  import {
26758
27256
  closeSync,
26759
27257
  createReadStream,
26760
- existsSync as existsSync19,
27258
+ existsSync as existsSync21,
26761
27259
  lstatSync as lstatSync2,
26762
- mkdirSync as mkdirSync9,
27260
+ mkdirSync as mkdirSync10,
26763
27261
  openSync,
26764
27262
  readSync,
26765
- readdirSync as readdirSync5,
26766
- readFileSync as readFileSync17,
27263
+ readdirSync as readdirSync6,
27264
+ readFileSync as readFileSync19,
26767
27265
  realpathSync,
26768
- renameSync as renameSync2,
26769
- rmSync as rmSync10,
27266
+ renameSync as renameSync3,
27267
+ rmSync as rmSync12,
26770
27268
  statSync as statSync7,
26771
- writeFileSync as writeFileSync7
27269
+ writeFileSync as writeFileSync9
26772
27270
  } from "fs";
26773
27271
  import { Readable } from "stream";
26774
- import { basename as basename5, dirname as dirname3, extname as extname2, join as join21, relative, resolve as resolve7, sep as sep3 } from "path";
27272
+ import { basename as basename6, dirname as dirname4, extname as extname2, join as join23, relative, resolve as resolve7, sep as sep3 } from "path";
26775
27273
  import { Hono as Hono4 } from "hono";
26776
27274
  import { streamSSE } from "hono/streaming";
26777
27275
 
@@ -26883,8 +27381,8 @@ var requireDocsAccess = async (c, next) => {
26883
27381
  };
26884
27382
 
26885
27383
  // src/dashboard/docs-watcher.ts
26886
- import { existsSync as existsSync16, watch } from "fs";
26887
- import { basename as basename4, join as join18 } from "path";
27384
+ import { existsSync as existsSync18, watch } from "fs";
27385
+ import { basename as basename5, join as join20 } from "path";
26888
27386
  var DEBOUNCE_MS = 200;
26889
27387
  var MAX_PENDING = 200;
26890
27388
  var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
@@ -26920,12 +27418,12 @@ function flush(cwd) {
26920
27418
  function watchDocs(cwd, listener) {
26921
27419
  let entry = entries.get(cwd);
26922
27420
  if (!entry) {
26923
- const root = basename4(cwd);
27421
+ const root = basename5(cwd);
26924
27422
  const watcher = watch(cwd, { recursive: true, persistent: false }, (_event, filename) => {
26925
27423
  const current = entries.get(cwd);
26926
27424
  if (!current || filename === null) return;
26927
27425
  const rel = filename.split("\\").join("/");
26928
- if (rel === root && !existsSync16(join18(cwd, rel))) return;
27426
+ if (rel === root && !existsSync18(join20(cwd, rel))) return;
26929
27427
  if (isIgnoredDocPath(rel)) return;
26930
27428
  if (current.pending.size < MAX_PENDING) current.pending.add(rel);
26931
27429
  if (current.timer === null) current.timer = setTimeout(() => flush(cwd), DEBOUNCE_MS);
@@ -26979,7 +27477,7 @@ async function putDocTranslation(input) {
26979
27477
  }
26980
27478
 
26981
27479
  // ../api/src/dashboard/share-translate.ts
26982
- import { createHash as createHash4 } from "crypto";
27480
+ import { createHash as createHash6 } from "crypto";
26983
27481
 
26984
27482
  // ../api/src/store/doc-share-store.ts
26985
27483
  function rowToKind(value) {
@@ -27289,7 +27787,7 @@ function languageName(lang) {
27289
27787
  return BY_CODE.get(lang)?.name ?? null;
27290
27788
  }
27291
27789
  function translationHash(title, content) {
27292
- return createHash4("sha256").update(`${RECIPE_VERSION}
27790
+ return createHash6("sha256").update(`${RECIPE_VERSION}
27293
27791
  ${title}
27294
27792
  ${content}`).digest("hex");
27295
27793
  }
@@ -27524,7 +28022,7 @@ async function clearStaleDocAudios(channelId, sourcePath, lang, exceptHash) {
27524
28022
  }
27525
28023
 
27526
28024
  // ../api/src/dashboard/share-audio.ts
27527
- import { createHash as createHash5 } from "crypto";
28025
+ import { createHash as createHash7 } from "crypto";
27528
28026
  import { DeleteObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-sdk/client-s3";
27529
28027
 
27530
28028
  // ../api/src/dashboard/tts-routes.ts
@@ -27723,7 +28221,7 @@ Pacing \u2014 the engine has NO pause control, so rhythm has to be built into th
27723
28221
  Output plain text ONLY. No tags of any kind, no angle brackets, no Markdown, no quotation wrapping. Any tag you emit will be deleted before synthesis, so it buys nothing and costs meaning.`;
27724
28222
  }
27725
28223
  function articleAudioHash(title, content) {
27726
- return createHash5("sha256").update(`v${RECIPE_VERSION2}
28224
+ return createHash7("sha256").update(`v${RECIPE_VERSION2}
27727
28225
  ${title}
27728
28226
 
27729
28227
  ${content}`).digest("hex").slice(0, 32);
@@ -27950,7 +28448,7 @@ function queueShareAudio(share) {
27950
28448
  var PENDING_STALE_MS = 30 * 60 * 1e3;
27951
28449
  var FAILED_RETRY_MS = 10 * 60 * 1e3;
27952
28450
  function langAudioHash(title, content, lang) {
27953
- return createHash5("sha256").update(`v${RECIPE_VERSION2}
28451
+ return createHash7("sha256").update(`v${RECIPE_VERSION2}
27954
28452
  ${lang}
27955
28453
  ${translationHash(title, content)}`).digest("hex").slice(0, 32);
27956
28454
  }
@@ -28237,8 +28735,8 @@ function createFeatureFlagsRouter() {
28237
28735
  }
28238
28736
 
28239
28737
  // ../api/src/dashboard/public-share-routes.ts
28240
- import { existsSync as existsSync18, readFileSync as readFileSync15, statSync as statSync6 } from "fs";
28241
- import { join as join20 } from "path";
28738
+ import { existsSync as existsSync20, readFileSync as readFileSync17, statSync as statSync6 } from "fs";
28739
+ import { join as join22 } from "path";
28242
28740
  import { Hono as Hono3 } from "hono";
28243
28741
  import { GetObjectCommand as GetObjectCommand3 } from "@aws-sdk/client-s3";
28244
28742
  import { getSignedUrl as getSignedUrl2 } from "@aws-sdk/s3-request-presigner";
@@ -28444,14 +28942,14 @@ function injectShareHead(html, head) {
28444
28942
  }
28445
28943
 
28446
28944
  // ../api/src/dashboard/app-icon.ts
28447
- import { createHash as createHash6 } from "crypto";
28448
- import { existsSync as existsSync17, readFileSync as readFileSync14 } from "fs";
28449
- import { join as join19 } from "path";
28450
- import sharp2 from "sharp";
28945
+ import { createHash as createHash8 } from "crypto";
28946
+ import { existsSync as existsSync19, readFileSync as readFileSync16 } from "fs";
28947
+ import { join as join21 } from "path";
28948
+ import sharp3 from "sharp";
28451
28949
  var PLATE = "#0A0A0F";
28452
- var BRAND_DIR = existsSync17(join19(paths.WEB_ROOT, "public")) ? join19(paths.WEB_ROOT, "public") : join19(paths.PACKAGE_ROOT, "dist", "brand");
28453
- var MARK_FILE = join19(BRAND_DIR, "icons", "icon-512.png");
28454
- var MARK_SVG_FILE = join19(BRAND_DIR, "favicon.svg");
28950
+ var BRAND_DIR = existsSync19(join21(paths.WEB_ROOT, "public")) ? join21(paths.WEB_ROOT, "public") : join21(paths.PACKAGE_ROOT, "dist", "brand");
28951
+ var MARK_FILE = join21(BRAND_DIR, "icons", "icon-512.png");
28952
+ var MARK_SVG_FILE = join21(BRAND_DIR, "favicon.svg");
28455
28953
  var LAYOUT = {
28456
28954
  standard: { logo: 0.7, logoCx: 0.5, logoCy: 0.48, badge: 0.27, badgeCx: 0.22, badgeCy: 0.76 },
28457
28955
  maskable: { logo: 0.56, logoCx: 0.5, logoCy: 0.48, badge: 0.23, badgeCx: 0.33, badgeCy: 0.66 }
@@ -28474,11 +28972,11 @@ function roundedPlate(size, fill = PLATE) {
28474
28972
  }
28475
28973
  async function renderBadge(box) {
28476
28974
  const transparent = { r: 0, g: 0, b: 0, alpha: 0 };
28477
- const raster = await sharp2(readFileSync14(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
28478
- return sharp2(raster).trim().resize(box, box, { fit: "contain", background: transparent }).png().toBuffer();
28975
+ const raster = await sharp3(readFileSync16(MARK_SVG_FILE)).resize(512, 512, { fit: "contain", background: transparent }).png().toBuffer();
28976
+ return sharp3(raster).trim().resize(box, box, { fit: "contain", background: transparent }).png().toBuffer();
28479
28977
  }
28480
28978
  async function sampleBackground(logo) {
28481
- const { data, info } = await sharp2(logo).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
28979
+ const { data, info } = await sharp3(logo).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
28482
28980
  const { width: w, height: h, channels } = info;
28483
28981
  const edge = 1;
28484
28982
  const samples = [
@@ -28523,13 +29021,13 @@ async function renderAppIcon({
28523
29021
  size,
28524
29022
  maskable ? "maskable" : "std",
28525
29023
  plain ? "plain" : "badged",
28526
- logo ? createHash6("sha1").update(logo).digest("hex").slice(0, 12) : transparent ? "stock-transparent" : "stock"
29024
+ logo ? createHash8("sha1").update(logo).digest("hex").slice(0, 12) : transparent ? "stock-transparent" : "stock"
28527
29025
  ].join(":");
28528
29026
  const hit = cache4.get(key);
28529
29027
  if (hit) return hit;
28530
29028
  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,
28531
29029
  // either on its usual dark plate or, for a favicon, trimmed and bare.
28532
- (transparent ? await renderBadge(size) : await sharp2(readFileSync14(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
29030
+ (transparent ? await renderBadge(size) : await sharp3(readFileSync16(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
28533
29031
  cache4.set(key, out);
28534
29032
  return out;
28535
29033
  }
@@ -28538,8 +29036,8 @@ async function composeIcon(logo, size, maskable, plain) {
28538
29036
  const plate = await sampleBackground(logo) ?? PLATE;
28539
29037
  const logoBox = Math.round(size * (plain ? PLAIN_LOGO : layout.logo));
28540
29038
  const badgeBox = Math.round(size * layout.badge);
28541
- const logoLayer = await sharp2(logo).resize(logoBox, logoBox, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } }).png().toBuffer();
28542
- const composed = await sharp2(roundedPlate(size, plate)).composite([
29039
+ const logoLayer = await sharp3(logo).resize(logoBox, logoBox, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } }).png().toBuffer();
29040
+ const composed = await sharp3(roundedPlate(size, plate)).composite([
28543
29041
  // Badge-less, the logo has the canvas to itself and sits dead centre;
28544
29042
  // otherwise it's nudged up to leave the badge its corner.
28545
29043
  { input: logoLayer, ...place(size, logoBox, layout.logoCx, plain ? 0.5 : layout.logoCy) },
@@ -28550,12 +29048,12 @@ async function composeIcon(logo, size, maskable, plain) {
28550
29048
  }
28551
29049
  ]
28552
29050
  ]).png().toBuffer();
28553
- return sharp2(composed).composite([{ input: roundedPlate(size), blend: "dest-in" }]).png().toBuffer();
29051
+ return sharp3(composed).composite([{ input: roundedPlate(size), blend: "dest-in" }]).png().toBuffer();
28554
29052
  }
28555
29053
 
28556
29054
  // ../api/src/dashboard/share-og.ts
28557
- import { createHash as createHash7 } from "crypto";
28558
- import sharp3 from "sharp";
29055
+ import { createHash as createHash9 } from "crypto";
29056
+ import sharp4 from "sharp";
28559
29057
  var WIDTH = 1200;
28560
29058
  var HEIGHT = 630;
28561
29059
  var PAD = 80;
@@ -28688,7 +29186,7 @@ function roundedMask(size, radius) {
28688
29186
  async function renderLogoChip(logo) {
28689
29187
  if (!logo) return null;
28690
29188
  try {
28691
- return await sharp3(logo).resize(LOGO_BOX, LOGO_BOX, { fit: "cover" }).composite([{ input: roundedMask(LOGO_BOX, LOGO_RADIUS), blend: "dest-in" }]).png().toBuffer();
29189
+ return await sharp4(logo).resize(LOGO_BOX, LOGO_BOX, { fit: "cover" }).composite([{ input: roundedMask(LOGO_BOX, LOGO_RADIUS), blend: "dest-in" }]).png().toBuffer();
28692
29190
  } catch {
28693
29191
  return null;
28694
29192
  }
@@ -28732,14 +29230,14 @@ function cacheKey(input) {
28732
29230
  input.logo ?? "",
28733
29231
  input.theme ?? ""
28734
29232
  ];
28735
- return createHash7("sha1").update(parts.join("\0")).digest("hex");
29233
+ return createHash9("sha1").update(parts.join("\0")).digest("hex");
28736
29234
  }
28737
29235
  async function renderShareOgImage(input) {
28738
29236
  const key = cacheKey(input);
28739
29237
  const hit = cache5.get(key);
28740
29238
  if (hit) return hit;
28741
29239
  const chip = input.workspaceName?.trim() ? await renderLogoChip(decodeLogo(input.logo)) : null;
28742
- const composed = sharp3(backdrop(input, !!chip));
29240
+ const composed = sharp4(backdrop(input, !!chip));
28743
29241
  const out = await (chip ? composed.composite([{ input: chip, left: PAD, top: LOGO_TOP }]) : composed).png({ compressionLevel: 9 }).toBuffer();
28744
29242
  if (cache5.size >= CACHE_MAX) cache5.delete(cache5.keys().next().value);
28745
29243
  cache5.set(key, out);
@@ -28747,7 +29245,7 @@ async function renderShareOgImage(input) {
28747
29245
  }
28748
29246
 
28749
29247
  // ../api/src/dashboard/share-ask.ts
28750
- import { createHash as createHash8 } from "crypto";
29248
+ import { createHash as createHash10 } from "crypto";
28751
29249
  var MAX_ARTICLE_CHARS3 = 24e3;
28752
29250
  var MAX_QUESTION_CHARS = 500;
28753
29251
  var SUGGESTION_COUNT = 4;
@@ -28812,7 +29310,7 @@ function parseSuggestions(raw) {
28812
29310
  var CACHE_LIMIT = 200;
28813
29311
  var suggestionCache = /* @__PURE__ */ new Map();
28814
29312
  function articleHash(title, content, lang) {
28815
- return createHash8("sha256").update(`${lang ?? ""}
29313
+ return createHash10("sha256").update(`${lang ?? ""}
28816
29314
  ${title}
28817
29315
 
28818
29316
  ${content}`).digest("hex").slice(0, 32);
@@ -29068,7 +29566,7 @@ var shellCache = null;
29068
29566
  function readShell(path) {
29069
29567
  const { mtimeMs } = statSync6(path);
29070
29568
  if (shellCache?.mtimeMs === mtimeMs) return shellCache.html;
29071
- const html = readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
29569
+ const html = readFileSync17(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`);
29072
29570
  shellCache = { mtimeMs, html };
29073
29571
  return html;
29074
29572
  }
@@ -29088,17 +29586,17 @@ function serveBuildFile(c, webDist, dir, name) {
29088
29586
  if (!type || !/^[A-Za-z0-9._-]+$/.test(name) || name.includes("..")) {
29089
29587
  return c.text("not found", 404);
29090
29588
  }
29091
- const path = join20(webDist, dir, name);
29092
- if (!existsSync18(path)) return c.text("not found", 404);
29589
+ const path = join22(webDist, dir, name);
29590
+ if (!existsSync20(path)) return c.text("not found", 404);
29093
29591
  c.header("Content-Type", type);
29094
29592
  c.header("Cache-Control", "public, max-age=31536000, immutable");
29095
29593
  if (ext === ".css") {
29096
- return c.body(readFileSync15(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
29594
+ return c.body(readFileSync17(path, "utf8").replaceAll("url(/fonts/", `url(${BUILD_PREFIX}/fonts/`));
29097
29595
  }
29098
29596
  if (ext === ".js") {
29099
- return c.body(readFileSync15(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
29597
+ return c.body(readFileSync17(path, "utf8").replaceAll('"/assets/', `"${BUILD_PREFIX}/`));
29100
29598
  }
29101
- return c.body(new Uint8Array(readFileSync15(path)));
29599
+ return c.body(new Uint8Array(readFileSync17(path)));
29102
29600
  }
29103
29601
  var HTML_SHARE_CSP = "sandbox allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox";
29104
29602
  function servePublishedHtml(c, share) {
@@ -29234,8 +29732,8 @@ ${analytics}` : head);
29234
29732
  const requested = c.req.param("lang");
29235
29733
  const lang = canonicalLanguage(requested);
29236
29734
  if (!isTranslatableLanguage(lang)) return next();
29237
- const shell = join20(webDist, "index.html");
29238
- if (!existsSync18(shell)) return next();
29735
+ const shell = join22(webDist, "index.html");
29736
+ if (!existsSync20(shell)) return next();
29239
29737
  const share = await getDocShare(c.req.param("id"));
29240
29738
  if (!share) return next();
29241
29739
  if (requested !== lang) return c.redirect(`/share/${share.id}/${lang}`, 302);
@@ -29270,8 +29768,8 @@ ${analytics}` : head);
29270
29768
  const share = await getDocShare(c.req.param("id"));
29271
29769
  if (!share) return next();
29272
29770
  if (share.kind === "html") return servePublishedHtml(c, share);
29273
- const shell = join20(webDist, "index.html");
29274
- if (!existsSync18(shell)) return next();
29771
+ const shell = join22(webDist, "index.html");
29772
+ if (!existsSync20(shell)) return next();
29275
29773
  return readerPage(
29276
29774
  c,
29277
29775
  share,
@@ -29296,7 +29794,7 @@ ${analytics}` : head);
29296
29794
  }
29297
29795
 
29298
29796
  // src/dashboard/artifact-export.ts
29299
- import { readFileSync as readFileSync16 } from "fs";
29797
+ import { readFileSync as readFileSync18 } from "fs";
29300
29798
  async function exportDocAsArtifact(channelId, docPath) {
29301
29799
  const owningProfile = findOwningProfile(channelId);
29302
29800
  const channelConfig = await runWithProfile(
@@ -29305,7 +29803,7 @@ async function exportDocAsArtifact(channelId, docPath) {
29305
29803
  );
29306
29804
  const abs = resolveDocPath(channelConfig.cwd, docPath);
29307
29805
  if (!abs) throw new Error(`doc not found: ${docPath}`);
29308
- const content = readFileSync16(abs, "utf8");
29806
+ const content = readFileSync18(abs, "utf8");
29309
29807
  const title = extractTitle(abs, "md");
29310
29808
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
29311
29809
  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).
@@ -29523,9 +30021,9 @@ function readHead(absPath) {
29523
30021
  }
29524
30022
  }
29525
30023
  function extractTitle(absPath, kind) {
29526
- if (kind === "url" || kind === "excalidraw") return basename5(absPath);
30024
+ if (kind === "url" || kind === "excalidraw") return basename6(absPath);
29527
30025
  const head = readHead(absPath);
29528
- if (!head) return basename5(absPath);
30026
+ if (!head) return basename6(absPath);
29529
30027
  if (kind === "md") {
29530
30028
  const m = head.match(/^#{1,3}\s+(.+?)\s*$/m);
29531
30029
  if (m) return m[1].replace(/[*_`]/g, "").trim();
@@ -29533,7 +30031,7 @@ function extractTitle(absPath, kind) {
29533
30031
  const t = head.match(/<title[^>]*>([^<]+)<\/title>/i) ?? head.match(/<h1[^>]*>([^<]+)<\/h1>/i);
29534
30032
  if (t) return t[1].trim();
29535
30033
  }
29536
- return basename5(absPath);
30034
+ return basename6(absPath);
29537
30035
  }
29538
30036
  function resolveDirPath(root, rel) {
29539
30037
  if (rel.includes("\0")) return null;
@@ -29554,7 +30052,7 @@ function probeDir(absDir, showHidden) {
29554
30052
  if (depth > MAX_SEARCH_DEPTH) return false;
29555
30053
  let entries2;
29556
30054
  try {
29557
- entries2 = readdirSync5(dir, { withFileTypes: true });
30055
+ entries2 = readdirSync6(dir, { withFileTypes: true });
29558
30056
  } catch {
29559
30057
  return false;
29560
30058
  }
@@ -29565,7 +30063,7 @@ function probeDir(absDir, showHidden) {
29565
30063
  return false;
29566
30064
  }
29567
30065
  if (!showHidden && entry.name.startsWith(".")) continue;
29568
- const abs = join21(dir, entry.name);
30066
+ const abs = join23(dir, entry.name);
29569
30067
  const kind = entryKind(entry, abs);
29570
30068
  if (kind === "dir") {
29571
30069
  if (SKIP_DIRS.has(entry.name)) hasOther = true;
@@ -29585,14 +30083,14 @@ function probeDir(absDir, showHidden) {
29585
30083
  }
29586
30084
  function readGitBranch(dir) {
29587
30085
  try {
29588
- let gitDir = join21(dir, ".git");
30086
+ let gitDir = join23(dir, ".git");
29589
30087
  if (statSync7(gitDir).isFile()) {
29590
- const pointer = readFileSync17(gitDir, "utf8").trim();
30088
+ const pointer = readFileSync19(gitDir, "utf8").trim();
29591
30089
  const match = pointer.match(/^gitdir:\s*(.+)$/);
29592
30090
  if (!match) return void 0;
29593
30091
  gitDir = resolve7(dir, match[1]);
29594
30092
  }
29595
- const head = readFileSync17(join21(gitDir, "HEAD"), "utf8").trim();
30093
+ const head = readFileSync19(join23(gitDir, "HEAD"), "utf8").trim();
29596
30094
  const branchMatch = head.match(/^ref:\s*refs\/heads\/(.+)$/);
29597
30095
  if (branchMatch) return branchMatch[1];
29598
30096
  return /^[0-9a-f]{7,40}$/i.test(head) ? head.slice(0, 7) : void 0;
@@ -29605,7 +30103,7 @@ function listDocLevel(root, relDir = "", sort = "newest", showHidden = false) {
29605
30103
  if (absDir === null) return [];
29606
30104
  let entries2;
29607
30105
  try {
29608
- entries2 = readdirSync5(absDir, { withFileTypes: true });
30106
+ entries2 = readdirSync6(absDir, { withFileTypes: true });
29609
30107
  } catch {
29610
30108
  return [];
29611
30109
  }
@@ -29614,14 +30112,14 @@ function listDocLevel(root, relDir = "", sort = "newest", showHidden = false) {
29614
30112
  for (const entry of entries2) {
29615
30113
  if (dirs.length + docs.length >= MAX_ENTRIES) break;
29616
30114
  if (!showHidden && entry.name.startsWith(".")) continue;
29617
- const abs = join21(absDir, entry.name);
30115
+ const abs = join23(absDir, entry.name);
29618
30116
  const path = relative(root, abs).split(sep3).join("/");
29619
30117
  const kind = entryKind(entry, abs);
29620
30118
  if (kind === "dir") {
29621
30119
  if (SKIP_DIRS.has(entry.name)) continue;
29622
30120
  const probe = probeDir(abs, showHidden);
29623
30121
  if (!probe.hasDocs && probe.hasOther) continue;
29624
- const isRepo = existsSync19(join21(abs, ".git"));
30122
+ const isRepo = existsSync21(join23(abs, ".git"));
29625
30123
  dirs.push({
29626
30124
  path,
29627
30125
  name: entry.name,
@@ -29650,14 +30148,14 @@ function flatDocs(root, {
29650
30148
  if (depth > MAX_SEARCH_DEPTH || hits.length >= MAX_FLAT_DOCS) return;
29651
30149
  let entries2;
29652
30150
  try {
29653
- entries2 = readdirSync5(dir, { withFileTypes: true });
30151
+ entries2 = readdirSync6(dir, { withFileTypes: true });
29654
30152
  } catch {
29655
30153
  return;
29656
30154
  }
29657
30155
  for (const entry of entries2) {
29658
30156
  if (hits.length >= MAX_FLAT_DOCS) return;
29659
30157
  if (!showHidden && entry.name.startsWith(".")) continue;
29660
- const abs = join21(dir, entry.name);
30158
+ const abs = join23(dir, entry.name);
29661
30159
  const kind = entryKind(entry, abs);
29662
30160
  if (kind === "dir") {
29663
30161
  if (!SKIP_DIRS.has(entry.name)) walk(abs, depth + 1);
@@ -29699,7 +30197,7 @@ function writeDocContent(root, rel, content, baseMtime) {
29699
30197
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) {
29700
30198
  return { status: "too-large" };
29701
30199
  }
29702
- writeFileSync7(abs, content, "utf8");
30200
+ writeFileSync9(abs, content, "utf8");
29703
30201
  return { status: "ok", mtime: statSync7(abs).mtime.toISOString() };
29704
30202
  }
29705
30203
  function resolveRawPath(root, rel) {
@@ -29721,7 +30219,7 @@ function resolveDownloadPath(root, rel) {
29721
30219
  if (!rel || rel.includes("\0")) return null;
29722
30220
  const abs = resolve7(root, rel);
29723
30221
  if (abs !== root && !abs.startsWith(root + sep3)) return null;
29724
- if (!isListableFile(basename5(abs))) return null;
30222
+ if (!isListableFile(basename6(abs))) return null;
29725
30223
  const contentType = MEDIA_EXTENSIONS[extname2(abs).toLowerCase()] ?? "application/octet-stream";
29726
30224
  return { abs, contentType };
29727
30225
  }
@@ -29737,7 +30235,7 @@ function uniqueName(absDir, name) {
29737
30235
  let candidate = name;
29738
30236
  for (let n = 1; n < 1e3; n++) {
29739
30237
  try {
29740
- statSync7(join21(absDir, candidate));
30238
+ statSync7(join23(absDir, candidate));
29741
30239
  } catch {
29742
30240
  return candidate;
29743
30241
  }
@@ -29759,8 +30257,8 @@ function saveUploadedFile(root, relDir, name, data) {
29759
30257
  if (!(ext in DOC_EXTENSIONS) && !ASSET_LIST_EXTENSIONS.has(ext)) return { status: "bad-type" };
29760
30258
  if (data.byteLength > MAX_UPLOAD_BYTES) return { status: "too-large" };
29761
30259
  const final = uniqueName(absDir, safe);
29762
- const abs = join21(absDir, final);
29763
- writeFileSync7(abs, data);
30260
+ const abs = join23(absDir, final);
30261
+ writeFileSync9(abs, data);
29764
30262
  return { status: "ok", path: relative(root, abs).split(sep3).join("/"), name: final };
29765
30263
  }
29766
30264
  function createDocFolder(root, relDir, name) {
@@ -29773,13 +30271,13 @@ function createDocFolder(root, relDir, name) {
29773
30271
  }
29774
30272
  const safe = sanitizeUploadName(name);
29775
30273
  if (!safe) return { status: "bad-name" };
29776
- const abs = join21(absDir, safe);
30274
+ const abs = join23(absDir, safe);
29777
30275
  try {
29778
30276
  statSync7(abs);
29779
30277
  return { status: "exists" };
29780
30278
  } catch {
29781
30279
  }
29782
- mkdirSync9(abs);
30280
+ mkdirSync10(abs);
29783
30281
  return { status: "ok", path: relative(root, abs).split(sep3).join("/"), name: safe };
29784
30282
  }
29785
30283
  function createDocFile(root, relDir, name, content) {
@@ -29796,9 +30294,9 @@ function createDocFile(root, relDir, name, content) {
29796
30294
  if (!(ext in DOC_EXTENSIONS) && !(ext in CODE_EXTENSIONS)) return { status: "bad-name" };
29797
30295
  if (SKIP_FILES.has(safe)) return { status: "bad-name" };
29798
30296
  if (Buffer.byteLength(content, "utf8") > MAX_CONTENT_BYTES) return { status: "too-large" };
29799
- const abs = join21(absDir, safe);
30297
+ const abs = join23(absDir, safe);
29800
30298
  try {
29801
- writeFileSync7(abs, content, { encoding: "utf8", flag: "wx" });
30299
+ writeFileSync9(abs, content, { encoding: "utf8", flag: "wx" });
29802
30300
  } catch (err) {
29803
30301
  if (err.code === "EEXIST") return { status: "exists" };
29804
30302
  throw err;
@@ -29819,7 +30317,7 @@ function moveDocEntry(root, from, to) {
29819
30317
  if (!isDir && !stat.isFile()) return { status: "not-found" };
29820
30318
  const absTo = resolve7(root, to);
29821
30319
  if (!absTo.startsWith(root + sep3)) return { status: "bad-target" };
29822
- const name = sanitizeUploadName(basename5(absTo));
30320
+ const name = sanitizeUploadName(basename6(absTo));
29823
30321
  if (!name) return { status: "bad-target" };
29824
30322
  if (!isDir) {
29825
30323
  const ext = extname2(name).toLowerCase();
@@ -29827,14 +30325,14 @@ function moveDocEntry(root, from, to) {
29827
30325
  return { status: "bad-target" };
29828
30326
  }
29829
30327
  }
29830
- const absToDir = dirname3(absTo);
30328
+ const absToDir = dirname4(absTo);
29831
30329
  if (resolveDirPath(root, relative(root, absToDir)) === null) return { status: "bad-target" };
29832
30330
  try {
29833
30331
  if (!statSync7(absToDir).isDirectory()) return { status: "bad-target" };
29834
30332
  } catch {
29835
30333
  return { status: "bad-target" };
29836
30334
  }
29837
- const finalAbs = join21(absToDir, name);
30335
+ const finalAbs = join23(absToDir, name);
29838
30336
  if (isDir && (finalAbs === absFrom || finalAbs.startsWith(absFrom + sep3))) {
29839
30337
  return { status: "into-self" };
29840
30338
  }
@@ -29842,7 +30340,7 @@ function moveDocEntry(root, from, to) {
29842
30340
  if (realpathSync(finalAbs) !== realpathSync(absFrom)) return { status: "exists" };
29843
30341
  } catch {
29844
30342
  }
29845
- renameSync2(absFrom, finalAbs);
30343
+ renameSync3(absFrom, finalAbs);
29846
30344
  return { status: "ok", path: relative(root, finalAbs).split(sep3).join("/"), name };
29847
30345
  }
29848
30346
  function deleteDocEntry(root, path) {
@@ -29857,7 +30355,7 @@ function deleteDocEntry(root, path) {
29857
30355
  }
29858
30356
  const isDir = stat.isDirectory();
29859
30357
  if (!isDir && !stat.isFile() && !stat.isSymbolicLink()) return { status: "not-found" };
29860
- rmSync10(abs, { recursive: isDir });
30358
+ rmSync12(abs, { recursive: isDir });
29861
30359
  return {
29862
30360
  status: "ok",
29863
30361
  path: relative(root, abs).split(sep3).join("/"),
@@ -29896,7 +30394,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29896
30394
  }
29897
30395
  if (!stat.isFile()) return c.json({ error: "not found" }, 404);
29898
30396
  if (stat.size > MAX_RAW_BYTES) return c.json({ error: "file too large" }, 413);
29899
- const name = basename5(resolved2.abs);
30397
+ const name = basename6(resolved2.abs);
29900
30398
  const asciiName = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
29901
30399
  const disposition = download ? "attachment" : "inline";
29902
30400
  const stream = Readable.toWeb(createReadStream(resolved2.abs));
@@ -29918,7 +30416,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29918
30416
  }
29919
30417
  if (!stat.isFile()) return c.json({ error: "not found" }, 404);
29920
30418
  if (stat.size > MAX_RAW_BYTES) return c.json({ error: "file too large" }, 413);
29921
- return c.body(withDocLinkBridge(readFileSync17(abs, "utf8")), 200, {
30419
+ return c.body(withDocLinkBridge(readFileSync19(abs, "utf8")), 200, {
29922
30420
  "Content-Type": "text/html; charset=utf-8",
29923
30421
  "Content-Security-Policy": HTML_SHARE_CSP,
29924
30422
  "X-Content-Type-Options": "nosniff",
@@ -29933,7 +30431,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29933
30431
  const dir = typeof form.get("path") === "string" ? form.get("path") : "";
29934
30432
  const files = form.getAll("file").filter((f) => f instanceof File);
29935
30433
  if (files.length === 0) return c.json({ error: "missing file" }, 400);
29936
- const uploaded = [];
30434
+ const uploaded2 = [];
29937
30435
  const failed = [];
29938
30436
  for (const file of files) {
29939
30437
  if (file.size > MAX_UPLOAD_BYTES) {
@@ -29946,7 +30444,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29946
30444
  const result = saveUploadedFile(cwd, dir, file.name, Buffer.from(await file.arrayBuffer()));
29947
30445
  switch (result.status) {
29948
30446
  case "ok":
29949
- uploaded.push({ path: result.path, name: result.name });
30447
+ uploaded2.push({ path: result.path, name: result.name });
29950
30448
  break;
29951
30449
  case "no-dir":
29952
30450
  return c.json({ error: "folder not found" }, 404);
@@ -29960,7 +30458,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
29960
30458
  failed.push({ name: file.name, error: "invalid filename" });
29961
30459
  }
29962
30460
  }
29963
- return c.json({ path: dir, uploaded, failed }, uploaded.length > 0 ? 201 : 400);
30461
+ return c.json({ path: dir, uploaded: uploaded2, failed }, uploaded2.length > 0 ? 201 : 400);
29964
30462
  });
29965
30463
  app.post("/:id/docs/folder", async (c) => {
29966
30464
  const { cwd } = resolveChannelConfig(c.req.param("id"));
@@ -30100,10 +30598,10 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30100
30598
  // by; only docs get a parsed title.
30101
30599
  kind: kind ?? "code",
30102
30600
  lang: kind ? void 0 : CODE_EXTENSIONS[ext],
30103
- title: kind ? extractTitle(abs, kind) : basename5(abs),
30601
+ title: kind ? extractTitle(abs, kind) : basename6(abs),
30104
30602
  mtime: stat.mtime.toISOString(),
30105
30603
  tooLarge: tooLarge || void 0,
30106
- content: tooLarge ? "" : readFileSync17(abs, "utf8")
30604
+ content: tooLarge ? "" : readFileSync19(abs, "utf8")
30107
30605
  });
30108
30606
  });
30109
30607
  app.put("/:id/docs/content", async (c) => {
@@ -30146,7 +30644,7 @@ function createDocsRouter({ gate = requireDocsAccess } = {}) {
30146
30644
  channel,
30147
30645
  rel,
30148
30646
  title: extractTitle(abs, "md"),
30149
- content: readFileSync17(abs, "utf8")
30647
+ content: readFileSync19(abs, "utf8")
30150
30648
  };
30151
30649
  };
30152
30650
  app.get("/:id/docs/translation/:lang", async (c) => {
@@ -30204,7 +30702,7 @@ function withDocLinkBridge(html) {
30204
30702
  var DOC_MENTION_RE = /(?<![\w@/`])@((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]{1,6})(?::(\d+))?(?![\w-])/g;
30205
30703
  function isRealDoc(root, rel) {
30206
30704
  const abs = resolveDocPath(root, rel);
30207
- if (!abs || !existsSync20(abs)) return false;
30705
+ if (!abs || !existsSync22(abs)) return false;
30208
30706
  try {
30209
30707
  return statSync8(abs).isFile();
30210
30708
  } catch {
@@ -30645,7 +31143,7 @@ var BACKGROUND_CHECK_IN_MS = 30 * 6e4;
30645
31143
  var MISSED_MESSAGE_WINDOW_MS = 24 * 60 * 60 * 1e3;
30646
31144
  var MISSED_MESSAGE_THREAD_LIMIT = 100;
30647
31145
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
30648
- function stripPathPrefixes(label, roots, home = homedir7()) {
31146
+ function stripPathPrefixes(label, roots, home = homedir8()) {
30649
31147
  let out = label;
30650
31148
  for (const root of roots) {
30651
31149
  if (root) out = out.replaceAll(`${root.replace(/\/+$/, "")}/`, "");
@@ -30808,7 +31306,9 @@ var ChatAgent = class {
30808
31306
  async wake(threadId, replyId, text) {
30809
31307
  const wakes = this.consecutiveWakes.get(threadId) ?? 0;
30810
31308
  if (wakes >= MAX_CONSECUTIVE_WAKES) {
30811
- console.log(`[chat-agent] wake refused, cap of ${MAX_CONSECUTIVE_WAKES} reached. thread=${threadId}`);
31309
+ console.log(
31310
+ `[chat-agent] wake refused, cap of ${MAX_CONSECUTIVE_WAKES} reached. thread=${threadId}`
31311
+ );
30812
31312
  return false;
30813
31313
  }
30814
31314
  const { data } = await this.supabase().from("thread_replies").select("author").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: false }).limit(50);
@@ -30850,7 +31350,8 @@ var ChatAgent = class {
30850
31350
  * background.
30851
31351
  */
30852
31352
  async continueAfterKilledTool(threadId, channelId, profile, topic, reply) {
30853
- if (!await this.shouldResume(topic, [{ author: AGENT_AUTHOR, body: reply }], "killed-tool")) return;
31353
+ if (!await this.shouldResume(topic, [{ author: AGENT_AUTHOR, body: reply }], "killed-tool"))
31354
+ return;
30854
31355
  const slot = this.claimAutoContinue(threadId, channelId);
30855
31356
  if (!slot) return;
30856
31357
  await this.autoContinue(
@@ -30873,7 +31374,10 @@ var ChatAgent = class {
30873
31374
  if (tasks.length === 0) return;
30874
31375
  this.watchedTasks.set(threadId, { profile, channelId, firstSeen: Date.now(), tasks });
30875
31376
  this.channelActivityNotifier()("background", { channelId, threadId, on: true });
30876
- this.backgroundSweep ??= setInterval(() => void this.sweepBackgroundTasks(), BACKGROUND_SWEEP_MS);
31377
+ this.backgroundSweep ??= setInterval(
31378
+ () => void this.sweepBackgroundTasks(),
31379
+ BACKGROUND_SWEEP_MS
31380
+ );
30877
31381
  this.backgroundSweep.unref?.();
30878
31382
  }
30879
31383
  async sweepBackgroundTasks() {
@@ -30882,7 +31386,11 @@ var ChatAgent = class {
30882
31386
  const tasks = live.get(threadId);
30883
31387
  if (tasks?.length) {
30884
31388
  watched.tasks = tasks;
30885
- this.channelActivityNotifier()("background", { channelId: watched.channelId, threadId, on: true });
31389
+ this.channelActivityNotifier()("background", {
31390
+ channelId: watched.channelId,
31391
+ threadId,
31392
+ on: true
31393
+ });
30886
31394
  const oldest = Math.min(...tasks.map((t) => t.startedAt));
30887
31395
  if (!watched.checkedIn && Date.now() - oldest >= BACKGROUND_CHECK_IN_MS) {
30888
31396
  watched.checkedIn = true;
@@ -30891,19 +31399,27 @@ var ChatAgent = class {
30891
31399
  await runWithProfile(watched.profile, async () => {
30892
31400
  const { replyId } = await postToDashboardChannel({ threadId, text: text2 });
30893
31401
  await this.wake(threadId, replyId, text2);
30894
- }).catch((err) => console.error("[chat-agent] background check-in failed:", err.message));
31402
+ }).catch(
31403
+ (err) => console.error("[chat-agent] background check-in failed:", err.message)
31404
+ );
30895
31405
  }
30896
31406
  continue;
30897
31407
  }
30898
31408
  this.watchedTasks.delete(threadId);
30899
- this.channelActivityNotifier()("background", { channelId: watched.channelId, threadId, on: false });
31409
+ this.channelActivityNotifier()("background", {
31410
+ channelId: watched.channelId,
31411
+ threadId,
31412
+ on: false
31413
+ });
30900
31414
  if ((this.lastWakeAt.get(threadId) ?? 0) >= watched.firstSeen) continue;
30901
31415
  console.log(`[chat-agent] background task ended without waking. thread=${threadId}`);
30902
31416
  const text = "Background task ended without reporting a result (it may have been killed or the machine restarted).";
30903
31417
  await runWithProfile(watched.profile, async () => {
30904
31418
  const { replyId } = await postToDashboardChannel({ threadId, text });
30905
31419
  await this.wake(threadId, replyId, text);
30906
- }).catch((err) => console.error("[chat-agent] background wake failed:", err.message));
31420
+ }).catch(
31421
+ (err) => console.error("[chat-agent] background wake failed:", err.message)
31422
+ );
30907
31423
  }
30908
31424
  if (this.watchedTasks.size === 0 && this.backgroundSweep) {
30909
31425
  clearInterval(this.backgroundSweep);
@@ -31035,10 +31551,9 @@ var ChatAgent = class {
31035
31551
  const { data: thread } = await this.supabase().from("threads").select("channel_id").eq("id", threadId).single();
31036
31552
  if (!thread?.channel_id) return false;
31037
31553
  const { data } = await this.supabase().from("workspaces").select("agent_paused, plan_status").eq("slug", findOwningProfile(thread.channel_id));
31038
- const paused = (data ?? []).some(
31039
- (r) => r.agent_paused === true || isLockedPlan(r.plan_status ?? null)
31040
- );
31041
- if (paused) console.log(`[chat-agent] agent paused or plan locked, not answering thread=${threadId}`);
31554
+ const paused = (data ?? []).some((r) => r.agent_paused === true || isLockedPlan(r.plan_status ?? null));
31555
+ if (paused)
31556
+ console.log(`[chat-agent] agent paused or plan locked, not answering thread=${threadId}`);
31042
31557
  return paused;
31043
31558
  } catch (err) {
31044
31559
  console.error(`[chat-agent] pause check failed for thread=${threadId}:`, err);
@@ -31302,12 +31817,16 @@ var ChatAgent = class {
31302
31817
  ...isHumanAuthor(msg.author) ? { requesterHandle: msg.author } : {},
31303
31818
  slackBound: !!channelRow?.external_channel_id
31304
31819
  };
31305
- if (memory.memoryPrompt) channelConfig = { ...channelConfig, memoryPrompt: memory.memoryPrompt };
31820
+ if (memory.memoryPrompt)
31821
+ channelConfig = { ...channelConfig, memoryPrompt: memory.memoryPrompt };
31306
31822
  const store = this.openSessionStore();
31307
31823
  try {
31308
31824
  const channelKey = `chat:${thread.channel_id}`;
31309
31825
  const session = store.getSession(channelKey, msg.threadId);
31310
- const docsNote = docsAccessPromptNote(channelConfig.docsAccess, channelConfig.docsAccessUnverified);
31826
+ const docsNote = docsAccessPromptNote(
31827
+ channelConfig.docsAccess,
31828
+ channelConfig.docsAccessUnverified
31829
+ );
31311
31830
  const header = (docsNote ? `[access: ${docsNote}]
31312
31831
 
31313
31832
  ` : "") + `[context: chat channel=${thread.channel_id}, thread_id=${thread.id}` + (thread.title ? `, thread="${thread.title}"` : "") + `, sender=${msg.author}. This is the Flyspace dashboard, not Slack \u2014 it renders full Markdown, so use normal paragraphs, line breaks, and real Markdown lists instead of Slack-style single-line replies. When you name a file that lives in this channel's folder, write it as @ + its cwd-relative path (@docs/spec.md, @web/src/App.tsx) as plain text, never inside backticks or a Markdown link \u2014 the dashboard turns that into a chip the reader clicks to open the file. A trailing line number (@src/app.ts:120) is fine. Paths outside the cwd stay in backticks.]
@@ -31419,7 +31938,13 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
31419
31938
  if (!response2 || response2.isError) {
31420
31939
  await this.postReply(
31421
31940
  msg.threadId,
31422
- this.failureReply(owningProfile, thread.channel_id, msg.threadId, "codex", response2?.failure)
31941
+ this.failureReply(
31942
+ owningProfile,
31943
+ thread.channel_id,
31944
+ msg.threadId,
31945
+ "codex",
31946
+ response2?.failure
31947
+ )
31423
31948
  );
31424
31949
  return;
31425
31950
  }
@@ -31498,7 +32023,13 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
31498
32023
  if (!response || this.isTransientFailure(response)) {
31499
32024
  await this.postReply(
31500
32025
  msg.threadId,
31501
- this.failureReply(owningProfile, thread.channel_id, msg.threadId, "claude", response?.failure)
32026
+ this.failureReply(
32027
+ owningProfile,
32028
+ thread.channel_id,
32029
+ msg.threadId,
32030
+ "claude",
32031
+ response?.failure
32032
+ )
31502
32033
  );
31503
32034
  return;
31504
32035
  }
@@ -31510,14 +32041,17 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
31510
32041
  if (response.isTimeout) {
31511
32042
  const slot = response.sessionId ? this.claimAutoContinue(msg.threadId, thread.channel_id) : null;
31512
32043
  if (slot) {
31513
- if (response.partialText) await this.postReply(msg.threadId, response.partialText, activities);
32044
+ if (response.partialText)
32045
+ await this.postReply(msg.threadId, response.partialText, activities);
31514
32046
  const idle = response.timeoutKind === "idle";
31515
32047
  void this.autoContinue(
31516
32048
  msg.threadId,
31517
32049
  owningProfile,
31518
32050
  `This turn hit its time limit, continuing automatically (${slot.n}/${slot.limit}).`,
31519
32051
  (idle ? "Your last turn was stopped after several minutes with no output, most likely a command that never exited or ran too long. Run long or open-ended commands in the background with a `flyspace chat wake` callback instead." : "Your last turn was stopped because it ran past the time limit for a single turn.") + " Check what already got done, then carry on with what is left."
31520
- ).catch((err) => console.error("[chat-agent] timeout continue failed:", err.message));
32052
+ ).catch(
32053
+ (err) => console.error("[chat-agent] timeout continue failed:", err.message)
32054
+ );
31521
32055
  return;
31522
32056
  }
31523
32057
  if (response.sessionId) {
@@ -31769,6 +32303,9 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
31769
32303
  ownPersona: channelConfig.ownPersona,
31770
32304
  slackBound: channelConfig.slackBound,
31771
32305
  onActivity,
32306
+ ...channelConfig.permissionThread ? {
32307
+ onPluginUi: (state) => void this.savePluginUi(channelConfig.profile, channelConfig.permissionThread.threadId, state)
32308
+ } : {},
31772
32309
  signal,
31773
32310
  mcpConfigPath,
31774
32311
  ...usageContext ? { usageContext } : {},
@@ -31789,6 +32326,27 @@ ${msg.body}` : expandSkillCommand(channelConfig.claudeConfigDir, channelConfig.c
31789
32326
  return failure ? { sessionId: sessionId ?? "", text: "", isError: true, isTransientError: true, failure } : null;
31790
32327
  }
31791
32328
  }
32329
+ pluginUiHashes = /* @__PURE__ */ new Map();
32330
+ /**
32331
+ * Keep the latest mod UI snapshot for a thread (0129). One row per thread,
32332
+ * overwritten only when it changed. Large SVGs go to R2 via the Data API (plugin-ui-store),
32333
+ * so the row stays a few KB. A turn with no panes clears the row, so a mod that closed its pane stops showing.
32334
+ */
32335
+ async savePluginUi(workspace, threadId, raw) {
32336
+ const empty = !raw.panes.length && !raw.status;
32337
+ const state = empty ? raw : await offloadPluginUi(workspace, raw);
32338
+ const hash = empty ? "" : pluginUiHash(state);
32339
+ if (this.pluginUiHashes.get(threadId) === hash) return;
32340
+ const table = this.supabase().from("thread_plugin_ui");
32341
+ const { error } = !empty ? await table.upsert({
32342
+ thread_id: threadId,
32343
+ panes: state.panes,
32344
+ status: state.status ?? null,
32345
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
32346
+ }) : await table.delete().eq("thread_id", threadId);
32347
+ if (error) console.error(`[chat-agent] save plugin UI ${threadId}: ${error.message}`);
32348
+ else this.pluginUiHashes.set(threadId, hash);
32349
+ }
31792
32350
  async tryAskCodex(channelConfig, prompt, sessionId, signal, onActivity, usageContext) {
31793
32351
  const name = subAgentName(channelConfig.agentName);
31794
32352
  const agentPersona = name ? readAgentPersona(channelConfig.claudeConfigDir, channelConfig.cwd, name) : void 0;
@@ -34200,6 +34758,7 @@ async function startServer() {
34200
34758
  const reactionStore = new ReactionStore(paths.DB_FILE);
34201
34759
  const slack = config.slackBotToken ? createSlackApp(config) : void 0;
34202
34760
  await refreshChannelRegistry();
34761
+ void autoSyncPersonaAvatars(getProfile());
34203
34762
  warnOnBrokenChannelCwds();
34204
34763
  const stopChannelPolling = startChannelRegistryPolling();
34205
34764
  await refreshAutomationRegistry();
@@ -34348,6 +34907,34 @@ export {
34348
34907
  DEFAULT_TIMEZONE,
34349
34908
  loadAutomations,
34350
34909
  loadEffectiveAutomations,
34910
+ DEFAULT_API_URL,
34911
+ AuthApiError,
34912
+ apiUrl,
34913
+ deviceKeyPath,
34914
+ credentialsPath,
34915
+ ensureDeviceKey,
34916
+ loadCredentials,
34917
+ saveCredentials,
34918
+ clearLocalAuth,
34919
+ requestDeviceCode,
34920
+ pollDeviceToken,
34921
+ fetchWhoAmI,
34922
+ boundWorkspaces,
34923
+ revokeDevice,
34924
+ getAccessToken,
34925
+ acquireHostLock,
34926
+ publishHostEndpoint,
34927
+ readHostEndpoint,
34928
+ setHostDbSender,
34929
+ handleHostDbResult,
34930
+ requestHostDb,
34931
+ handleAttachmentUrlResult,
34932
+ handlePluginSvgResult,
34933
+ handleShouldRespondResult,
34934
+ LOCAL_DB_PATH,
34935
+ createHostDbClient,
34936
+ useHostDbWithoutCredentials,
34937
+ runPersonaCmd,
34351
34938
  MEMORY_TYPES,
34352
34939
  isMemoryType,
34353
34940
  validateMemoryInput,
@@ -34413,16 +35000,6 @@ export {
34413
35000
  CLI_VERSION,
34414
35001
  isOlderVersion,
34415
35002
  latestCliVersion,
34416
- acquireHostLock,
34417
- publishHostEndpoint,
34418
- readHostEndpoint,
34419
- setHostDbSender,
34420
- handleHostDbResult,
34421
- requestHostDb,
34422
- handleAttachmentUrlResult,
34423
- handleShouldRespondResult,
34424
- LOCAL_DB_PATH,
34425
- createHostDbClient,
34426
35003
  workspaceSkillsDir,
34427
35004
  channelSkillsDir,
34428
35005
  isValidSkillName,