flyspace-cli 0.1.65 → 0.1.67

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
@@ -2,7 +2,6 @@
2
2
  import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
3
  const require = __flyspaceCreateRequire(import.meta.url);
4
4
  import {
5
- AGENT_AUTHOR,
6
5
  AutomationManager,
7
6
  BOT_DM_KEY,
8
7
  BOT_LABEL,
@@ -10,11 +9,10 @@ import {
10
9
  BRANDING_DEFAULTS,
11
10
  BUILT_IN_OUTPUT_STYLES,
12
11
  CLI_VERSION,
13
- ChannelCwdError,
14
12
  ChatAgent,
15
13
  DEFAULT_TIMEZONE,
16
- DefaultChannelError,
17
14
  DocShareSlugTakenError,
15
+ GUIDE_RULES,
18
16
  HANDLE_PATTERN,
19
17
  HandleTakenError,
20
18
  InvalidTransferError,
@@ -25,19 +23,18 @@ import {
25
23
  SHARE_ASSET_PLACEHOLDER,
26
24
  SKIP_SUBTYPES,
27
25
  SUPPORT_AVATAR_URL,
26
+ SUPPORT_GRANT_HOURS,
28
27
  TRANSLATION_LANGUAGES,
29
28
  TRIAL_DAYS,
30
29
  UsageStore,
31
30
  agentViewer,
32
31
  allowedOrigins,
33
- auditChannelCwds,
34
32
  authorFor,
35
33
  blockToFallbackText,
36
34
  bodyTextFor,
37
35
  buildAuthorizeUrl,
38
36
  buildAutoTitle,
39
37
  cachedProfileConfig,
40
- canSeeChannel,
41
38
  canonicalLanguage,
42
39
  channelSkillsDir,
43
40
  claudeAuthFailed,
@@ -46,7 +43,6 @@ import {
46
43
  codexAuthAvailable,
47
44
  consumeOAuthState,
48
45
  corsForShell,
49
- createChannel,
50
46
  createDocShare,
51
47
  createDocsRouter,
52
48
  createFeatureFlagsRouter,
@@ -59,6 +55,7 @@ import {
59
55
  createRequestSupabaseClient,
60
56
  createSkillFile,
61
57
  createStateToken,
58
+ createSupportGrant,
62
59
  createTtsRouter,
63
60
  createWorkspace,
64
61
  crossOriginShell,
@@ -75,33 +72,27 @@ import {
75
72
  deleteWorkspace,
76
73
  deleteWorkspaceDomain,
77
74
  deriveConnectionSlug,
78
- deriveThreadTitle,
79
75
  detectSourceLanguage,
80
76
  displayNameFor,
81
77
  dropShareAudio,
82
78
  dropShareLangAudioKeys,
83
79
  effectiveModel,
84
- ensureAgentDmChannel,
85
- ensureGeneralChannel,
86
- ensureMemberDmChannel,
87
80
  ensureUsersCached,
88
81
  escalateToHuman,
89
82
  exchangeCode,
90
- expandPath,
91
83
  explainCost,
92
84
  extractCategories,
85
+ extractGuide,
93
86
  filterReadableDocsChannels,
94
- findChannel,
95
- findChannelById,
96
87
  findDocShareBySource,
97
88
  findOwningProfile,
98
89
  findSkillDetail,
99
90
  flatDocs,
91
+ getActiveSupportGrant,
100
92
  getAgentPaused,
101
93
  getAllowGuestAccess,
102
94
  getChannelDocsMemberAccess,
103
95
  getChannelMemory,
104
- getChannelRegistry,
105
96
  getLocalCache,
106
97
  getMcpConnection,
107
98
  getMcpProvider,
@@ -109,7 +100,6 @@ import {
109
100
  getMembershipByUserId,
110
101
  getMemory,
111
102
  getOutputStyleDefault,
112
- getProfileChannelRegistry,
113
103
  getWorkspaceAutoContinueLimit,
114
104
  getWorkspaceBilling,
115
105
  getWorkspaceBranding,
@@ -121,26 +111,22 @@ import {
121
111
  getWorkspaceOwnPersona,
122
112
  getWorkspacePermissionMode,
123
113
  getWorkspacePlanStatus,
114
+ grantSupportMembership,
124
115
  handleSupportMention,
125
116
  insertMcpConnection,
126
117
  insertWorkspaceDomain,
127
118
  installUsageRecording,
128
119
  invalidateAuthContextCache,
129
120
  isAllowedModel,
130
- isCwdUsable,
131
121
  isDevHost,
132
122
  isDocsAccess,
133
123
  isFeatureEnabled,
134
- isHumanAuthor,
135
124
  isLockedPlan,
136
- isLogicalCwd,
137
125
  isMemoryType,
138
126
  isOlderVersion,
139
- isPermissionMode,
140
127
  isSlugAvailable,
141
128
  isSourceLanguage,
142
129
  isTranslatableLanguage,
143
- isUnderLogicalRoot,
144
130
  isUnknownWorkspaceHost,
145
131
  isUuid,
146
132
  isValidSkillName,
@@ -164,6 +150,8 @@ import {
164
150
  listSkillFiles,
165
151
  listSkills,
166
152
  listSlashItems,
153
+ listSupportLog,
154
+ listSupportWorkspaceIds,
167
155
  listThreadMemoryEvents,
168
156
  listWorkspaceSummaries,
169
157
  listWorkspaces,
@@ -176,7 +164,7 @@ import {
176
164
  loadWorkspaceBranding,
177
165
  loadWorkspacePrompt,
178
166
  localDefaults,
179
- markChannelGreeted,
167
+ logSupportAction,
180
168
  markInviteResent,
181
169
  markMemoryUsed,
182
170
  markWorkspaceGreeted,
@@ -186,7 +174,6 @@ import {
186
174
  onboardingPending,
187
175
  pinnedClaudeConfigDir,
188
176
  platformAdminEmails,
189
- postToDashboardChannel,
190
177
  profileClaudeConfigDir,
191
178
  profileEnv,
192
179
  profileFromHost,
@@ -199,7 +186,6 @@ import {
199
186
  recentRunsForWorkspace,
200
187
  refreshAutomationRegistry,
201
188
  refreshCache,
202
- refreshChannelRegistry,
203
189
  refreshUserCache,
204
190
  removeChannelMember,
205
191
  renderAppIcon,
@@ -210,12 +196,12 @@ import {
210
196
  resolveAuthContext,
211
197
  resolveChannelConfig,
212
198
  resolveChannelId,
213
- resolveCwd,
214
- resolveDashboardChannelId,
215
199
  resolveDocsAccess,
216
200
  resolveRateCard,
217
201
  resolveUserId,
218
202
  revokeDocShare,
203
+ revokeSupportGrants,
204
+ revokeSupportMembership,
219
205
  rowToMemory,
220
206
  runAutomation,
221
207
  runPersonaCmd,
@@ -243,6 +229,7 @@ import {
243
229
  setMemoryAutoPaused,
244
230
  setOutputStyleDefault,
245
231
  setProfileConfigCache,
232
+ setWorkspaceAgentDefaults,
246
233
  setWorkspaceArchived,
247
234
  setWorkspaceAutoContinueLimit,
248
235
  setWorkspaceOwnPersona,
@@ -250,19 +237,15 @@ import {
250
237
  setWorkspaceStripeSubscription,
251
238
  slackMrkdwnToMarkdown,
252
239
  startAutomationRegistryPolling,
253
- startChannelRegistryPolling,
254
240
  startServer,
255
241
  suggestChannelField,
256
- syncPostToDashboard,
257
242
  syncSlackAvatars,
258
243
  syncSupportReply,
259
244
  transferWorkspaceAdmin,
260
245
  trustedHost,
261
246
  tsToIso,
262
247
  undoMemoryEvent,
263
- updateChannelById,
264
248
  updateChannelMemory,
265
- updateChannelsMcpConnections,
266
249
  updateDocShareFeatures,
267
250
  updateDocShareSnapshot,
268
251
  updateMcpConnectionSettings,
@@ -279,37 +262,49 @@ import {
279
262
  useDirectSupabase,
280
263
  useLocalCache,
281
264
  validateMemoryInput,
282
- warnOnBrokenChannelCwds,
283
265
  watchDocs,
284
266
  workspaceHostname,
285
267
  workspaceSkillsDir,
286
268
  writeSkillFile
287
- } from "./chunk-5ISKGSFF.js";
269
+ } from "./chunk-GT2SOVPK.js";
288
270
  import {
271
+ CALL_TIMEOUT_MS,
272
+ DEFAULT_DATA_API_PORT,
273
+ DOCS_CALL_TIMEOUT_MS,
274
+ HEARTBEAT_TIMEOUT_MS,
275
+ HOST_SOCKET_PATH,
276
+ LOCAL_RELAY_PATH,
277
+ MEMORY_EXTRACTION_TIMEOUT_MS,
278
+ RELAYED_METHODS,
289
279
  checkPermissionAction,
280
+ createChannelAction,
290
281
  createThreadAction,
291
- firstReplyBody,
292
- getThread,
282
+ encodeWireMessage,
293
283
  listAutoUpdateSharesAction,
294
- listChannels,
295
284
  listChannelsAction,
296
- listThreads,
297
- moveThread,
298
285
  moveThreadAction,
299
286
  openDocAction,
287
+ parseWireMessage,
300
288
  postReplyAction,
301
289
  readThreadAction,
290
+ renameChannelAction,
302
291
  requestPermissionAction,
303
292
  resolveChannel,
293
+ runChatCmd,
304
294
  runDocsCmd,
305
295
  searchThreadsAction,
296
+ setChannelSlackAction,
306
297
  setUiZoomAction,
307
298
  shareDocAction
308
- } from "./chunk-GQ2QZ5WF.js";
299
+ } from "./chunk-KP64MCSF.js";
309
300
  import {
301
+ AGENT_AUTHOR,
310
302
  AuthApiError,
303
+ CHANNEL_DESCRIPTION_MAX,
304
+ ChannelCwdError,
311
305
  DEFAULT_API_URL,
312
306
  DEFAULT_PROFILE,
307
+ DefaultChannelError,
313
308
  LOCAL_ACTION_PATH,
314
309
  LOCAL_DB_PATH,
315
310
  SCRATCH_PREFIX,
@@ -317,17 +312,30 @@ import {
317
312
  SessionStore,
318
313
  acquireHostLock,
319
314
  apiUrl,
315
+ auditChannelCwds,
320
316
  boundWorkspaces,
317
+ canSeeChannel,
321
318
  clearLocalAuth,
319
+ createChannel,
322
320
  createHostDbClient,
323
321
  credentialsPath,
324
322
  databaseReachable,
323
+ deriveThreadTitle,
325
324
  deviceKeyPath,
325
+ displayCwd,
326
+ ensureAgentDmChannel,
326
327
  ensureDeviceKey,
327
328
  ensureDirs,
329
+ ensureGeneralChannel,
330
+ ensureMemberDmChannel,
331
+ expandPath,
328
332
  fetchWhoAmI,
333
+ findChannel,
334
+ findChannelById,
329
335
  getAccessToken,
336
+ getChannelRegistry,
330
337
  getProfile,
338
+ getProfileChannelRegistry,
331
339
  getR2Bucket,
332
340
  getR2Client,
333
341
  getSupabaseClient,
@@ -337,27 +345,42 @@ import {
337
345
  handlePluginSvgResult,
338
346
  handleScratchImageResult,
339
347
  handleShouldRespondResult,
348
+ isCwdUsable,
340
349
  isEffort,
350
+ isHumanAuthor,
351
+ isLogicalCwd,
352
+ isPermissionMode,
353
+ isUnderLogicalRoot,
341
354
  loadConfig,
342
355
  loadCredentials,
343
356
  loadEnvFiles,
357
+ markChannelGreeted,
358
+ normaliseChannelDescription,
344
359
  paths,
345
360
  pollDeviceToken,
346
361
  publishHostEndpoint,
347
362
  readHostEndpoint,
363
+ refreshChannelRegistry,
348
364
  requestAction,
349
365
  requestDeviceCode,
350
366
  requestHostDb,
351
367
  requireSlackBotToken,
368
+ resolveCwd,
369
+ resolveDashboardChannelId,
352
370
  revokeDevice,
353
371
  runWithProfile,
354
372
  saveCredentials,
355
373
  setHostDbSender,
356
374
  setSupabaseClient,
357
375
  slackConfigured,
376
+ startChannelRegistryPolling,
358
377
  sumR2PrefixBytes,
359
- useHostDbWithoutCredentials
360
- } from "./chunk-O7OYNQND.js";
378
+ syncPostToDashboard,
379
+ updateChannelById,
380
+ updateChannelsMcpConnections,
381
+ useHostDbWithoutCredentials,
382
+ warnOnBrokenChannelCwds
383
+ } from "./chunk-JH66T2SW.js";
361
384
 
362
385
  // ../core/src/logger.ts
363
386
  var ALREADY_STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
@@ -696,10 +719,10 @@ function restartHostService() {
696
719
  }
697
720
  return false;
698
721
  }
699
- function serviceActive(label2, unit) {
722
+ function serviceActive(label, unit) {
700
723
  try {
701
724
  if (platform() === "darwin") {
702
- const out = execSync(`launchctl print gui/${process.getuid?.()}/${label2}`, { encoding: "utf-8", stdio: "pipe" });
725
+ const out = execSync(`launchctl print gui/${process.getuid?.()}/${label}`, { encoding: "utf-8", stdio: "pipe" });
703
726
  return /^\s*state = running$/m.test(out);
704
727
  }
705
728
  if (platform() === "linux") {
@@ -1252,9 +1275,15 @@ function assertLinkable(target) {
1252
1275
  const root = existsSync5(flyspaceRoot()) ? realpathSync2(flyspaceRoot()) : flyspaceRoot();
1253
1276
  const denied = [join5(home2, ".ssh"), join5(home2, "Library"), join5(home2, ".config"), join5(home2, ".gnupg")];
1254
1277
  if (target === home2 || target === "/" || target === root || target.startsWith(`${root}/`)) {
1255
- throw new Error(`cannot link ${target}`);
1278
+ throw new Error(`cannot link ${target}: this folder can't be a channel folder, pick a project folder instead`);
1279
+ }
1280
+ const hit = denied.find((d) => target === d || target.startsWith(`${d}/`));
1281
+ if (hit) {
1282
+ const shown = hit.replace(home2, "~");
1283
+ throw new Error(
1284
+ `cannot link ${target}: ${shown} is blocked for security reasons, copy or move the folder outside ${shown}`
1285
+ );
1256
1286
  }
1257
- if (denied.some((d) => target === d || target.startsWith(`${d}/`))) throw new Error(`cannot link ${target}`);
1258
1287
  }
1259
1288
  function linkProjectFolders(slug, items2) {
1260
1289
  if (!SLUG_RE.test(slug)) throw new Error(`invalid workspace slug: ${slug}`);
@@ -2214,7 +2243,7 @@ function npmEnv(target) {
2214
2243
  return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
2215
2244
  }
2216
2245
  async function runUpgrade() {
2217
- const current = "0.1.65";
2246
+ const current = "0.1.67";
2218
2247
  console.log(`Current version: ${current}`);
2219
2248
  console.log("Checking for updates...\n");
2220
2249
  try {
@@ -2367,10 +2396,10 @@ function printList(manager) {
2367
2396
  }
2368
2397
  for (const channelRef2 of [...groups.keys()].sort()) {
2369
2398
  const channel = findChannel(channelRef2);
2370
- const label2 = channel ? `${channelRef2} (${channel.name})` : channelRef2;
2399
+ const label = channel ? `${channelRef2} (${channel.name})` : channelRef2;
2371
2400
  const cwd = channel?.cwd ? ` \u2014 cwd: ${channel.cwd}` : "";
2372
2401
  console.log(`
2373
- ${label2}${cwd}`);
2402
+ ${label}${cwd}`);
2374
2403
  for (const line of groups.get(channelRef2)) console.log(line);
2375
2404
  }
2376
2405
  console.log();
@@ -2630,9 +2659,18 @@ async function runAutomationCmd(args) {
2630
2659
  }
2631
2660
  await handleEdit(manager, args[1], args.slice(2));
2632
2661
  break;
2633
- case "add":
2634
- await handleAdd(manager, args.slice(1));
2662
+ case "add": {
2663
+ const addArgs = args.slice(1);
2664
+ const ref = getArg(addArgs, "--channel") ?? getArg(addArgs, "--target-channel");
2665
+ const owner = findChannel(ref)?.profile;
2666
+ if (owner && owner !== getProfile()) {
2667
+ console.log(`Channel ${ref} belongs to workspace "${owner}"; adding the automation there.`);
2668
+ await runWithProfile(owner, () => handleAdd(new AutomationManager(), addArgs));
2669
+ } else {
2670
+ await handleAdd(manager, addArgs);
2671
+ }
2635
2672
  break;
2673
+ }
2636
2674
  case "remove":
2637
2675
  if (!args[1]) {
2638
2676
  console.error("Usage: flyspace automation remove <name>");
@@ -3443,8 +3481,8 @@ function callbackUrl(c) {
3443
3481
  function workspaceOrigin(c, slug) {
3444
3482
  const proto = c.req.header("x-forwarded-proto") ?? "http";
3445
3483
  const host = trustedHost(c) ?? "";
3446
- const [label2 = "", ...rest] = host.split(".");
3447
- const prefix = label2.startsWith("dev-") ? "dev-" : "";
3484
+ const [label = "", ...rest] = host.split(".");
3485
+ const prefix = label.startsWith("dev-") ? "dev-" : "";
3448
3486
  return `${proto}://${[prefix + slug, ...rest].join(".")}`;
3449
3487
  }
3450
3488
 
@@ -3997,8 +4035,8 @@ async function findInvite(token) {
3997
4035
  return lookupInviteByToken(token);
3998
4036
  }
3999
4037
  var PASSWORD_MIN = 8;
4000
- function passwordField(name, label2, autocomplete, display, invalid, value = "") {
4001
- return `<label for="${name}" class="fs-ink" style="display:block;font:600 13px/1.4 ${display};color:${DARK.ink};margin-bottom:6px;">${label2}</label><div style="position:relative;margin-bottom:16px;"><input id="${name}" name="${name}" type="password" required${name === "password" ? " autofocus" : ""} minlength="${PASSWORD_MIN}" autocomplete="${autocomplete}" value="${escapeHtml(value)}" style="display:block;box-sizing:border-box;width:100%;border:1px solid ${invalid ? "#d33" : DARK.line};border-radius:8px;background:transparent;padding:12px 44px 12px 12px;font:500 15px/1.2 ${display};color:inherit;outline:0;"><button type="button" data-toggle-password="${name}" aria-label="Show password" aria-pressed="false" class="fs-dim" style="position:absolute;top:0;right:0;height:100%;width:44px;display:flex;align-items:center;justify-content:center;border:0;background:transparent;color:${DARK.dim};cursor:pointer;"><svg data-eye viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg><svg data-eye-off viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="display:none"><path d="M17.94 17.94A10.9 10.9 0 0 1 12 19c-6.5 0-10-7-10-7a18.5 18.5 0 0 1 5.06-5.94M9.9 4.24A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a18.5 18.5 0 0 1-2.16 3.19M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg></button></div>`;
4038
+ function passwordField(name, label, autocomplete, display, invalid, value = "") {
4039
+ return `<label for="${name}" class="fs-ink" style="display:block;font:600 13px/1.4 ${display};color:${DARK.ink};margin-bottom:6px;">${label}</label><div style="position:relative;margin-bottom:16px;"><input id="${name}" name="${name}" type="password" required${name === "password" ? " autofocus" : ""} minlength="${PASSWORD_MIN}" autocomplete="${autocomplete}" value="${escapeHtml(value)}" style="display:block;box-sizing:border-box;width:100%;border:1px solid ${invalid ? "#d33" : DARK.line};border-radius:8px;background:transparent;padding:12px 44px 12px 12px;font:500 15px/1.2 ${display};color:inherit;outline:0;"><button type="button" data-toggle-password="${name}" aria-label="Show password" aria-pressed="false" class="fs-dim" style="position:absolute;top:0;right:0;height:100%;width:44px;display:flex;align-items:center;justify-content:center;border:0;background:transparent;color:${DARK.dim};cursor:pointer;"><svg data-eye viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg><svg data-eye-off viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="display:none"><path d="M17.94 17.94A10.9 10.9 0 0 1 12 19c-6.5 0-10-7-10-7a18.5 18.5 0 0 1 5.06-5.94M9.9 4.24A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a18.5 18.5 0 0 1-2.16 3.19M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg></button></div>`;
4002
4040
  }
4003
4041
  var CLAUDE_PATH = "m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z";
4004
4042
  var CODEX_PATH = "M8.086.457a6.105 6.105 0 013.046-.415c1.333.153 2.521.72 3.564 1.7a.117.117 0 00.107.029c1.408-.346 2.762-.224 4.061.366l.063.03.154.076c1.357.703 2.33 1.77 2.918 3.198.278.679.418 1.388.421 2.126a5.655 5.655 0 01-.18 1.631.167.167 0 00.04.155 5.982 5.982 0 011.578 2.891c.385 1.901-.01 3.615-1.183 5.14l-.182.22a6.063 6.063 0 01-2.934 1.851.162.162 0 00-.108.102c-.255.736-.511 1.364-.987 1.992-1.199 1.582-2.962 2.462-4.948 2.451-1.583-.008-2.986-.587-4.21-1.736a.145.145 0 00-.14-.032c-.518.167-1.04.191-1.604.185a5.924 5.924 0 01-2.595-.622 6.058 6.058 0 01-2.146-1.781c-.203-.269-.404-.522-.551-.821a7.74 7.74 0 01-.495-1.283 6.11 6.11 0 01-.017-3.064.166.166 0 00.008-.074.115.115 0 00-.037-.064 5.958 5.958 0 01-1.38-2.202 5.196 5.196 0 01-.333-1.589 6.915 6.915 0 01.188-2.132c.45-1.484 1.309-2.648 2.577-3.493.282-.188.55-.334.802-.438.286-.12.573-.22.861-.304a.129.129 0 00.087-.087A6.016 6.016 0 015.635 2.31C6.315 1.464 7.132.846 8.086.457zm-.804 7.85a.848.848 0 00-1.473.842l1.694 2.965-1.688 2.848a.849.849 0 001.46.864l1.94-3.272a.849.849 0 00.007-.854l-1.94-3.393zm5.446 6.24a.849.849 0 000 1.695h4.848a.849.849 0 000-1.696h-4.848z";
@@ -4152,10 +4190,10 @@ function createAuthConfirmRouter() {
4152
4190
  const target = workspaceOrigin(c, workspace?.slug ?? "app");
4153
4191
  const href = escapeHtml(target);
4154
4192
  const branding = workspace ? await loadWorkspaceBranding(workspace.slug) : null;
4155
- const label2 = escapeHtml(branding?.displayName?.trim() || workspace?.slug || "Flyspace");
4193
+ const label = escapeHtml(branding?.displayName?.trim() || workspace?.slug || "Flyspace");
4156
4194
  return c.html(
4157
4195
  page(
4158
- masthead2("Flyspace", FLYSPACE_MARK, display, true) + `<div class="fs-ink" style="font:600 20px/1.3 ${display};color:${DARK.ink};margin-bottom:10px;">This invitation has already been used</div><p class="fs-muted" style="margin:0;font:400 14px/1.6 ${display};color:${DARK.muted};">Your workspace has been created.</p><p class="fs-muted" style="margin:10px 0 0;font:400 14px/1.6 ${display};color:${DARK.muted};">Taking you to <a href="${href}" style="color:inherit;">${label2}</a> in <span id="n">5</span> seconds.</p><script>(()=>{let n=5;const e=document.getElementById('n');const t=setInterval(()=>{n--;e.textContent=String(n);if(n<=0){clearInterval(t);location.replace(${JSON.stringify(target)})}},1000)})()</script>`,
4196
+ masthead2("Flyspace", FLYSPACE_MARK, display, true) + `<div class="fs-ink" style="font:600 20px/1.3 ${display};color:${DARK.ink};margin-bottom:10px;">This invitation has already been used</div><p class="fs-muted" style="margin:0;font:400 14px/1.6 ${display};color:${DARK.muted};">Your workspace has been created.</p><p class="fs-muted" style="margin:10px 0 0;font:400 14px/1.6 ${display};color:${DARK.muted};">Taking you to <a href="${href}" style="color:inherit;">${label}</a> in <span id="n">5</span> seconds.</p><script>(()=>{let n=5;const e=document.getElementById('n');const t=setInterval(()=>{n--;e.textContent=String(n);if(n<=0){clearInterval(t);location.replace(${JSON.stringify(target)})}},1000)})()</script>`,
4159
4197
  void 0,
4160
4198
  void 0,
4161
4199
  true
@@ -4769,7 +4807,7 @@ function createClient3() {
4769
4807
  const config = loadConfig();
4770
4808
  return new WebClient3(requireSlackBotToken(config));
4771
4809
  }
4772
- async function listChannels2(client2, refresh) {
4810
+ async function listChannels(client2, refresh) {
4773
4811
  if (refresh) await refreshCache(client2);
4774
4812
  let channels = listMemberChannels();
4775
4813
  if (channels.length === 0) {
@@ -4911,9 +4949,9 @@ async function threadReplies(client2, nameOrId, ts2) {
4911
4949
  }) : "?";
4912
4950
  const author = msg.user ? displayNameFor(msg.user) : msg.bot_id ?? "unknown";
4913
4951
  const text = renderText(msg.text ?? "").replace(/\n/g, "\n ");
4914
- const label2 = i === 0 ? "[parent]" : `[reply ${i}]`;
4952
+ const label = i === 0 ? "[parent]" : `[reply ${i}]`;
4915
4953
  console.log(
4916
- ` ${label2} [${time}] ${author} (${msg.user ?? msg.bot_id ?? "?"}, ts: ${msg.ts}):`
4954
+ ` ${label} [${time}] ${author} (${msg.user ?? msg.bot_id ?? "?"}, ts: ${msg.ts}):`
4917
4955
  );
4918
4956
  console.log(` ${text}`);
4919
4957
  console.log();
@@ -5598,7 +5636,7 @@ async function runSlackCmd(args) {
5598
5636
  }
5599
5637
  case "channels": {
5600
5638
  const client2 = createClient3();
5601
- await listChannels2(client2, args.includes("--refresh"));
5639
+ await listChannels(client2, args.includes("--refresh"));
5602
5640
  break;
5603
5641
  }
5604
5642
  case "users": {
@@ -5675,234 +5713,6 @@ async function runSlackCmd(args) {
5675
5713
  }
5676
5714
  }
5677
5715
 
5678
- // src/store/thread-move.ts
5679
- async function moveThreadFully(threadId, toChannelId) {
5680
- const thread = await getThread(threadId);
5681
- if (!thread) throw new Error(`No thread with id ${threadId}.`);
5682
- if (thread.channelId === toChannelId) return "unchanged";
5683
- const channels = await listChannels();
5684
- const to = channels.find((c) => c.id === toChannelId);
5685
- if (!to) throw new Error(`No channel with id ${toChannelId}.`);
5686
- const from = channels.find((c) => c.id === thread.channelId);
5687
- const store = new SessionStore(paths.DB_FILE);
5688
- try {
5689
- await moveThread(thread.id, to.id);
5690
- const counts = store.moveThread(`chat:${thread.channelId}`, `chat:${to.id}`, thread.id);
5691
- return { from, to, ...counts, cwdChanged: !!from && from.cwd !== to.cwd };
5692
- } finally {
5693
- store.close();
5694
- }
5695
- }
5696
-
5697
- // ../core/src/bridge-protocol.ts
5698
- var HOST_SOCKET_PATH = "/internal/host-socket";
5699
- var DEFAULT_DATA_API_PORT = 4757;
5700
- var CALL_TIMEOUT_MS = 15e3;
5701
- var DOCS_CALL_TIMEOUT_MS = 12e4;
5702
- var MEMORY_EXTRACTION_TIMEOUT_MS = 165e3;
5703
- var HEARTBEAT_INTERVAL_MS = 15e3;
5704
- var HEARTBEAT_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 2.5;
5705
- var LOCAL_RELAY_PATH = "/internal/agent-call";
5706
- var RELAYED_METHODS = [
5707
- "onChatMessage",
5708
- "isAgentThinking",
5709
- "getAgentActivities",
5710
- "getBackgroundTasks",
5711
- "cancelAgentRun",
5712
- "regenerateAgentRun",
5713
- "listAgentRuns",
5714
- "wakeAgentRun"
5715
- ];
5716
- function encodeWireMessage(msg) {
5717
- return JSON.stringify(msg);
5718
- }
5719
- function parseWireMessage(raw) {
5720
- try {
5721
- return JSON.parse(String(raw));
5722
- } catch {
5723
- return null;
5724
- }
5725
- }
5726
-
5727
- // src/commands/chat.ts
5728
- var USAGE4 = `
5729
- Usage: flyspace chat <subcommand> [options]
5730
-
5731
- Subcommands:
5732
- channels [--profile-name <p>] List dashboard chat channels (id, name, cwd)
5733
- threads <channel> [--limit <n>] List recent threads in a channel (default: 20)
5734
- move <thread-id> --to <channel> Move a thread to another channel
5735
- post --channel <c> --text <t> Start a new thread, or reply with --thread
5736
- [--thread <id>] [--title <t>]
5737
- wake --thread <id> --text <t> Post a background task's result AND start a
5738
- new agent turn on the thread to act on it
5739
- [--about <t>] What the job waits for (shown in the thread)
5740
-
5741
- Options:
5742
- --to <name-or-id> Destination channel for "move"
5743
- --limit <n> Max threads to list (default: 20)
5744
- --profile-name <p> Only channels belonging to this profile
5745
- --dry-run Show what "move" would do, change nothing
5746
- --channel <name-or-id> Target channel for "post"
5747
- --thread <id> Reply to this thread instead of starting one
5748
- --text <t> Message body for "post"
5749
- --title <t> Thread title for "post" (new threads only)
5750
- `;
5751
- function getArg3(args, flag) {
5752
- const idx = args.indexOf(flag);
5753
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : void 0;
5754
- }
5755
- function label(thread, opener) {
5756
- const text = thread.title ?? opener ?? "(empty)";
5757
- const oneLine = text.replace(/\s+/g, " ").trim();
5758
- return oneLine.length > 60 ? `${oneLine.slice(0, 59)}\u2026` : oneLine;
5759
- }
5760
- async function runChannels(args) {
5761
- const channels = await listChannels(getArg3(args, "--profile-name"));
5762
- if (channels.length === 0) {
5763
- console.log("No chat channels found.");
5764
- return;
5765
- }
5766
- const width = Math.max(...channels.map((c) => c.name.length));
5767
- for (const channel of channels) {
5768
- console.log(`${channel.id} ${channel.name.padEnd(width)} ${channel.profile} ${channel.cwd}`);
5769
- }
5770
- }
5771
- async function runThreads(args) {
5772
- const nameOrId = args[0];
5773
- if (!nameOrId) throw new Error("Usage: flyspace chat threads <channel> [--limit <n>]");
5774
- const channel = await resolveChannel(nameOrId, getArg3(args, "--profile-name"));
5775
- const limit = Number(getArg3(args, "--limit") ?? 20);
5776
- const threads = await listThreads(channel.id, limit);
5777
- if (threads.length === 0) {
5778
- console.log(`No threads in ${channel.name}.`);
5779
- return;
5780
- }
5781
- console.log(`${channel.name} (${channel.id}):`);
5782
- for (const thread of threads) {
5783
- const opener = thread.title ? void 0 : await firstReplyBody(thread.id);
5784
- const when = thread.updatedAt.slice(0, 16).replace("T", " ");
5785
- const replies = String(thread.replies).padStart(3);
5786
- console.log(` ${thread.id} ${when} ${replies} replies ${label(thread, opener)}`);
5787
- }
5788
- }
5789
- async function runMove(args) {
5790
- const threadId = args[0];
5791
- const to = getArg3(args, "--to");
5792
- if (!threadId || !to) {
5793
- throw new Error("Usage: flyspace chat move <thread-id> --to <channel> [--dry-run]");
5794
- }
5795
- const thread = await getThread(threadId);
5796
- if (!thread) throw new Error(`No thread with id ${threadId}.`);
5797
- const destination = await resolveChannel(to, getArg3(args, "--profile-name"));
5798
- if (thread.channelId === destination.id) {
5799
- console.log(`Thread is already in ${destination.name} \u2014 nothing to do.`);
5800
- return;
5801
- }
5802
- const channels = await listChannels();
5803
- const source = channels.find((c) => c.id === thread.channelId);
5804
- const opener = thread.title ? void 0 : await firstReplyBody(thread.id);
5805
- const from = source ? `${source.name} (${source.id})` : thread.channelId;
5806
- console.log(`Thread: ${label(thread, opener)}`);
5807
- console.log(` ${thread.replies} replies, last active ${thread.updatedAt.slice(0, 16)}`);
5808
- console.log(`From: ${from}`);
5809
- console.log(`To: ${destination.name} (${destination.id})`);
5810
- if (args.includes("--dry-run")) {
5811
- console.log("\n--dry-run: nothing changed.");
5812
- return;
5813
- }
5814
- const moved = await moveThreadFully(thread.id, destination.id);
5815
- if (moved === "unchanged") return;
5816
- console.log(
5817
- `
5818
- Moved. Re-keyed ${moved.sessions} session(s), ${moved.modelOverrides} model override(s), ${moved.effortOverrides} effort override(s).`
5819
- );
5820
- if (moved.cwdChanged && source) {
5821
- console.log(
5822
- `
5823
- Note: the channels have different working directories.
5824
- ${source.cwd}
5825
- ${destination.cwd}
5826
- Files this thread created live in the old one, move them yourself if the
5827
- thread still refers to them.`
5828
- );
5829
- }
5830
- console.log("Reload the dashboard to see it in its new home.");
5831
- }
5832
- async function runPost(args) {
5833
- const channelArg = getArg3(args, "--channel");
5834
- const threadArg = getArg3(args, "--thread");
5835
- const text = getArg3(args, "--text");
5836
- const title = getArg3(args, "--title");
5837
- if (!text || !channelArg && !threadArg) {
5838
- throw new Error(
5839
- "Usage: flyspace chat post --channel <c> --text <t> [--thread <id>] [--title <t>]"
5840
- );
5841
- }
5842
- const channelId = threadArg ? void 0 : (await resolveChannel(channelArg, getArg3(args, "--profile-name"))).id;
5843
- const { threadId } = await postToDashboardChannel({
5844
- channelId,
5845
- threadId: threadArg,
5846
- text,
5847
- title
5848
- });
5849
- console.log(threadArg ? `Replied in thread ${threadId}.` : `Posted new thread ${threadId}.`);
5850
- }
5851
- async function runWake(args) {
5852
- const threadId = getArg3(args, "--thread");
5853
- const text = getArg3(args, "--text");
5854
- if (!threadId || !text) throw new Error("Usage: flyspace chat wake --thread <id> --text <t>");
5855
- const { replyId } = await postToDashboardChannel({ threadId, text });
5856
- const endpoint = readHostEndpoint();
5857
- if (!endpoint) {
5858
- console.log(`Replied in thread ${threadId}, but no Host is running to wake the agent.`);
5859
- return;
5860
- }
5861
- const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_RELAY_PATH}`, {
5862
- method: "POST",
5863
- headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
5864
- body: JSON.stringify({ method: "wakeAgentRun", profile: getProfile(), args: [threadId, replyId, text] }),
5865
- signal: AbortSignal.timeout(3e4)
5866
- });
5867
- if (!res.ok) throw new Error(`Replied in thread ${threadId}, but the Host answered ${res.status}`);
5868
- const { value } = await res.json();
5869
- console.log(
5870
- value ? `Replied in thread ${threadId} and woke the agent.` : `Replied in thread ${threadId}; wake refused (too many wakes in a row without a human message).`
5871
- );
5872
- }
5873
- async function runChatCmd(args) {
5874
- loadEnvFiles();
5875
- useHostDbWithoutCredentials();
5876
- const subcommand = args[0];
5877
- const rest = args.slice(1);
5878
- switch (subcommand) {
5879
- case "channels":
5880
- await runChannels(rest);
5881
- break;
5882
- case "threads":
5883
- await runThreads(rest);
5884
- break;
5885
- case "move":
5886
- await runMove(rest);
5887
- break;
5888
- case "post":
5889
- await runPost(rest);
5890
- break;
5891
- case "wake":
5892
- await runWake(rest);
5893
- break;
5894
- case "-h":
5895
- case "--help":
5896
- case void 0:
5897
- console.log(USAGE4);
5898
- break;
5899
- default:
5900
- console.error(`Unknown subcommand: ${subcommand}`);
5901
- console.log(USAGE4);
5902
- process.exit(1);
5903
- }
5904
- }
5905
-
5906
5716
  // src/commands/memory.ts
5907
5717
  import { readFileSync as readFileSync13 } from "fs";
5908
5718
 
@@ -5983,7 +5793,7 @@ async function importClaudeMemories(dir, channelId, opts = {}) {
5983
5793
  }
5984
5794
 
5985
5795
  // src/commands/memory.ts
5986
- var USAGE5 = `
5796
+ var USAGE4 = `
5987
5797
  Usage: flyspace memory <subcommand> --channel <name-or-id> [options]
5988
5798
 
5989
5799
  A channel's persistent agent memory (docs/features/workspace-memory.md).
@@ -6010,7 +5820,7 @@ var USAGE5 = `
6010
5820
 
6011
5821
  Types: ${MEMORY_TYPES.join(", ")}
6012
5822
  `;
6013
- function getArg4(args, flag) {
5823
+ function getArg3(args, flag) {
6014
5824
  const idx = args.indexOf(flag);
6015
5825
  return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : void 0;
6016
5826
  }
@@ -6031,12 +5841,12 @@ async function runMemoryCmd(args) {
6031
5841
  const subcommand = args[0];
6032
5842
  const rest = args.slice(1);
6033
5843
  if (!subcommand || subcommand === "-h" || subcommand === "--help") {
6034
- console.log(USAGE5);
5844
+ console.log(USAGE4);
6035
5845
  return;
6036
5846
  }
6037
- const channelArg = getArg4(rest, "--channel");
5847
+ const channelArg = getArg3(rest, "--channel");
6038
5848
  if (!channelArg) throw new Error("--channel <name-or-id> is required");
6039
- const channel = await resolveChannel(channelArg, getArg4(rest, "--profile-name"));
5849
+ const channel = await resolveChannel(channelArg, getArg3(rest, "--profile-name"));
6040
5850
  const words = positionals(rest);
6041
5851
  const target = await resolveTarget(rest, channel);
6042
5852
  const where = target.scope === "channel" ? channel.name : `${target.scope} memory`;
@@ -6069,10 +5879,10 @@ ${memory.body}`);
6069
5879
  break;
6070
5880
  }
6071
5881
  case "save": {
6072
- const name = getArg4(rest, "--name");
6073
- const type = getArg4(rest, "--type");
6074
- const description = getArg4(rest, "--description");
6075
- const bodyArg = getArg4(rest, "--body");
5882
+ const name = getArg3(rest, "--name");
5883
+ const type = getArg3(rest, "--type");
5884
+ const description = getArg3(rest, "--description");
5885
+ const bodyArg = getArg3(rest, "--body");
6076
5886
  if (!name || !type || !description || bodyArg === void 0) {
6077
5887
  throw new Error(
6078
5888
  "Usage: flyspace memory save --channel <c> --name <slug> --type <type> --description <one line> --body <text | -> [--thread <id>]"
@@ -6080,7 +5890,7 @@ ${memory.body}`);
6080
5890
  }
6081
5891
  if (!isMemoryType(type)) throw new Error(`--type must be one of ${MEMORY_TYPES.join(", ")}`);
6082
5892
  const body = bodyArg === "-" ? readFileSync13(0, "utf-8") : bodyArg;
6083
- const thread = getArg4(rest, "--thread");
5893
+ const thread = getArg3(rest, "--thread");
6084
5894
  const { created, changed } = await saveMemory(
6085
5895
  target,
6086
5896
  {
@@ -6100,14 +5910,14 @@ ${memory.body}`);
6100
5910
  case "delete": {
6101
5911
  const ref = words[0];
6102
5912
  if (!ref) throw new Error("Usage: flyspace memory delete --channel <c> <name-or-id>");
6103
- const deleted = await deleteMemory(target, ref, "agent", getArg4(rest, "--thread"));
5913
+ const deleted = await deleteMemory(target, ref, "agent", getArg3(rest, "--thread"));
6104
5914
  if (!deleted) throw new Error(`No memory ${ref} in ${where}.`);
6105
5915
  console.log(`Deleted memory ${ref}.`);
6106
5916
  break;
6107
5917
  }
6108
5918
  case "import": {
6109
5919
  if (target.scope !== "channel") throw new Error("import only fills a channel memory");
6110
- const dir = getArg4(rest, "--dir") ?? claudeMemoryDir(channel.cwd, profileClaudeConfigDirFor(channel.profile));
5920
+ const dir = getArg3(rest, "--dir") ?? claudeMemoryDir(channel.cwd, profileClaudeConfigDirFor(channel.profile));
6111
5921
  const dryRun = rest.includes("--dry-run");
6112
5922
  const results = await importClaudeMemories(dir, channel.id, { dryRun });
6113
5923
  for (const r of results) {
@@ -6122,12 +5932,12 @@ ${memory.body}`);
6122
5932
  }
6123
5933
  default:
6124
5934
  console.error(`Unknown subcommand: ${subcommand}`);
6125
- console.log(USAGE5);
5935
+ console.log(USAGE4);
6126
5936
  process.exit(1);
6127
5937
  }
6128
5938
  }
6129
5939
  async function resolveTarget(args, channel) {
6130
- const scope = getArg4(args, "--scope") ?? "channel";
5940
+ const scope = getArg3(args, "--scope") ?? "channel";
6131
5941
  if (scope === "channel") return { scope: "channel", channelId: channel.id };
6132
5942
  if (scope !== "user" && scope !== "workspace") {
6133
5943
  throw new Error("--scope must be channel, user or workspace");
@@ -6135,13 +5945,13 @@ async function resolveTarget(args, channel) {
6135
5945
  const workspace = await getWorkspaceBySlug(channel.profile);
6136
5946
  if (!workspace) throw new Error(`No workspace for ${channel.profile}.`);
6137
5947
  if (scope === "workspace") return { scope, workspaceId: workspace.id };
6138
- const userId = getArg4(args, "--user");
5948
+ const userId = getArg3(args, "--user");
6139
5949
  if (!userId) throw new Error("--scope user needs --user <user-id>");
6140
5950
  return { scope, workspaceId: workspace.id, userId };
6141
5951
  }
6142
5952
 
6143
5953
  // src/commands/mcp.ts
6144
- var USAGE6 = `
5954
+ var USAGE5 = `
6145
5955
  Usage: flyspace mcp <server>
6146
5956
 
6147
5957
  Run one of Flyspace's own MCP servers on stdio. Spawned by the agent runtime
@@ -6150,7 +5960,8 @@ Usage: flyspace mcp <server>
6150
5960
  Servers:
6151
5961
  threads Search, read, and write this workspace's chat threads
6152
5962
  (search_threads, read_thread, list_channels, create_thread,
6153
- post_reply, move_thread, share_doc)
5963
+ post_reply, move_thread, rename_channel, create_channel,
5964
+ set_channel_slack, share_doc)
6154
5965
 
6155
5966
  Try it by hand (type a JSON-RPC line, or pipe one in):
6156
5967
  flyspace mcp threads
@@ -6158,7 +5969,7 @@ Usage: flyspace mcp <server>
6158
5969
  async function runMcpCmd(args) {
6159
5970
  const server = args[0];
6160
5971
  if (!server || server === "-h" || server === "--help") {
6161
- console.log(USAGE6.trim());
5972
+ console.log(USAGE5.trim());
6162
5973
  return;
6163
5974
  }
6164
5975
  restoreStdout();
@@ -6166,13 +5977,13 @@ async function runMcpCmd(args) {
6166
5977
  useHostDbWithoutCredentials();
6167
5978
  switch (server) {
6168
5979
  case "threads": {
6169
- const { startThreadsServer } = await import("./threads-AR6D7V3Y.js");
5980
+ const { startThreadsServer } = await import("./threads-B5FBIJLG.js");
6170
5981
  await startThreadsServer();
6171
5982
  return;
6172
5983
  }
6173
5984
  default:
6174
5985
  console.error(`Unknown MCP server: ${server}`);
6175
- console.error(USAGE6.trim());
5986
+ console.error(USAGE5.trim());
6176
5987
  process.exit(1);
6177
5988
  }
6178
5989
  }
@@ -6247,7 +6058,7 @@ async function ensureServices() {
6247
6058
  }
6248
6059
 
6249
6060
  // ../api/src/dashboard/api.ts
6250
- import { Hono as Hono35 } from "hono";
6061
+ import { Hono as Hono39 } from "hono";
6251
6062
 
6252
6063
  // ../api/src/dashboard/guest-routes.ts
6253
6064
  import { Hono as Hono4 } from "hono";
@@ -6675,7 +6486,9 @@ function createUploadsRouter() {
6675
6486
  );
6676
6487
  });
6677
6488
  app.get("/attachments/:key{.+}", async (c) => {
6678
- const url = await presignAttachmentRead(c.req.param("key"));
6489
+ const key = c.req.param("key");
6490
+ if (key.split("/")[1] !== getProfile()) return c.json({ error: "not found" }, 404);
6491
+ const url = await presignAttachmentRead(key);
6679
6492
  if (!url) return c.json({ error: "not found" }, 404);
6680
6493
  c.header("Cache-Control", `private, max-age=${PRESIGN_TTL_SECONDS - 60}`);
6681
6494
  return c.redirect(url, 302);
@@ -7064,7 +6877,7 @@ var readThread = async (input2, ctx) => {
7064
6877
  replies: replies ?? []
7065
6878
  };
7066
6879
  };
7067
- var listChannels3 = async (_input, ctx) => {
6880
+ var listChannels2 = async (_input, ctx) => {
7068
6881
  let query = getSupabaseClient().from("channels").select("id, name, profile, cwd");
7069
6882
  if (ctx.scope !== null) query = query.in("profile", ctx.scope);
7070
6883
  const { data, error: error2 } = await query.order("name");
@@ -7089,7 +6902,7 @@ var postReply = async (input2, ctx) => {
7089
6902
  const owner = await threadInScope(ctx, input2.thread_id);
7090
6903
  return { threadId: owner.threadId, replyId: await insertAgentReply(owner.threadId, input2.text) };
7091
6904
  };
7092
- var moveThread2 = async (input2, ctx) => {
6905
+ var moveThread = async (input2, ctx) => {
7093
6906
  const owner = await threadInScope(ctx, input2.thread_id);
7094
6907
  if (owner.channelId === input2.to_channel_id) return "unchanged";
7095
6908
  const to = await channelInScope(ctx, input2.to_channel_id);
@@ -7104,6 +6917,52 @@ var moveThread2 = async (input2, ctx) => {
7104
6917
  to: { id: to.id, name: to.name, cwd: to.cwd }
7105
6918
  };
7106
6919
  };
6920
+ var renameChannel = async (input2, ctx) => {
6921
+ const channel = await channelInScope(ctx, input2.channel_id);
6922
+ const { error: error2 } = await getSupabaseClient().from("channels").update({ name: input2.name }).eq("id", channel.id);
6923
+ if (error2) throw new Error(`rename failed: ${error2.message}`);
6924
+ return { id: channel.id, from: channel.name, to: input2.name };
6925
+ };
6926
+ async function assertSlackFree(ctx, slackId, exceptId) {
6927
+ const { data, error: error2 } = await getSupabaseClient().from("channels").select("id, name, profile").eq("external_channel_id", slackId).maybeSingle();
6928
+ if (error2) throw new Error(error2.message);
6929
+ if (!data || data["id"] === exceptId) return;
6930
+ throw new ActionError(
6931
+ inScope(ctx, data["profile"]) ? `Slack channel ${slackId} is already bound to #${data["name"]} (${data["id"]}).` : `Slack channel ${slackId} is already bound to another workspace's channel.`
6932
+ );
6933
+ }
6934
+ var createChannel2 = async (input2, ctx) => {
6935
+ const profile = input2.workspace?.trim() || ctx.requester.workspace || (ctx.scope?.length === 1 ? ctx.scope[0] : void 0);
6936
+ if (!profile) throw new ActionError("Which workspace? Pass workspace.");
6937
+ if (!inScope(ctx, profile)) throw new ActionError(`No workspace ${profile}.`);
6938
+ const supabase = getSupabaseClient();
6939
+ const { data: taken, error: takenError } = await supabase.from("channels").select("id").eq("profile", profile).eq("name", input2.name).maybeSingle();
6940
+ if (takenError) throw new Error(takenError.message);
6941
+ if (taken) throw new ActionError(`#${input2.name} already exists (${taken["id"]}).`);
6942
+ if (input2.slack_channel_id) await assertSlackFree(ctx, input2.slack_channel_id);
6943
+ const cwd = `${profile}/${input2.name}`;
6944
+ const { data, error: error2 } = await supabase.from("channels").insert({
6945
+ name: input2.name,
6946
+ cwd,
6947
+ profile,
6948
+ external_channel_id: input2.slack_channel_id ?? null
6949
+ }).select("id, name, profile, cwd").single();
6950
+ if (error2 || !data) throw new Error(`create failed: ${error2?.message ?? "no row returned"}`);
6951
+ await refreshChannelRegistry();
6952
+ return data;
6953
+ };
6954
+ var setChannelSlack = async (input2, ctx) => {
6955
+ const channel = await channelInScope(ctx, input2.channel_id);
6956
+ const supabase = getSupabaseClient();
6957
+ const { data: row, error: readError } = await supabase.from("channels").select("external_channel_id").eq("id", channel.id).single();
6958
+ if (readError) throw new Error(readError.message);
6959
+ const to = input2.slack_channel_id ?? null;
6960
+ if (to) await assertSlackFree(ctx, to, channel.id);
6961
+ const { error: error2 } = await supabase.from("channels").update({ external_channel_id: to, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", channel.id);
6962
+ if (error2) throw new Error(`update failed: ${error2.message}`);
6963
+ await refreshChannelRegistry();
6964
+ return { id: channel.id, from: row["external_channel_id"] ?? null, to };
6965
+ };
7107
6966
  var shareDoc = async (input2, ctx) => {
7108
6967
  const res = await publishDocShareForHost(ctx.scope, {
7109
6968
  channelId: input2.channel_id,
@@ -7210,10 +7069,13 @@ var checkPermission = async (input2, ctx) => {
7210
7069
  var HANDLERS = {
7211
7070
  [searchThreadsAction.name]: searchThreads,
7212
7071
  [readThreadAction.name]: readThread,
7213
- [listChannelsAction.name]: listChannels3,
7072
+ [listChannelsAction.name]: listChannels2,
7214
7073
  [createThreadAction.name]: createThread,
7215
7074
  [postReplyAction.name]: postReply,
7216
- [moveThreadAction.name]: moveThread2,
7075
+ [moveThreadAction.name]: moveThread,
7076
+ [renameChannelAction.name]: renameChannel,
7077
+ [createChannelAction.name]: createChannel2,
7078
+ [setChannelSlackAction.name]: setChannelSlack,
7217
7079
  [shareDocAction.name]: shareDoc,
7218
7080
  [openDocAction.name]: openDoc,
7219
7081
  [setUiZoomAction.name]: setUiZoom,
@@ -7324,6 +7186,7 @@ function remoteAgentCallbacks() {
7324
7186
  cancelAgentRun: async (threadId) => await callHost("cancelAgentRun", [threadId]) ?? false,
7325
7187
  regenerateAgentRun: async (threadId, stoppedReplyId) => await callHost("regenerateAgentRun", [threadId, stoppedReplyId]) ?? false,
7326
7188
  listAgentRuns: async () => await callHost("listAgentRuns", []) ?? [],
7189
+ listBackgroundThreads: async () => await callHost("listBackgroundThreads", []) ?? [],
7327
7190
  // `null` (no Host, or no answer in time) passes through: the extractor
7328
7191
  // reads it as a failed call and retries the thread next sweep.
7329
7192
  completeMemoryExtraction: (req) => callHost("completeMemoryExtraction", [req], MEMORY_EXTRACTION_TIMEOUT_MS),
@@ -7693,7 +7556,8 @@ function createAuthRouter() {
7693
7556
  owner: isWorkspaceOwner(ctx),
7694
7557
  // Only the Host's owner can run `flyspace upgrade` on it, so other
7695
7558
  // admins never see the upgrade banner. Support staff can tell them to.
7696
- hostOwner: await isHostOwner(ctx)
7559
+ hostOwner: await isHostOwner(ctx),
7560
+ ...ctx.isSupport ? { isSupport: true } : {}
7697
7561
  });
7698
7562
  });
7699
7563
  auth.patch("/handle", async (c) => {
@@ -7724,70 +7588,22 @@ function createAuthRouter() {
7724
7588
  return auth;
7725
7589
  }
7726
7590
 
7727
- // ../api/src/store/support-store.ts
7728
- var SUPPORT_HANDLE = "flyspace-support";
7729
- async function logSupportAction(entry) {
7730
- const { error: error2 } = await getSupabaseClient().from("support_access_log").insert({
7731
- workspace_id: entry.workspaceId,
7732
- staff_user_id: entry.staffUserId,
7733
- staff_email: entry.staffEmail,
7734
- action: entry.action,
7735
- detail: entry.detail ?? null
7736
- });
7737
- if (error2) throw new Error(`logSupportAction(${entry.action}): ${error2.message}`);
7738
- }
7739
- async function listSupportWorkspaceIds(userId) {
7740
- const { data, error: error2 } = await getSupabaseClient().from("memberships").select("workspace_id").eq("user_id", userId).eq("is_support", true);
7741
- if (error2) throw new Error(`listSupportWorkspaceIds: ${error2.message}`);
7742
- return new Set((data ?? []).map((r) => r.workspace_id));
7743
- }
7744
- async function grantSupportMembership(params) {
7745
- const db = getSupabaseClient();
7746
- const { data: existing, error: readError } = await db.from("memberships").select("is_support").eq("workspace_id", params.workspaceId).eq("user_id", params.userId).maybeSingle();
7747
- if (readError) throw new Error(`grantSupportMembership: ${readError.message}`);
7748
- if (existing) {
7749
- if (existing.is_support === true) return "existing";
7750
- throw new Error("already a regular member of this workspace");
7751
- }
7752
- const { data: taken } = await db.from("memberships").select("id").eq("workspace_id", params.workspaceId).eq("handle", SUPPORT_HANDLE).maybeSingle();
7753
- const handle = taken ? `${SUPPORT_HANDLE}-${params.userId.slice(0, 8)}` : SUPPORT_HANDLE;
7754
- const { error: error2 } = await db.from("memberships").insert({
7755
- workspace_id: params.workspaceId,
7756
- user_id: params.userId,
7757
- email: params.email,
7758
- handle,
7759
- role: "admin",
7760
- status: "active",
7761
- is_support: true,
7762
- accepted_at: (/* @__PURE__ */ new Date()).toISOString()
7763
- });
7764
- if (error2) throw new Error(`grantSupportMembership: ${error2.message}`);
7765
- return "granted";
7766
- }
7767
- async function revokeSupportMembership(workspaceId, userId) {
7768
- const { data, error: error2 } = await getSupabaseClient().from("memberships").delete().eq("workspace_id", workspaceId).eq("user_id", userId).eq("is_support", true).select("id");
7769
- if (error2) throw new Error(`revokeSupportMembership: ${error2.message}`);
7770
- return (data ?? []).length > 0;
7771
- }
7772
- async function listSupportLog(filter) {
7773
- let query = getSupabaseClient().from("support_access_log").select("*").order("created_at", { ascending: false }).limit(Math.min(filter.limit ?? 200, 1e3));
7774
- if (filter.workspaceId) query = query.eq("workspace_id", filter.workspaceId);
7775
- const { data, error: error2 } = await query;
7776
- if (error2) throw new Error(`listSupportLog: ${error2.message}`);
7777
- return (data ?? []).map((r) => ({
7778
- id: r.id,
7779
- workspaceId: r.workspace_id,
7780
- staffUserId: r.staff_user_id,
7781
- staffEmail: r.staff_email,
7782
- action: r.action,
7783
- detail: r.detail ?? null,
7784
- createdAt: r.created_at
7785
- }));
7786
- }
7787
-
7788
7591
  // ../api/src/dashboard/auth-middleware.ts
7789
7592
  var ENTER_WINDOW_MS = 8 * 60 * 60 * 1e3;
7790
7593
  var lastEnter = /* @__PURE__ */ new Map();
7594
+ var READ_DEDUPE_MS = 60 * 1e3;
7595
+ var lastRead = /* @__PURE__ */ new Map();
7596
+ function shouldLogRead(key, now) {
7597
+ if ((lastRead.get(key) ?? 0) + READ_DEDUPE_MS > now) return false;
7598
+ lastRead.set(key, now);
7599
+ if (lastRead.size > 5e3) {
7600
+ for (const [k, t] of lastRead) if (t + READ_DEDUPE_MS < now) lastRead.delete(k);
7601
+ }
7602
+ return true;
7603
+ }
7604
+ function isPassiveRequest(path) {
7605
+ return path.endsWith("/read") || path.endsWith("/autocomplete") || path.includes("/translat") || path.endsWith("/support-access/view");
7606
+ }
7791
7607
  function auditSupport(ctx, action, detail) {
7792
7608
  logSupportAction({
7793
7609
  workspaceId: ctx.workspaceId,
@@ -7809,7 +7625,7 @@ var requireWorkspaceMembership = async (c, next) => {
7809
7625
  auditSupport(ctx, "enter");
7810
7626
  }
7811
7627
  await next();
7812
- if (!["GET", "HEAD", "OPTIONS"].includes(c.req.method)) {
7628
+ if (!["GET", "HEAD", "OPTIONS"].includes(c.req.method) && !isPassiveRequest(c.req.path)) {
7813
7629
  auditSupport(ctx, "write", { method: c.req.method, path: c.req.path, status: c.res.status });
7814
7630
  }
7815
7631
  };
@@ -8031,6 +7847,9 @@ function createAdminRouter() {
8031
7847
  const operator = c.get("platformOperator");
8032
7848
  const workspaceId = c.req.param("id");
8033
7849
  let result;
7850
+ if (!await getActiveSupportGrant(workspaceId)) {
7851
+ return c.json({ error: "workspace has not granted support access" }, 403);
7852
+ }
8034
7853
  try {
8035
7854
  result = await grantSupportMembership({
8036
7855
  workspaceId,
@@ -8091,53 +7910,190 @@ function createAdminRouter() {
8091
7910
  import { existsSync as existsSync17 } from "fs";
8092
7911
  import sharp4 from "sharp";
8093
7912
 
8094
- // ../api/src/dashboard/automations-routes.ts
7913
+ // ../api/src/dashboard/channel-agent-routes.ts
7914
+ import { Hono as Hono11 } from "hono";
7915
+
7916
+ // ../api/src/dashboard/channel-members-routes.ts
8095
7917
  import { Hono as Hono10 } from "hono";
8096
- var TYPES2 = ["schedule", "trigger", "mention-trigger"];
8097
- function isType(t) {
8098
- return TYPES2.includes(t);
8099
- }
8100
- function sanitize(body) {
8101
- const { created_by: _b, created_at: _a, ...rest } = body;
8102
- void _b;
8103
- void _a;
8104
- return rest;
8105
- }
8106
- function statusFor(message) {
8107
- if (/already exists/.test(message)) return 409;
8108
- if (/not found/.test(message)) return 404;
8109
- return 400;
7918
+ async function isChannelAdmin(ctx, channelId) {
7919
+ if (ctx.role === "admin") return true;
7920
+ const membership = await getMembershipByUserId(ctx.workspaceId, ctx.userId);
7921
+ if (!membership) return false;
7922
+ const members = await listChannelMembers(channelId);
7923
+ return members.some((m) => m.membershipId === membership.id && m.role === "channel_admin");
8110
7924
  }
8111
- function createAutomationWriteRouter() {
8112
- const app = new Hono10();
8113
- const manager = () => new AutomationManager();
8114
- app.get("/:type/:name", (c) => {
8115
- const item = manager().get(c.req.param("name"));
8116
- if (!item) return c.json({ error: "not found" }, 404);
8117
- return c.json(item);
7925
+ function createChannelMembersRouter() {
7926
+ const router = new Hono10();
7927
+ router.get("/:id/members", async (c) => {
7928
+ const ctx = await resolveAuthContext(c);
7929
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7930
+ const members = await listChannelMembers(c.req.param("id"));
7931
+ return c.json({ members });
8118
7932
  });
8119
- app.post("/:type", async (c) => {
8120
- const type = c.req.param("type");
8121
- if (!isType(type)) return c.json({ error: "unknown type" }, 400);
8122
- const body = sanitize(await c.req.json());
8123
- const next = { ...body, created_at: (/* @__PURE__ */ new Date()).toISOString() };
8124
- try {
8125
- const m = manager();
8126
- if (type === "schedule") await m.addSchedule(next);
8127
- else if (type === "trigger") await m.addTrigger(next);
8128
- else await m.addMentionTrigger(next);
8129
- return c.json(next, 201);
8130
- } catch (e) {
8131
- const msg = e.message;
8132
- const status = statusFor(msg);
8133
- return c.json(status === 400 ? { errors: [msg] } : { error: msg }, status);
7933
+ router.put("/:id/members/:membershipId", async (c) => {
7934
+ const ctx = await resolveAuthContext(c);
7935
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7936
+ const channelId = c.req.param("id");
7937
+ if (!await isChannelAdmin(ctx, channelId)) {
7938
+ return c.json({ error: "channel admin access required" }, 403);
7939
+ }
7940
+ const body = await c.req.json().catch(() => ({}));
7941
+ if (body.role !== "channel_admin" && body.role !== "channel_member") {
7942
+ return c.json({ error: "role must be 'channel_admin' or 'channel_member'" }, 400);
8134
7943
  }
7944
+ const member = await upsertChannelMember({
7945
+ channelId,
7946
+ membershipId: c.req.param("membershipId"),
7947
+ role: body.role
7948
+ });
7949
+ return c.json({ member });
8135
7950
  });
8136
- app.put("/:type/:name", async (c) => {
8137
- const type = c.req.param("type");
8138
- if (!isType(type)) return c.json({ error: "unknown type" }, 400);
8139
- const name = c.req.param("name");
8140
- const body = sanitize(await c.req.json());
7951
+ router.delete("/:id/members/:membershipId", async (c) => {
7952
+ const ctx = await resolveAuthContext(c);
7953
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7954
+ const channelId = c.req.param("id");
7955
+ if (!await isChannelAdmin(ctx, channelId)) {
7956
+ return c.json({ error: "channel admin access required" }, 403);
7957
+ }
7958
+ const removed = await removeChannelMember(channelId, c.req.param("membershipId"));
7959
+ if (!removed) return c.json({ error: "no such channel member" }, 404);
7960
+ return c.body(null, 204);
7961
+ });
7962
+ router.get("/:id/docs-access/me", async (c) => {
7963
+ const ctx = await resolveAuthContext(c);
7964
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7965
+ return c.json({ access: await resolveDocsAccess(ctx, c.req.param("id")) });
7966
+ });
7967
+ router.get("/:id/docs-access", async (c) => {
7968
+ const ctx = await resolveAuthContext(c);
7969
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7970
+ const channelId = c.req.param("id");
7971
+ if (!await isChannelAdmin(ctx, channelId)) {
7972
+ return c.json({ error: "channel admin access required" }, 403);
7973
+ }
7974
+ return c.json({ memberAccess: await getChannelDocsMemberAccess(channelId) });
7975
+ });
7976
+ router.put("/:id/docs-access", async (c) => {
7977
+ const ctx = await resolveAuthContext(c);
7978
+ if (!ctx) return c.json({ error: "workspace access required" }, 403);
7979
+ const channelId = c.req.param("id");
7980
+ if (!await isChannelAdmin(ctx, channelId)) {
7981
+ return c.json({ error: "channel admin access required" }, 403);
7982
+ }
7983
+ const body = await c.req.json().catch(() => ({}));
7984
+ if (!isDocsAccess(body.memberAccess)) {
7985
+ return c.json({ error: "memberAccess must be 'none', 'read' or 'write'" }, 400);
7986
+ }
7987
+ if (!await setChannelDocsMemberAccess(channelId, body.memberAccess)) {
7988
+ return c.json({ error: "no such channel" }, 404);
7989
+ }
7990
+ return c.json({ memberAccess: body.memberAccess });
7991
+ });
7992
+ return router;
7993
+ }
7994
+
7995
+ // ../api/src/dashboard/channel-agent-routes.ts
7996
+ function coerce(body, key, valid) {
7997
+ if (!(key in body)) return void 0;
7998
+ const raw = body[key];
7999
+ if (raw === null || raw === "") return null;
8000
+ if (typeof raw !== "string") return "invalid";
8001
+ const value = raw.trim();
8002
+ return valid(value) ? value : "invalid";
8003
+ }
8004
+ function createChannelAgentRouter() {
8005
+ const router = new Hono11();
8006
+ router.patch("/:id", async (c, next) => {
8007
+ const body = await c.req.raw.clone().json().catch(() => null);
8008
+ if (!body || typeof body !== "object" || !("model" in body || "effort" in body || "description" in body)) {
8009
+ return next();
8010
+ }
8011
+ const auth = await resolveAuthContext(c);
8012
+ if (!auth) return c.json({ error: "workspace access required" }, 403);
8013
+ const id = c.req.param("id");
8014
+ const channel = findChannelById(id);
8015
+ if (!channel || channel.profile !== getProfile()) return c.json({ error: "not found" }, 404);
8016
+ if (!await isChannelAdmin(auth, id)) {
8017
+ return c.json({ error: "channel admin access required" }, 403);
8018
+ }
8019
+ const model = coerce(body, "model", isAllowedModel);
8020
+ const effort = coerce(body, "effort", isEffort);
8021
+ if (model === "invalid") return c.json({ error: "unknown model" }, 400);
8022
+ if (effort === "invalid") {
8023
+ return c.json({ error: "effort must be low, medium, high, xhigh or max" }, 400);
8024
+ }
8025
+ const description = "description" in body ? normaliseChannelDescription(body["description"]) : void 0;
8026
+ if (description === "invalid") {
8027
+ return c.json({ error: `description must be text of at most ${CHANNEL_DESCRIPTION_MAX} characters` }, 400);
8028
+ }
8029
+ const own = ["model", "effort", "description"];
8030
+ if (Object.keys(body).some((k) => !own.includes(k))) return next();
8031
+ try {
8032
+ const updated = await updateChannelById(id, {
8033
+ ...model !== void 0 ? { model } : {},
8034
+ ...effort !== void 0 ? { effort } : {},
8035
+ ...description !== void 0 ? { description } : {}
8036
+ });
8037
+ return c.json({
8038
+ id: updated.id,
8039
+ model: updated.model ?? null,
8040
+ effort: updated.effort ?? null,
8041
+ description: updated.description
8042
+ });
8043
+ } catch (err) {
8044
+ return c.json({ error: err.message }, 500);
8045
+ }
8046
+ });
8047
+ return router;
8048
+ }
8049
+
8050
+ // ../api/src/dashboard/automations-routes.ts
8051
+ import { Hono as Hono12 } from "hono";
8052
+ var TYPES2 = ["schedule", "trigger", "mention-trigger"];
8053
+ function isType(t) {
8054
+ return TYPES2.includes(t);
8055
+ }
8056
+ function sanitize(body) {
8057
+ const { created_by: _b, created_at: _a, ...rest } = body;
8058
+ void _b;
8059
+ void _a;
8060
+ return rest;
8061
+ }
8062
+ function statusFor(message) {
8063
+ if (/already exists/.test(message)) return 409;
8064
+ if (/not found/.test(message)) return 404;
8065
+ return 400;
8066
+ }
8067
+ function createAutomationWriteRouter() {
8068
+ const app = new Hono12();
8069
+ const manager = () => new AutomationManager();
8070
+ app.get("/:type/:name", (c) => {
8071
+ const item = manager().get(c.req.param("name"));
8072
+ if (!item) return c.json({ error: "not found" }, 404);
8073
+ return c.json(item);
8074
+ });
8075
+ app.post("/:type", async (c) => {
8076
+ const type = c.req.param("type");
8077
+ if (!isType(type)) return c.json({ error: "unknown type" }, 400);
8078
+ const body = sanitize(await c.req.json());
8079
+ const next = { ...body, created_at: (/* @__PURE__ */ new Date()).toISOString() };
8080
+ try {
8081
+ const m = manager();
8082
+ if (type === "schedule") await m.addSchedule(next);
8083
+ else if (type === "trigger") await m.addTrigger(next);
8084
+ else await m.addMentionTrigger(next);
8085
+ return c.json(next, 201);
8086
+ } catch (e) {
8087
+ const msg = e.message;
8088
+ const status = statusFor(msg);
8089
+ return c.json(status === 400 ? { errors: [msg] } : { error: msg }, status);
8090
+ }
8091
+ });
8092
+ app.put("/:type/:name", async (c) => {
8093
+ const type = c.req.param("type");
8094
+ if (!isType(type)) return c.json({ error: "unknown type" }, 400);
8095
+ const name = c.req.param("name");
8096
+ const body = sanitize(await c.req.json());
8141
8097
  try {
8142
8098
  const m = manager();
8143
8099
  const existing = m.get(name);
@@ -8165,9 +8121,9 @@ function createAutomationWriteRouter() {
8165
8121
  }
8166
8122
 
8167
8123
  // ../api/src/dashboard/categories-routes.ts
8168
- import { Hono as Hono11 } from "hono";
8124
+ import { Hono as Hono13 } from "hono";
8169
8125
  function createCategoryWriteRouter() {
8170
- const app = new Hono11();
8126
+ const app = new Hono13();
8171
8127
  app.get("/", async (c) => {
8172
8128
  const { data, error: error2 } = await getSupabaseClient().from("categories").select("*").eq("profile", getProfile()).order("position", { ascending: true });
8173
8129
  if (error2) return c.json({ error: error2.message }, 500);
@@ -8221,7 +8177,7 @@ function createCategoryWriteRouter() {
8221
8177
  }
8222
8178
 
8223
8179
  // ../api/src/dashboard/chat-routes.ts
8224
- import { Hono as Hono13 } from "hono";
8180
+ import { Hono as Hono15 } from "hono";
8225
8181
 
8226
8182
  // ../api/src/dashboard/fork-summary.ts
8227
8183
  var MAX_INPUT_CHARS = 6e4;
@@ -8266,7 +8222,7 @@ async function relevantThreadsPage(supabase, handle, channelIds, opts) {
8266
8222
  }
8267
8223
 
8268
8224
  // ../api/src/dashboard/continuous-chat.ts
8269
- import { Hono as Hono12 } from "hono";
8225
+ import { Hono as Hono14 } from "hono";
8270
8226
  var GROQ_API_URL2 = "https://api.groq.com/openai/v1/chat/completions";
8271
8227
  var MODEL = "openai/gpt-oss-120b";
8272
8228
  var STREAM_DAYS = 30;
@@ -8374,7 +8330,7 @@ function tagStoredReply(c, args) {
8374
8330
  }
8375
8331
  var backfilling = /* @__PURE__ */ new Set();
8376
8332
  function createContinuousChatRouter() {
8377
- const app = new Hono12();
8333
+ const app = new Hono14();
8378
8334
  app.get("/channels/:channelId/continuous", async (c) => {
8379
8335
  if (!await isFeatureEnabled(c, "continuous-chat"))
8380
8336
  return c.json({ error: "feature not enabled" }, 403);
@@ -8896,6 +8852,9 @@ var NO_STATUS_COLUMN = "none";
8896
8852
  function isBoardStatus(v) {
8897
8853
  return typeof v === "string" && BOARD_STATUSES.includes(v);
8898
8854
  }
8855
+ function callerAuthor(c) {
8856
+ return c.get("auth").handle;
8857
+ }
8899
8858
  async function callerMembershipId(c) {
8900
8859
  const viewer = c.get("auth");
8901
8860
  if (!viewer) return null;
@@ -9056,7 +9015,7 @@ async function generateAutoTitle(threadId, channelId, body) {
9056
9015
  await supabase.from("threads").update({ auto_title: autoTitle }).eq("id", threadId).is("title", null);
9057
9016
  }
9058
9017
  function createChatRouter(agent = {}) {
9059
- const app = new Hono13();
9018
+ const app = new Hono15();
9060
9019
  const {
9061
9020
  onChatMessage: onMessage,
9062
9021
  isAgentThinking,
@@ -9064,7 +9023,8 @@ function createChatRouter(agent = {}) {
9064
9023
  getBackgroundTasks,
9065
9024
  cancelAgentRun,
9066
9025
  regenerateAgentRun,
9067
- listAgentRuns
9026
+ listAgentRuns,
9027
+ listBackgroundThreads
9068
9028
  } = agent;
9069
9029
  const askSupport = (c, threadId, author, body) => {
9070
9030
  const viewer = c.get("auth");
@@ -9089,7 +9049,13 @@ function createChatRouter(agent = {}) {
9089
9049
  background: await getBackgroundTasks?.(c.req.param("id")) ?? []
9090
9050
  })
9091
9051
  );
9092
- app.get("/agent-runs", async (c) => c.json({ threadIds: await listAgentRuns?.() ?? [] }));
9052
+ app.get("/agent-runs", async (c) => {
9053
+ const [threadIds, backgroundThreadIds] = await Promise.all([
9054
+ listAgentRuns?.(),
9055
+ listBackgroundThreads?.()
9056
+ ]);
9057
+ return c.json({ threadIds: threadIds ?? [], backgroundThreadIds: backgroundThreadIds ?? [] });
9058
+ });
9093
9059
  app.get("/channels/:channelId/threads", async (c) => {
9094
9060
  const channelId = c.req.param("channelId");
9095
9061
  if (!ownChannelIds(c).has(channelId)) return c.json({ error: "unknown channel" }, 404);
@@ -9492,10 +9458,10 @@ function createChatRouter(agent = {}) {
9492
9458
  app.patch("/replies/:replyId", async (c) => {
9493
9459
  const replyId = c.req.param("replyId");
9494
9460
  const input2 = await c.req.json().catch(() => null);
9495
- const author = input2?.author;
9461
+ const author = callerAuthor(c);
9496
9462
  const body = input2?.body;
9497
- if (!isNonEmptyString(author) || !isNonEmptyString(body)) {
9498
- return c.json({ errors: ["author and body are required"] }, 400);
9463
+ if (!isNonEmptyString(body)) {
9464
+ return c.json({ errors: ["body is required"] }, 400);
9499
9465
  }
9500
9466
  const supabase = getSupabaseClient();
9501
9467
  const { data: existing, error: fetchError } = await supabase.from("thread_replies").select("*").eq("id", replyId).single();
@@ -9518,10 +9484,10 @@ function createChatRouter(agent = {}) {
9518
9484
  app.post("/replies/:replyId/reactions", async (c) => {
9519
9485
  const replyId = c.req.param("replyId");
9520
9486
  const input2 = await c.req.json().catch(() => null);
9521
- const author = input2?.author;
9487
+ const author = callerAuthor(c);
9522
9488
  const emoji = input2?.emoji;
9523
- if (!isNonEmptyString(author) || !isNonEmptyString(emoji)) {
9524
- return c.json({ errors: ["author and emoji are required"] }, 400);
9489
+ if (!isNonEmptyString(emoji)) {
9490
+ return c.json({ errors: ["emoji is required"] }, 400);
9525
9491
  }
9526
9492
  const supabase = getSupabaseClient();
9527
9493
  const { data: reply, error: replyError } = await supabase.from("thread_replies").select("thread_id").eq("id", replyId).single();
@@ -9559,9 +9525,10 @@ function createChatRouter(agent = {}) {
9559
9525
  const channelId = c.req.param("channelId");
9560
9526
  if (!ownChannelIds(c).has(channelId)) return c.json({ error: "unknown channel" }, 404);
9561
9527
  const input2 = await c.req.json();
9562
- if (!isNonEmptyString(input2.author) || !isNonEmptyString(input2.body)) {
9563
- return c.json({ errors: ["author and body are required"] }, 400);
9528
+ if (!isNonEmptyString(input2.body)) {
9529
+ return c.json({ errors: ["body is required"] }, 400);
9564
9530
  }
9531
+ const author = callerAuthor(c);
9565
9532
  const clientKey2 = isNonEmptyString(input2.clientKey) ? input2.clientKey : null;
9566
9533
  const model = requestedModel(c, input2.model);
9567
9534
  const effort = requestedEffort(c, input2.effort);
@@ -9581,7 +9548,7 @@ function createChatRouter(agent = {}) {
9581
9548
  // name, so it lands as null and the topic is derived from the
9582
9549
  // opening message at display time (see threadCrumbLabel).
9583
9550
  title: isNonEmptyString(input2.title) ? input2.title.trim() : null,
9584
- author: input2.author,
9551
+ author,
9585
9552
  client_key: clientKey2,
9586
9553
  board_status: pickedStatus ?? null
9587
9554
  }).select().single();
@@ -9601,7 +9568,7 @@ function createChatRouter(agent = {}) {
9601
9568
  if (!reply) {
9602
9569
  const { data: insertedReply, error: replyError } = await supabase.from("thread_replies").insert({
9603
9570
  thread_id: thread.id,
9604
- author: input2.author,
9571
+ author,
9605
9572
  body: input2.body,
9606
9573
  client_key: clientKey2,
9607
9574
  model,
@@ -9615,7 +9582,7 @@ function createChatRouter(agent = {}) {
9615
9582
  onMessage?.({
9616
9583
  threadId: thread.id,
9617
9584
  replyId: reply.id,
9618
- author: input2.author,
9585
+ author,
9619
9586
  body: input2.body,
9620
9587
  // From the row, not `model`/`effort`: on the replay path the reply
9621
9588
  // predates this request, so its own stored override is the source of
@@ -9623,12 +9590,12 @@ function createChatRouter(agent = {}) {
9623
9590
  model: reply["model"] ?? void 0,
9624
9591
  effort: effortFromRow(reply["effort"])
9625
9592
  });
9626
- askSupport(c, thread.id, input2.author, input2.body);
9593
+ askSupport(c, thread.id, author, input2.body);
9627
9594
  recordReplyLanguage(reply.id, input2.body);
9628
9595
  tagStoredReply(c, {
9629
9596
  threadId: thread.id,
9630
9597
  replyId: reply.id,
9631
- author: input2.author,
9598
+ author,
9632
9599
  body: input2.body
9633
9600
  });
9634
9601
  }
@@ -9656,10 +9623,7 @@ function createChatRouter(agent = {}) {
9656
9623
  app.post("/replies/:replyId/fork", async (c) => {
9657
9624
  const replyId = c.req.param("replyId");
9658
9625
  const input2 = await c.req.json().catch(() => null);
9659
- const author = input2?.author;
9660
- if (!isNonEmptyString(author)) {
9661
- return c.json({ errors: ["author is required"] }, 400);
9662
- }
9626
+ const author = callerAuthor(c);
9663
9627
  const mode = input2?.mode === "focus" ? "focus" : "condense";
9664
9628
  const instructions = isNonEmptyString(input2?.instructions) ? input2.instructions.trim() : void 0;
9665
9629
  const model = requestedModel(c, input2?.model);
@@ -9718,16 +9682,17 @@ function createChatRouter(agent = {}) {
9718
9682
  app.post("/threads/:id/replies", async (c) => {
9719
9683
  const threadId = c.req.param("id");
9720
9684
  const input2 = await c.req.json();
9721
- if (!isNonEmptyString(input2.author) || !isNonEmptyString(input2.body)) {
9722
- return c.json({ errors: ["author and body are required"] }, 400);
9685
+ if (!isNonEmptyString(input2.body)) {
9686
+ return c.json({ errors: ["body is required"] }, 400);
9723
9687
  }
9688
+ const author = callerAuthor(c);
9724
9689
  const clientKey2 = isNonEmptyString(input2.clientKey) ? input2.clientKey : null;
9725
9690
  const effort = requestedEffort(c, input2.effort);
9726
9691
  if (!await threadIsKnown(threadId, c)) return c.json({ error: "not found" }, 404);
9727
9692
  const model = requestedModel(c, input2.model) ?? await threadModel(threadId);
9728
9693
  const { data, error: error2 } = await getSupabaseClient().from("thread_replies").insert({
9729
9694
  thread_id: threadId,
9730
- author: input2.author,
9695
+ author,
9731
9696
  body: input2.body,
9732
9697
  client_key: clientKey2,
9733
9698
  model,
@@ -9743,21 +9708,21 @@ function createChatRouter(agent = {}) {
9743
9708
  onMessage?.({
9744
9709
  threadId,
9745
9710
  replyId: data.id,
9746
- author: input2.author,
9711
+ author,
9747
9712
  body: input2.body,
9748
9713
  model: data.model ?? void 0,
9749
9714
  effort: effortFromRow(data.effort)
9750
9715
  });
9751
- askSupport(c, threadId, input2.author, input2.body);
9716
+ askSupport(c, threadId, author, input2.body);
9752
9717
  recordReplyLanguage(data.id, input2.body);
9753
9718
  tagStoredReply(c, {
9754
9719
  threadId,
9755
9720
  replyId: data.id,
9756
- author: input2.author,
9721
+ author,
9757
9722
  body: input2.body,
9758
9723
  replyToId: isNonEmptyString(input2.replyToId) ? input2.replyToId : void 0
9759
9724
  });
9760
- void syncSupportReply({ threadId, author: input2.author, body: input2.body });
9725
+ void syncSupportReply({ threadId, author, body: input2.body });
9761
9726
  return c.json(data, 201);
9762
9727
  });
9763
9728
  app.post("/replies/:replyId/support-escalate", async (c) => {
@@ -9770,9 +9735,8 @@ function createChatRouter(agent = {}) {
9770
9735
  );
9771
9736
  return c.json({ error: "not found" }, 404);
9772
9737
  }
9773
- const { author } = await c.req.json().catch(() => ({}));
9774
9738
  try {
9775
- const result = await escalateToHuman(replyId, isNonEmptyString(author) ? author : "a member");
9739
+ const result = await escalateToHuman(replyId, callerAuthor(c));
9776
9740
  if (!result.ok) {
9777
9741
  console.warn(`Support escalation ${result.status}: reply=${replyId} ${result.error}`);
9778
9742
  return c.json({ error: result.error }, result.status);
@@ -9787,7 +9751,7 @@ function createChatRouter(agent = {}) {
9787
9751
  }
9788
9752
 
9789
9753
  // ../api/src/dashboard/doc-shares-routes.ts
9790
- import { Hono as Hono14 } from "hono";
9754
+ import { Hono as Hono16 } from "hono";
9791
9755
 
9792
9756
  // ../api/src/dashboard/share-tags.ts
9793
9757
  var MAX_TAGS = 10;
@@ -9876,7 +9840,7 @@ function resolveChannel2(c) {
9876
9840
  }
9877
9841
  var LIST_LIMIT = 500;
9878
9842
  function createDocShareListRouter() {
9879
- const app = new Hono14();
9843
+ const app = new Hono16();
9880
9844
  app.get("/shares", async (c) => {
9881
9845
  const viewer = c.get("auth");
9882
9846
  const readable = await filterReadableDocsChannels(
@@ -9921,7 +9885,7 @@ function createDocShareListRouter() {
9921
9885
  return app;
9922
9886
  }
9923
9887
  function createDocShareWriteRouter(agent = {}) {
9924
- const app = new Hono14();
9888
+ const app = new Hono16();
9925
9889
  app.use("/:id/docs/share", requireDocsAccess);
9926
9890
  app.use("/:id/docs/share/*", requireDocsAccess);
9927
9891
  app.use("/:id/docs/shares", requireDocsAccess);
@@ -10103,7 +10067,7 @@ function createDocShareWriteRouter(agent = {}) {
10103
10067
  }
10104
10068
 
10105
10069
  // ../api/src/dashboard/search-routes.ts
10106
- import { Hono as Hono15 } from "hono";
10070
+ import { Hono as Hono17 } from "hono";
10107
10071
  function matchScore(q, fields) {
10108
10072
  const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
10109
10073
  if (terms.length === 0) return 0;
@@ -10251,7 +10215,7 @@ function searchAutomations(q) {
10251
10215
  }
10252
10216
  var RESULT_LIMIT = 30;
10253
10217
  function createSearchRouter() {
10254
- const app = new Hono15();
10218
+ const app = new Hono17();
10255
10219
  app.get("/", async (c) => {
10256
10220
  const q = c.req.query("q")?.trim();
10257
10221
  if (!q) return c.json({ results: [] });
@@ -10267,7 +10231,7 @@ function createSearchRouter() {
10267
10231
  }
10268
10232
 
10269
10233
  // ../api/src/dashboard/domain-routes.ts
10270
- import { Hono as Hono16 } from "hono";
10234
+ import { Hono as Hono18 } from "hono";
10271
10235
  var FALLBACK_ORIGIN = "custom.flyspace.ai";
10272
10236
  function isValidCustomHostname(hostname2) {
10273
10237
  if (hostname2.length > 253 || hostname2.endsWith(".flyspace.ai") || hostname2 === "flyspace.ai") {
@@ -10337,7 +10301,7 @@ function view(row, dcv) {
10337
10301
  };
10338
10302
  }
10339
10303
  function createDomainRouter() {
10340
- const app = new Hono16();
10304
+ const app = new Hono18();
10341
10305
  app.use("*", async (c, next) => {
10342
10306
  const auth = c.get("auth");
10343
10307
  if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
@@ -10400,15 +10364,119 @@ function createDomainRouter() {
10400
10364
  return app;
10401
10365
  }
10402
10366
 
10367
+ // ../api/src/dashboard/support-grant-routes.ts
10368
+ import { Hono as Hono19 } from "hono";
10369
+ function createSupportGrantRouter() {
10370
+ const app = new Hono19();
10371
+ app.use("*", async (c, next) => {
10372
+ const auth = c.get("auth");
10373
+ const readOnly = c.req.method === "GET" || auth.isSupport && c.req.path.endsWith("/view");
10374
+ if (auth.role !== "admin" || auth.isSupport && !readOnly) {
10375
+ return c.json({ error: "workspace admin access required" }, 403);
10376
+ }
10377
+ await next();
10378
+ });
10379
+ app.get("/", async (c) => {
10380
+ return c.json({ grant: await getActiveSupportGrant(c.get("auth").workspaceId) });
10381
+ });
10382
+ app.get("/activity", async (c) => {
10383
+ const limit = Number(c.req.query("limit")) || 200;
10384
+ const entries = await listSupportLog({ workspaceId: c.get("auth").workspaceId, limit });
10385
+ const people = await resolvePeople([...new Set(entries.map((e) => e.staffUserId))]);
10386
+ return c.json({
10387
+ entries: entries.map(({ staffEmail, staffUserId, ...e }) => ({
10388
+ ...e,
10389
+ actor: people.get(staffUserId) ?? { name: staffEmail.split("@")[0], avatarUrl: null }
10390
+ }))
10391
+ });
10392
+ });
10393
+ app.post("/view", async (c) => {
10394
+ const auth = c.get("auth");
10395
+ if (!auth.isSupport) return c.json({ ok: true });
10396
+ const body = await c.req.json().catch(() => ({}));
10397
+ const path = typeof body.path === "string" ? body.path.slice(0, 500) : "";
10398
+ const title = typeof body.title === "string" ? body.title.trim().slice(0, 200) : "";
10399
+ if (!path || !shouldLogRead(`${auth.userId}:${auth.workspaceId}:view:${path}`, Date.now())) {
10400
+ return c.json({ ok: true });
10401
+ }
10402
+ await logSupportAction({
10403
+ workspaceId: auth.workspaceId,
10404
+ staffUserId: auth.userId,
10405
+ staffEmail: auth.email,
10406
+ action: "read",
10407
+ detail: { page: path, ...title ? { title } : {} }
10408
+ });
10409
+ return c.json({ ok: true });
10410
+ });
10411
+ app.post("/", async (c) => {
10412
+ const auth = c.get("auth");
10413
+ const body = await c.req.json().catch(() => ({}));
10414
+ const hours = Number(body.hours);
10415
+ if (!SUPPORT_GRANT_HOURS.includes(hours)) {
10416
+ return c.json({ error: `hours must be one of ${SUPPORT_GRANT_HOURS.join(", ")}` }, 400);
10417
+ }
10418
+ const reason = typeof body.reason === "string" ? body.reason.trim().slice(0, 500) : "";
10419
+ const grant = await createSupportGrant({
10420
+ workspaceId: auth.workspaceId,
10421
+ userId: auth.userId,
10422
+ email: auth.email,
10423
+ hours,
10424
+ ...reason ? { reason } : {}
10425
+ });
10426
+ await logSupportAction({
10427
+ workspaceId: auth.workspaceId,
10428
+ staffUserId: auth.userId,
10429
+ staffEmail: auth.email,
10430
+ action: "granted",
10431
+ detail: { hours, expiresAt: grant.expiresAt, ...reason ? { reason } : {} }
10432
+ });
10433
+ invalidateAuthContextCache();
10434
+ return c.json({ grant });
10435
+ });
10436
+ app.delete("/", async (c) => {
10437
+ const auth = c.get("auth");
10438
+ if (await revokeSupportGrants(auth.workspaceId, auth.userId) > 0) {
10439
+ await logSupportAction({
10440
+ workspaceId: auth.workspaceId,
10441
+ staffUserId: auth.userId,
10442
+ staffEmail: auth.email,
10443
+ action: "revoked"
10444
+ });
10445
+ }
10446
+ invalidateAuthContextCache();
10447
+ return c.json({ grant: null });
10448
+ });
10449
+ return app;
10450
+ }
10451
+ async function resolvePeople(ids) {
10452
+ const out = /* @__PURE__ */ new Map();
10453
+ await Promise.all(
10454
+ ids.map(async (id) => {
10455
+ const { data } = await getSupabaseClient().auth.admin.getUserById(id);
10456
+ const user = data?.user;
10457
+ if (!user) return;
10458
+ const meta = user.user_metadata ?? {};
10459
+ out.set(id, {
10460
+ name: meta.name?.trim() || (user.email ?? "").split("@")[0],
10461
+ avatarUrl: meta.avatarKey ? await signAvatarUrl(meta.avatarKey) : null
10462
+ });
10463
+ })
10464
+ );
10465
+ return out;
10466
+ }
10467
+
10403
10468
  // ../api/src/dashboard/transcribe-routes.ts
10404
- import { Hono as Hono17 } from "hono";
10469
+ import { Hono as Hono20 } from "hono";
10405
10470
  var GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
10406
10471
  var MODEL2 = "whisper-large-v3-turbo";
10407
10472
  var MAX_AUDIO_BYTES = 25 * 1024 * 1024;
10408
10473
  var MAX_PROMPT_CHARS = 400;
10409
10474
  var MAX_TAIL_CHARS = 200;
10410
10475
  var MAX_GLOSSARY_CHARS = 150;
10411
- var STYLE_SEED = "\u9019\u662F\u7E41\u9AD4\u4E2D\u6587\u7684\u53E3\u8FF0\uFF0C\u4E2D\u9593\u593E\u96DC English \u8853\u8A9E\uFF0C\u4F8B\u5982 component\u3001API\u3001deploy\u3002";
10476
+ var STYLE_SEEDS = {
10477
+ "zh-Hant": "\u9019\u662F\u7E41\u9AD4\u4E2D\u6587\u7684\u53E3\u8FF0\uFF0C\u4E2D\u9593\u593E\u96DC English \u8853\u8A9E\uFF0C\u4F8B\u5982 component\u3001API\u3001deploy\u3002",
10478
+ "zh-Hans": "\u8FD9\u662F\u7B80\u4F53\u4E2D\u6587\u7684\u53E3\u8FF0\uFF0C\u4E2D\u95F4\u5939\u6742 English \u672F\u8BED\uFF0C\u4F8B\u5982 component\u3001API\u3001deploy\u3002"
10479
+ };
10412
10480
  var HALLUCINATIONS = [
10413
10481
  /^(謝謝|感謝)(大家|您|你)?(的)?(收看|觀看|收聽|觀賞)[。!!.]?$/,
10414
10482
  /^請不吝點讚.*$/,
@@ -10420,18 +10488,18 @@ function isHallucination(text) {
10420
10488
  const t = text.trim();
10421
10489
  return HALLUCINATIONS.some((re) => re.test(t));
10422
10490
  }
10423
- function buildPrompt(terms, tail) {
10491
+ function buildPrompt(terms, tail, locale) {
10424
10492
  let glossary = "";
10425
10493
  for (const term of terms) {
10426
10494
  const next = glossary ? `${glossary}\u3001${term}` : term;
10427
10495
  if (next.length > MAX_GLOSSARY_CHARS) break;
10428
10496
  glossary = next;
10429
10497
  }
10430
- return [glossary && `${glossary}\u3002`, STYLE_SEED, tail.slice(-MAX_TAIL_CHARS)].filter(Boolean).join(" ").slice(-MAX_PROMPT_CHARS);
10498
+ return [glossary && `${glossary}.`, locale && STYLE_SEEDS[locale], tail.slice(-MAX_TAIL_CHARS)].filter(Boolean).join(" ").slice(-MAX_PROMPT_CHARS);
10431
10499
  }
10432
10500
  var NO_SPEECH_THRESHOLD = 0.6;
10433
10501
  function createTranscribeRouter() {
10434
- const app = new Hono17();
10502
+ const app = new Hono20();
10435
10503
  app.post("/transcribe", async (c) => {
10436
10504
  const apiKey = process.env["GROQ_API_KEY"];
10437
10505
  if (!apiKey) return c.json({ error: "transcription is not configured" }, 503);
@@ -10454,7 +10522,9 @@ function createTranscribeRouter() {
10454
10522
  terms = (glossary.get(channelId)?.terms ?? []).map((t) => t.term);
10455
10523
  }
10456
10524
  }
10457
- form.append("prompt", buildPrompt(terms, tail));
10525
+ const locale = typeof body?.["locale"] === "string" ? body["locale"] : void 0;
10526
+ const prompt = buildPrompt(terms, tail, locale);
10527
+ if (prompt) form.append("prompt", prompt);
10458
10528
  const language = body?.["language"];
10459
10529
  if (typeof language === "string" && /^[a-z]{2}$/.test(language)) {
10460
10530
  form.append("language", language);
@@ -10476,10 +10546,401 @@ function createTranscribeRouter() {
10476
10546
  return app;
10477
10547
  }
10478
10548
 
10479
- // ../api/src/dashboard/autocomplete-routes.ts
10480
- import { Hono as Hono18 } from "hono";
10549
+ // ../api/src/dashboard/voice-routes.ts
10550
+ import { Hono as Hono21 } from "hono";
10551
+
10552
+ // ../api/src/dashboard/voice-embed.ts
10553
+ import { createRequire } from "module";
10554
+ var extractor;
10555
+ function getExtractor() {
10556
+ if (extractor !== void 0) return extractor;
10557
+ const model = process.env["VOICE_MODEL_PATH"];
10558
+ if (!model) return extractor = null;
10559
+ try {
10560
+ const sherpa = createRequire(import.meta.url)("sherpa-onnx-node");
10561
+ extractor = new sherpa.SpeakerEmbeddingExtractor({ model, numThreads: 1 });
10562
+ } catch (err) {
10563
+ console.error("[voice] speaker model failed to load", err);
10564
+ extractor = null;
10565
+ }
10566
+ return extractor;
10567
+ }
10568
+ function embedVoice(samples) {
10569
+ const ex = getExtractor();
10570
+ if (!ex) return null;
10571
+ const stream = ex.createStream();
10572
+ stream.acceptWaveform({ sampleRate: 16e3, samples });
10573
+ stream.inputFinished();
10574
+ const v = Array.from(ex.compute(stream));
10575
+ const n = Math.hypot(...v) || 1;
10576
+ return v.map((x) => x / n);
10577
+ }
10578
+
10579
+ // ../api/src/dashboard/voice-routes.ts
10580
+ var CLIENT_SECRETS_URL = "https://api.openai.com/v1/realtime/client_secrets";
10581
+ var MODEL3 = process.env["REALTIME_MODEL"] ?? "gpt-realtime-mini";
10481
10582
  var GROQ_API_URL4 = "https://api.groq.com/openai/v1/chat/completions";
10482
- var MODEL3 = "openai/gpt-oss-120b";
10583
+ var GROQ_MODEL = "openai/gpt-oss-120b";
10584
+ var INSTRUCTIONS = `You are the voice of {NAME}, the agent in a Flyspace thread. Warm, relaxed, short sentences.
10585
+ Answer directly yourself, without any tool, when it is general knowledge or small talk that needs nothing from their project or workspace (for example how to reload a page, a keyboard shortcut, what a word means). Keep it to one or two short sentences.
10586
+ You know nothing about their project yourself. For any question or request about their project, code or data: first say one short, natural filler sentence, different each time (for example "Let me check.", "One sec."), then call ask_agent with their request in their own words. Never answer from memory and never make up names or numbers.
10587
+ If what they said sounds unfinished or too vague to act on, do not call ask_agent yet: reply with a few words that keep them talking, then wait.
10588
+ ask_agent returns the agent's full written answer, which is already posted in the thread. Say only the gist in at most three short spoken sentences, no Markdown, no code, no URLs, then mention that the details are in the thread if it was long.
10589
+ For small talk like hello or thanks, reply in a few words.
10590
+ Call end_call only when they say goodbye together with your name (for example "Bye {NAME}"): say a very short goodbye first. A goodbye without your name does not end the call.
10591
+ Call pause_listening when they ask you to pause or stop listening together with your name (for example "Pause {NAME}" or "\u66AB\u505C {NAME}"). Say nothing after it: they resume with the button or by saying "Hey {NAME}". A pause request without your name (for example "\u66AB\u505C\u4E00\u4E0B", "wait") does not pause: just wait for them.
10592
+ If what they said seems meant for someone else in the room, ask briefly "Was that for me?" and wait.
10593
+ When they ask where something is or how to do something in the Flyspace app itself (open settings, invite someone, create a channel), call show_me instead of ask_agent: it points at the right place on screen. Say one short sentence about what you are showing.
10594
+ When they ask what was discussed, decided or said somewhere in the workspace (for example "where did the X discussion get to", "what did we decide about Y"), call search_workspace first: it answers in seconds. Use ask_agent only if search_workspace finds nothing useful or the request needs real work (reading code, running something, changing files).`;
10595
+ var VOICES = /* @__PURE__ */ new Set([
10596
+ "marin",
10597
+ "cedar",
10598
+ "alloy",
10599
+ "ash",
10600
+ "ballad",
10601
+ "coral",
10602
+ "echo",
10603
+ "sage",
10604
+ "shimmer",
10605
+ "verse"
10606
+ ]);
10607
+ var VOICE_MATCH_MIN = 0.35;
10608
+ var LANGUAGES = {
10609
+ auto: { rule: "Speak the same language the user speaks." },
10610
+ "zh-TW": {
10611
+ rule: "Speak Taiwan Mandarin unless the user speaks another language. Chinese always means Traditional Chinese with Taiwanese wording (zh-TW), never Simplified Chinese, including the question text you pass to tools.",
10612
+ transcribe: "\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\u7528\u8A9E\uFF09\uFF0C\u593E\u96DC\u82F1\u6587\u6280\u8853\u540D\u8A5E\u3002"
10613
+ },
10614
+ "zh-CN": {
10615
+ rule: "Speak Mandarin unless the user speaks another language. Chinese means Simplified Chinese (zh-CN), including the question text you pass to tools.",
10616
+ transcribe: "\u7B80\u4F53\u4E2D\u6587\uFF0C\u5939\u6742\u82F1\u6587\u6280\u672F\u540D\u8BCD\u3002"
10617
+ },
10618
+ yue: {
10619
+ rule: "Speak Cantonese (Hong Kong) unless the user speaks another language. Write Chinese in Traditional Chinese with Hong Kong wording, including the question text you pass to tools.",
10620
+ transcribe: "\u5EE3\u6771\u8A71\uFF08\u9999\u6E2F\uFF09\uFF0C\u593E\u96DC\u82F1\u6587\u3002"
10621
+ },
10622
+ en: { rule: "Speak English unless the user speaks another language." },
10623
+ ja: { rule: "Speak Japanese unless the user speaks another language." }
10624
+ };
10625
+ var ACCENTS = {
10626
+ taiwan: "When speaking Mandarin, use a natural Taiwanese accent and Taiwanese wording.",
10627
+ mainland: "When speaking Mandarin, use a natural standard mainland Chinese accent.",
10628
+ australian: "When speaking English, use a natural Australian accent.",
10629
+ american: "When speaking English, use a natural American accent.",
10630
+ british: "When speaking English, use a natural British accent.",
10631
+ indian: "When speaking English, use a natural Indian English accent.",
10632
+ singaporean: "When speaking English, use a natural Singaporean English accent."
10633
+ };
10634
+ function languageRule(raw) {
10635
+ const code = String(raw ?? "auto");
10636
+ if (LANGUAGES[code]) return LANGUAGES[code];
10637
+ if (/^zh-(Hant|HK|MO)/i.test(code)) return LANGUAGES["zh-TW"];
10638
+ if (/^zh/i.test(code)) return LANGUAGES["zh-CN"];
10639
+ if (/^en/i.test(code)) return LANGUAGES["en"];
10640
+ if (/^[a-z]{2,3}(-[A-Za-z0-9]{2,4})?$/.test(code)) {
10641
+ return {
10642
+ rule: `Speak the language with BCP 47 code "${code}" unless the user speaks another language.`
10643
+ };
10644
+ }
10645
+ return LANGUAGES["auto"];
10646
+ }
10647
+ function customAccent(raw) {
10648
+ const text = String(raw ?? "").replace(/[^\p{L}\p{N} ,.()'-]/gu, "").trim().slice(0, 60);
10649
+ return text ? `Speak with this accent or style: ${text}.` : "";
10650
+ }
10651
+ function agentName(raw) {
10652
+ const name = String(raw ?? "").replace(/[^\p{L}\p{N} ._-]/gu, "").trim().slice(0, 40);
10653
+ return name || "Custie";
10654
+ }
10655
+ function buildSession(style) {
10656
+ const name = agentName(style.name);
10657
+ const voice = VOICES.has(String(style.voice)) ? String(style.voice) : "marin";
10658
+ const language = languageRule(style.language);
10659
+ const accent = style.accent === "custom" ? customAccent(style.customAccent) : ACCENTS[String(style.accent)];
10660
+ const n = Number(style.speed);
10661
+ const speed = Number.isFinite(n) ? Math.min(1.5, Math.max(0.25, n)) : 1;
10662
+ const instructions = [INSTRUCTIONS.replaceAll("{NAME}", name), language.rule, accent].filter(Boolean).join("\n");
10663
+ const { transcription } = SESSION.audio.input;
10664
+ return {
10665
+ ...SESSION,
10666
+ instructions,
10667
+ tools: SESSION.tools.map((tool) => ({
10668
+ ...tool,
10669
+ description: tool.description?.replaceAll("{NAME}", name)
10670
+ })),
10671
+ audio: {
10672
+ input: {
10673
+ ...SESSION.audio.input,
10674
+ transcription: language.transcribe ? { ...transcription, prompt: language.transcribe } : { model: transcription.model }
10675
+ },
10676
+ output: { voice, speed }
10677
+ }
10678
+ };
10679
+ }
10680
+ var SESSION = {
10681
+ type: "realtime",
10682
+ model: MODEL3,
10683
+ instructions: INSTRUCTIONS,
10684
+ audio: {
10685
+ input: {
10686
+ transcription: {
10687
+ model: "gpt-4o-mini-transcribe",
10688
+ prompt: "\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\u7528\u8A9E\uFF09\uFF0C\u593E\u96DC\u82F1\u6587\u6280\u8853\u540D\u8A5E\u3002"
10689
+ },
10690
+ turn_detection: { type: "semantic_vad", eagerness: "low" }
10691
+ },
10692
+ output: { voice: "marin" }
10693
+ },
10694
+ tools: [
10695
+ {
10696
+ type: "function",
10697
+ name: "ask_agent",
10698
+ description: "Sends the user's question or request about their project, code or data to the thread's agent and returns its written answer. Not for general knowledge or small talk; answer those yourself. Say a short filler sentence before calling it.",
10699
+ parameters: {
10700
+ type: "object",
10701
+ properties: { question: { type: "string" } },
10702
+ required: ["question"]
10703
+ }
10704
+ },
10705
+ {
10706
+ type: "function",
10707
+ name: "show_me",
10708
+ description: 'Shows the user where something is in the Flyspace app: opens the page and spotlights the buttons. Use for "where is" and "how do I" questions about the app itself.',
10709
+ parameters: {
10710
+ type: "object",
10711
+ properties: { question: { type: "string" } },
10712
+ required: ["question"]
10713
+ }
10714
+ },
10715
+ {
10716
+ type: "function",
10717
+ name: "search_workspace",
10718
+ description: 'Searches past threads across the whole workspace and returns a short spoken summary. Use for "what did we discuss or decide about X" questions. Pass a few keywords plus the question.',
10719
+ parameters: {
10720
+ type: "object",
10721
+ properties: {
10722
+ query: {
10723
+ type: "string",
10724
+ description: 'Two to four distinctive keywords naming the topic (feature or product names, not generic words like "voice" or "latest"), in the words likely used in the threads'
10725
+ },
10726
+ question: { type: "string", description: "The user's question in their own words" }
10727
+ },
10728
+ required: ["query", "question"]
10729
+ }
10730
+ },
10731
+ {
10732
+ type: "function",
10733
+ name: "pause_listening",
10734
+ description: 'When the user asks you to pause or stop listening with your name, e.g. "Pause {NAME}" or "\u66AB\u505C {NAME}". Mutes their mic; they resume with the button or "Hey {NAME}".',
10735
+ parameters: { type: "object", properties: {} }
10736
+ },
10737
+ {
10738
+ type: "function",
10739
+ name: "end_call",
10740
+ description: 'Only when the user says goodbye with your name, e.g. "Bye {NAME}". Say a short goodbye first.',
10741
+ parameters: { type: "object", properties: {} }
10742
+ }
10743
+ ],
10744
+ tool_choice: "auto"
10745
+ };
10746
+ function createVoiceRouter() {
10747
+ const app = new Hono21();
10748
+ app.post("/voice/session", async (c) => {
10749
+ if (!await isFeatureEnabled(c, "voice-chat")) {
10750
+ return c.json({ error: "voice chat is not enabled" }, 403);
10751
+ }
10752
+ const apiKey = process.env["OPENAI_API_KEY"];
10753
+ if (!apiKey) return c.json({ error: "voice chat is not configured" }, 503);
10754
+ const style = await c.req.json().catch(() => ({}));
10755
+ const res = await fetch(CLIENT_SECRETS_URL, {
10756
+ method: "POST",
10757
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
10758
+ body: JSON.stringify({ session: buildSession(style ?? {}) })
10759
+ });
10760
+ const body = await res.json().catch(() => ({}));
10761
+ if (!res.ok || !body.value) {
10762
+ console.error("[voice] client_secrets failed", res.status, body.error?.message);
10763
+ return c.json({ error: `voice session failed (${res.status})` }, 502);
10764
+ }
10765
+ return c.json({ value: body.value, expiresAt: body.expires_at, model: MODEL3 });
10766
+ });
10767
+ app.post("/voice/triage", async (c) => {
10768
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10769
+ const body = await c.req.json().catch(() => ({}));
10770
+ const request = String(body.request ?? "").slice(0, 1e3);
10771
+ const utterance = String(body.utterance ?? "").slice(0, 1e3);
10772
+ const out = await groqJson(
10773
+ `The user asked an agent to do something, and while it works they said something else. Decide:
10774
+ - "interrupt": they want to stop, change or replace the current request (e.g. "stop", "never mind", "actually do X instead").
10775
+ - "queue": a new, separate question or request to handle after the current one.
10776
+ - "ignore": filler, thanks, thinking aloud, or talk not meant for the agent.
10777
+ Reply with JSON only: {"decision": "interrupt" | "queue" | "ignore"}`,
10778
+ JSON.stringify({ current_request: request, utterance })
10779
+ );
10780
+ const decision = ["interrupt", "queue", "ignore"].includes(String(out?.["decision"])) ? String(out?.["decision"]) : "queue";
10781
+ return c.json({ decision });
10782
+ });
10783
+ app.post("/voice/embed", async (c) => {
10784
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10785
+ const buf = await c.req.arrayBuffer();
10786
+ if (buf.byteLength % 4 !== 0 || buf.byteLength < 32e3 || buf.byteLength > 384e4) {
10787
+ return c.json({ error: "expected 0.5 to 60 s of 16 kHz Float32 PCM" }, 400);
10788
+ }
10789
+ const samples = new Float32Array(buf);
10790
+ const started = performance.now();
10791
+ const embedding = embedVoice(samples);
10792
+ if (!embedding) return c.json({ error: "speaker model unavailable" }, 503);
10793
+ return c.json({
10794
+ embedding,
10795
+ dim: embedding.length,
10796
+ seconds: samples.length / 16e3,
10797
+ ms: Math.round(performance.now() - started)
10798
+ });
10799
+ });
10800
+ app.get("/voice/profile", async (c) => {
10801
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10802
+ const auth = c.get("auth");
10803
+ const { data, error: error2 } = await getSupabaseClient().from("voice_profiles").select("seconds, updated_at").eq("user_id", auth.userId).maybeSingle();
10804
+ if (error2) return c.json({ error: error2.message }, 500);
10805
+ return c.json({ profile: data ? { seconds: data.seconds, updatedAt: data.updated_at } : null });
10806
+ });
10807
+ app.put("/voice/profile", async (c) => {
10808
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10809
+ const auth = c.get("auth");
10810
+ const buf = await c.req.arrayBuffer();
10811
+ if (buf.byteLength % 4 !== 0 || buf.byteLength < 64e4 || buf.byteLength > 384e4) {
10812
+ return c.json({ error: "expected 10 to 60 s of 16 kHz Float32 PCM" }, 400);
10813
+ }
10814
+ const samples = new Float32Array(buf);
10815
+ const embedding = embedVoice(samples);
10816
+ if (!embedding) return c.json({ error: "speaker model unavailable" }, 503);
10817
+ const row = {
10818
+ user_id: auth.userId,
10819
+ embedding,
10820
+ seconds: samples.length / 16e3,
10821
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
10822
+ };
10823
+ const { error: error2 } = await getSupabaseClient().from("voice_profiles").upsert(row);
10824
+ if (error2) return c.json({ error: error2.message }, 500);
10825
+ return c.json({ profile: { seconds: row.seconds, updatedAt: row.updated_at } });
10826
+ });
10827
+ app.post("/voice/verify", async (c) => {
10828
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10829
+ const auth = c.get("auth");
10830
+ const buf = await c.req.arrayBuffer();
10831
+ if (buf.byteLength % 4 !== 0 || buf.byteLength < 16e3 || buf.byteLength > 64e4) {
10832
+ return c.json({ error: "expected 0.25 to 10 s of 16 kHz Float32 PCM" }, 400);
10833
+ }
10834
+ const { data, error: error2 } = await getSupabaseClient().from("voice_profiles").select("embedding").eq("user_id", auth.userId).maybeSingle();
10835
+ if (error2) return c.json({ error: error2.message }, 500);
10836
+ if (!data) return c.json({ match: true, score: null });
10837
+ const embedding = embedVoice(new Float32Array(buf));
10838
+ if (!embedding) return c.json({ error: "speaker model unavailable" }, 503);
10839
+ const saved = data.embedding;
10840
+ let dot = 0;
10841
+ let a = 0;
10842
+ let b = 0;
10843
+ for (let i = 0; i < embedding.length; i++) {
10844
+ dot += embedding[i] * saved[i];
10845
+ a += embedding[i] * embedding[i];
10846
+ b += saved[i] * saved[i];
10847
+ }
10848
+ const score = dot / Math.sqrt(a * b || 1);
10849
+ return c.json({ match: score >= VOICE_MATCH_MIN, score });
10850
+ });
10851
+ app.delete("/voice/profile", async (c) => {
10852
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10853
+ const auth = c.get("auth");
10854
+ const { error: error2 } = await getSupabaseClient().from("voice_profiles").delete().eq("user_id", auth.userId);
10855
+ if (error2) return c.json({ error: error2.message }, 500);
10856
+ return c.json({ profile: null });
10857
+ });
10858
+ app.post("/voice/guide", async (c) => {
10859
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10860
+ const body = await c.req.json().catch(() => ({}));
10861
+ const question = String(body.question ?? "").slice(0, 1e3);
10862
+ if (!question.trim()) return c.json({ guide: null });
10863
+ const text = await groqText(
10864
+ `You point people at the right place in the Flyspace web app. Write nothing but the guide line.${GUIDE_RULES}`,
10865
+ question
10866
+ );
10867
+ return c.json({ guide: text ? extractGuide(text).guide : null });
10868
+ });
10869
+ app.post("/voice/search", async (c) => {
10870
+ if (!await isFeatureEnabled(c, "voice-chat")) return c.json({ error: "not enabled" }, 403);
10871
+ const body = await c.req.json().catch(() => ({}));
10872
+ const query = String(body.query ?? "").slice(0, 200).trim();
10873
+ const question = String(body.question ?? query).slice(0, 1e3);
10874
+ if (!query) return c.json({ answer: null, results: [] });
10875
+ const hits = (await searchThreads2(query)).slice(0, 8);
10876
+ if (hits.length === 0) return c.json({ answer: null, results: [] });
10877
+ const tails = await Promise.all(hits.slice(0, 3).map((h) => threadTail(h.id)));
10878
+ const context = hits.map((h, i) => ({
10879
+ title: h.title,
10880
+ channel: h.channelName,
10881
+ date: h.createdAt?.slice(0, 10),
10882
+ excerpt: h.snippet,
10883
+ ...tails[i]?.length ? { latestReplies: tails[i] } : {}
10884
+ }));
10885
+ const answer = await groqText(
10886
+ `Answer the question using ONLY facts stated explicitly in these workspace threads. Never guess, infer causes, or combine unrelated threads. Prefer the most recent replies, since later replies override earlier ones. Reply in at most two short spoken sentences, in the language of the question (Chinese means Taiwan Traditional Chinese), and name the thread it came from. No Markdown, no URLs. If the threads do not clearly answer it, say exactly: NOT_FOUND`,
10887
+ JSON.stringify({ question, threads: context })
10888
+ );
10889
+ const found = answer && !answer.includes("NOT_FOUND") ? answer.trim() : null;
10890
+ return c.json({
10891
+ answer: found,
10892
+ results: hits.map((h) => ({ id: h.id, title: h.title, url: h.url, channel: h.channelName }))
10893
+ });
10894
+ });
10895
+ return app;
10896
+ }
10897
+ async function threadTail(threadId) {
10898
+ const { data, error: error2 } = await getSupabaseClient().from("thread_replies").select("author, body, created_at").eq("thread_id", threadId).order("created_at", { ascending: false }).limit(10);
10899
+ if (error2 || !data) return [];
10900
+ return data.reverse().map((r) => ({
10901
+ author: String(r.author ?? ""),
10902
+ date: String(r.created_at ?? "").slice(0, 10),
10903
+ text: String(r.body ?? "").slice(0, 800)
10904
+ }));
10905
+ }
10906
+ async function groqText(system, user) {
10907
+ const apiKey = process.env["GROQ_API_KEY"];
10908
+ if (!apiKey) return null;
10909
+ const res = await fetch(GROQ_API_URL4, {
10910
+ method: "POST",
10911
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10912
+ signal: AbortSignal.timeout(12e3),
10913
+ body: JSON.stringify({
10914
+ model: GROQ_MODEL,
10915
+ max_completion_tokens: 600,
10916
+ reasoning_effort: "low",
10917
+ include_reasoning: false,
10918
+ temperature: 0,
10919
+ messages: [
10920
+ { role: "system", content: system },
10921
+ { role: "user", content: user }
10922
+ ]
10923
+ })
10924
+ }).catch(() => null);
10925
+ if (!res?.ok) return null;
10926
+ const data = await res.json().catch(() => null);
10927
+ return data?.choices?.[0]?.message?.content ?? null;
10928
+ }
10929
+ async function groqJson(system, user) {
10930
+ const text = await groqText(system, user);
10931
+ const match = text?.match(/\{[\s\S]*\}/);
10932
+ if (!match) return null;
10933
+ try {
10934
+ return JSON.parse(match[0]);
10935
+ } catch {
10936
+ return null;
10937
+ }
10938
+ }
10939
+
10940
+ // ../api/src/dashboard/autocomplete-routes.ts
10941
+ import { Hono as Hono22 } from "hono";
10942
+ var GROQ_API_URL5 = "https://api.groq.com/openai/v1/chat/completions";
10943
+ var MODEL4 = "openai/gpt-oss-120b";
10483
10944
  var MAX_REPLY_CHARS = 4e3;
10484
10945
  var MAX_EARLIER_CHARS = 1500;
10485
10946
  var THREAD_TAIL_REPLIES = 5;
@@ -10488,7 +10949,7 @@ Base it on the agent's last reply: answer a question it asked, approve or pick a
10488
10949
  Keep it short (under 15 words), in the language the user writes in. No greetings, thanks or filler.
10489
10950
  Output ONLY the message text, no quotes or explanation. If there is no clear next step, output nothing.`;
10490
10951
  function createAutocompleteRouter() {
10491
- const app = new Hono18();
10952
+ const app = new Hono22();
10492
10953
  app.post("/autocomplete", async (c) => {
10493
10954
  const apiKey = process.env["GROQ_API_KEY"];
10494
10955
  if (!apiKey) return c.json({ error: "autocomplete is not configured" }, 503);
@@ -10501,12 +10962,12 @@ function createAutocompleteRouter() {
10501
10962
  const context = `Channel: #${channel.name}${channel.prompt ? `
10502
10963
  Channel instructions: ${channel.prompt.slice(0, 500)}` : ""}
10503
10964
  ${thread}`;
10504
- const res = await fetch(GROQ_API_URL4, {
10965
+ const res = await fetch(GROQ_API_URL5, {
10505
10966
  method: "POST",
10506
10967
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10507
10968
  signal: AbortSignal.timeout(5e3),
10508
10969
  body: JSON.stringify({
10509
- model: MODEL3,
10970
+ model: MODEL4,
10510
10971
  // gpt-oss reasons first; a newline stop would cut it off before any content.
10511
10972
  max_completion_tokens: 200,
10512
10973
  reasoning_effort: "low",
@@ -10554,9 +11015,9 @@ ${last.body.slice(-MAX_REPLY_CHARS)}`;
10554
11015
  }
10555
11016
 
10556
11017
  // ../api/src/dashboard/daily-line-routes.ts
10557
- import { Hono as Hono19 } from "hono";
10558
- var GROQ_API_URL5 = "https://api.groq.com/openai/v1/chat/completions";
10559
- var MODEL4 = "openai/gpt-oss-120b";
11018
+ import { Hono as Hono23 } from "hono";
11019
+ var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
11020
+ var MODEL5 = "openai/gpt-oss-120b";
10560
11021
  var DAY_MS = 864e5;
10561
11022
  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.
10562
11023
  You are given what the team recently built and decided. Draw on its real substance to remind them how far they have come or why the work matters, so they feel like pushing on.
@@ -10580,7 +11041,7 @@ function pickMemories(memories, day, now = Date.now()) {
10580
11041
  return [...pool, ...pool].slice(start, start + Math.min(CONTEXT_COUNT, pool.length));
10581
11042
  }
10582
11043
  function createDailyLineRouter() {
10583
- const app = new Hono19();
11044
+ const app = new Hono23();
10584
11045
  app.get("/daily-line", async (c) => {
10585
11046
  if (!await isFeatureEnabled(c, "daily-line"))
10586
11047
  return c.json({ error: "feature not enabled" }, 403);
@@ -10601,12 +11062,12 @@ function createDailyLineRouter() {
10601
11062
  const key = `${day}:${memory.id}:${language}`;
10602
11063
  let text = cache3.get(key);
10603
11064
  if (text === void 0) {
10604
- const res = await fetch(GROQ_API_URL5, {
11065
+ const res = await fetch(GROQ_API_URL6, {
10605
11066
  method: "POST",
10606
11067
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10607
11068
  signal: AbortSignal.timeout(8e3),
10608
11069
  body: JSON.stringify({
10609
- model: MODEL4,
11070
+ model: MODEL5,
10610
11071
  max_completion_tokens: 300,
10611
11072
  reasoning_effort: "low",
10612
11073
  include_reasoning: false,
@@ -10636,9 +11097,9 @@ Write it in ${language} (BCP 47 tag). For Chinese use Traditional Chinese (Taiwa
10636
11097
  }
10637
11098
 
10638
11099
  // ../api/src/dashboard/channel-route.ts
10639
- import { Hono as Hono20 } from "hono";
10640
- var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
10641
- var MODEL5 = "openai/gpt-oss-120b";
11100
+ import { Hono as Hono24 } from "hono";
11101
+ var GROQ_API_URL7 = "https://api.groq.com/openai/v1/chat/completions";
11102
+ var MODEL6 = "openai/gpt-oss-120b";
10642
11103
  var MAX_MESSAGE_CHARS2 = 3e3;
10643
11104
  var MAX_PROMPT_CHARS2 = 300;
10644
11105
  var TITLES_PER_CHANNEL = 8;
@@ -10655,7 +11116,7 @@ async function describeImages(text, workspace, apiKey) {
10655
11116
  (u) => !!u
10656
11117
  );
10657
11118
  if (urls.length === 0) return "";
10658
- const res = await fetch(GROQ_API_URL6, {
11119
+ const res = await fetch(GROQ_API_URL7, {
10659
11120
  method: "POST",
10660
11121
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10661
11122
  signal: AbortSignal.timeout(1e4),
@@ -10706,7 +11167,7 @@ A topic word that could fit many projects (notification, scrollbar, login, bug)
10706
11167
  When a screenshot description is given, the app and names visible in it are strong evidence of the project.
10707
11168
  Output ONLY the channel's number and your confidence, e.g. "3 high" or "3 low". Say low when the message could reasonably belong to more than one channel.`;
10708
11169
  function createChannelRouteRouter() {
10709
- const app = new Hono20();
11170
+ const app = new Hono24();
10710
11171
  app.post("/route-channel", async (c) => {
10711
11172
  if (!await isFeatureEnabled(c, "auto-channel"))
10712
11173
  return c.json({ error: "feature not enabled" }, 403);
@@ -10730,12 +11191,12 @@ function createChannelRouteRouter() {
10730
11191
  titles.get(ch.id)?.length ? ` Recent topics: ${titles.get(ch.id).join(" | ")}` : ""
10731
11192
  ].filter(Boolean).join("\n")
10732
11193
  ).join("\n");
10733
- const res = await fetch(GROQ_API_URL6, {
11194
+ const res = await fetch(GROQ_API_URL7, {
10734
11195
  method: "POST",
10735
11196
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
10736
11197
  signal: AbortSignal.timeout(8e3),
10737
11198
  body: JSON.stringify({
10738
- model: MODEL5,
11199
+ model: MODEL6,
10739
11200
  max_completion_tokens: 400,
10740
11201
  reasoning_effort: "low",
10741
11202
  include_reasoning: false,
@@ -10766,7 +11227,7 @@ ${screenshots}` : ""}` }
10766
11227
 
10767
11228
  // ../api/src/dashboard/avatars-routes.ts
10768
11229
  import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
10769
- import { Hono as Hono21 } from "hono";
11230
+ import { Hono as Hono25 } from "hono";
10770
11231
  import sharp3 from "sharp";
10771
11232
  import { PutObjectCommand as PutObjectCommand3, DeleteObjectCommand as DeleteObjectCommand2 } from "@aws-sdk/client-s3";
10772
11233
  var AVATAR_SIZE = 192;
@@ -10819,7 +11280,7 @@ function avatarKeyPrefix() {
10819
11280
  return `${KEY_PREFIX2}/${getProfile()}/`;
10820
11281
  }
10821
11282
  function createAvatarsRouter() {
10822
- const app = new Hono21();
11283
+ const app = new Hono25();
10823
11284
  app.get("/avatars/slack", async (c) => {
10824
11285
  const ctx = await resolveAuthContext(c);
10825
11286
  if (!ctx) return c.json({ error: "not signed in" }, 401);
@@ -10868,7 +11329,7 @@ function createAvatarsRouter() {
10868
11329
  }
10869
11330
 
10870
11331
  // ../api/src/dashboard/members-routes.ts
10871
- import { Hono as Hono22 } from "hono";
11332
+ import { Hono as Hono26 } from "hono";
10872
11333
  function inviteLinkFor(c, token) {
10873
11334
  const url = new URL("/auth/invite", callbackUrl(c));
10874
11335
  url.searchParams.set("token", token);
@@ -10876,7 +11337,7 @@ function inviteLinkFor(c, token) {
10876
11337
  }
10877
11338
  var EMAIL_RE2 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
10878
11339
  function createMembersRouter() {
10879
- const members = new Hono22();
11340
+ const members = new Hono26();
10880
11341
  members.get("/", async (c) => {
10881
11342
  const ctx = await resolveAuthContext(c);
10882
11343
  if (ctx?.role !== "admin") return c.json({ error: "admin access required" }, 403);
@@ -11099,7 +11560,7 @@ function createMembersRouter() {
11099
11560
  }
11100
11561
 
11101
11562
  // ../api/src/dashboard/notifications-routes.ts
11102
- import { Hono as Hono23 } from "hono";
11563
+ import { Hono as Hono27 } from "hono";
11103
11564
 
11104
11565
  // ../api/src/store/push-store.ts
11105
11566
  function rowToSubscription(row) {
@@ -11284,7 +11745,7 @@ function startPushWatcher() {
11284
11745
 
11285
11746
  // ../api/src/dashboard/notifications-routes.ts
11286
11747
  function createNotificationsRouter() {
11287
- const notifications = new Hono23();
11748
+ const notifications = new Hono27();
11288
11749
  notifications.get("/", async (c) => {
11289
11750
  const auth = c.get("auth");
11290
11751
  const channelIds = getProfileChannelRegistry().filter((ch) => canSeeChannel(ch, auth)).map((ch) => ch.id);
@@ -11311,7 +11772,7 @@ function createNotificationsRouter() {
11311
11772
  return notifications;
11312
11773
  }
11313
11774
  function createThreadReadRouter() {
11314
- const threads = new Hono23();
11775
+ const threads = new Hono27();
11315
11776
  threads.post("/threads/:threadId/read", async (c) => {
11316
11777
  const { userId } = c.get("auth");
11317
11778
  const threadId = c.req.param("threadId");
@@ -11335,9 +11796,9 @@ function createThreadReadRouter() {
11335
11796
  }
11336
11797
 
11337
11798
  // ../api/src/dashboard/push-routes.ts
11338
- import { Hono as Hono24 } from "hono";
11799
+ import { Hono as Hono28 } from "hono";
11339
11800
  function createPushRouter() {
11340
- const push = new Hono24();
11801
+ const push = new Hono28();
11341
11802
  push.get("/key", (c) => c.json({ publicKey: getVapidPublicKey() }));
11342
11803
  push.post("/subscribe", async (c) => {
11343
11804
  const { userId } = c.get("auth");
@@ -11368,7 +11829,7 @@ function createPushRouter() {
11368
11829
  }
11369
11830
 
11370
11831
  // ../api/src/dashboard/mcp-oauth-routes.ts
11371
- import { Hono as Hono25 } from "hono";
11832
+ import { Hono as Hono29 } from "hono";
11372
11833
  var CONNECTIONS_PAGE = "/settings/connections";
11373
11834
  function callbackUri(c) {
11374
11835
  const proto = c.req.header("x-forwarded-proto") ?? "http";
@@ -11383,7 +11844,7 @@ function backToDashboard(c, to, params) {
11383
11844
  return c.redirect(`${target.pathname}${target.search}`);
11384
11845
  }
11385
11846
  function createMcpOAuthRouter() {
11386
- const app = new Hono25();
11847
+ const app = new Hono29();
11387
11848
  app.get("/oauth/:provider/start", async (c) => {
11388
11849
  const auth = c.get("auth");
11389
11850
  if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
@@ -11510,7 +11971,7 @@ function createMcpOAuthRouter() {
11510
11971
  }
11511
11972
 
11512
11973
  // ../api/src/dashboard/mcp-routes.ts
11513
- import { Hono as Hono26 } from "hono";
11974
+ import { Hono as Hono30 } from "hono";
11514
11975
 
11515
11976
  // ../api/src/mcp/transport.ts
11516
11977
  var KINDS = ["inherit", "npx", "local", "http", "sse"];
@@ -11640,7 +12101,7 @@ function bindingsByConnection() {
11640
12101
  return map;
11641
12102
  }
11642
12103
  function createMcpRouter() {
11643
- const app = new Hono26();
12104
+ const app = new Hono30();
11644
12105
  app.get("/providers", async (c) => {
11645
12106
  const denied = requireAdmin(c.get("auth"));
11646
12107
  if (denied) return c.json({ error: denied }, 403);
@@ -11678,8 +12139,8 @@ function createMcpRouter() {
11678
12139
  const denied = requireAdmin(auth);
11679
12140
  if (denied) return c.json({ error: denied }, 403);
11680
12141
  const body = await c.req.json().catch(() => null);
11681
- const label2 = typeof body?.label === "string" ? body.label.trim() : "";
11682
- if (!label2) return c.json({ error: "label is required" }, 400);
12142
+ const label = typeof body?.label === "string" ? body.label.trim() : "";
12143
+ if (!label) return c.json({ error: "label is required" }, 400);
11683
12144
  const slug = typeof body?.slug === "string" ? body.slug.trim() : "";
11684
12145
  if (!/^[a-z][a-z0-9_]{0,38}$/.test(slug)) {
11685
12146
  return c.json(
@@ -11696,7 +12157,7 @@ function createMcpRouter() {
11696
12157
  const created = await insertMcpConnection({
11697
12158
  workspaceId: auth.workspaceId,
11698
12159
  providerSlug: CUSTOM_PROVIDER,
11699
- label: label2,
12160
+ label,
11700
12161
  slug,
11701
12162
  serverCommand: toServerCommand(parsed.transport),
11702
12163
  createdBy: auth.userId ?? null
@@ -11718,9 +12179,9 @@ function createMcpRouter() {
11718
12179
  if (!body) return c.json({ error: "a body is required" }, 400);
11719
12180
  const patch = {};
11720
12181
  if (body.label !== void 0) {
11721
- const label2 = typeof body.label === "string" ? body.label.trim() : "";
11722
- if (!label2) return c.json({ error: "label cannot be empty" }, 400);
11723
- patch.label = label2;
12182
+ const label = typeof body.label === "string" ? body.label.trim() : "";
12183
+ if (!label) return c.json({ error: "label cannot be empty" }, 400);
12184
+ patch.label = label;
11724
12185
  }
11725
12186
  if (body.enabled !== void 0) {
11726
12187
  if (typeof body.enabled !== "boolean")
@@ -12170,9 +12631,9 @@ ${transcriptOf(data ?? [])}`
12170
12631
  }
12171
12632
 
12172
12633
  // ../api/src/dashboard/permission-routes.ts
12173
- import { Hono as Hono27 } from "hono";
12634
+ import { Hono as Hono31 } from "hono";
12174
12635
  function createPermissionRequestsRouter() {
12175
- const app = new Hono27();
12636
+ const app = new Hono31();
12176
12637
  app.post("/:id", async (c) => {
12177
12638
  const auth = c.get("auth");
12178
12639
  if (auth.role !== "admin") return c.json({ error: "only an admin can answer this" }, 403);
@@ -12202,7 +12663,7 @@ function createPermissionRequestsRouter() {
12202
12663
  }
12203
12664
 
12204
12665
  // ../api/src/dashboard/channel-greeting.ts
12205
- import { Hono as Hono28 } from "hono";
12666
+ import { Hono as Hono32 } from "hono";
12206
12667
  function eligible(ch) {
12207
12668
  return !!ch && !ch.isDefault && !ch.dmKey && !ch.agentName && !ch.archivedAt;
12208
12669
  }
@@ -12231,7 +12692,7 @@ function introOpening(channelName) {
12231
12692
  return `Welcome to #${channelName}. I'm reading this project's folder, docs, skills and automations to work out how I can help here. Below you'll find a short intro and a few first steps you can click to try.`;
12232
12693
  }
12233
12694
  function createChannelGreetingRouter(agent) {
12234
- const app = new Hono28();
12695
+ const app = new Hono32();
12235
12696
  app.get("/:id/greeting", async (c) => {
12236
12697
  const ctx = await resolveAuthContext(c);
12237
12698
  const ch = findChannelById(c.req.param("id"));
@@ -12289,7 +12750,7 @@ async function ensureIntroThread(ch) {
12289
12750
  }
12290
12751
 
12291
12752
  // ../api/src/dashboard/channel-suggest.ts
12292
- import { Hono as Hono29 } from "hono";
12753
+ import { Hono as Hono33 } from "hono";
12293
12754
  var CATEGORY_MAX_CHARS = 16;
12294
12755
  var CATEGORY_MAX_ITEMS = 30;
12295
12756
  var PROMPT_MAX_CHARS = 4e3;
@@ -12337,7 +12798,7 @@ function parseSuggestion(field, raw) {
12337
12798
  return items2.length ? items2.slice(0, CATEGORY_MAX_ITEMS).join("\n") : null;
12338
12799
  }
12339
12800
  function createChannelSuggestRouter(agent) {
12340
- const router = new Hono29();
12801
+ const router = new Hono33();
12341
12802
  router.post("/:id/suggest", async (c) => {
12342
12803
  const channel = findChannel(c.req.param("id"));
12343
12804
  if (!channel || !canSeeChannel(channel, c.get("auth"))) {
@@ -12374,87 +12835,104 @@ function createChannelSuggestRouter(agent) {
12374
12835
  return router;
12375
12836
  }
12376
12837
 
12377
- // ../api/src/dashboard/channel-members-routes.ts
12378
- import { Hono as Hono30 } from "hono";
12379
- async function isChannelAdmin(ctx, channelId) {
12380
- if (ctx.role === "admin") return true;
12381
- const membership = await getMembershipByUserId(ctx.workspaceId, ctx.userId);
12382
- if (!membership) return false;
12383
- const members = await listChannelMembers(channelId);
12384
- return members.some((m) => m.membershipId === membership.id && m.role === "channel_admin");
12385
- }
12386
- function createChannelMembersRouter() {
12387
- const router = new Hono30();
12388
- router.get("/:id/members", async (c) => {
12389
- const ctx = await resolveAuthContext(c);
12390
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12391
- const members = await listChannelMembers(c.req.param("id"));
12392
- return c.json({ members });
12838
+ // ../api/src/dashboard/channel-destroy-routes.ts
12839
+ import { Hono as Hono34 } from "hono";
12840
+ import { DeleteObjectCommand as DeleteObjectCommand3, ListObjectsV2Command } from "@aws-sdk/client-s3";
12841
+ function createChannelDestroyRouter() {
12842
+ const router = new Hono34();
12843
+ const gate = async (c) => {
12844
+ const auth = await resolveAuthContext(c);
12845
+ if (!auth || auth.role !== "admin" || auth.isSupport) return null;
12846
+ return auth;
12847
+ };
12848
+ const loadChannel = async (id) => {
12849
+ const { data } = await getSupabaseClient().from("channels").select(
12850
+ "id, name, cwd, profile, archived_at, is_default, dm_key, agent_name, external_channel_id"
12851
+ ).eq("id", id).maybeSingle();
12852
+ return data && data.profile === getProfile() ? data : null;
12853
+ };
12854
+ const refusal = (ch) => ch.is_default || ch.dm_key || ch.agent_name || ch.id === process.env["SUPPORT_TICKET_CHANNEL_ID"];
12855
+ router.get("/:id/destroy-preview", async (c) => {
12856
+ if (!await gate(c)) return c.json({ error: "workspace admin only" }, 403);
12857
+ const ch = await loadChannel(c.req.param("id"));
12858
+ if (!ch) return c.json({ error: "channel not found" }, 404);
12859
+ const { data, error: error2 } = await getSupabaseClient().rpc("destroy_channel_preview", {
12860
+ p_channel_id: ch.id,
12861
+ p_profile: ch.profile
12862
+ });
12863
+ if (error2) return c.json({ error: error2.message }, 500);
12864
+ return c.json({
12865
+ name: ch.name,
12866
+ cwd: ch.cwd,
12867
+ cwdDisplay: displayCwd(ch.cwd, cachedProfileConfig()?.home),
12868
+ slackBound: !!ch.external_channel_id,
12869
+ counts: data
12870
+ });
12393
12871
  });
12394
- router.put("/:id/members/:membershipId", async (c) => {
12395
- const ctx = await resolveAuthContext(c);
12396
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12397
- const channelId = c.req.param("id");
12398
- if (!await isChannelAdmin(ctx, channelId)) {
12399
- return c.json({ error: "channel admin access required" }, 403);
12400
- }
12872
+ router.delete("/:id", async (c) => {
12873
+ if (!await gate(c)) return c.json({ error: "workspace admin only" }, 403);
12874
+ const ch = await loadChannel(c.req.param("id"));
12875
+ if (!ch) return c.json({ error: "channel not found" }, 404);
12876
+ if (!ch.archived_at) return c.json({ error: "archive the channel first" }, 409);
12877
+ if (refusal(ch)) return c.json({ error: "this channel cannot be destroyed" }, 400);
12401
12878
  const body = await c.req.json().catch(() => ({}));
12402
- if (body.role !== "channel_admin" && body.role !== "channel_member") {
12403
- return c.json({ error: "role must be 'channel_admin' or 'channel_member'" }, 400);
12404
- }
12405
- const member = await upsertChannelMember({
12406
- channelId,
12407
- membershipId: c.req.param("membershipId"),
12408
- role: body.role
12879
+ if (typeof body.confirmName !== "string" || body.confirmName.trim() !== ch.name)
12880
+ return c.json({ error: "confirmName does not match" }, 400);
12881
+ const { data, error: error2 } = await getSupabaseClient().rpc("destroy_channel", {
12882
+ p_channel_id: ch.id,
12883
+ p_profile: ch.profile
12409
12884
  });
12410
- return c.json({ member });
12411
- });
12412
- router.delete("/:id/members/:membershipId", async (c) => {
12413
- const ctx = await resolveAuthContext(c);
12414
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12415
- const channelId = c.req.param("id");
12416
- if (!await isChannelAdmin(ctx, channelId)) {
12417
- return c.json({ error: "channel admin access required" }, 403);
12418
- }
12419
- const removed = await removeChannelMember(channelId, c.req.param("membershipId"));
12420
- if (!removed) return c.json({ error: "no such channel member" }, 404);
12421
- return c.body(null, 204);
12422
- });
12423
- router.get("/:id/docs-access/me", async (c) => {
12424
- const ctx = await resolveAuthContext(c);
12425
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12426
- return c.json({ access: await resolveDocsAccess(ctx, c.req.param("id")) });
12427
- });
12428
- router.get("/:id/docs-access", async (c) => {
12429
- const ctx = await resolveAuthContext(c);
12430
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12431
- const channelId = c.req.param("id");
12432
- if (!await isChannelAdmin(ctx, channelId)) {
12433
- return c.json({ error: "channel admin access required" }, 403);
12434
- }
12435
- return c.json({ memberAccess: await getChannelDocsMemberAccess(channelId) });
12885
+ if (error2) {
12886
+ const status = error2.code === "P0002" ? 404 : error2.code === "55000" ? 409 : error2.code === "22023" ? 400 : 500;
12887
+ return c.json({ error: error2.message }, status);
12888
+ }
12889
+ const {
12890
+ shareIds = [],
12891
+ audioKeys = [],
12892
+ attachmentKeys = [],
12893
+ ...deleted
12894
+ } = data;
12895
+ const r2 = await purgeR2(shareIds, [
12896
+ ...audioKeys,
12897
+ ...attachmentKeys.flatMap(
12898
+ (k) => k.endsWith(".webp") ? [k, k.replace(/\.webp$/, ".thumb.webp")] : [k]
12899
+ )
12900
+ ]);
12901
+ await refreshChannelRegistry().catch(() => {
12902
+ });
12903
+ return c.json({ ok: true, deleted, r2 });
12436
12904
  });
12437
- router.put("/:id/docs-access", async (c) => {
12438
- const ctx = await resolveAuthContext(c);
12439
- if (!ctx) return c.json({ error: "workspace access required" }, 403);
12440
- const channelId = c.req.param("id");
12441
- if (!await isChannelAdmin(ctx, channelId)) {
12442
- return c.json({ error: "channel admin access required" }, 403);
12443
- }
12444
- const body = await c.req.json().catch(() => ({}));
12445
- if (!isDocsAccess(body.memberAccess)) {
12446
- return c.json({ error: "memberAccess must be 'none', 'read' or 'write'" }, 400);
12905
+ return router;
12906
+ }
12907
+ async function purgeR2(shareIds, keys) {
12908
+ let deleted = 0;
12909
+ let failed2 = 0;
12910
+ const del = async (key) => {
12911
+ try {
12912
+ await getR2Client().send(new DeleteObjectCommand3({ Bucket: getR2Bucket(), Key: key }));
12913
+ deleted++;
12914
+ } catch (err) {
12915
+ failed2++;
12916
+ console.error(`[channel-destroy] R2 delete failed for ${key}:`, err);
12447
12917
  }
12448
- if (!await setChannelDocsMemberAccess(channelId, body.memberAccess)) {
12449
- return c.json({ error: "no such channel" }, 404);
12918
+ };
12919
+ for (const id of shareIds) {
12920
+ try {
12921
+ const list = await getR2Client().send(
12922
+ new ListObjectsV2Command({ Bucket: getR2Bucket(), Prefix: `share/${id}/` })
12923
+ );
12924
+ for (const o of list.Contents ?? []) if (o.Key) await del(o.Key);
12925
+ } catch (err) {
12926
+ failed2++;
12927
+ console.error(`[channel-destroy] R2 list failed for share/${id}/:`, err);
12450
12928
  }
12451
- return c.json({ memberAccess: body.memberAccess });
12452
- });
12453
- return router;
12929
+ }
12930
+ for (const key of keys) await del(key);
12931
+ return { deleted, failed: failed2 };
12454
12932
  }
12455
12933
 
12456
12934
  // ../api/src/dashboard/memories-routes.ts
12457
- import { Hono as Hono31 } from "hono";
12935
+ import { Hono as Hono35 } from "hono";
12458
12936
  async function readPatch(c) {
12459
12937
  const body = await c.req.json().catch(() => ({}));
12460
12938
  const patch = {};
@@ -12482,7 +12960,7 @@ var requireAgentMemory = async (c, next) => {
12482
12960
  await next();
12483
12961
  };
12484
12962
  function createMemoriesRouter() {
12485
- const router = new Hono31();
12963
+ const router = new Hono35();
12486
12964
  for (const path of [
12487
12965
  "/:id/memories",
12488
12966
  "/:id/memories/*",
@@ -12555,7 +13033,7 @@ function createMemoriesRouter() {
12555
13033
  return router;
12556
13034
  }
12557
13035
  function createScopedMemoriesRouter() {
12558
- const router = new Hono31();
13036
+ const router = new Hono35();
12559
13037
  router.use("*", requireAgentMemory);
12560
13038
  const workspace = (c) => ({
12561
13039
  scope: "workspace",
@@ -12615,7 +13093,7 @@ function createScopedMemoriesRouter() {
12615
13093
  }
12616
13094
 
12617
13095
  // ../api/src/dashboard/session-import-routes.ts
12618
- import { Hono as Hono32 } from "hono";
13096
+ import { Hono as Hono36 } from "hono";
12619
13097
  var MAX_FOLDERS2 = 20;
12620
13098
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
12621
13099
  var IMPORT_RANGES = ["all", "7d", "latest5"];
@@ -12722,7 +13200,7 @@ async function syncSession(agent, channelId, session, author, existing) {
12722
13200
  return messages.length;
12723
13201
  }
12724
13202
  function createSessionImportRouter(agent) {
12725
- const app = new Hono32();
13203
+ const app = new Hono36();
12726
13204
  const scanFolders = async () => {
12727
13205
  const scan = await ask(agent, { op: "scan", slug: getProfile() });
12728
13206
  return scan && importableFolders(scan.folders, getProfileChannelRegistry());
@@ -12984,6 +13462,7 @@ function registerDataRoutes(api, agent = {}) {
12984
13462
  const auth = c.get("auth");
12985
13463
  const channels = getProfileChannelRegistry().filter((ch) => canSeeChannel(ch, auth));
12986
13464
  const missingCwds = await agent.listMissingCwds?.();
13465
+ const hostHome = cachedProfileConfig()?.home;
12987
13466
  const list = channels.map((ch) => ({
12988
13467
  id: ch.id,
12989
13468
  externalChannelId: ch.externalChannelId,
@@ -12993,6 +13472,8 @@ function registerDataRoutes(api, agent = {}) {
12993
13472
  name: ch.dmKey && !ch.agentName ? ch.name.split(", ").filter((h) => h !== auth.handle).join(", ") || ch.name : ch.name,
12994
13473
  configured: true,
12995
13474
  cwd: ch.cwd,
13475
+ // What the UI shows: never a full absolute path (see displayCwd).
13476
+ cwdDisplay: displayCwd(ch.cwd, hostHome),
12996
13477
  // Surfaces a rotted working directory in the sidebar instead of
12997
13478
  // waiting for the next @agent mention to fail (see auditChannelCwds).
12998
13479
  cwdMissing: missingCwds ? missingCwds.includes(ch.id) : void 0,
@@ -13007,7 +13488,8 @@ function registerDataRoutes(api, agent = {}) {
13007
13488
  agentName: ch.agentName,
13008
13489
  dmKey: ch.dmKey,
13009
13490
  isDefault: ch.isDefault,
13010
- archived: !!ch.archivedAt
13491
+ archived: !!ch.archivedAt,
13492
+ description: ch.description
13011
13493
  }));
13012
13494
  return c.json({
13013
13495
  channels: list,
@@ -13030,6 +13512,8 @@ function registerDataRoutes(api, agent = {}) {
13030
13512
  api.route("/channels", createChannelGreetingRouter(agent));
13031
13513
  api.route("/channels", createChannelSuggestRouter(agent));
13032
13514
  api.route("/channels", createChannelMembersRouter());
13515
+ api.route("/channels", createChannelAgentRouter());
13516
+ api.route("/channels", createChannelDestroyRouter());
13033
13517
  api.route("/channels", createMemoriesRouter());
13034
13518
  api.route("/memories", createScopedMemoriesRouter());
13035
13519
  api.route("/docs", createDocShareListRouter());
@@ -13153,6 +13637,7 @@ function registerDataRoutes(api, agent = {}) {
13153
13637
  api.route("/tts", createTtsRouter());
13154
13638
  api.route("/feature-flags", createFeatureFlagsRouter());
13155
13639
  api.route("/domain", createDomainRouter());
13640
+ api.route("/support-access", createSupportGrantRouter());
13156
13641
  api.route("/members", createMembersRouter());
13157
13642
  api.route("/notifications", createNotificationsRouter());
13158
13643
  api.route("/push", createPushRouter());
@@ -13185,6 +13670,18 @@ function registerDataRoutes(api, agent = {}) {
13185
13670
  await setWorkspacePermissionMode(auth.workspaceId, body.permissionMode);
13186
13671
  return c.json({ permissionMode: body.permissionMode });
13187
13672
  });
13673
+ api.put("/default-effort", async (c) => {
13674
+ const auth = c.get("auth");
13675
+ if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
13676
+ const { defaultEffort: raw } = await c.req.json().catch(() => ({}));
13677
+ const value = raw === null || raw === "" ? null : typeof raw === "string" && isEffort(raw) ? raw : void 0;
13678
+ if (value === void 0) {
13679
+ return c.json({ error: "defaultEffort must be low, medium, high, xhigh, max or null" }, 400);
13680
+ }
13681
+ await setWorkspaceAgentDefaults(auth.workspaceId, { defaultEffort: value });
13682
+ await refreshChannelRegistry();
13683
+ return c.json({ defaultEffort: value });
13684
+ });
13188
13685
  api.get("/own-persona", async (c) => {
13189
13686
  const auth = c.get("auth");
13190
13687
  return c.json({ enabled: await getWorkspaceOwnPersona(auth.workspaceId) });
@@ -13242,6 +13739,7 @@ function registerDataRoutes(api, agent = {}) {
13242
13739
  });
13243
13740
  api.route("/", createUploadsRouter());
13244
13741
  api.route("/", createTranscribeRouter());
13742
+ api.route("/", createVoiceRouter());
13245
13743
  api.route("/", createAutocompleteRouter());
13246
13744
  api.route("/", createDailyLineRouter());
13247
13745
  api.route("/", createChannelRouteRouter());
@@ -13347,7 +13845,7 @@ function registerDataRoutes(api, agent = {}) {
13347
13845
  // ../api/src/dashboard/device-auth-routes.ts
13348
13846
  import { verify } from "crypto";
13349
13847
  import { getConnInfo } from "@hono/node-server/conninfo";
13350
- import { Hono as Hono33 } from "hono";
13848
+ import { Hono as Hono37 } from "hono";
13351
13849
  var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13352
13850
  function cleanText(value, max) {
13353
13851
  if (typeof value !== "string") return null;
@@ -13395,7 +13893,7 @@ async function boundWorkspaceIds(publicKey, userId) {
13395
13893
  return new Set(existing ? (await listDeviceWorkspaces(existing)).map((w) => w.id) : []);
13396
13894
  }
13397
13895
  function createDeviceAuthRouter() {
13398
- const app = new Hono33();
13896
+ const app = new Hono37();
13399
13897
  app.post("/code", async (c) => {
13400
13898
  const body = await readBody(c);
13401
13899
  const publicKey = typeof body["public_key"] === "string" ? body["public_key"] : "";
@@ -13714,7 +14212,7 @@ var workspaceRef = () => ({ kind: "workspace" });
13714
14212
  var channelRef = (c) => ({ kind: "channel", channelId: c.req.param("id") });
13715
14213
 
13716
14214
  // ../api/src/dashboard/output-styles-routes.ts
13717
- import { Hono as Hono34 } from "hono";
14215
+ import { Hono as Hono38 } from "hono";
13718
14216
  function requireAdmin3(auth) {
13719
14217
  return auth?.role === "admin" ? null : "admin access required";
13720
14218
  }
@@ -13734,7 +14232,7 @@ function failure(c, err) {
13734
14232
  return c.json({ error: message }, err instanceof OutputStyleConflictError ? 409 : 500);
13735
14233
  }
13736
14234
  function createOutputStylesRouter() {
13737
- const app = new Hono34();
14235
+ const app = new Hono38();
13738
14236
  app.get("/", (c) => {
13739
14237
  const auth = c.get("auth");
13740
14238
  const denied = requireAdmin3(auth);
@@ -13826,7 +14324,7 @@ function createOutputStylesRouter() {
13826
14324
  return app;
13827
14325
  }
13828
14326
  async function handleOutputStylesRequest(req) {
13829
- const app = new Hono34();
14327
+ const app = new Hono38();
13830
14328
  app.use("*", async (c, next) => {
13831
14329
  c.set("auth", { role: "admin" });
13832
14330
  await next();
@@ -13865,7 +14363,7 @@ async function viewerProfile(c, known) {
13865
14363
  return candidates[0]?.w.slug ?? null;
13866
14364
  }
13867
14365
  function createGatedRouter(agent, register) {
13868
- const api = new Hono35();
14366
+ const api = new Hono39();
13869
14367
  api.use("*", async (c, next) => {
13870
14368
  const known = await listKnownWorkspaces();
13871
14369
  const fromHost = profileFromHost(trustedHost(c), known);
@@ -13917,7 +14415,7 @@ import sharp5 from "sharp";
13917
14415
 
13918
14416
  // src/dashboard/channels-routes.ts
13919
14417
  import { existsSync as existsSync19, mkdirSync as mkdirSync8 } from "fs";
13920
- import { Hono as Hono36 } from "hono";
14418
+ import { Hono as Hono40 } from "hono";
13921
14419
  function coerceAccess(raw) {
13922
14420
  if (raw === "open" || raw === "*" || raw === "all") return raw;
13923
14421
  if (Array.isArray(raw) && raw.every((v) => typeof v === "string")) return raw;
@@ -13985,11 +14483,12 @@ function toResponse3(channel) {
13985
14483
  agentName: channel.agentName,
13986
14484
  dmKey: channel.dmKey,
13987
14485
  isDefault: channel.isDefault,
13988
- archived: !!channel.archivedAt
14486
+ archived: !!channel.archivedAt,
14487
+ description: channel.description
13989
14488
  };
13990
14489
  }
13991
14490
  function createChannelWriteRouter() {
13992
- const app = new Hono36();
14491
+ const app = new Hono40();
13993
14492
  app.post("/", async (c) => {
13994
14493
  const body = await c.req.json().catch(() => ({}));
13995
14494
  const name = typeof body["name"] === "string" ? body["name"].trim() : "";
@@ -14099,6 +14598,11 @@ function createChannelWriteRouter() {
14099
14598
  if (r) patch.runtime = r;
14100
14599
  }
14101
14600
  if ("mounts" in body) patch.mounts = coerceMounts(body["mounts"]);
14601
+ if ("description" in body) {
14602
+ const d = normaliseChannelDescription(body["description"]);
14603
+ if (d === "invalid") return c.json({ error: "description must be text of at most 1000 characters" }, 400);
14604
+ patch.description = d;
14605
+ }
14102
14606
  if ("permissionMode" in body) patch.permissionMode = coercePermissionMode(body["permissionMode"]);
14103
14607
  if (typeof body["archived"] === "boolean") {
14104
14608
  patch.archivedAt = body["archived"] ? (/* @__PURE__ */ new Date()).toISOString() : null;
@@ -14118,7 +14622,7 @@ function createChannelWriteRouter() {
14118
14622
  // src/dashboard/skills-routes-host.ts
14119
14623
  import { existsSync as existsSync20, statSync as statSync4 } from "fs";
14120
14624
  import { dirname as dirname7 } from "path";
14121
- import { Hono as Hono37 } from "hono";
14625
+ import { Hono as Hono41 } from "hono";
14122
14626
  function workspaceScope() {
14123
14627
  const claudeConfigDir = profileClaudeConfigDir();
14124
14628
  const cwd = defaultClaudeCwd();
@@ -14224,12 +14728,12 @@ var diskBackend = {
14224
14728
  write: writeSkillAndSync
14225
14729
  };
14226
14730
  function createWorkspaceSkillsRouter() {
14227
- const app = new Hono37();
14731
+ const app = new Hono41();
14228
14732
  mountSkillRoutes(app, "/skills", workspaceRef, diskBackend);
14229
14733
  return app;
14230
14734
  }
14231
14735
  function createChannelSkillsRouter() {
14232
- const app = new Hono37();
14736
+ const app = new Hono41();
14233
14737
  mountSkillRoutes(app, "/:id/skill-files", channelRef, diskBackend);
14234
14738
  return app;
14235
14739
  }
@@ -14293,21 +14797,21 @@ function claudeAuthAvailable() {
14293
14797
  }
14294
14798
  }
14295
14799
  function probe2(runner) {
14296
- const label2 = PROVIDER_LABELS[runner];
14800
+ const label = PROVIDER_LABELS[runner];
14297
14801
  const bin = runner === "codex" ? "codex" : "claude";
14298
14802
  if (!binaryOnPath(bin)) {
14299
- return { runner, label: label2, connected: false, reason: `The ${bin} CLI isn't on this machine's PATH.` };
14803
+ return { runner, label, connected: false, reason: `The ${bin} CLI isn't on this machine's PATH.` };
14300
14804
  }
14301
14805
  const signedIn = runner === "codex" ? codexAuthAvailable() : claudeAuthAvailable();
14302
14806
  if (!signedIn) {
14303
14807
  return {
14304
14808
  runner,
14305
- label: label2,
14809
+ label,
14306
14810
  connected: false,
14307
- reason: `${label2} is installed but signed out. Use Sign in below.`
14811
+ reason: `${label} is installed but signed out. Use Sign in below.`
14308
14812
  };
14309
14813
  }
14310
- return { runner, label: label2, connected: true, account: runner === "codex" ? codexAccount() : claudeAccount() };
14814
+ return { runner, label, connected: true, account: runner === "codex" ? codexAccount() : claudeAccount() };
14311
14815
  }
14312
14816
  function claudeAccount() {
14313
14817
  const token = profileOauthToken();
@@ -14359,9 +14863,9 @@ function providerStatuses() {
14359
14863
  import { spawn as spawn4 } from "child_process";
14360
14864
  import { randomUUID as randomUUID4 } from "crypto";
14361
14865
  import { chmodSync, existsSync as existsSync22, mkdirSync as mkdirSync9, readFileSync as readFileSync16, writeFileSync as writeFileSync8 } from "fs";
14362
- import { createRequire } from "module";
14866
+ import { createRequire as createRequire2 } from "module";
14363
14867
  import { dirname as dirname8, join as join14 } from "path";
14364
- import { Hono as Hono38 } from "hono";
14868
+ import { Hono as Hono42 } from "hono";
14365
14869
  var SESSION_TTL_MS = 10 * 6e4;
14366
14870
  var URL_WAIT_MS = 3e4;
14367
14871
  var TOKEN_WAIT_MS = 6e4;
@@ -14422,7 +14926,7 @@ function waitFor(s, parse, ms) {
14422
14926
  });
14423
14927
  }
14424
14928
  function loadPty() {
14425
- const require2 = createRequire(import.meta.url);
14929
+ const require2 = createRequire2(import.meta.url);
14426
14930
  const root = dirname8(require2.resolve("node-pty/package.json"));
14427
14931
  const helper = join14(root, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
14428
14932
  try {
@@ -14520,7 +15024,7 @@ function failure2(c, err) {
14520
15024
  return c.json({ error: err.message }, 500);
14521
15025
  }
14522
15026
  function createProviderLoginRouter() {
14523
- const app = new Hono38();
15027
+ const app = new Hono42();
14524
15028
  app.use("*", async (c, next) => {
14525
15029
  const denied = requireAdmin4(c.get("auth"));
14526
15030
  if (denied) return c.json({ error: denied }, 403);
@@ -14564,7 +15068,7 @@ function createProviderLoginRouter() {
14564
15068
  return app;
14565
15069
  }
14566
15070
  async function handleProviderLoginRequest(req) {
14567
- const app = new Hono38();
15071
+ const app = new Hono42();
14568
15072
  app.use("*", async (c, next) => {
14569
15073
  c.set("auth", { role: "admin" });
14570
15074
  await next();
@@ -14719,6 +15223,7 @@ function createHostApiRouter(agent = {}) {
14719
15223
  }
14720
15224
 
14721
15225
  // src/dashboard/agent-bridge-host.ts
15226
+ import { homedir as homedir9 } from "os";
14722
15227
  import { sign as signRaw, timingSafeEqual } from "crypto";
14723
15228
  import { existsSync as existsSync25, readFileSync as readFileSync19 } from "fs";
14724
15229
  import dotenv2 from "dotenv";
@@ -14967,13 +15472,13 @@ function handleSessionImportRequest(req) {
14967
15472
  }
14968
15473
 
14969
15474
  // src/dashboard/docs-relay-host.ts
14970
- import { Hono as Hono39 } from "hono";
15475
+ import { Hono as Hono43 } from "hono";
14971
15476
  var RETURNED_HEADERS = ["content-type", "content-disposition", "content-security-policy", "cache-control"];
14972
15477
  async function handleDocsRequest(req) {
14973
15478
  return runRelayed(req, (app) => app.route("/channels", createDocsRouter({ gate: async (_c, next) => next() })));
14974
15479
  }
14975
15480
  async function runRelayed(req, register) {
14976
- const app = new Hono39();
15481
+ const app = new Hono43();
14977
15482
  app.use("*", async (c, next) => {
14978
15483
  c.set("auth", req.auth);
14979
15484
  await next();
@@ -15118,6 +15623,7 @@ function localAgentCallbacks(chatAgent) {
15118
15623
  cancelAgentRun: (threadId) => chatAgent.cancel(threadId),
15119
15624
  regenerateAgentRun: (threadId, stoppedReplyId) => chatAgent.regenerate(threadId, stoppedReplyId),
15120
15625
  listAgentRuns: () => chatAgent.runningThreadIds(),
15626
+ listBackgroundThreads: () => chatAgent.backgroundThreadIds(),
15121
15627
  wakeAgentRun: (threadId, replyId, text) => chatAgent.wake(threadId, replyId, text),
15122
15628
  completeMemoryExtraction: (req) => chatAgent.completeMemoryExtraction(req),
15123
15629
  suggestChannelField: (req) => suggestChannelField(req),
@@ -15156,7 +15662,8 @@ function buildHostConfigSnapshot() {
15156
15662
  env: existsSync25(paths.CONFIG_FILE) ? dotenv2.parse(readFileSync19(paths.CONFIG_FILE, "utf-8")) : {},
15157
15663
  // Only a model someone actually saved: before that it is just the Claude
15158
15664
  // default, which would show the wrong agent in admin for a Codex user.
15159
- agentModel: existsSync25(paths.DASHBOARD_SETTINGS_FILE) ? loadDashboardSettings().agent : void 0
15665
+ agentModel: existsSync25(paths.DASHBOARD_SETTINGS_FILE) ? loadDashboardSettings().agent : void 0,
15666
+ home: homedir9()
15160
15667
  }));
15161
15668
  }
15162
15669
  return snapshot2;
@@ -15358,7 +15865,7 @@ import { join as join17 } from "path";
15358
15865
  import { serveStatic } from "@hono/node-server/serve-static";
15359
15866
 
15360
15867
  // ../api/src/dashboard/app-icon-routes.ts
15361
- import { Hono as Hono40 } from "hono";
15868
+ import { Hono as Hono44 } from "hono";
15362
15869
  var MANIFEST = {
15363
15870
  id: "/",
15364
15871
  name: "Flyspace",
@@ -15392,7 +15899,7 @@ async function resolvedProfileHost(c) {
15392
15899
  return profileFromHost(trustedHost(c), known);
15393
15900
  }
15394
15901
  function createAppIconRouter() {
15395
- const app = new Hono40();
15902
+ const app = new Hono44();
15396
15903
  app.get("/manifest.json", (c) => c.json(MANIFEST));
15397
15904
  app.get("/icons/app/:profile/:file", async (c) => {
15398
15905
  const profile = c.req.param("profile");
@@ -15768,7 +16275,7 @@ async function runDashboard(args) {
15768
16275
 
15769
16276
  // src/commands/workspace.ts
15770
16277
  import { existsSync as existsSync28, mkdirSync as mkdirSync12, writeFileSync as writeFileSync9 } from "fs";
15771
- var USAGE7 = `
16278
+ var USAGE6 = `
15772
16279
  Usage: flyspace workspace <subcommand> [options]
15773
16280
 
15774
16281
  Subcommands:
@@ -15785,7 +16292,7 @@ var USAGE7 = `
15785
16292
  --no-invite Never send an invite email. Fails if the admin
15786
16293
  has no existing account.
15787
16294
  `;
15788
- function getArg5(args, flag) {
16295
+ function getArg4(args, flag) {
15789
16296
  const idx = args.indexOf(flag);
15790
16297
  return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : void 0;
15791
16298
  }
@@ -15886,10 +16393,10 @@ async function provisionChannels(specs) {
15886
16393
  async function handleCreate(args) {
15887
16394
  const slug = args[0];
15888
16395
  if (!slug || slug.startsWith("-")) fail2("Usage: flyspace workspace create <slug> --admin-email <email>");
15889
- const adminEmail = getArg5(args, "--admin-email");
16396
+ const adminEmail = getArg4(args, "--admin-email");
15890
16397
  if (!adminEmail?.includes("@")) fail2("--admin-email is required and must be an email address");
15891
- const botName = getArg5(args, "--bot-name") ?? slug;
15892
- const baseDomain = getArg5(args, "--base-domain") ?? "flyspace.ai";
16398
+ const botName = getArg4(args, "--bot-name") ?? slug;
16399
+ const baseDomain = getArg4(args, "--base-domain") ?? "flyspace.ai";
15893
16400
  const allowInvite = !args.includes("--no-invite");
15894
16401
  const channels = getAllArgs(args, "--channel").map(parseChannelSpec);
15895
16402
  loadEnvFiles();
@@ -15912,13 +16419,13 @@ async function runWorkspaceCmd(args) {
15912
16419
  await handleCreate(args.slice(1));
15913
16420
  break;
15914
16421
  default:
15915
- console.log(USAGE7);
16422
+ console.log(USAGE6);
15916
16423
  process.exit(args[0] ? 1 : 0);
15917
16424
  }
15918
16425
  }
15919
16426
 
15920
16427
  // src/commands/reconcile.ts
15921
- var USAGE8 = `
16428
+ var USAGE7 = `
15922
16429
  Usage: flyspace reconcile [<workspace> | --all]
15923
16430
 
15924
16431
  Repair a workspace's local filesystem state (profile dir, config.env,
@@ -15938,7 +16445,7 @@ function printLog(name, log5) {
15938
16445
  }
15939
16446
  async function runReconcileCmd(args) {
15940
16447
  if (args.includes("-h") || args.includes("--help")) {
15941
- console.log(USAGE8);
16448
+ console.log(USAGE7);
15942
16449
  return;
15943
16450
  }
15944
16451
  loadEnvFiles();
@@ -15956,11 +16463,11 @@ async function runReconcileCmd(args) {
15956
16463
  import { spawnSync as spawnSync2 } from "child_process";
15957
16464
  var SCRIPT_SH = "https://flyspace.ai/install-desktop.sh";
15958
16465
  var SCRIPT_PS1 = "https://flyspace.ai/install-desktop.ps1";
15959
- var USAGE9 = "Usage: flyspace desktop install [--dev]";
16466
+ var USAGE8 = "Usage: flyspace desktop install [--dev]";
15960
16467
  async function runDesktopCmd(args) {
15961
16468
  const [sub, ...rest] = args;
15962
16469
  if (sub !== "install" || rest.some((a) => a !== "--dev")) {
15963
- printRaw(USAGE9);
16470
+ printRaw(USAGE8);
15964
16471
  process.exit(1);
15965
16472
  }
15966
16473
  const dev = rest.includes("--dev");
@@ -15978,6 +16485,7 @@ async function runDesktopCmd(args) {
15978
16485
 
15979
16486
  // src/cli.ts
15980
16487
  import { join as join20 } from "path";
16488
+ import { existsSync as existsSync29, readdirSync as readdirSync5 } from "fs";
15981
16489
  var home = flyspaceHome();
15982
16490
  if (home) {
15983
16491
  const bin = join20(home, "bin");
@@ -15985,7 +16493,7 @@ if (home) {
15985
16493
  if (!path.split(":").includes(bin)) process.env.PATH = path ? `${bin}:${path}` : bin;
15986
16494
  }
15987
16495
  var XERO_USAGE = false ? " xero Connect to Xero and expose it as an MCP server\n" : "";
15988
- var USAGE10 = `
16496
+ var USAGE9 = `
15989
16497
  Usage: flyspace <command> [options]
15990
16498
 
15991
16499
  Commands:
@@ -16036,12 +16544,27 @@ function extractProfileFlag(argv) {
16036
16544
  }
16037
16545
  return { profile, args };
16038
16546
  }
16547
+ function soleNamedProfile() {
16548
+ if (existsSync29(paths.CONFIG_FILE)) return void 0;
16549
+ let names;
16550
+ try {
16551
+ names = readdirSync5(paths.PROFILES_DIR).filter(
16552
+ (n) => existsSync29(join20(paths.PROFILES_DIR, n, "config.env"))
16553
+ );
16554
+ } catch {
16555
+ return void 0;
16556
+ }
16557
+ return names.length === 1 ? names[0] : void 0;
16558
+ }
16039
16559
  async function main() {
16040
16560
  useDirectSupabase();
16041
16561
  useLocalCache();
16042
16562
  const { profile, args } = extractProfileFlag(process.argv.slice(2));
16043
16563
  if (profile) {
16044
16564
  process.env["FLYSPACE_WORKSPACE"] = profile;
16565
+ } else if (!process.env["FLYSPACE_WORKSPACE"]) {
16566
+ const sole = soleNamedProfile();
16567
+ if (sole) process.env["FLYSPACE_WORKSPACE"] = sole;
16045
16568
  }
16046
16569
  getProfile();
16047
16570
  const command = args[0];
@@ -16130,12 +16653,12 @@ async function main() {
16130
16653
  break;
16131
16654
  case "-v":
16132
16655
  case "--version":
16133
- printRaw("0.1.65");
16656
+ printRaw("0.1.67");
16134
16657
  break;
16135
16658
  case "-h":
16136
16659
  case "--help":
16137
16660
  case void 0:
16138
- printRaw(USAGE10);
16661
+ printRaw(USAGE9);
16139
16662
  break;
16140
16663
  case "xero":
16141
16664
  if (false) {
@@ -16146,7 +16669,7 @@ async function main() {
16146
16669
  // falls through
16147
16670
  default:
16148
16671
  printRaw(`Unknown command: ${command}`);
16149
- printRaw(USAGE10);
16672
+ printRaw(USAGE9);
16150
16673
  process.exit(1);
16151
16674
  }
16152
16675
  }