flyspace-cli 0.1.53 → 0.1.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3,14 +3,14 @@ import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
3
  const require = __flyspaceCreateRequire(import.meta.url);
4
4
  import {
5
5
  AutomationManager,
6
+ BOT_DM_KEY,
7
+ BOT_LABEL,
6
8
  BOT_PROFILE_KEY,
7
9
  BRANDING_DEFAULTS,
8
10
  BUILT_IN_OUTPUT_STYLES,
9
11
  CLI_VERSION,
10
- ChannelCwdError,
11
12
  ChatAgent,
12
13
  DEFAULT_TIMEZONE,
13
- DefaultChannelError,
14
14
  DocShareSlugTakenError,
15
15
  HANDLE_PATTERN,
16
16
  HandleTakenError,
@@ -22,21 +22,18 @@ import {
22
22
  PLATE,
23
23
  SKIP_SUBTYPES,
24
24
  SLACK_ENV,
25
- SOURCE_LANGUAGES,
26
- SessionStore,
25
+ SUPPORT_AVATAR_URL,
27
26
  TRANSLATION_LANGUAGES,
28
27
  TRIAL_DAYS,
29
28
  UsageStore,
30
29
  acquireHostLock,
31
- activateMembership,
32
- auditChannelCwds,
30
+ agentViewer,
33
31
  authorFor,
34
32
  blockToFallbackText,
35
33
  bodyTextFor,
36
34
  buildAuthorizeUrl,
37
35
  buildAutoTitle,
38
36
  cachedProfileConfig,
39
- canSeeChannel,
40
37
  canonicalLanguage,
41
38
  channelSkillsDir,
42
39
  claudeAuthFailed,
@@ -45,7 +42,6 @@ import {
45
42
  codexAuthAvailable,
46
43
  consumeOAuthState,
47
44
  corsForShell,
48
- createChannel,
49
45
  createDocShare,
50
46
  createDocsRouter,
51
47
  createFeatureFlagsRouter,
@@ -56,6 +52,7 @@ import {
56
52
  createPkcePair,
57
53
  createPublicShareApiRouter,
58
54
  createPublicShareAssetRouter,
55
+ createRequestSupabaseClient,
59
56
  createSkillFile,
60
57
  createStateToken,
61
58
  createTtsRouter,
@@ -74,23 +71,18 @@ import {
74
71
  deleteWorkspace,
75
72
  deleteWorkspaceDomain,
76
73
  deriveConnectionSlug,
74
+ detectSourceLanguage,
77
75
  displayNameFor,
78
76
  dropShareAudio,
79
77
  dropShareLangAudioKeys,
80
78
  effectiveModel,
81
- ensureAgentDmChannel,
82
- ensureGeneralChannel,
83
- ensureMemberDmChannel,
84
79
  ensureUsersCached,
85
80
  escalateToHuman,
86
81
  exchangeCode,
87
- expandPath,
88
82
  explainCost,
89
83
  extractCategories,
90
84
  extractTitle,
91
85
  filterReadableDocsChannels,
92
- findChannel,
93
- findChannelById,
94
86
  findDocShareBySource,
95
87
  findOwningProfile,
96
88
  findSkillDetail,
@@ -99,7 +91,6 @@ import {
99
91
  getAllowGuestAccess,
100
92
  getChannelDocsMemberAccess,
101
93
  getChannelMemory,
102
- getChannelRegistry,
103
94
  getLocalCache,
104
95
  getMcpConnection,
105
96
  getMcpProvider,
@@ -107,7 +98,6 @@ import {
107
98
  getMembershipByUserId,
108
99
  getMemory,
109
100
  getOutputStyleDefault,
110
- getProfileChannelRegistry,
111
101
  getWorkspaceAutoContinueLimit,
112
102
  getWorkspaceBilling,
113
103
  getWorkspaceBranding,
@@ -116,29 +106,27 @@ import {
116
106
  getWorkspaceByStripeCustomerId,
117
107
  getWorkspaceDomain,
118
108
  getWorkspaceGreetedAt,
109
+ getWorkspaceOwnPersona,
119
110
  getWorkspacePermissionMode,
120
111
  getWorkspacePlanStatus,
121
112
  handleAttachmentUrlResult,
122
113
  handleHostDbResult,
114
+ handleShouldRespondResult,
123
115
  handleSupportMention,
124
116
  highlightLanguageOf,
125
117
  insertMcpConnection,
126
118
  insertWorkspaceDomain,
127
119
  installUsageRecording,
120
+ invalidateAuthContextCache,
128
121
  isAllowedModel,
129
- isCwdUsable,
130
122
  isDevHost,
131
123
  isDocsAccess,
132
- isEffort,
133
124
  isFeatureEnabled,
134
125
  isLockedPlan,
135
- isLogicalCwd,
136
126
  isMemoryType,
137
127
  isOlderVersion,
138
- isPermissionMode,
139
128
  isSlugAvailable,
140
129
  isTranslatableLanguage,
141
- isUnderLogicalRoot,
142
130
  isUnknownWorkspaceHost,
143
131
  isUuid,
144
132
  isValidSkillName,
@@ -173,13 +161,13 @@ import {
173
161
  loadFullDashboardSettings,
174
162
  loadWorkspaceBranding,
175
163
  loadWorkspacePrompt,
176
- markChannelGreeted,
177
164
  markInviteResent,
178
165
  markMemoryUsed,
179
166
  markWorkspaceGreeted,
180
167
  markWorkspaceProjectsSetup,
181
168
  markdownToBlocks,
182
169
  mentionedUserIds,
170
+ onboardingPending,
183
171
  pinnedClaudeConfigDir,
184
172
  profileClaudeConfigDir,
185
173
  profileEnv,
@@ -194,7 +182,6 @@ import {
194
182
  recentRunsForWorkspace,
195
183
  refreshAutomationRegistry,
196
184
  refreshCache,
197
- refreshChannelRegistry,
198
185
  refreshUserCache,
199
186
  removeChannelMember,
200
187
  renderAppIcon,
@@ -203,9 +190,9 @@ import {
203
190
  requireSlackBotToken,
204
191
  resetWorkspaceOnboarding,
205
192
  resetWorkspacePrompt,
193
+ resolveAuthContext,
206
194
  resolveChannelConfig,
207
195
  resolveChannelId,
208
- resolveCwd,
209
196
  resolveDocPath,
210
197
  resolveDocsAccess,
211
198
  resolveRateCard,
@@ -240,12 +227,12 @@ import {
240
227
  setProfileConfigCache,
241
228
  setWorkspaceArchived,
242
229
  setWorkspaceAutoContinueLimit,
230
+ setWorkspaceOwnPersona,
243
231
  setWorkspacePermissionMode,
244
232
  setWorkspaceStripeSubscription,
245
233
  slackConfigured,
246
234
  slackMrkdwnToMarkdown,
247
235
  startAutomationRegistryPolling,
248
- startChannelRegistryPolling,
249
236
  startServer,
250
237
  suggestChannelField,
251
238
  syncSlackAvatars,
@@ -254,9 +241,7 @@ import {
254
241
  trustedHost,
255
242
  tsToIso,
256
243
  undoMemoryEvent,
257
- updateChannelById,
258
244
  updateChannelMemory,
259
- updateChannelsMcpConnections,
260
245
  updateDocShareFeatures,
261
246
  updateDocShareSnapshot,
262
247
  updateMcpConnectionSettings,
@@ -273,39 +258,66 @@ import {
273
258
  useDirectSupabase,
274
259
  useLocalCache,
275
260
  validateMemoryInput,
276
- warnOnBrokenChannelCwds,
277
261
  workspaceHostname,
278
262
  workspaceSkillsDir,
279
263
  writeSkillFile
280
- } from "./chunk-GX5467VC.js";
264
+ } from "./chunk-CN6YV335.js";
281
265
  import {
266
+ canReadThread,
282
267
  firstReplyBody,
283
268
  getThread,
284
269
  listChannels,
285
270
  listThreads,
286
- moveThread,
287
- resolveChannel
288
- } from "./chunk-PIAF4FJX.js";
271
+ moveThreadFully,
272
+ resolveChannel,
273
+ resolveThreadOwner
274
+ } from "./chunk-44WHW7NK.js";
289
275
  import {
290
276
  AGENT_AUTHOR,
277
+ ChannelCwdError,
291
278
  DEFAULT_PROFILE,
279
+ DefaultChannelError,
292
280
  SCRATCH_PREFIX,
281
+ SessionStore,
282
+ auditChannelCwds,
283
+ canSeeChannel,
284
+ createChannel,
293
285
  databaseReachable,
286
+ ensureAgentDmChannel,
294
287
  ensureDirs,
288
+ ensureGeneralChannel,
289
+ ensureMemberDmChannel,
290
+ expandPath,
291
+ findChannel,
292
+ findChannelById,
293
+ getChannelRegistry,
295
294
  getProfile,
295
+ getProfileChannelRegistry,
296
296
  getR2Bucket,
297
297
  getR2Client,
298
298
  getSupabaseClient,
299
299
  hasSupabaseCredentials,
300
+ isCwdUsable,
301
+ isEffort,
300
302
  isHumanAuthor,
303
+ isLogicalCwd,
304
+ isPermissionMode,
305
+ isUnderLogicalRoot,
306
+ markChannelGreeted,
301
307
  paths,
302
308
  postToDashboardChannel,
309
+ refreshChannelRegistry,
310
+ resolveCwd,
303
311
  resolveDashboardChannelId,
304
312
  runWithProfile,
305
313
  setSupabaseClient,
314
+ startChannelRegistryPolling,
306
315
  sumR2PrefixBytes,
307
- syncPostToDashboard
308
- } from "./chunk-HTFQL66T.js";
316
+ syncPostToDashboard,
317
+ updateChannelById,
318
+ updateChannelsMcpConnections,
319
+ warnOnBrokenChannelCwds
320
+ } from "./chunk-XACRG7BO.js";
309
321
 
310
322
  // ../core/src/logger.ts
311
323
  var ALREADY_STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
@@ -2347,7 +2359,7 @@ function npmEnv(target) {
2347
2359
  return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
2348
2360
  }
2349
2361
  async function runUpgrade() {
2350
- const current = "0.1.53";
2362
+ const current = "0.1.55";
2351
2363
  console.log(`Current version: ${current}`);
2352
2364
  console.log("Checking for updates...\n");
2353
2365
  try {
@@ -2407,11 +2419,15 @@ function loadAutomationsFile() {
2407
2419
  }
2408
2420
 
2409
2421
  // src/commands/automation.ts
2422
+ import { readFileSync as readFileSync11 } from "fs";
2410
2423
  var USAGE2 = `
2411
2424
  Usage: flyspace automation <subcommand> [options]
2412
2425
 
2413
2426
  Subcommands:
2414
2427
  list List all automations (grouped by channel)
2428
+ show <name> Print one automation as JSON, prompt included
2429
+ edit <name> --prompt <text>|--prompt-file <path>
2430
+ Replace an automation's prompt
2415
2431
  add --type schedule|trigger|mention-trigger Add an automation
2416
2432
  remove <name> Remove an automation
2417
2433
  enable <name> Enable an automation
@@ -2662,6 +2678,43 @@ async function handleRun(manager, name) {
2662
2678
  });
2663
2679
  console.log("Done.");
2664
2680
  }
2681
+ function automationType(item) {
2682
+ if ("cron" in item) return "schedule";
2683
+ if ("patterns" in item) return "trigger";
2684
+ return "mention-trigger";
2685
+ }
2686
+ function handleShow(manager, name) {
2687
+ const located = manager.locate(name);
2688
+ if (!located) {
2689
+ console.error(`Automation "${name}" not found.`);
2690
+ process.exit(1);
2691
+ }
2692
+ console.log(JSON.stringify({ type: automationType(located.item), ...located.item }, null, 2));
2693
+ }
2694
+ async function handleEdit(manager, name, args) {
2695
+ const inline = getArg(args, "--prompt");
2696
+ const file = getArg(args, "--prompt-file");
2697
+ if (!inline === !file) {
2698
+ console.error("Specify exactly one of --prompt or --prompt-file");
2699
+ process.exit(1);
2700
+ }
2701
+ const located = manager.locate(name);
2702
+ if (!located) {
2703
+ console.error(`Automation "${name}" not found.`);
2704
+ process.exit(1);
2705
+ }
2706
+ if ("script" in located.item && located.item.script) {
2707
+ console.error(`"${name}" runs a script, not a prompt.`);
2708
+ process.exit(1);
2709
+ }
2710
+ const prompt = inline ?? readFileSync11(file, "utf8");
2711
+ if (!prompt.trim()) {
2712
+ console.error("Prompt must not be empty.");
2713
+ process.exit(1);
2714
+ }
2715
+ await manager.update(automationType(located.item), name, { ...located.item, prompt });
2716
+ console.log(`Prompt of "${name}" updated.`);
2717
+ }
2665
2718
  async function handleImport(manager) {
2666
2719
  const file = loadAutomationsFile();
2667
2720
  const existing = new Set(loadAutomations().schedules.map((s) => s.name));
@@ -2708,6 +2761,20 @@ async function runAutomationCmd(args) {
2708
2761
  case "list":
2709
2762
  printList(manager);
2710
2763
  break;
2764
+ case "show":
2765
+ if (!args[1]) {
2766
+ console.error("Usage: flyspace automation show <name>");
2767
+ process.exit(1);
2768
+ }
2769
+ handleShow(manager, args[1]);
2770
+ break;
2771
+ case "edit":
2772
+ if (!args[1]) {
2773
+ console.error("Usage: flyspace automation edit <name> --prompt <text>|--prompt-file <path>");
2774
+ process.exit(1);
2775
+ }
2776
+ await handleEdit(manager, args[1], args.slice(2));
2777
+ break;
2711
2778
  case "add":
2712
2779
  await handleAdd(manager, args.slice(1));
2713
2780
  break;
@@ -3025,7 +3092,7 @@ async function runLogs(args) {
3025
3092
 
3026
3093
  // src/commands/slack.ts
3027
3094
  import { execFileSync as execFileSync3 } from "child_process";
3028
- import { existsSync as existsSync13, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "fs";
3095
+ import { existsSync as existsSync13, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
3029
3096
  import { resolve as resolve4 } from "path";
3030
3097
  import { tmpdir as tmpdir2, homedir as homedir5 } from "os";
3031
3098
  import { input, confirm as confirm4, select, checkbox } from "@inquirer/prompts";
@@ -3538,6 +3605,7 @@ async function issueSetupInvite(params) {
3538
3605
  message: params.message,
3539
3606
  invited_by: params.invitedBy,
3540
3607
  token_hash: hashInviteToken(token),
3608
+ link_token: token,
3541
3609
  expires_at: expiresAt.toISOString()
3542
3610
  });
3543
3611
  if (error2) throw new Error(`issueSetupInvite(${params.email}): ${error2.message}`);
@@ -3560,6 +3628,7 @@ async function reissueSetupInvite(id) {
3560
3628
  const expiresAt = new Date(Date.now() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1e3);
3561
3629
  const { error: updateError } = await db.from("workspace_setup_invites").update({
3562
3630
  token_hash: hashInviteToken(token),
3631
+ link_token: token,
3563
3632
  previous_token_hashes: [
3564
3633
  ...data.previous_token_hashes ?? [],
3565
3634
  data.token_hash
@@ -3576,11 +3645,18 @@ async function reissueSetupInvite(id) {
3576
3645
  }
3577
3646
  };
3578
3647
  }
3648
+ async function currentSetupInviteToken(id) {
3649
+ const { data, error: error2 } = await getSupabaseClient().from("workspace_setup_invites").select("link_token").eq("id", id).is("accepted_at", null).maybeSingle();
3650
+ if (error2) throw new Error(`currentSetupInviteToken(${id}): ${error2.message}`);
3651
+ if (!data) throw new Error("no pending invite with that id");
3652
+ return data.link_token ?? (await reissueSetupInvite(id)).token;
3653
+ }
3579
3654
  async function lookupSetupInvite(token) {
3580
3655
  const { data, error: error2 } = await getSupabaseClient().from("workspace_setup_invites").select("id, email, owner_name, plan, message, expires_at, accepted_at, workspace_id").or(tokenHashFilter(token)).maybeSingle();
3581
3656
  if (error2) throw new Error(`lookupSetupInvite: ${error2.message}`);
3582
3657
  if (!data) return { state: "unknown" };
3583
- if (data.accepted_at) return { state: "used", workspaceId: data.workspace_id ?? null };
3658
+ if (data.accepted_at)
3659
+ return { state: "used", workspaceId: data.workspace_id ?? null };
3584
3660
  if (new Date(data.expires_at).getTime() <= Date.now()) return { state: "expired" };
3585
3661
  return {
3586
3662
  state: "valid",
@@ -3646,6 +3722,18 @@ var RESERVED = /* @__PURE__ */ new Set([
3646
3722
  "portal",
3647
3723
  "home",
3648
3724
  "root",
3725
+ // Top-level Workspace routes: the slug is the first URL path segment
3726
+ // (`app.flyspace.ai/<slug>/...`), see packages/ui/src/lib/workspace-path.ts.
3727
+ "chat",
3728
+ "global",
3729
+ "device",
3730
+ "onboarding",
3731
+ "reset-password",
3732
+ "channels",
3733
+ "automations",
3734
+ "profiles",
3735
+ "sessions",
3736
+ "logs",
3649
3737
  "share",
3650
3738
  "shared",
3651
3739
  "data",
@@ -4976,7 +5064,7 @@ async function threadReplies(client2, nameOrId, ts2) {
4976
5064
  async function postMessage(client2, args) {
4977
5065
  const channelArg = getArg2(args, "--channel");
4978
5066
  const textFilePath = getArg2(args, "--text-file");
4979
- const text = textFilePath ? readFileSync11(textFilePath, "utf8") : getArg2(args, "--text");
5067
+ const text = textFilePath ? readFileSync12(textFilePath, "utf8") : getArg2(args, "--text");
4980
5068
  const threadTs = getArg2(args, "--thread");
4981
5069
  const markdown = args.includes("--markdown");
4982
5070
  const broadcast = args.includes("--broadcast") && Boolean(threadTs);
@@ -5131,7 +5219,7 @@ async function ensureClaudeCodeReady() {
5131
5219
  }
5132
5220
  function getManifestYaml(botName) {
5133
5221
  const manifestPath = resolve4(paths.PACKAGE_ROOT, "slack-app-manifest.yml");
5134
- const raw = readFileSync11(manifestPath, "utf-8");
5222
+ const raw = readFileSync12(manifestPath, "utf-8");
5135
5223
  return raw.replace(/name: Custie/g, `name: ${botName}`);
5136
5224
  }
5137
5225
  async function stepPersonalise() {
@@ -5563,7 +5651,7 @@ function copyDefaultPrompt(botName) {
5563
5651
  if (!existsSync13(paths.PROMPT_FILE)) {
5564
5652
  const defaultPrompt = resolve4(paths.PACKAGE_ROOT, "system.default.md");
5565
5653
  if (existsSync13(defaultPrompt)) {
5566
- const content = readFileSync11(defaultPrompt, "utf-8").replace(/\{\{botName\}\}/g, botName);
5654
+ const content = readFileSync12(defaultPrompt, "utf-8").replace(/\{\{botName\}\}/g, botName);
5567
5655
  writeFileSync6(paths.PROMPT_FILE, content);
5568
5656
  success4(`Default prompt copied to ${paths.PROMPT_FILE}`);
5569
5657
  }
@@ -5844,25 +5932,19 @@ async function runMove(args) {
5844
5932
  console.log("\n--dry-run: nothing changed.");
5845
5933
  return;
5846
5934
  }
5847
- await moveThread(thread.id, destination.id);
5848
- const store = new SessionStore(paths.DB_FILE);
5849
- const moved = store.moveThread(
5850
- `chat:${thread.channelId}`,
5851
- `chat:${destination.id}`,
5852
- thread.id
5853
- );
5854
- store.close();
5935
+ const moved = await moveThreadFully(thread.id, destination.id);
5936
+ if (moved === "unchanged") return;
5855
5937
  console.log(
5856
5938
  `
5857
5939
  Moved. Re-keyed ${moved.sessions} session(s), ${moved.modelOverrides} model override(s), ${moved.effortOverrides} effort override(s).`
5858
5940
  );
5859
- if (source && source.cwd !== destination.cwd) {
5941
+ if (moved.cwdChanged && source) {
5860
5942
  console.log(
5861
5943
  `
5862
5944
  Note: the channels have different working directories.
5863
5945
  ${source.cwd}
5864
5946
  ${destination.cwd}
5865
- Files this thread created live in the old one \u2014 move them yourself if the
5947
+ Files this thread created live in the old one, move them yourself if the
5866
5948
  thread still refers to them.`
5867
5949
  );
5868
5950
  }
@@ -5943,10 +6025,10 @@ async function runChatCmd(args) {
5943
6025
  }
5944
6026
 
5945
6027
  // src/commands/memory.ts
5946
- import { readFileSync as readFileSync13 } from "fs";
6028
+ import { readFileSync as readFileSync14 } from "fs";
5947
6029
 
5948
6030
  // src/store/claude-memory-import.ts
5949
- import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as readFileSync12 } from "fs";
6031
+ import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as readFileSync13 } from "fs";
5950
6032
  import { homedir as homedir6 } from "os";
5951
6033
  import { basename as basename5, join as join12 } from "path";
5952
6034
  import dotenv from "dotenv";
@@ -5956,7 +6038,7 @@ function claudeMemoryDir(cwd, configDir2) {
5956
6038
  function profileClaudeConfigDirFor(profile) {
5957
6039
  const dir = profile === "default" ? paths.BASE_CONFIG_DIR : join12(paths.PROFILES_DIR, profile);
5958
6040
  const file = join12(dir, "config.env");
5959
- const env = existsSync14(file) ? dotenv.parse(readFileSync12(file)) : {};
6041
+ const env = existsSync14(file) ? dotenv.parse(readFileSync13(file)) : {};
5960
6042
  return env["CLAUDE_CONFIG_DIR"]?.trim() || join12(homedir6(), ".claude");
5961
6043
  }
5962
6044
  var TYPE_MAP = {
@@ -6006,7 +6088,7 @@ async function importClaudeMemories(dir, channelId, opts = {}) {
6006
6088
  const files = readdirSync3(dir).filter((f) => f.endsWith(".md") && f !== "MEMORY.md").sort();
6007
6089
  const results = [];
6008
6090
  for (const file of files) {
6009
- const parsed = parseClaudeMemory(file, readFileSync12(join12(dir, file), "utf-8"), channelId);
6091
+ const parsed = parseClaudeMemory(file, readFileSync13(join12(dir, file), "utf-8"), channelId);
6010
6092
  if ("skip" in parsed) {
6011
6093
  results.push({ file, outcome: "skipped", reason: parsed.skip });
6012
6094
  continue;
@@ -6118,7 +6200,7 @@ ${memory.body}`);
6118
6200
  );
6119
6201
  }
6120
6202
  if (!isMemoryType(type)) throw new Error(`--type must be one of ${MEMORY_TYPES.join(", ")}`);
6121
- const body = bodyArg === "-" ? readFileSync13(0, "utf-8") : bodyArg;
6203
+ const body = bodyArg === "-" ? readFileSync14(0, "utf-8") : bodyArg;
6122
6204
  const thread = getArg4(rest, "--thread");
6123
6205
  const { created, changed } = await saveMemory(
6124
6206
  target,
@@ -6202,9 +6284,10 @@ async function runMcpCmd(args) {
6202
6284
  }
6203
6285
  restoreStdout();
6204
6286
  loadEnvFiles();
6287
+ useHostDbWithoutCredentials();
6205
6288
  switch (server) {
6206
6289
  case "threads": {
6207
- const { startThreadsServer } = await import("./threads-QAVO2Z4L.js");
6290
+ const { startThreadsServer } = await import("./threads-I52LSA5X.js");
6208
6291
  await startThreadsServer();
6209
6292
  return;
6210
6293
  }
@@ -6287,92 +6370,6 @@ async function ensureServices() {
6287
6370
  // ../api/src/dashboard/api.ts
6288
6371
  import { Hono as Hono35 } from "hono";
6289
6372
 
6290
- // ../api/src/dashboard/supabase-server-client.ts
6291
- import { createServerClient, parseCookieHeader, serializeCookieHeader } from "@supabase/ssr";
6292
-
6293
- // ../api/src/dashboard/scoped-auth-cookies.ts
6294
- import { stringFromBase64URL } from "@supabase/ssr";
6295
- var SESSION_NAME = /^(sb-.+-auth-token)(?:\.\d+)?$/;
6296
- var SCOPE_MARK = "fsw_";
6297
- var SCOPE_END = "__";
6298
- function hostLabel(host) {
6299
- return host.toLowerCase().replace(/:\d+$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
6300
- }
6301
- var scopePrefix = (label2) => `${SCOPE_MARK}${label2}${SCOPE_END}`;
6302
- function sessionUserId(cookies) {
6303
- const base = cookies.map((c) => SESSION_NAME.exec(c.name)?.[1]).find(Boolean);
6304
- if (!base) return null;
6305
- const whole = cookies.find((c) => c.name === base)?.value;
6306
- const raw = whole ?? cookies.filter((c) => c.name.startsWith(`${base}.`)).sort((a, b) => Number(a.name.split(".").pop()) - Number(b.name.split(".").pop())).map((c) => c.value).join("");
6307
- if (!raw) return null;
6308
- try {
6309
- const json = raw.startsWith("base64-") ? stringFromBase64URL(raw.slice(7)) : raw;
6310
- const id = JSON.parse(json).user?.id;
6311
- return typeof id === "string" ? id : null;
6312
- } catch {
6313
- return null;
6314
- }
6315
- }
6316
- var isScoped = (name) => name.startsWith(SCOPE_MARK);
6317
- function readScopedCookies(all, label2) {
6318
- const prefix = scopePrefix(label2);
6319
- const own = all.filter((c) => c.name.startsWith(prefix)).map((c) => ({ name: c.name.slice(prefix.length), value: c.value }));
6320
- return own.length ? own : all.filter((c) => !isScoped(c.name));
6321
- }
6322
- function routeCookieWrites(all, label2, writes) {
6323
- const prefix = scopePrefix(label2);
6324
- const hasOwn = all.some((c) => c.name.startsWith(prefix));
6325
- const incoming = sessionUserId(writes.filter((c) => c.value !== ""));
6326
- const shared = sessionUserId(all.filter((c) => !isScoped(c.name)));
6327
- const toScoped = hasOwn || incoming !== null && shared !== null && incoming !== shared;
6328
- return writes.map(
6329
- (c) => toScoped ? { name: prefix + c.name, value: c.value, scoped: true } : { ...c, scoped: false }
6330
- );
6331
- }
6332
-
6333
- // ../api/src/dashboard/supabase-server-client.ts
6334
- var REQUEST_TIMEOUT_MS = 5e3;
6335
- function fetchWithTimeout(input2, init2) {
6336
- return fetch(input2, { ...init2, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
6337
- }
6338
- function createRequestSupabaseClient(c) {
6339
- const url = process.env["SUPABASE_URL"];
6340
- const key = process.env["VITE_SUPABASE_PUBLISHABLE_KEY"];
6341
- if (!url || !key) {
6342
- throw new Error("SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_KEY not set \u2014 check .env");
6343
- }
6344
- const origin = c.req.header("Origin");
6345
- const label2 = hostLabel(
6346
- (origin ? URL.parse(origin)?.host : void 0) ?? c.req.header("X-Forwarded-Host") ?? c.req.header("Host") ?? ""
6347
- );
6348
- const rawCookies = () => parseCookieHeader(c.req.header("Cookie") ?? "").map(({ name, value }) => ({
6349
- name,
6350
- value: value ?? ""
6351
- }));
6352
- return createServerClient(url, key, {
6353
- global: { fetch: fetchWithTimeout },
6354
- cookies: {
6355
- // `parseCookieHeader` types `value` as optional; the client requires a
6356
- // string, and a valueless cookie is the same as an empty one here.
6357
- getAll: () => readScopedCookies(rawCookies(), label2),
6358
- setAll: (cookies) => {
6359
- const domain = process.env["AUTH_COOKIE_DOMAIN"]?.trim();
6360
- const overrides = {
6361
- ...domain ? { domain } : {},
6362
- ...crossOriginShell(c) ? { sameSite: "none", secure: true } : {}
6363
- };
6364
- const routed = routeCookieWrites(rawCookies(), label2, cookies);
6365
- cookies.forEach(({ options }, i) => {
6366
- const { name, value } = routed[i];
6367
- c.header("Set-Cookie", serializeCookieHeader(name, value, { ...options, ...overrides }), {
6368
- append: true
6369
- });
6370
- });
6371
- }
6372
- }
6373
- });
6374
- }
6375
-
6376
6373
  // ../api/src/dashboard/guest-routes.ts
6377
6374
  import { Hono as Hono4 } from "hono";
6378
6375
  async function guestAccessAllowed() {
@@ -6417,110 +6414,6 @@ function createGuestRouter() {
6417
6414
  // ../api/src/dashboard/auth-routes.ts
6418
6415
  import { Hono as Hono7 } from "hono";
6419
6416
 
6420
- // ../api/src/dashboard/auth-context.ts
6421
- import { HTTPException as HTTPException2 } from "hono/http-exception";
6422
- import { isAuthApiError, isAuthRetryableFetchError } from "@supabase/supabase-js";
6423
- function onboardingPending(ctx) {
6424
- const pending = [];
6425
- if (!ctx.onboarded && !ctx.passwordSet) pending.push("account");
6426
- if (!ctx.onboarded) pending.push("profile");
6427
- if (ctx.role === "admin" && !ctx.agentConnectedAt) pending.push("agent");
6428
- if (ctx.role === "admin" && !ctx.projectsSetupAt) pending.push("projects");
6429
- return pending;
6430
- }
6431
- var inFlight = /* @__PURE__ */ new Map();
6432
- var CACHE_TTL_MS = 3e4;
6433
- var resolved = /* @__PURE__ */ new Map();
6434
- function invalidateAuthContextCache() {
6435
- resolved.clear();
6436
- }
6437
- function pruneExpired(now) {
6438
- for (const [key, entry] of resolved) {
6439
- if (entry.expires <= now) resolved.delete(key);
6440
- }
6441
- }
6442
- var SUPPORT_NAME = "Flyspace Support";
6443
- var SUPPORT_AVATAR_URL = "/logo/flyspace-support.svg";
6444
- function workspaceArchivedError() {
6445
- return new HTTPException2(403, {
6446
- res: Response.json({ error: "workspace archived", archived: true }, { status: 403 })
6447
- });
6448
- }
6449
- async function resolveAuthContext(c, opts = {}) {
6450
- const ctx = await resolveAuthContextCached(c, opts);
6451
- if (ctx?.archived && !ctx.isSupport) throw workspaceArchivedError();
6452
- return ctx;
6453
- }
6454
- async function resolveAuthContextCached(c, opts) {
6455
- const cookie = c.req?.header("Cookie") ?? "";
6456
- if (!cookie) return resolveAuthContextUncached(c);
6457
- const key = `${getProfile()}\0${cookie}`;
6458
- const now = Date.now();
6459
- pruneExpired(now);
6460
- if (opts.fresh) resolved.delete(key);
6461
- const cached = resolved.get(key);
6462
- if (cached) return cached.value;
6463
- const inflight = inFlight.get(key);
6464
- if (inflight) return inflight;
6465
- const promise = resolveAuthContextUncached(c).then((value) => {
6466
- resolved.set(key, { value, expires: Date.now() + CACHE_TTL_MS });
6467
- return value;
6468
- }).finally(() => inFlight.delete(key));
6469
- inFlight.set(key, promise);
6470
- return promise;
6471
- }
6472
- async function getUserWithRetry(supabase) {
6473
- let result = await supabase.auth.getUser();
6474
- if (isAuthRetryableFetchError(result.error)) result = await supabase.auth.getUser();
6475
- const { error: error2 } = result;
6476
- if (isAuthRetryableFetchError(error2) || isAuthApiError(error2) && error2.status === 429) {
6477
- throw error2;
6478
- }
6479
- return result;
6480
- }
6481
- async function resolveAuthContextUncached(c) {
6482
- const supabase = createRequestSupabaseClient(c);
6483
- let user;
6484
- try {
6485
- ({
6486
- data: { user }
6487
- } = await getUserWithRetry(supabase));
6488
- } catch (err) {
6489
- if (isAuthRetryableFetchError(err)) {
6490
- throw new HTTPException2(503, { message: "auth service unreachable" });
6491
- }
6492
- if (isAuthApiError(err) && err.status === 429) {
6493
- throw new HTTPException2(503, { message: "auth service rate limited" });
6494
- }
6495
- return null;
6496
- }
6497
- if (!user?.email) return null;
6498
- const workspace = await getWorkspaceBySlug(getProfile());
6499
- if (!workspace) return null;
6500
- const membership = await getMembershipByEmail(workspace.id, user.email);
6501
- if (!membership) return null;
6502
- if (membership.status === "invited") {
6503
- await activateMembership(workspace.id, user.email);
6504
- }
6505
- const metadata = user.user_metadata ?? {};
6506
- return {
6507
- email: user.email,
6508
- userId: user.id,
6509
- handle: membership.handle,
6510
- role: membership.role,
6511
- workspaceId: workspace.id,
6512
- // A support admin posts into a customer's workspace as Flyspace, not as
6513
- // the staff member's personal profile.
6514
- ...membership.isSupport ? { name: SUPPORT_NAME, isSupport: true } : { name: metadata.name, avatarKey: metadata.avatarKey },
6515
- onboarded: Boolean(metadata.onboardedAt),
6516
- passwordSet: Boolean(metadata.passwordSetAt),
6517
- agentConnectedAt: workspace.agentConnectedAt ?? null,
6518
- projectsSetupAt: workspace.projectsSetupAt ?? null,
6519
- plan: workspace.plan ?? null,
6520
- ...workspace.archivedAt ? { archived: true } : {}
6521
- };
6522
- }
6523
-
6524
6417
  // ../api/src/dashboard/avatar-url.ts
6525
6418
  import { GetObjectCommand } from "@aws-sdk/client-s3";
6526
6419
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
@@ -6543,13 +6436,13 @@ async function signAvatarUrl(key) {
6543
6436
 
6544
6437
  // ../api/src/dashboard/turnstile.ts
6545
6438
  var VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
6546
- var REQUEST_TIMEOUT_MS2 = 5e3;
6439
+ var REQUEST_TIMEOUT_MS = 5e3;
6547
6440
  function siteverify(secret, token) {
6548
6441
  return fetch(VERIFY_URL, {
6549
6442
  method: "POST",
6550
6443
  headers: { "content-type": "application/x-www-form-urlencoded" },
6551
6444
  body: new URLSearchParams({ secret, response: token }),
6552
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
6445
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
6553
6446
  });
6554
6447
  }
6555
6448
  async function verifyTurnstileToken(token) {
@@ -6816,7 +6709,7 @@ import { WebSocket, WebSocketServer } from "ws";
6816
6709
 
6817
6710
  // ../api/src/dashboard/host-identity.ts
6818
6711
  import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey3, generateKeyPairSync as generateKeyPairSync2 } from "crypto";
6819
- import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as readFileSync14, writeFileSync as writeFileSync8 } from "fs";
6712
+ import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as readFileSync15, writeFileSync as writeFileSync8 } from "fs";
6820
6713
  import { dirname as dirname6, join as join13 } from "path";
6821
6714
  function hostPrivateKeyPath() {
6822
6715
  return process.env["FLYSPACE_HOST_KEY_PATH"] || join13(paths.BASE_CONFIG_DIR, "host.key");
@@ -6827,7 +6720,7 @@ function loadHostPrivateKey(path = hostPrivateKeyPath()) {
6827
6720
  `No Host identity at ${path}. Run \`pnpm run generate-host-key\` on this machine, then set FLYSPACE_HOST_PUBLIC_KEY on the Data process to the printed public key.`
6828
6721
  );
6829
6722
  }
6830
- return createPrivateKey2(readFileSync14(path, "utf8"));
6723
+ return createPrivateKey2(readFileSync15(path, "utf8"));
6831
6724
  }
6832
6725
 
6833
6726
  // ../api/src/dashboard/uploads-routes.ts
@@ -7542,6 +7435,17 @@ function createAdminRouter() {
7542
7435
  await revokeSetupInvite(c.req.param("id"));
7543
7436
  return c.json({ revoked: true });
7544
7437
  });
7438
+ admin.get("/setup-invites/:id/link", async (c) => {
7439
+ let token;
7440
+ try {
7441
+ token = await currentSetupInviteToken(c.req.param("id"));
7442
+ } catch (err) {
7443
+ return c.json({ error: err instanceof Error ? err.message : "lookup failed" }, 404);
7444
+ }
7445
+ const inviteUrl = new URL(`${workspaceOrigin(c, "app")}/auth/new-workspace`);
7446
+ inviteUrl.searchParams.set("token", token);
7447
+ return c.json({ inviteLink: inviteUrl.toString() });
7448
+ });
7545
7449
  admin.post("/setup-invites/:id/resend", async (c) => {
7546
7450
  const operator = c.get("platformOperator");
7547
7451
  let token;
@@ -7632,14 +7536,6 @@ function createAdminRouter() {
7632
7536
  return admin;
7633
7537
  }
7634
7538
 
7635
- // ../api/src/dashboard/agent-identities.ts
7636
- var BOT_LABEL = "Workspace Agent";
7637
- var BOT_DM_KEY = "claude";
7638
- async function agentViewer(c) {
7639
- const ctx = await resolveAuthContext(c);
7640
- return ctx?.userId && ctx.email ? { userId: ctx.userId, email: ctx.email } : null;
7641
- }
7642
-
7643
7539
  // ../api/src/dashboard/data-api.ts
7644
7540
  import { existsSync as existsSync18 } from "fs";
7645
7541
  import sharp4 from "sharp";
@@ -8190,14 +8086,14 @@ async function translateBatch(batch, context, lang, scope) {
8190
8086
  };
8191
8087
  });
8192
8088
  }
8193
- var inFlight2 = /* @__PURE__ */ new Map();
8089
+ var inFlight = /* @__PURE__ */ new Map();
8194
8090
  async function translateCached(lang, scope, messages, contextFor) {
8195
8091
  if (!BY_CODE.has(lang)) throw new Error(`unsupported translation language: ${lang}`);
8196
8092
  if (messages.length === 0) return [];
8197
8093
  const keyed = messages.map((m) => ({ ...m, hash: translationHash(m.author, m.body) }));
8198
8094
  const shape = createHash3("sha256").update(keyed.map((m) => `${m.kind}:${m.id}:${m.hash}`).join("\n")).digest("hex");
8199
8095
  const key = `${lang}:${shape}`;
8200
- const running2 = inFlight2.get(key);
8096
+ const running2 = inFlight.get(key);
8201
8097
  if (running2) return running2;
8202
8098
  const job = (async () => {
8203
8099
  const kinds = ["reply", "title"];
@@ -8253,8 +8149,8 @@ async function translateCached(lang, scope, messages, contextFor) {
8253
8149
  if (hit) return { id: m.id, body: hit.body, passthrough: hit.passthrough };
8254
8150
  return fresh.get(freshKey(m)) ?? { id: m.id, body: m.body, passthrough: true };
8255
8151
  });
8256
- })().finally(() => inFlight2.delete(key));
8257
- inFlight2.set(key, job);
8152
+ })().finally(() => inFlight.delete(key));
8153
+ inFlight.set(key, job);
8258
8154
  return job;
8259
8155
  }
8260
8156
  async function translateThread(lang, scope, messages) {
@@ -8307,6 +8203,75 @@ async function getChannelGlossaries(channelIds) {
8307
8203
  return found;
8308
8204
  }
8309
8205
 
8206
+ // ../api/src/store/notification-store.ts
8207
+ function rowToNotification(row) {
8208
+ const reply = row["thread_replies"];
8209
+ return {
8210
+ id: row["id"],
8211
+ threadId: row["thread_id"],
8212
+ channelId: row["channel_id"],
8213
+ replyId: row["reply_id"] ?? null,
8214
+ kind: row["kind"],
8215
+ createdAt: row["created_at"],
8216
+ author: reply?.author ?? null,
8217
+ body: reply?.body ?? null
8218
+ };
8219
+ }
8220
+ async function listUnreadNotifications(channelIds, userId, limit = 100) {
8221
+ if (channelIds.length === 0) return [];
8222
+ const { data, error: error2 } = await getSupabaseClient().from("notifications").select("id, thread_id, channel_id, reply_id, kind, created_at, thread_replies (author, body)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).order("created_at", { ascending: false }).limit(limit);
8223
+ if (error2) throw new Error(`listUnreadNotifications(${userId}): ${error2.message}`);
8224
+ return (data ?? []).map(rowToNotification);
8225
+ }
8226
+ async function countUnreadNotifications(channelIds, userId) {
8227
+ if (channelIds.length === 0) return 0;
8228
+ const { count, error: error2 } = await getSupabaseClient().from("notifications").select("id, threads!inner(archived_at)", { count: "exact", head: true }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
8229
+ if (error2) throw new Error(`countUnreadNotifications(${userId}): ${error2.message}`);
8230
+ return count ?? 0;
8231
+ }
8232
+ async function countUnreadByChannel(channelIds, userId) {
8233
+ if (channelIds.length === 0) return {};
8234
+ const { data, error: error2 } = await getSupabaseClient().from("notifications").select("channel_id, thread_id, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
8235
+ if (error2) throw new Error(`countUnreadByChannel(${userId}): ${error2.message}`);
8236
+ const threads = /* @__PURE__ */ new Map();
8237
+ for (const row of data ?? []) {
8238
+ const channelId = row["channel_id"];
8239
+ const set = threads.get(channelId) ?? /* @__PURE__ */ new Set();
8240
+ set.add(row["thread_id"]);
8241
+ threads.set(channelId, set);
8242
+ }
8243
+ return Object.fromEntries([...threads].map(([id, set]) => [id, set.size]));
8244
+ }
8245
+ async function countUnreadByThread(channelIds, userId) {
8246
+ if (channelIds.length === 0) return {};
8247
+ const { data, error: error2 } = await getSupabaseClient().from("notifications").select("thread_id, kind, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
8248
+ if (error2) throw new Error(`countUnreadByThread(${userId}): ${error2.message}`);
8249
+ const byThread = {};
8250
+ for (const row of data ?? []) {
8251
+ const threadId = row["thread_id"];
8252
+ const entry = byThread[threadId] ?? { count: 0, mention: false };
8253
+ entry.count += 1;
8254
+ if (row["kind"] === "mention") entry.mention = true;
8255
+ byThread[threadId] = entry;
8256
+ }
8257
+ return byThread;
8258
+ }
8259
+ async function markThreadRead(userId, threadId) {
8260
+ const supabase = getSupabaseClient();
8261
+ const { error: readError } = await supabase.from("thread_reads").upsert(
8262
+ { user_id: userId, thread_id: threadId, seen_at: (/* @__PURE__ */ new Date()).toISOString() },
8263
+ { onConflict: "user_id,thread_id" }
8264
+ );
8265
+ if (readError) throw new Error(`markThreadRead(${threadId}): ${readError.message}`);
8266
+ const { error: notifError } = await supabase.from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).eq("thread_id", threadId).is("read_at", null);
8267
+ if (notifError) throw new Error(`markThreadRead(${threadId}): ${notifError.message}`);
8268
+ }
8269
+ async function markAllRead(channelIds, userId) {
8270
+ if (channelIds.length === 0) return;
8271
+ const { error: error2 } = await getSupabaseClient().from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null);
8272
+ if (error2) throw new Error(`markAllRead(${userId}): ${error2.message}`);
8273
+ }
8274
+
8310
8275
  // ../api/src/dashboard/chat-routes.ts
8311
8276
  function isNonEmptyString(v) {
8312
8277
  return typeof v === "string" && v.trim().length > 0;
@@ -8469,7 +8434,7 @@ var MARKDOWN_IMAGE_RE = /!\[[^\]]*\]\(\s*<?([^\s)>]+)>?(?:\s+"[^"]*")?\s*\)/g;
8469
8434
  function markdownImageUrls(markdown) {
8470
8435
  return [...markdown.matchAll(MARKDOWN_IMAGE_RE)].map((m) => m[1]);
8471
8436
  }
8472
- async function labelThread(channelId, body, scope) {
8437
+ async function labelThread(channelId, body, scope, language) {
8473
8438
  const channel = getProfileChannelRegistry().find(
8474
8439
  (ch) => ch.id === channelId || ch.externalChannelId === channelId
8475
8440
  );
@@ -8490,7 +8455,8 @@ async function labelThread(channelId, body, scope) {
8490
8455
  titlePrompt: (await loadWorkspaceBranding()).autoTitlePrompt,
8491
8456
  existingCategories,
8492
8457
  body,
8493
- scope
8458
+ scope,
8459
+ language
8494
8460
  });
8495
8461
  }
8496
8462
  function deriveForkTitle(body) {
@@ -8555,6 +8521,12 @@ function createChatRouter(agent = {}) {
8555
8521
  const supabase = getSupabaseClient();
8556
8522
  let query = supabase.from("threads").select("*").eq("channel_id", channelId).is("archived_at", null).order(sortColumn, { ascending: false }).limit(limit);
8557
8523
  if (before) query = query.lt(sortColumn, before);
8524
+ if (c.req.query("unread") === "1") {
8525
+ const userId = c.get("auth")?.userId;
8526
+ const ids = userId ? Object.keys(await countUnreadByThread([channelId], userId)) : [];
8527
+ if (ids.length === 0) return c.json({ threads: [], nextCursor: null });
8528
+ query = query.in("id", ids);
8529
+ }
8558
8530
  if (statusFilter.length) {
8559
8531
  const withoutNone = statusFilter.filter((s) => s !== NO_STATUS_COLUMN);
8560
8532
  const includeNone = statusFilter.includes(NO_STATUS_COLUMN);
@@ -8887,12 +8859,14 @@ function createChatRouter(agent = {}) {
8887
8859
  app.post("/threads/:id/suggest-title", async (c) => {
8888
8860
  const id = c.req.param("id");
8889
8861
  if (!await threadIsKnown(id, c)) return c.json({ error: "not found" }, 404);
8862
+ const input2 = await c.req.json().catch(() => null);
8863
+ const language = typeof input2?.language === "string" && /^[A-Za-z-]{2,16}$/.test(input2.language) ? input2.language : void 0;
8890
8864
  const { data: thread } = await getSupabaseClient().from("threads").select("channel_id").eq("id", id).single();
8891
8865
  if (!thread) return c.json({ error: "not found" }, 404);
8892
8866
  const { data: rows, error: error2 } = await getSupabaseClient().from("thread_replies").select("author, body").eq("thread_id", id).is("archived_at", null).order("created_at", { ascending: true });
8893
8867
  if (error2) return c.json({ error: error2.message }, 500);
8894
8868
  const transcript = (rows ?? []).map((r) => `${r.author}: ${slackMrkdwnToMarkdown(r.body)}`).join("\n\n");
8895
- const title = await labelThread(thread.channel_id, transcript, "thread");
8869
+ const title = await labelThread(thread.channel_id, transcript, "thread", language);
8896
8870
  if (!title) return c.json({ error: "could not generate a topic" }, 502);
8897
8871
  return c.json({ title });
8898
8872
  });
@@ -9257,72 +9231,6 @@ import { CopyObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-s
9257
9231
  // ../api/src/dashboard/bridge-types.ts
9258
9232
  var SHARE_ASSET_PLACEHOLDER = "/share/{{flyspace-share-id}}/assets/";
9259
9233
 
9260
- // ../api/src/dashboard/share-language.ts
9261
- var GROQ_API_URL4 = "https://api.groq.com/openai/v1/chat/completions";
9262
- var CLASSIFIER_MODEL = "openai/gpt-oss-20b";
9263
- var SAMPLE_CHARS = 4e3;
9264
- var NOISE = [
9265
- /```[\s\S]*?```/g,
9266
- /`[^`\n]*`/g,
9267
- /!?\[[^\]]*\]\([^)]*\)/g,
9268
- /https?:\/\/\S+/g
9269
- ];
9270
- function languageSample(title, content) {
9271
- let text = content;
9272
- for (const pattern of NOISE) text = text.replace(pattern, " ");
9273
- return `${title}
9274
-
9275
- ${text}`.replace(/\s+/g, " ").trim().slice(0, SAMPLE_CHARS);
9276
- }
9277
- var MIN_SAMPLE_CHARS = 40;
9278
- var CODES = SOURCE_LANGUAGES.map((l) => l.code);
9279
- function systemPrompt2() {
9280
- const list = SOURCE_LANGUAGES.map((l) => `${l.code} (${l.name})`).join("\n");
9281
- return `You identify the language an article is written in.
9282
-
9283
- Reply with exactly one code from this list, and nothing else:
9284
- ${list}
9285
-
9286
- If the article is written in a language that is not on the list, or you cannot tell, reply with exactly: unknown
9287
-
9288
- Rules:
9289
- - Judge by the PROSE the author wrote, not by code, product names, technical terms, or quoted fragments. An article written in one language routinely keeps technical vocabulary in English; that does not make it English.
9290
- - Mixed-language articles take the language the body is mostly written in.
9291
- - Traditional Chinese is zh-TW and Simplified Chinese is zh-CN. Decide by the characters used, not by the topic.
9292
- - Output the code alone. No explanation, no punctuation, no quotes.`;
9293
- }
9294
- async function detectSourceLanguage(title, content) {
9295
- const apiKey = process.env["GROQ_API_KEY"];
9296
- if (!apiKey) return null;
9297
- const sample = languageSample(title, content);
9298
- if (sample.length < MIN_SAMPLE_CHARS) return null;
9299
- try {
9300
- const res = await fetch(GROQ_API_URL4, {
9301
- method: "POST",
9302
- headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
9303
- body: JSON.stringify({
9304
- model: CLASSIFIER_MODEL,
9305
- temperature: 0,
9306
- reasoning_effort: "low",
9307
- // gpt-oss reasons before it answers, and those tokens count against
9308
- // this cap — 8 was right for the old non-reasoning model but leaves
9309
- // no room for the answer itself here.
9310
- max_tokens: 150,
9311
- messages: [
9312
- { role: "system", content: systemPrompt2() },
9313
- { role: "user", content: sample }
9314
- ]
9315
- })
9316
- });
9317
- if (!res.ok) return null;
9318
- const data = await res.json();
9319
- const answer = data.choices?.[0]?.message?.content?.trim() ?? "";
9320
- return CODES.find((code) => code.toLowerCase() === answer.toLowerCase()) ?? null;
9321
- } catch {
9322
- return null;
9323
- }
9324
- }
9325
-
9326
9234
  // ../api/src/dashboard/doc-share-publish.ts
9327
9235
  var SHARE_KEY_PREFIX = "share";
9328
9236
  function generateShareId() {
@@ -9576,17 +9484,17 @@ function createDocShareWriteRouter(agent = {}) {
9576
9484
  app.use("/:id/docs/share/*", requireDocsAccess);
9577
9485
  app.use("/:id/docs/shares", requireDocsAccess);
9578
9486
  app.get("/:id/docs/share", async (c) => {
9579
- const resolved2 = resolveChannel2(c);
9580
- if ("error" in resolved2) return resolved2.error;
9487
+ const resolved = resolveChannel2(c);
9488
+ if ("error" in resolved) return resolved.error;
9581
9489
  const path = c.req.query("path") ?? "";
9582
9490
  if (!path) return c.json({ error: "path is required" }, 400);
9583
- const share = await findDocShareBySource(resolved2.auth.workspaceId, resolved2.channel.id, path);
9491
+ const share = await findDocShareBySource(resolved.auth.workspaceId, resolved.channel.id, path);
9584
9492
  return c.json({ share: share ? shareJson(c, share) : null });
9585
9493
  });
9586
9494
  app.get("/:id/docs/shares", async (c) => {
9587
- const resolved2 = resolveChannel2(c);
9588
- if ("error" in resolved2) return resolved2.error;
9589
- const shares = await listLiveDocShares([resolved2.channel.id], LIST_LIMIT + 1);
9495
+ const resolved = resolveChannel2(c);
9496
+ if ("error" in resolved) return resolved.error;
9497
+ const shares = await listLiveDocShares([resolved.channel.id], LIST_LIMIT + 1);
9590
9498
  return c.json({
9591
9499
  truncated: shares.length > LIST_LIMIT,
9592
9500
  shares: shares.slice(0, LIST_LIMIT).map((s) => ({
@@ -9599,14 +9507,14 @@ function createDocShareWriteRouter(agent = {}) {
9599
9507
  });
9600
9508
  });
9601
9509
  app.get("/:id/docs/share/slug", async (c) => {
9602
- const resolved2 = resolveChannel2(c);
9603
- if ("error" in resolved2) return resolved2.error;
9510
+ const resolved = resolveChannel2(c);
9511
+ if ("error" in resolved) return resolved.error;
9604
9512
  const normalized = normalizeSlug(c.req.query("slug") ?? "");
9605
9513
  if ("error" in normalized) {
9606
9514
  return c.json({ available: false, reason: slugErrorMessage(normalized.error) });
9607
9515
  }
9608
9516
  const path = c.req.query("path");
9609
- const own = path ? await findDocShareBySource(resolved2.auth.workspaceId, resolved2.channel.id, path) : null;
9517
+ const own = path ? await findDocShareBySource(resolved.auth.workspaceId, resolved.channel.id, path) : null;
9610
9518
  const available = await isSlugAvailable(normalized.slug, own?.id);
9611
9519
  return c.json({
9612
9520
  slug: normalized.slug,
@@ -9615,8 +9523,8 @@ function createDocShareWriteRouter(agent = {}) {
9615
9523
  });
9616
9524
  });
9617
9525
  app.post("/:id/docs/share", async (c) => {
9618
- const resolved2 = resolveChannel2(c);
9619
- if ("error" in resolved2) return resolved2.error;
9526
+ const resolved = resolveChannel2(c);
9527
+ if ("error" in resolved) return resolved.error;
9620
9528
  const body = await c.req.json().catch(() => null);
9621
9529
  if (!body || typeof body["path"] !== "string" || !body["path"]) {
9622
9530
  return c.json({ error: "path is required" }, 400);
@@ -9624,18 +9532,18 @@ function createDocShareWriteRouter(agent = {}) {
9624
9532
  const slug = readSlug(body);
9625
9533
  if ("invalid" in slug)
9626
9534
  return c.json({ error: slugErrorMessage(slug.invalid), field: "slug" }, 400);
9627
- const { cwd } = resolveChannelConfig(resolved2.channel.id);
9535
+ const { cwd } = resolveChannelConfig(resolved.channel.id);
9628
9536
  let result;
9629
9537
  try {
9630
9538
  const readBundle = agent.readDocShareBundle;
9631
9539
  result = readBundle ? await publishDocShare(
9632
9540
  {
9633
9541
  cwd,
9634
- workspaceId: resolved2.auth.workspaceId,
9635
- profile: resolved2.channel.profile,
9636
- channelId: resolved2.channel.id,
9542
+ workspaceId: resolved.auth.workspaceId,
9543
+ profile: resolved.channel.profile,
9544
+ channelId: resolved.channel.id,
9637
9545
  sourcePath: body["path"],
9638
- createdBy: resolved2.auth.email,
9546
+ createdBy: resolved.auth.email,
9639
9547
  ..."slug" in slug ? { slug: slug.slug } : {},
9640
9548
  features: readFeatures(body)
9641
9549
  },
@@ -9674,8 +9582,8 @@ function createDocShareWriteRouter(agent = {}) {
9674
9582
  }
9675
9583
  });
9676
9584
  app.patch("/:id/docs/share", async (c) => {
9677
- const resolved2 = resolveChannel2(c);
9678
- if ("error" in resolved2) return resolved2.error;
9585
+ const resolved = resolveChannel2(c);
9586
+ if ("error" in resolved) return resolved.error;
9679
9587
  const body = await c.req.json().catch(() => null);
9680
9588
  if (!body || typeof body["path"] !== "string" || !body["path"]) {
9681
9589
  return c.json({ error: "path is required" }, 400);
@@ -9694,8 +9602,8 @@ function createDocShareWriteRouter(agent = {}) {
9694
9602
  );
9695
9603
  }
9696
9604
  const existing = await findDocShareBySource(
9697
- resolved2.auth.workspaceId,
9698
- resolved2.channel.id,
9605
+ resolved.auth.workspaceId,
9606
+ resolved.channel.id,
9699
9607
  body["path"]
9700
9608
  );
9701
9609
  if (!existing) return c.json({ error: "not shared" }, 404);
@@ -9721,13 +9629,13 @@ function createDocShareWriteRouter(agent = {}) {
9721
9629
  return c.json(shareJson(c, updated));
9722
9630
  });
9723
9631
  app.delete("/:id/docs/share", async (c) => {
9724
- const resolved2 = resolveChannel2(c);
9725
- if ("error" in resolved2) return resolved2.error;
9632
+ const resolved = resolveChannel2(c);
9633
+ if ("error" in resolved) return resolved.error;
9726
9634
  const path = c.req.query("path") ?? "";
9727
9635
  if (!path) return c.json({ error: "path is required" }, 400);
9728
9636
  const existing = await findDocShareBySource(
9729
- resolved2.auth.workspaceId,
9730
- resolved2.channel.id,
9637
+ resolved.auth.workspaceId,
9638
+ resolved.channel.id,
9731
9639
  path
9732
9640
  );
9733
9641
  if (!existing) return c.json({ error: "not shared" }, 404);
@@ -10087,7 +9995,7 @@ function createTranscribeRouter() {
10087
9995
 
10088
9996
  // ../api/src/dashboard/autocomplete-routes.ts
10089
9997
  import { Hono as Hono18 } from "hono";
10090
- var GROQ_API_URL5 = "https://api.groq.com/openai/v1/chat/completions";
9998
+ var GROQ_API_URL4 = "https://api.groq.com/openai/v1/chat/completions";
10091
9999
  var MODEL3 = "openai/gpt-oss-120b";
10092
10000
  var MAX_REPLY_CHARS = 4e3;
10093
10001
  var MAX_EARLIER_CHARS = 1500;
@@ -10110,7 +10018,7 @@ function createAutocompleteRouter() {
10110
10018
  const context = `Channel: #${channel.name}${channel.prompt ? `
10111
10019
  Channel instructions: ${channel.prompt.slice(0, 500)}` : ""}
10112
10020
  ${thread}`;
10113
- const res = await fetch(GROQ_API_URL5, {
10021
+ const res = await fetch(GROQ_API_URL4, {
10114
10022
  method: "POST",
10115
10023
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10116
10024
  signal: AbortSignal.timeout(5e3),
@@ -10164,7 +10072,7 @@ ${last.body.slice(-MAX_REPLY_CHARS)}`;
10164
10072
 
10165
10073
  // ../api/src/dashboard/daily-line-routes.ts
10166
10074
  import { Hono as Hono19 } from "hono";
10167
- var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
10075
+ var GROQ_API_URL5 = "https://api.groq.com/openai/v1/chat/completions";
10168
10076
  var MODEL4 = "openai/gpt-oss-120b";
10169
10077
  var DAY_MS = 864e5;
10170
10078
  var RULES3 = `You write one short line of encouragement shown in the corner of an empty screen, for a founder building a product with a small team.
@@ -10210,7 +10118,7 @@ function createDailyLineRouter() {
10210
10118
  const key = `${day}:${memory.id}:${language}`;
10211
10119
  let text = cache3.get(key);
10212
10120
  if (text === void 0) {
10213
- const res = await fetch(GROQ_API_URL6, {
10121
+ const res = await fetch(GROQ_API_URL5, {
10214
10122
  method: "POST",
10215
10123
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10216
10124
  signal: AbortSignal.timeout(8e3),
@@ -10246,7 +10154,7 @@ Write it in ${language} (BCP 47 tag). For Chinese use Traditional Chinese (Taiwa
10246
10154
 
10247
10155
  // ../api/src/dashboard/channel-route.ts
10248
10156
  import { Hono as Hono20 } from "hono";
10249
- var GROQ_API_URL7 = "https://api.groq.com/openai/v1/chat/completions";
10157
+ var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
10250
10158
  var MODEL5 = "openai/gpt-oss-120b";
10251
10159
  var MAX_MESSAGE_CHARS2 = 3e3;
10252
10160
  var MAX_PROMPT_CHARS2 = 300;
@@ -10264,7 +10172,7 @@ async function describeImages(text, workspace, apiKey) {
10264
10172
  (u) => !!u
10265
10173
  );
10266
10174
  if (urls.length === 0) return "";
10267
- const res = await fetch(GROQ_API_URL7, {
10175
+ const res = await fetch(GROQ_API_URL6, {
10268
10176
  method: "POST",
10269
10177
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10270
10178
  signal: AbortSignal.timeout(1e4),
@@ -10339,7 +10247,7 @@ function createChannelRouteRouter() {
10339
10247
  titles.get(ch.id)?.length ? ` Recent topics: ${titles.get(ch.id).join(" | ")}` : ""
10340
10248
  ].filter(Boolean).join("\n")
10341
10249
  ).join("\n");
10342
- const res = await fetch(GROQ_API_URL7, {
10250
+ const res = await fetch(GROQ_API_URL6, {
10343
10251
  method: "POST",
10344
10252
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10345
10253
  signal: AbortSignal.timeout(8e3),
@@ -10710,73 +10618,6 @@ function createMembersRouter() {
10710
10618
  // ../api/src/dashboard/notifications-routes.ts
10711
10619
  import { Hono as Hono23 } from "hono";
10712
10620
 
10713
- // ../api/src/store/notification-store.ts
10714
- function rowToNotification(row) {
10715
- const reply = row["thread_replies"];
10716
- return {
10717
- id: row["id"],
10718
- threadId: row["thread_id"],
10719
- channelId: row["channel_id"],
10720
- replyId: row["reply_id"] ?? null,
10721
- kind: row["kind"],
10722
- createdAt: row["created_at"],
10723
- author: reply?.author ?? null,
10724
- body: reply?.body ?? null
10725
- };
10726
- }
10727
- async function listUnreadNotifications(channelIds, userId, limit = 100) {
10728
- if (channelIds.length === 0) return [];
10729
- const { data, error: error2 } = await getSupabaseClient().from("notifications").select("id, thread_id, channel_id, reply_id, kind, created_at, thread_replies (author, body)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).order("created_at", { ascending: false }).limit(limit);
10730
- if (error2) throw new Error(`listUnreadNotifications(${userId}): ${error2.message}`);
10731
- return (data ?? []).map(rowToNotification);
10732
- }
10733
- async function countUnreadNotifications(channelIds, userId) {
10734
- if (channelIds.length === 0) return 0;
10735
- const { count, error: error2 } = await getSupabaseClient().from("notifications").select("id, threads!inner(archived_at)", { count: "exact", head: true }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
10736
- if (error2) throw new Error(`countUnreadNotifications(${userId}): ${error2.message}`);
10737
- return count ?? 0;
10738
- }
10739
- async function countUnreadByChannel(channelIds, userId) {
10740
- if (channelIds.length === 0) return {};
10741
- const { data, error: error2 } = await getSupabaseClient().from("notifications").select("channel_id, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
10742
- if (error2) throw new Error(`countUnreadByChannel(${userId}): ${error2.message}`);
10743
- const byChannel = {};
10744
- for (const row of data ?? []) {
10745
- const channelId = row["channel_id"];
10746
- byChannel[channelId] = (byChannel[channelId] ?? 0) + 1;
10747
- }
10748
- return byChannel;
10749
- }
10750
- async function countUnreadByThread(channelIds, userId) {
10751
- if (channelIds.length === 0) return {};
10752
- const { data, error: error2 } = await getSupabaseClient().from("notifications").select("thread_id, kind, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
10753
- if (error2) throw new Error(`countUnreadByThread(${userId}): ${error2.message}`);
10754
- const byThread = {};
10755
- for (const row of data ?? []) {
10756
- const threadId = row["thread_id"];
10757
- const entry = byThread[threadId] ?? { count: 0, mention: false };
10758
- entry.count += 1;
10759
- if (row["kind"] === "mention") entry.mention = true;
10760
- byThread[threadId] = entry;
10761
- }
10762
- return byThread;
10763
- }
10764
- async function markThreadRead(userId, threadId) {
10765
- const supabase = getSupabaseClient();
10766
- const { error: readError } = await supabase.from("thread_reads").upsert(
10767
- { user_id: userId, thread_id: threadId, seen_at: (/* @__PURE__ */ new Date()).toISOString() },
10768
- { onConflict: "user_id,thread_id" }
10769
- );
10770
- if (readError) throw new Error(`markThreadRead(${threadId}): ${readError.message}`);
10771
- const { error: notifError } = await supabase.from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).eq("thread_id", threadId).is("read_at", null);
10772
- if (notifError) throw new Error(`markThreadRead(${threadId}): ${notifError.message}`);
10773
- }
10774
- async function markAllRead(channelIds, userId) {
10775
- if (channelIds.length === 0) return;
10776
- const { error: error2 } = await getSupabaseClient().from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null);
10777
- if (error2) throw new Error(`markAllRead(${userId}): ${error2.message}`);
10778
- }
10779
-
10780
10621
  // ../api/src/store/push-store.ts
10781
10622
  function rowToSubscription(row) {
10782
10623
  return {
@@ -10995,6 +10836,18 @@ function createThreadReadRouter() {
10995
10836
  await markThreadRead(userId, threadId);
10996
10837
  return c.json({ ok: true });
10997
10838
  });
10839
+ threads.get("/threads/:threadId/workspace", async (c) => {
10840
+ const { userId } = c.get("auth");
10841
+ const owner = await resolveThreadOwner(c.req.param("threadId"));
10842
+ if (!owner || !await canReadThread(owner, userId)) {
10843
+ return c.json({ error: "not found" }, 404);
10844
+ }
10845
+ return c.json({
10846
+ workspace: owner.workspace,
10847
+ channelId: owner.channelId,
10848
+ threadId: owner.threadId
10849
+ });
10850
+ });
10998
10851
  return threads;
10999
10852
  }
11000
10853
 
@@ -11700,7 +11553,7 @@ async function buildChannelUsageReport(channelId, days, labelChannel) {
11700
11553
  }
11701
11554
  }
11702
11555
  }
11703
- var COMPACT_THRESHOLD_TOKENS = Number(process.env["SESSION_COMPACT_THRESHOLD_TOKENS"]) || 14e4;
11556
+ var COMPACT_THRESHOLD_TOKENS = Number(process.env["SESSION_COMPACT_THRESHOLD_TOKENS"]) || 8e4;
11704
11557
  function contextOf(run4) {
11705
11558
  if (!run4) return void 0;
11706
11559
  const total = run4.inputTokens + run4.cacheReadTokens + run4.cacheCreationTokens;
@@ -12326,8 +12179,9 @@ var rowKey = (channelId, agent, sessionId) => `${channelId}:${agent}:${sessionId
12326
12179
  function replyRows(threadId, messages, author, fallbackAt) {
12327
12180
  return messages.map((m, i) => ({
12328
12181
  thread_id: threadId,
12329
- author: m.role === "user" ? author : AGENT_AUTHOR,
12182
+ author: m.role === "user" && !m.compactSummary ? author : AGENT_AUTHOR,
12330
12183
  body: m.text,
12184
+ ...m.compactSummary ? { author_kind: "compact_summary" } : {},
12331
12185
  created_at: m.at ?? new Date(fallbackAt + i).toISOString()
12332
12186
  }));
12333
12187
  }
@@ -12848,6 +12702,18 @@ function registerDataRoutes(api, agent = {}) {
12848
12702
  await setWorkspacePermissionMode(auth.workspaceId, body.permissionMode);
12849
12703
  return c.json({ permissionMode: body.permissionMode });
12850
12704
  });
12705
+ api.get("/own-persona", async (c) => {
12706
+ const auth = c.get("auth");
12707
+ return c.json({ enabled: await getWorkspaceOwnPersona(auth.workspaceId) });
12708
+ });
12709
+ api.put("/own-persona", async (c) => {
12710
+ const auth = c.get("auth");
12711
+ if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
12712
+ const body = await c.req.json().catch(() => ({}));
12713
+ if (typeof body.enabled !== "boolean") return c.json({ error: "enabled must be a boolean" }, 400);
12714
+ await setWorkspaceOwnPersona(auth.workspaceId, body.enabled);
12715
+ return c.json({ enabled: body.enabled });
12716
+ });
12851
12717
  api.get("/auto-continue", async (c) => {
12852
12718
  const auth = c.get("auth");
12853
12719
  return c.json({ limit: await getWorkspaceAutoContinueLimit(auth.workspaceId) });
@@ -12911,12 +12777,17 @@ function registerDataRoutes(api, agent = {}) {
12911
12777
  const memberOf = new Set(
12912
12778
  (memberships ?? []).map((m) => m.workspace_id)
12913
12779
  );
12914
- const allowed = new Set(workspaces.filter((w) => memberOf.has(w.id)).map((w) => w.slug));
12915
- allowed.add(active);
12780
+ const live = workspaces.filter((w) => !w.archivedAt);
12781
+ const allowed = new Set(live.filter((w) => memberOf.has(w.id)).map((w) => w.slug));
12782
+ if (live.some((w) => w.slug === active)) allowed.add(active);
12783
+ const bySlug = new Map(live.map((w) => [w.slug, w]));
12916
12784
  const list = await Promise.all(
12917
12785
  known.filter((name) => allowed.has(name)).map(async (name) => {
12918
12786
  const branding = await loadWorkspaceBranding(name);
12787
+ const w = bySlug.get(name);
12788
+ const billing = w?.planStatus === "canceled" ? "expired" : w?.planStatus === "paused" || w?.trialEndsAt && Date.parse(w.trialEndsAt) < Date.now() ? "trial_ended" : void 0;
12919
12789
  return {
12790
+ billing,
12920
12791
  name,
12921
12792
  active: name === active,
12922
12793
  running: running2.has(name),
@@ -13023,7 +12894,7 @@ async function readBody(c) {
13023
12894
  return {};
13024
12895
  }
13025
12896
  }
13026
- async function sessionUserId2(c) {
12897
+ async function sessionUserId(c) {
13027
12898
  try {
13028
12899
  const { data } = await createRequestSupabaseClient(c).auth.getUser();
13029
12900
  return data.user?.id ?? null;
@@ -13126,7 +12997,7 @@ function createDeviceAuthRouter() {
13126
12997
  return c.json({ ok: true });
13127
12998
  });
13128
12999
  app.get("/lookup", async (c) => {
13129
- const userId = await sessionUserId2(c);
13000
+ const userId = await sessionUserId(c);
13130
13001
  if (!userId) return c.json({ error: "not signed in" }, 401);
13131
13002
  const userCode = normalizeUserCode(c.req.query("user_code") ?? "");
13132
13003
  const pending = userCode ? await getDeviceCodeByUserCode(userCode) : null;
@@ -13151,7 +13022,7 @@ function createDeviceAuthRouter() {
13151
13022
  });
13152
13023
  });
13153
13024
  app.get("/workspace", async (c) => {
13154
- const userId = await sessionUserId2(c);
13025
+ const userId = await sessionUserId(c);
13155
13026
  if (!userId) return c.json({ error: "not signed in" }, 401);
13156
13027
  const slug = getProfile();
13157
13028
  const workspace = (await listAdminWorkspaces(userId)).find((w) => w.slug === slug);
@@ -13164,7 +13035,7 @@ function createDeviceAuthRouter() {
13164
13035
  });
13165
13036
  });
13166
13037
  app.post("/approve", async (c) => {
13167
- const userId = await sessionUserId2(c);
13038
+ const userId = await sessionUserId(c);
13168
13039
  if (!userId) return c.json({ error: "not signed in" }, 401);
13169
13040
  const body = await readBody(c);
13170
13041
  const userCode = normalizeUserCode(typeof body["user_code"] === "string" ? body["user_code"] : "");
@@ -13502,12 +13373,13 @@ async function viewerProfile(c, known) {
13502
13373
  listMembershipsByEmail(user.email),
13503
13374
  listWorkspaces()
13504
13375
  ]);
13505
- const slugById = new Map(workspaces.map((w) => [w.id, w.slug]));
13506
- for (const m of memberships) {
13507
- const slug = slugById.get(m.workspaceId);
13508
- if (slug && known.includes(slug)) return slug;
13509
- }
13510
- return null;
13376
+ const byId = new Map(workspaces.filter((w) => !w.archivedAt).map((w) => [w.id, w]));
13377
+ const candidates = memberships.map((m) => ({ m, w: byId.get(m.workspaceId) })).filter(
13378
+ (x) => !!x.w && known.includes(x.w.slug)
13379
+ );
13380
+ const rank = ({ m, w }) => (m.isSupport ? 2 : 0) + (isLockedPlan(w.planStatus ?? null) ? 1 : 0);
13381
+ candidates.sort((a, b) => rank(a) - rank(b));
13382
+ return candidates[0]?.w.slug ?? null;
13511
13383
  }
13512
13384
  function createGatedRouter(agent, register) {
13513
13385
  const api = new Hono35();
@@ -13530,8 +13402,8 @@ function createGatedRouter(agent, register) {
13530
13402
  api.get("/public-branding", async (c) => {
13531
13403
  const requested = c.req.query("workspace");
13532
13404
  const known = await listKnownWorkspaces();
13533
- const resolved2 = requested && known.includes(requested) ? requested : profileFromHost(trustedHost(c), known);
13534
- if (!resolved2) {
13405
+ const resolved = requested && known.includes(requested) ? requested : profileFromHost(trustedHost(c), known);
13406
+ if (!resolved) {
13535
13407
  return c.json({
13536
13408
  unknownWorkspace: isUnknownWorkspaceHost(trustedHost(c), known),
13537
13409
  theme: BRANDING_DEFAULTS.theme,
@@ -13542,7 +13414,7 @@ function createGatedRouter(agent, register) {
13542
13414
  logo: "/icons/favicon-64.png"
13543
13415
  });
13544
13416
  }
13545
- const branding = await loadWorkspaceBranding(resolved2);
13417
+ const branding = await loadWorkspaceBranding(resolved);
13546
13418
  return c.json({
13547
13419
  theme: branding.theme,
13548
13420
  font: branding.font,
@@ -13557,7 +13429,7 @@ function createGatedRouter(agent, register) {
13557
13429
  }
13558
13430
 
13559
13431
  // src/dashboard/host-api.ts
13560
- import { existsSync as existsSync24, readFileSync as readFileSync17, statSync as statSync5 } from "fs";
13432
+ import { existsSync as existsSync24, readFileSync as readFileSync18, statSync as statSync5 } from "fs";
13561
13433
  import sharp5 from "sharp";
13562
13434
 
13563
13435
  // src/dashboard/channels-routes.ts
@@ -13903,7 +13775,7 @@ async function resolveAgentIdentities(viewer) {
13903
13775
 
13904
13776
  // ../api/src/dashboard/providers.ts
13905
13777
  import { execFileSync as execFileSync4 } from "child_process";
13906
- import { existsSync as existsSync22, readFileSync as readFileSync15 } from "fs";
13778
+ import { existsSync as existsSync22, readFileSync as readFileSync16 } from "fs";
13907
13779
  import { homedir as homedir7 } from "os";
13908
13780
  import { join as join14, resolve as resolve5 } from "path";
13909
13781
  var PROVIDER_LABELS = {
@@ -13972,7 +13844,7 @@ function claudeAccount() {
13972
13844
  function codexAccount() {
13973
13845
  const home2 = process.env["CODEX_HOME"]?.trim() || join14(homedir7(), ".codex");
13974
13846
  try {
13975
- const auth = JSON.parse(readFileSync15(join14(home2, "auth.json"), "utf8"));
13847
+ const auth = JSON.parse(readFileSync16(join14(home2, "auth.json"), "utf8"));
13976
13848
  const payload = auth.tokens?.id_token?.split(".")[1];
13977
13849
  if (!payload) return void 0;
13978
13850
  const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
@@ -14003,7 +13875,7 @@ function providerStatuses() {
14003
13875
  // src/dashboard/provider-login-host.ts
14004
13876
  import { spawn as spawn4 } from "child_process";
14005
13877
  import { randomUUID as randomUUID4 } from "crypto";
14006
- import { chmodSync, existsSync as existsSync23, mkdirSync as mkdirSync10, readFileSync as readFileSync16, writeFileSync as writeFileSync9 } from "fs";
13878
+ import { chmodSync, existsSync as existsSync23, mkdirSync as mkdirSync10, readFileSync as readFileSync17, writeFileSync as writeFileSync9 } from "fs";
14007
13879
  import { createRequire } from "module";
14008
13880
  import { dirname as dirname9, join as join15 } from "path";
14009
13881
  import { Hono as Hono38 } from "hono";
@@ -14112,7 +13984,7 @@ async function startClaude() {
14112
13984
  }
14113
13985
  function saveClaudeToken(configFile, token) {
14114
13986
  mkdirSync10(dirname9(configFile), { recursive: true });
14115
- const current = existsSync23(configFile) ? readFileSync16(configFile, "utf-8") : "";
13987
+ const current = existsSync23(configFile) ? readFileSync17(configFile, "utf-8") : "";
14116
13988
  writeFileSync9(configFile, upsertEnvLine(current, "CLAUDE_CODE_OAUTH_TOKEN", token), { mode: 384 });
14117
13989
  const cached = cachedProfileConfig();
14118
13990
  if (cached) cached.env["CLAUDE_CODE_OAUTH_TOKEN"] = token;
@@ -14347,7 +14219,7 @@ function registerHostRoutes(api) {
14347
14219
  }
14348
14220
  function tailFile(file, limit) {
14349
14221
  if (!existsSync24(file)) return [];
14350
- const lines = readFileSync17(file, "utf-8").split("\n");
14222
+ const lines = readFileSync18(file, "utf-8").split("\n");
14351
14223
  if (lines.at(-1) === "") lines.pop();
14352
14224
  return lines.slice(-limit);
14353
14225
  }
@@ -14365,7 +14237,7 @@ function createHostApiRouter(agent = {}) {
14365
14237
 
14366
14238
  // src/dashboard/agent-bridge-host.ts
14367
14239
  import { sign as signRaw, timingSafeEqual } from "crypto";
14368
- import { existsSync as existsSync26, readFileSync as readFileSync20 } from "fs";
14240
+ import { existsSync as existsSync26, readFileSync as readFileSync21 } from "fs";
14369
14241
  import dotenv2 from "dotenv";
14370
14242
  import { WebSocket as WebSocket2 } from "ws";
14371
14243
 
@@ -14375,7 +14247,7 @@ import {
14375
14247
  existsSync as existsSync25,
14376
14248
  openSync as openSync2,
14377
14249
  readdirSync as readdirSync4,
14378
- readFileSync as readFileSync18,
14250
+ readFileSync as readFileSync19,
14379
14251
  readSync as readSync2,
14380
14252
  realpathSync as realpathSync4
14381
14253
  } from "fs";
@@ -14435,11 +14307,18 @@ function claudeMessages(lines) {
14435
14307
  continue;
14436
14308
  if (o["entrypoint"] === "sdk-cli") continue;
14437
14309
  const role = o["type"];
14438
- const text = blocksText(o["message"]?.content, ["text"]);
14310
+ const message = o["message"];
14311
+ if (message?.model === "<synthetic>") continue;
14312
+ const text = blocksText(message?.content, ["text"]);
14439
14313
  if (!text || typeof o["uuid"] !== "string") continue;
14314
+ if (role === "user" && text.startsWith("[Request interrupted by user")) continue;
14440
14315
  const at = typeof o["timestamp"] === "string" ? o["timestamp"] : null;
14316
+ if (o["isCompactSummary"]) {
14317
+ out.push({ uuid: o["uuid"], role: "assistant", text, at, compactSummary: true });
14318
+ continue;
14319
+ }
14441
14320
  const last = out[out.length - 1];
14442
- if (role === "assistant" && last?.role === "assistant") {
14321
+ if (role === "assistant" && last?.role === "assistant" && !last.compactSummary) {
14443
14322
  last.text += `
14444
14323
 
14445
14324
  ${text}`;
@@ -14577,7 +14456,7 @@ function findTranscript(agent, sessionId) {
14577
14456
  function readSessionMessages(agent, sessionId, afterUuid) {
14578
14457
  const file = findTranscript(agent, sessionId);
14579
14458
  if (!file) return null;
14580
- const lines = parseLines(readFileSync18(file, "utf-8"));
14459
+ const lines = parseLines(readFileSync19(file, "utf-8"));
14581
14460
  const messages = agent === "claude" ? claudeMessages(lines) : codexMessages(lines);
14582
14461
  if (!afterUuid) return messages;
14583
14462
  const idx = messages.findIndex((m) => m.uuid === afterUuid);
@@ -14634,7 +14513,7 @@ async function handleHostRequest(req) {
14634
14513
  }
14635
14514
 
14636
14515
  // src/dashboard/doc-share-publisher.ts
14637
- import { readFileSync as readFileSync19, statSync as statSync6 } from "fs";
14516
+ import { readFileSync as readFileSync20, statSync as statSync6 } from "fs";
14638
14517
  import { extname, posix } from "path";
14639
14518
  var MAX_ASSET_BYTES = 20 * 1024 * 1024;
14640
14519
  var MAX_CONTENT_BYTES = 2 * 1024 * 1024;
@@ -14749,7 +14628,7 @@ function readDocShareBundle({ cwd, sourcePath }) {
14749
14628
  }
14750
14629
  if (!stat.isFile()) return { status: "not-found" };
14751
14630
  if (stat.size > MAX_CONTENT_BYTES) return { status: "too-large" };
14752
- const source = readFileSync19(abs, "utf8");
14631
+ const source = readFileSync20(abs, "utf8");
14753
14632
  const title = extractTitle(abs, kind === "markdown" ? "md" : kind);
14754
14633
  if (kind === "excalidraw") {
14755
14634
  try {
@@ -14820,7 +14699,7 @@ function readDocShareBundle({ cwd, sourcePath }) {
14820
14699
  let text = null;
14821
14700
  try {
14822
14701
  const size = statSync6(docAbs).size;
14823
- if (size <= budget) text = readFileSync19(docAbs, "utf8");
14702
+ if (size <= budget) text = readFileSync20(docAbs, "utf8");
14824
14703
  } catch {
14825
14704
  continue;
14826
14705
  }
@@ -14832,19 +14711,19 @@ function readDocShareBundle({ cwd, sourcePath }) {
14832
14711
  continue;
14833
14712
  }
14834
14713
  }
14835
- const resolved2 = resolveRawPath(cwd, ref.rel) ?? (docAbs ? { abs: docAbs, contentType: "text/plain; charset=utf-8" } : null);
14836
- if (!resolved2) continue;
14714
+ const resolved = resolveRawPath(cwd, ref.rel) ?? (docAbs ? { abs: docAbs, contentType: "text/plain; charset=utf-8" } : null);
14715
+ if (!resolved) continue;
14837
14716
  let body;
14838
14717
  try {
14839
- if (statSync6(resolved2.abs).size > MAX_ASSET_BYTES) continue;
14840
- body = readFileSync19(resolved2.abs);
14718
+ if (statSync6(resolved.abs).size > MAX_ASSET_BYTES) continue;
14719
+ body = readFileSync20(resolved.abs);
14841
14720
  } catch {
14842
14721
  continue;
14843
14722
  }
14844
14723
  assetBytes += body.length;
14845
14724
  if (assetBytes > MAX_BUNDLE_ASSET_BYTES) return { status: "too-large" };
14846
14725
  const name = claimName(ref.rel.split("/").pop() ?? "file");
14847
- assets.push({ name, contentType: resolved2.contentType, data: body.toString("base64") });
14726
+ assets.push({ name, contentType: resolved.contentType, data: body.toString("base64") });
14848
14727
  rewritten.set(href, `${SHARE_ASSET_PLACEHOLDER}${name}`);
14849
14728
  }
14850
14729
  if (kind === "html") {
@@ -15016,7 +14895,7 @@ function buildHostConfigSnapshot() {
15016
14895
  const snapshot2 = {};
15017
14896
  for (const profile of listProfiles()) {
15018
14897
  snapshot2[profile] = runWithProfile(profile, () => ({
15019
- env: existsSync26(paths.CONFIG_FILE) ? dotenv2.parse(readFileSync20(paths.CONFIG_FILE, "utf-8")) : {},
14898
+ env: existsSync26(paths.CONFIG_FILE) ? dotenv2.parse(readFileSync21(paths.CONFIG_FILE, "utf-8")) : {},
15020
14899
  // Only a model someone actually saved: before that it is just the Claude
15021
14900
  // default, which would show the wrong agent in admin for a Codex user.
15022
14901
  agentModel: existsSync26(paths.DASHBOARD_SETTINGS_FILE) ? loadDashboardSettings().agent : void 0
@@ -15106,6 +14985,10 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
15106
14985
  handleAttachmentUrlResult(msg.id, msg.url);
15107
14986
  return;
15108
14987
  }
14988
+ if (msg.type === "should-respond-result") {
14989
+ handleShouldRespondResult(msg.id, msg.respond);
14990
+ return;
14991
+ }
15109
14992
  if (msg.type === "call") {
15110
14993
  void handleCall(msg, callbacks, ws);
15111
14994
  }
@@ -15715,6 +15598,30 @@ async function runReconcileCmd(args) {
15715
15598
  printLog(target, log5);
15716
15599
  }
15717
15600
 
15601
+ // src/commands/desktop.ts
15602
+ import { spawnSync as spawnSync2 } from "child_process";
15603
+ var SCRIPT_SH = "https://flyspace.ai/install-desktop.sh";
15604
+ var SCRIPT_PS1 = "https://flyspace.ai/install-desktop.ps1";
15605
+ var USAGE9 = "Usage: flyspace desktop install [--dev]";
15606
+ async function runDesktopCmd(args) {
15607
+ const [sub, ...rest] = args;
15608
+ if (sub !== "install" || rest.some((a) => a !== "--dev")) {
15609
+ printRaw(USAGE9);
15610
+ process.exit(1);
15611
+ }
15612
+ const dev = rest.includes("--dev");
15613
+ const result = process.platform === "win32" ? spawnSync2(
15614
+ "powershell",
15615
+ ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `& ([scriptblock]::Create((irm ${SCRIPT_PS1})))${dev ? " -Dev" : ""}`],
15616
+ { stdio: "inherit" }
15617
+ ) : spawnSync2("bash", ["-c", `curl -fsSL ${SCRIPT_SH} | bash -s --${dev ? " --dev" : ""}`], { stdio: "inherit" });
15618
+ if (result.error) {
15619
+ printRaw(`Could not run the desktop installer: ${result.error.message}`);
15620
+ process.exit(1);
15621
+ }
15622
+ if (result.status !== 0) process.exit(result.status ?? 1);
15623
+ }
15624
+
15718
15625
  // src/cli.ts
15719
15626
  import { join as join21 } from "path";
15720
15627
  var home = flyspaceHome();
@@ -15724,7 +15631,7 @@ if (home) {
15724
15631
  if (!path.split(":").includes(bin)) process.env.PATH = path ? `${bin}:${path}` : bin;
15725
15632
  }
15726
15633
  var XERO_USAGE = false ? " xero Connect to Xero and expose it as an MCP server\n" : "";
15727
- var USAGE9 = `
15634
+ var USAGE10 = `
15728
15635
  Usage: flyspace <command> [options]
15729
15636
 
15730
15637
  Commands:
@@ -15737,6 +15644,7 @@ var USAGE9 = `
15737
15644
  restart Restart the service
15738
15645
  logs Tail the service log (-e for error log)
15739
15646
  upgrade Upgrade Flyspace to the latest version
15647
+ desktop Install or update the desktop app (desktop install [--dev])
15740
15648
  uninstall Remove Flyspace from this machine (CLI, services, config)
15741
15649
  config Show resolved config (--edit to edit, --path for file path)
15742
15650
  automation Manage scheduled tasks and triggers
@@ -15852,17 +15760,20 @@ async function main() {
15852
15760
  case "dashboard":
15853
15761
  await runDashboard(args.slice(1));
15854
15762
  break;
15763
+ case "desktop":
15764
+ await runDesktopCmd(args.slice(1));
15765
+ break;
15855
15766
  case "mcp":
15856
15767
  await runMcpCmd(args.slice(1));
15857
15768
  break;
15858
15769
  case "-v":
15859
15770
  case "--version":
15860
- printRaw("0.1.53");
15771
+ printRaw("0.1.55");
15861
15772
  break;
15862
15773
  case "-h":
15863
15774
  case "--help":
15864
15775
  case void 0:
15865
- printRaw(USAGE9);
15776
+ printRaw(USAGE10);
15866
15777
  break;
15867
15778
  case "xero":
15868
15779
  if (false) {
@@ -15873,7 +15784,7 @@ async function main() {
15873
15784
  // falls through
15874
15785
  default:
15875
15786
  printRaw(`Unknown command: ${command}`);
15876
- printRaw(USAGE9);
15787
+ printRaw(USAGE10);
15877
15788
  process.exit(1);
15878
15789
  }
15879
15790
  }