flyspace-cli 0.1.66 → 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.
@@ -318,6 +318,593 @@ function loadConfig() {
318
318
  };
319
319
  }
320
320
 
321
+ // ../api/src/channels.ts
322
+ import { createHash } from "crypto";
323
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, realpathSync, statSync as statSync2 } from "fs";
324
+ import { homedir as homedir2 } from "os";
325
+ import { isAbsolute, relative, resolve as resolve3, sep } from "path";
326
+ function isPermissionMode(value) {
327
+ return value === "bypass" || value === "ask";
328
+ }
329
+ function isLogicalCwd(p) {
330
+ return /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(p);
331
+ }
332
+ function logicalRoot() {
333
+ return process.env["FLYSPACE_ROOT"] || resolve3(homedir2(), "Flyspace");
334
+ }
335
+ var workspaceRoots = /* @__PURE__ */ new Map();
336
+ var workspacePermissionModes = /* @__PURE__ */ new Map();
337
+ var workspaceAutoContinueLimits = /* @__PURE__ */ new Map();
338
+ var DEFAULT_AUTO_CONTINUE_LIMIT = 3;
339
+ async function refreshWorkspaceAutoContinueLimits() {
340
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, auto_continue_limit");
341
+ if (error) return;
342
+ workspaceAutoContinueLimits = new Map(
343
+ (data ?? []).filter((w) => typeof w.auto_continue_limit === "number").map((w) => [w.slug, w.auto_continue_limit])
344
+ );
345
+ }
346
+ function resolveAutoContinueLimit(channelId) {
347
+ const channel = channelId ? findChannel(channelId) : void 0;
348
+ return workspaceAutoContinueLimits.get(channel?.profile ?? getProfile()) ?? DEFAULT_AUTO_CONTINUE_LIMIT;
349
+ }
350
+ var workspaceOwnPersona = /* @__PURE__ */ new Set();
351
+ async function refreshWorkspaceOwnPersona() {
352
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, own_persona");
353
+ if (error) return;
354
+ workspaceOwnPersona = new Set(
355
+ (data ?? []).filter((w) => w.own_persona === true).map((w) => w.slug)
356
+ );
357
+ }
358
+ function resolveOwnPersona(channelId) {
359
+ const channel = channelId ? findChannel(channelId) : void 0;
360
+ return workspaceOwnPersona.has(channel?.profile ?? getProfile());
361
+ }
362
+ var workspaceAgentDefaults = /* @__PURE__ */ new Map();
363
+ async function refreshWorkspaceAgentDefaults() {
364
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, default_model, default_effort");
365
+ if (error) return;
366
+ workspaceAgentDefaults = new Map(
367
+ (data ?? []).map((w) => [
368
+ w.slug,
369
+ {
370
+ model: typeof w.default_model === "string" && w.default_model.trim() ? w.default_model.trim() : void 0,
371
+ effort: typeof w.default_effort === "string" && isEffort(w.default_effort) ? w.default_effort : void 0
372
+ }
373
+ ])
374
+ );
375
+ }
376
+ function workspaceAgentDefault(profile = getProfile()) {
377
+ return workspaceAgentDefaults.get(profile) ?? {};
378
+ }
379
+ function displayCwd(cwd, hostHome) {
380
+ const logical = isLogicalCwd(cwd) ? cwd : toLogicalCwd(cwd);
381
+ let path = cwd;
382
+ if (isLogicalCwd(logical)) {
383
+ const [slug, name] = logical.split("/");
384
+ const root = workspaceRoots.get(slug);
385
+ path = root ? `${root.replace(/[/\\]+$/, "")}/${name}` : `~/Flyspace/${logical}`;
386
+ }
387
+ const home2 = hostHome?.replace(/[/\\]+$/, "");
388
+ if (home2 && (path === home2 || path.startsWith(`${home2}/`) || path.startsWith(`${home2}\\`))) {
389
+ return `~${path.slice(home2.length)}`;
390
+ }
391
+ return path.replace(/^\/(Users|home)\/[^/]+/, "~").replace(/^\/root(?=\/|$)/, "~").replace(/^[A-Za-z]:\\Users\\[^\\]+/, "~");
392
+ }
393
+ async function refreshWorkspacePermissionModes() {
394
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, permission_mode");
395
+ if (error) return;
396
+ workspacePermissionModes = new Map(
397
+ (data ?? []).filter((w) => isPermissionMode(w.permission_mode)).map((w) => [w.slug, w.permission_mode])
398
+ );
399
+ }
400
+ async function refreshWorkspaceRoots() {
401
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
402
+ if (error) return;
403
+ workspaceRoots = new Map(
404
+ (data ?? []).filter((w) => w.root_path).map((w) => [w.slug, expandPath(w.root_path)])
405
+ );
406
+ }
407
+ function resolveLogicalCwd(p) {
408
+ const [slug, name] = p.split("/");
409
+ const root = workspaceRoots.get(slug);
410
+ return root ? resolve3(root, name) : resolve3(logicalRoot(), p);
411
+ }
412
+ function isUnderLogicalRoot(cwd) {
413
+ return [logicalRoot(), ...workspaceRoots.values()].some((r) => cwd.startsWith(r + sep));
414
+ }
415
+ function toLogicalCwd(cwd) {
416
+ const fromRoot = relative(logicalRoot(), cwd).split(sep).join("/");
417
+ if (isLogicalCwd(fromRoot)) return fromRoot;
418
+ for (const [slug, root] of workspaceRoots) {
419
+ const name = relative(root, cwd);
420
+ if (isLogicalCwd(`${slug}/${name}`)) return `${slug}/${name}`;
421
+ }
422
+ return cwd;
423
+ }
424
+ function ensureLogicalCwdDir(cwd) {
425
+ if (!isUnderLogicalRoot(cwd) || existsSync3(cwd)) return;
426
+ mkdirSync2(cwd, { recursive: true });
427
+ }
428
+ function expandPath(p) {
429
+ let expanded = p;
430
+ if (expanded === "~") {
431
+ expanded = homedir2();
432
+ } else if (expanded.startsWith("~/")) {
433
+ expanded = resolve3(homedir2(), expanded.slice(2));
434
+ }
435
+ return isAbsolute(expanded) ? expanded : resolve3(expanded);
436
+ }
437
+ function normaliseMemberEmails(raw) {
438
+ if (!Array.isArray(raw)) return [];
439
+ const seen = /* @__PURE__ */ new Set();
440
+ for (const v of raw) {
441
+ if (typeof v !== "string") continue;
442
+ const email = v.trim().toLowerCase();
443
+ if (email) seen.add(email);
444
+ }
445
+ return [...seen];
446
+ }
447
+ function canSeeChannel(channel, viewer) {
448
+ if (channel.visibility === "public") return true;
449
+ if (viewer?.role === "admin" && !channel.dmKey) return true;
450
+ const email = viewer?.email?.trim().toLowerCase();
451
+ return !!email && channel.memberEmails.includes(email);
452
+ }
453
+ function rowToChannel(row) {
454
+ return {
455
+ id: row.id,
456
+ name: row.name,
457
+ categoryId: row.category_id,
458
+ cwd: isLogicalCwd(row.cwd) ? resolveLogicalCwd(row.cwd) : expandPath(row.cwd),
459
+ externalChannelId: row.external_channel_id,
460
+ model: row.model,
461
+ effort: row.effort && isEffort(row.effort) ? row.effort : null,
462
+ prompt: row.prompt?.trim() || null,
463
+ topicCategories: normaliseTopicCategories(row.topic_categories),
464
+ // A uuid[] arrives as a real array; anything else (an older row read
465
+ // through a cached client, a hand-edited value) reads as "no MCP", which
466
+ // is the safe direction for a list that decides which credentials a run
467
+ // can reach.
468
+ mcpConnections: Array.isArray(row.mcp_connections) ? row.mcp_connections.filter((id) => typeof id === "string") : [],
469
+ access: row.access ?? void 0,
470
+ visibility: row.visibility === "public" ? "public" : "private",
471
+ memberEmails: normaliseMemberEmails(row.member_emails),
472
+ // The CHECK constraint (0035, extended by 0070 for 'sandbox') means the
473
+ // stored value is always one of these three, so this narrowing is
474
+ // unreachable in practice and exists to satisfy the type. Note it cannot
475
+ // degrade *safely* the way `mcpConnections` does: an unreadable value here
476
+ // would drop a channel back to the unisolated runtime, which is why the
477
+ // constraint is the real guarantee and this is only a type-level
478
+ // fallback.
479
+ runtime: row.runtime === "container" ? "container" : row.runtime === "sandbox" ? "sandbox" : "host",
480
+ // Same shape and same defensive read as `mcpConnections`: anything that
481
+ // isn't a clean string array reads as "no mounts", which exposes less
482
+ // rather than more.
483
+ mounts: Array.isArray(row.mounts) ? row.mounts.filter((p) => typeof p === "string").map(expandPath) : [],
484
+ permissionMode: isPermissionMode(row.permission_mode) ? row.permission_mode : null,
485
+ position: row.position,
486
+ automations: row.automations ?? void 0,
487
+ agentName: row.agent_name,
488
+ dmKey: row.dm_key,
489
+ isDefault: row.is_default === true,
490
+ profile: row.profile,
491
+ archivedAt: row.archived_at,
492
+ description: row.description ?? null,
493
+ greetedAt: row.greeted_at,
494
+ createdAt: row.created_at,
495
+ updatedAt: row.updated_at
496
+ };
497
+ }
498
+ var registry = [];
499
+ var byId = /* @__PURE__ */ new Map();
500
+ var byExternalId = /* @__PURE__ */ new Map();
501
+ var changeListeners = /* @__PURE__ */ new Set();
502
+ var lastSnapshot;
503
+ function indexRegistry(list) {
504
+ registry = list;
505
+ byId = new Map(list.map((c) => [c.id, c]));
506
+ byExternalId = new Map(
507
+ list.filter((c) => !!c.externalChannelId).map((c) => [c.externalChannelId, c])
508
+ );
509
+ }
510
+ async function refreshChannelRegistry() {
511
+ const rootsBefore = JSON.stringify([...workspaceRoots]);
512
+ await Promise.all([
513
+ refreshWorkspaceRoots(),
514
+ refreshWorkspacePermissionModes(),
515
+ refreshWorkspaceOwnPersona(),
516
+ refreshWorkspaceAutoContinueLimits(),
517
+ refreshWorkspaceAgentDefaults()
518
+ ]);
519
+ if (JSON.stringify([...workspaceRoots]) !== rootsBefore) lastSnapshot = void 0;
520
+ const { data, error } = await getSupabaseClient().from("channels").select("*").order("position", { ascending: true });
521
+ if (error) {
522
+ console.error("[channels] refreshChannelRegistry failed:", error.message);
523
+ return;
524
+ }
525
+ const rows = data ?? [];
526
+ const snapshot = JSON.stringify(
527
+ rows,
528
+ (key, value) => key === "updated_at" || key === "created_at" ? void 0 : value
529
+ );
530
+ if (snapshot === lastSnapshot) return;
531
+ lastSnapshot = snapshot;
532
+ indexRegistry(rows.map(rowToChannel));
533
+ for (const cb of changeListeners) {
534
+ try {
535
+ cb();
536
+ } catch (err) {
537
+ console.error("[channels] onChannelRegistryChange listener failed:", err);
538
+ }
539
+ }
540
+ }
541
+ function getChannelRegistry() {
542
+ return registry;
543
+ }
544
+ function getProfileChannelRegistry() {
545
+ const profile = getProfile();
546
+ return registry.filter((ch) => ch.profile === profile);
547
+ }
548
+ function onChannelRegistryChange(cb) {
549
+ changeListeners.add(cb);
550
+ return () => changeListeners.delete(cb);
551
+ }
552
+ function findChannelById(id) {
553
+ return byId.get(id);
554
+ }
555
+ function findChannelByExternalId(externalId) {
556
+ return byExternalId.get(externalId);
557
+ }
558
+ function agentDmKey(agentName, userId) {
559
+ return `agent:${agentName}:${userId}`;
560
+ }
561
+ function dmCwd(dmKey, profile = getProfile()) {
562
+ return `${profile}/dm-${createHash("sha256").update(dmKey).digest("hex").slice(0, 24)}`;
563
+ }
564
+ function findChannelByAgentName(agentName, userId) {
565
+ const dmKey = agentDmKey(agentName, userId);
566
+ return getProfileChannelRegistry().find((c) => c.agentName === agentName && c.dmKey === dmKey);
567
+ }
568
+ function findChannel(ref) {
569
+ if (!ref) return void 0;
570
+ return byId.get(ref) ?? byExternalId.get(ref) ?? registry.find((c) => c.name === ref || c.name === ref.replace(/^#/, ""));
571
+ }
572
+ var DEFAULT_POLL_INTERVAL_MS = 2e4;
573
+ var pollTimer;
574
+ var realtimeChannel;
575
+ function startChannelRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
576
+ stopChannelRegistryPolling();
577
+ pollTimer = setInterval(() => void refreshChannelRegistry(), intervalMs);
578
+ try {
579
+ realtimeChannel = getSupabaseClient().channel("channels-registry").on(
580
+ "postgres_changes",
581
+ { event: "*", schema: "public", table: "channels" },
582
+ () => void refreshChannelRegistry()
583
+ ).subscribe();
584
+ } catch (err) {
585
+ console.warn(
586
+ "[channels] realtime subscribe failed \u2014 falling back to polling only:",
587
+ err.message
588
+ );
589
+ }
590
+ return stopChannelRegistryPolling;
591
+ }
592
+ function stopChannelRegistryPolling() {
593
+ if (pollTimer) clearInterval(pollTimer);
594
+ pollTimer = void 0;
595
+ if (realtimeChannel) {
596
+ void getSupabaseClient().removeChannel(realtimeChannel);
597
+ realtimeChannel = void 0;
598
+ }
599
+ }
600
+ function isCwdUsable(cwd) {
601
+ try {
602
+ return existsSync3(cwd) && statSync2(cwd).isDirectory();
603
+ } catch {
604
+ return false;
605
+ }
606
+ }
607
+ function auditChannelCwds(list = registry) {
608
+ return list.filter((ch) => ch.cwd && !isCwdUsable(ch.cwd));
609
+ }
610
+ function warnOnBrokenChannelCwds(list = registry) {
611
+ const broken = auditChannelCwds(list);
612
+ for (const ch of broken) {
613
+ console.warn(
614
+ `[channels] "${ch.name}" (${ch.id}): cwd "${ch.cwd}" does not exist \u2014 the agent will fall back to CLAUDE_CWD. Fix it in the channel's settings.`
615
+ );
616
+ }
617
+ return broken;
618
+ }
619
+ function resolveChannelCwd(channelId) {
620
+ if (!channelId) return void 0;
621
+ const entry = findChannel(channelId);
622
+ if (!entry?.cwd) return void 0;
623
+ if (!isCwdUsable(entry.cwd)) {
624
+ console.warn(
625
+ `[channels] ${channelId}: cwd "${entry.cwd}" does not exist \u2014 falling back to CLAUDE_CWD`
626
+ );
627
+ return void 0;
628
+ }
629
+ return entry.cwd;
630
+ }
631
+ function isChannelAccessAllowed(channelId, userId) {
632
+ if (!channelId) return false;
633
+ const access = findChannel(channelId)?.access;
634
+ if (!access) return false;
635
+ if (typeof access === "string") {
636
+ return access === "open" || access === "*" || access === "all";
637
+ }
638
+ return !!userId && access.includes(userId);
639
+ }
640
+ function resolveCwd(explicitCwd, channelId, fallback) {
641
+ if (explicitCwd) return explicitCwd;
642
+ return resolveChannelCwd(channelId) ?? fallback;
643
+ }
644
+ function resolveChannelModel(channelId) {
645
+ if (!channelId) return void 0;
646
+ return findChannel(channelId)?.model?.trim() || void 0;
647
+ }
648
+ function resolveChannelEffort(channelId) {
649
+ if (!channelId) return void 0;
650
+ return findChannel(channelId)?.effort ?? void 0;
651
+ }
652
+ function resolveChannelPermissionMode(channelId) {
653
+ const channel = channelId ? findChannel(channelId) : void 0;
654
+ return channel?.permissionMode ?? workspacePermissionModes.get(channel?.profile ?? getProfile()) ?? "bypass";
655
+ }
656
+ function resolveChannelPrompt(channelId) {
657
+ if (!channelId) return void 0;
658
+ return findChannel(channelId)?.prompt?.trim() || void 0;
659
+ }
660
+ function resolveModel(explicitModel, channelId, fallback) {
661
+ if (explicitModel?.trim()) return explicitModel.trim();
662
+ return resolveChannelModel(channelId) ?? fallback;
663
+ }
664
+ function resolveEffort(explicitEffort, channelId, fallback) {
665
+ if (explicitEffort) return explicitEffort;
666
+ return resolveChannelEffort(channelId) ?? fallback;
667
+ }
668
+ var CHANNEL_DESCRIPTION_MAX = 1e3;
669
+ function normaliseChannelDescription(value) {
670
+ if (value === null || value === void 0) return null;
671
+ if (typeof value !== "string") return "invalid";
672
+ const t = value.trim();
673
+ if (t.length > CHANNEL_DESCRIPTION_MAX) return "invalid";
674
+ return t || null;
675
+ }
676
+ function normaliseTopicCategories(value) {
677
+ if (!Array.isArray(value)) return [];
678
+ const out = [];
679
+ for (const v of value) {
680
+ const t = typeof v === "string" ? v.trim() : "";
681
+ if (t && !out.includes(t)) out.push(t);
682
+ }
683
+ return out;
684
+ }
685
+ function toRow(input) {
686
+ const row = {};
687
+ if (input.name !== void 0) row["name"] = input.name;
688
+ if (input.cwd !== void 0) row["cwd"] = isLogicalCwd(input.cwd) ? input.cwd : toLogicalCwd(expandPath(input.cwd));
689
+ if (input.categoryId !== void 0) row["category_id"] = input.categoryId;
690
+ if (input.externalChannelId !== void 0) row["external_channel_id"] = input.externalChannelId;
691
+ if (input.model !== void 0) row["model"] = input.model;
692
+ if (input.effort !== void 0) row["effort"] = input.effort;
693
+ if (input.prompt !== void 0) row["prompt"] = input.prompt?.trim() || null;
694
+ if (input.topicCategories !== void 0) {
695
+ const list = normaliseTopicCategories(input.topicCategories);
696
+ row["topic_categories"] = list.length ? list : null;
697
+ }
698
+ if (input.access !== void 0) row["access"] = input.access;
699
+ if (input.visibility !== void 0) row["visibility"] = input.visibility;
700
+ if (input.memberEmails !== void 0) {
701
+ row["member_emails"] = normaliseMemberEmails(input.memberEmails);
702
+ }
703
+ if (input.runtime !== void 0) row["runtime"] = input.runtime;
704
+ if (input.mounts !== void 0) {
705
+ row["mounts"] = input.mounts.map((p) => p.trim()).filter(Boolean).map(expandPath);
706
+ }
707
+ if (input.permissionMode !== void 0) row["permission_mode"] = input.permissionMode;
708
+ if (input.position !== void 0) row["position"] = input.position;
709
+ if (input.automations !== void 0) row["automations"] = input.automations;
710
+ if (input.agentName !== void 0) row["agent_name"] = input.agentName;
711
+ if (input.dmKey !== void 0) row["dm_key"] = input.dmKey;
712
+ if (input.isDefault !== void 0) row["is_default"] = input.isDefault;
713
+ if (input.mcpConnections !== void 0) row["mcp_connections"] = input.mcpConnections;
714
+ if (input.archivedAt !== void 0) row["archived_at"] = input.archivedAt;
715
+ if (input.description !== void 0) {
716
+ const d = normaliseChannelDescription(input.description);
717
+ if (d === "invalid") throw new Error(`description must be at most ${CHANNEL_DESCRIPTION_MAX} characters`);
718
+ row["description"] = d;
719
+ }
720
+ return row;
721
+ }
722
+ var ChannelCwdError = class extends Error {
723
+ constructor(message) {
724
+ super(message);
725
+ this.name = "ChannelCwdError";
726
+ }
727
+ };
728
+ function realpathOrSelf(p) {
729
+ try {
730
+ return realpathSync(p);
731
+ } catch {
732
+ return p;
733
+ }
734
+ }
735
+ async function assertCwdInWorkspace(profile, cwd) {
736
+ if (isLogicalCwd(cwd)) {
737
+ if (cwd.split("/")[0] !== profile) {
738
+ throw new ChannelCwdError(`Folder "${cwd}" belongs to another workspace.`);
739
+ }
740
+ return cwd;
741
+ }
742
+ const logical = relative(logicalRoot(), cwd).split(sep).join("/");
743
+ if (isLogicalCwd(logical)) return assertCwdInWorkspace(profile, logical);
744
+ const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
745
+ if (error) throw new Error(error.message);
746
+ const workspaces = data ?? [];
747
+ const ownRoot = workspaces.find((w) => w.slug === profile)?.root_path;
748
+ const home2 = ownRoot?.match(/^(\/Users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/)?.[1];
749
+ const absolute = home2 && (cwd === "~" || cwd.startsWith("~/")) ? resolve3(home2, cwd.slice(2)) : expandPath(cwd);
750
+ const path = realpathOrSelf(absolute);
751
+ const roots = workspaces.filter((w) => w.root_path).map((w) => ({ slug: w.slug, root: realpathOrSelf(expandPath(w.root_path)) }));
752
+ const owner = roots.filter(({ root }) => path === root || path.startsWith(root + sep)).sort((a, b) => b.root.length - a.root.length)[0];
753
+ if (owner ? owner.slug !== profile : roots.some((r) => r.slug === profile)) {
754
+ throw new ChannelCwdError(
755
+ owner ? `Folder "${cwd}" belongs to the "${owner.slug}" workspace.` : `Folder "${cwd}" is outside this workspace's folder.`
756
+ );
757
+ }
758
+ return absolute;
759
+ }
760
+ async function createChannel(input) {
761
+ input = { ...input, cwd: await assertCwdInWorkspace(getProfile(), input.cwd) };
762
+ const { data, error } = await getSupabaseClient().from("channels").insert({ ...toRow(input), profile: getProfile() }).select().single();
763
+ if (error) throw new Error(error.message);
764
+ const channel = rowToChannel(data);
765
+ if (channel.cwd && !isLogicalCwd(input.cwd) && !isCwdUsable(channel.cwd)) {
766
+ try {
767
+ mkdirSync2(channel.cwd, { recursive: true });
768
+ } catch (err) {
769
+ console.error(`[channels] failed to create cwd for "${channel.name}":`, err.message);
770
+ }
771
+ }
772
+ await refreshChannelRegistry();
773
+ return channel;
774
+ }
775
+ var DefaultChannelError = class extends Error {
776
+ constructor() {
777
+ super("The default channel must stay public and cannot be renamed or archived.");
778
+ this.name = "DefaultChannelError";
779
+ }
780
+ };
781
+ async function updateChannelById(id, patch) {
782
+ const existing = findChannelById(id);
783
+ if (existing?.isDefault && (patch.visibility === "private" || patch.archivedAt || patch.isDefault === false || patch.name !== void 0 && patch.name.trim() !== existing.name)) {
784
+ throw new DefaultChannelError();
785
+ }
786
+ if (patch.cwd !== void 0 && existing && patch.cwd === existing.cwd) {
787
+ const { cwd: _unchanged, ...rest } = patch;
788
+ patch = rest;
789
+ }
790
+ if (patch.cwd !== void 0) {
791
+ patch = { ...patch, cwd: await assertCwdInWorkspace(existing?.profile ?? getProfile(), patch.cwd) };
792
+ }
793
+ const { data, error } = await getSupabaseClient().from("channels").update({ ...toRow(patch), updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
794
+ if (error) throw new Error(error.message);
795
+ await refreshChannelRegistry();
796
+ return rowToChannel(data);
797
+ }
798
+ async function markChannelGreeted(id) {
799
+ const { data, error } = await getSupabaseClient().from("channels").update({ greeted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).is("greeted_at", null).select("id");
800
+ if (error) throw new Error(error.message);
801
+ await refreshChannelRegistry();
802
+ return (data ?? []).length > 0;
803
+ }
804
+ async function updateChannelsMcpConnections(updates) {
805
+ if (!updates.length) return;
806
+ const supabase = getSupabaseClient();
807
+ for (const update of updates) {
808
+ const { error } = await supabase.from("channels").update({ mcp_connections: update.mcpConnections, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", update.id);
809
+ if (error) throw new Error(`Failed to update channel ${update.id}: ${error.message}`);
810
+ }
811
+ await refreshChannelRegistry();
812
+ }
813
+ function defaultFallbackCwd() {
814
+ return process.env["CLAUDE_CWD"] ?? process.cwd();
815
+ }
816
+ async function ensureChannelProvisioned(externalChannelId, opts = {}) {
817
+ const existing = findChannelByExternalId(externalChannelId);
818
+ if (existing) {
819
+ if (existing.profile !== getProfile()) return null;
820
+ if (existing.name === externalChannelId && opts.name && opts.name !== externalChannelId) {
821
+ try {
822
+ return await updateChannelById(existing.id, { name: opts.name });
823
+ } catch (err) {
824
+ console.error(`[channels] failed to heal name for ${externalChannelId}:`, err);
825
+ return existing;
826
+ }
827
+ }
828
+ return existing;
829
+ }
830
+ try {
831
+ const created = await createChannel({
832
+ name: opts.name ?? externalChannelId,
833
+ cwd: opts.fallbackCwd ?? defaultFallbackCwd(),
834
+ externalChannelId
835
+ });
836
+ console.log(`[channels] auto-provisioned a new channel for Slack channel ${externalChannelId}`);
837
+ return created;
838
+ } catch (err) {
839
+ await refreshChannelRegistry();
840
+ const raced = findChannelByExternalId(externalChannelId);
841
+ if (raced) return raced.profile === getProfile() ? raced : null;
842
+ throw err;
843
+ }
844
+ }
845
+ async function ensureAgentDmChannel(agentName, viewer, opts) {
846
+ const existing = findChannelByAgentName(agentName, viewer.userId);
847
+ if (existing) {
848
+ return existing.name === opts.name ? existing : updateChannelById(existing.id, { name: opts.name });
849
+ }
850
+ const dmKey = agentDmKey(agentName, viewer.userId);
851
+ try {
852
+ return await createChannel({
853
+ name: opts.name,
854
+ cwd: dmCwd(dmKey),
855
+ visibility: "private",
856
+ memberEmails: [viewer.email],
857
+ agentName,
858
+ dmKey
859
+ });
860
+ } catch (err) {
861
+ await refreshChannelRegistry();
862
+ const raced = findChannelByAgentName(agentName, viewer.userId);
863
+ if (raced) return raced;
864
+ throw err;
865
+ }
866
+ }
867
+ async function ensureGeneralChannel() {
868
+ const find = () => getProfileChannelRegistry().find((c) => c.isDefault);
869
+ const existing = find();
870
+ if (existing) return existing;
871
+ try {
872
+ return await createChannel({
873
+ name: "general",
874
+ cwd: `${getProfile()}/general`,
875
+ visibility: "public",
876
+ isDefault: true
877
+ });
878
+ } catch (err) {
879
+ await refreshChannelRegistry();
880
+ const raced = find();
881
+ if (raced) return raced;
882
+ throw err;
883
+ }
884
+ }
885
+ async function ensureMemberDmChannel(a, b) {
886
+ const dmKey = [a.userId, b.userId].sort().join(":");
887
+ const find = () => [...getProfileChannelRegistry()].find((c) => c.dmKey === dmKey && c.profile === getProfile());
888
+ const existing = find();
889
+ if (existing) return existing;
890
+ try {
891
+ return await createChannel({
892
+ name: `${a.handle}, ${b.handle}`,
893
+ // Hash the whole key: a prefix of the sorted ids is just the first user's
894
+ // id, which put every DM that user sorts first in into one shared folder.
895
+ cwd: dmCwd(dmKey),
896
+ visibility: "private",
897
+ memberEmails: [a.email, b.email],
898
+ dmKey
899
+ });
900
+ } catch (err) {
901
+ await refreshChannelRegistry();
902
+ const raced = find();
903
+ if (raced) return raced;
904
+ throw err;
905
+ }
906
+ }
907
+
321
908
  // ../api/src/dashboard/attachment-uploader.ts
322
909
  import { randomUUID } from "crypto";
323
910
  import { readFile, stat } from "fs/promises";
@@ -623,9 +1210,134 @@ var SessionStore = class {
623
1210
  }
624
1211
  };
625
1212
 
1213
+ // ../api/src/store/authors.ts
1214
+ var AGENT_AUTHOR = "agent";
1215
+ var SYNCED_BOT_AUTHOR = "Bot";
1216
+ var LEGACY_BOT_AUTHOR = "Custie";
1217
+ var SUPPORT_BOT_AUTHOR = "Flyspace Support";
1218
+ var NON_HUMAN_AUTHORS = new Set(
1219
+ [AGENT_AUTHOR, SYNCED_BOT_AUTHOR, LEGACY_BOT_AUTHOR, SUPPORT_BOT_AUTHOR].map((a) => a.toLowerCase())
1220
+ );
1221
+ function isHumanAuthor(author) {
1222
+ return !NON_HUMAN_AUTHORS.has(author.toLowerCase());
1223
+ }
1224
+
1225
+ // ../api/src/store/thread-title.ts
1226
+ var TITLE_MAX_LENGTH = 80;
1227
+ function deriveThreadTitle(text) {
1228
+ const firstLine = text.split("\n").find((line) => line.trim().length > 0);
1229
+ if (!firstLine) return null;
1230
+ const cleaned = firstLine.replace(/^\s*(?::[a-z0-9_+-]+:\s*)+/i, "").replace(/^\s*\p{Extended_Pictographic}[️‍]*\s*/u, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\*([^*]+)\*/g, "$1").replace(/(^|\s)_([^_\n]+)_(?=\s|$|[.,:;,。、:])/g, "$1$2").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
1231
+ if (!cleaned) return null;
1232
+ return cleaned.length > TITLE_MAX_LENGTH ? `${cleaned.slice(0, TITLE_MAX_LENGTH).trim()}\u2026` : cleaned;
1233
+ }
1234
+
1235
+ // src/store/dashboard-sync.ts
1236
+ async function syncPostToDashboard(opts) {
1237
+ const { channelId, ts, threadTs, text } = opts;
1238
+ if (!databaseReachable()) {
1239
+ console.warn("[dashboard-sync] Supabase not configured \u2014 skipping dashboard sync");
1240
+ return;
1241
+ }
1242
+ try {
1243
+ const supabase = getSupabaseClient();
1244
+ const dashboardChannelId = await resolveDashboardChannelId(supabase, channelId);
1245
+ const threadId = threadTs ? await ensureThreadId(supabase, channelId, dashboardChannelId, threadTs) : await createOwnThread(supabase, channelId, dashboardChannelId, ts, text);
1246
+ const { error } = await supabase.from("thread_replies").upsert(
1247
+ {
1248
+ thread_id: threadId,
1249
+ // This mirror only ever runs for the bot's own posts (automation
1250
+ // output, `flyspace slack post`), so the author is the agent itself —
1251
+ // labelling it anything else makes the chat agent count it as a
1252
+ // second human and stop replying without an explicit mention.
1253
+ author: AGENT_AUTHOR,
1254
+ body: await uploadLocalImages(text),
1255
+ external_thread_replies_id: `${channelId}:${ts}`
1256
+ },
1257
+ { onConflict: "external_thread_replies_id" }
1258
+ );
1259
+ if (error) {
1260
+ console.warn(`[dashboard-sync] failed to write reply: ${error.message}`);
1261
+ }
1262
+ } catch (err) {
1263
+ console.warn(
1264
+ `[dashboard-sync] sync failed: ${err instanceof Error ? err.message : String(err)}`
1265
+ );
1266
+ }
1267
+ }
1268
+ async function resolveDashboardChannelId(supabase, slackChannelId) {
1269
+ const { data, error } = await supabase.from("channels").select("id").eq("external_channel_id", slackChannelId).maybeSingle();
1270
+ if (error || !data) return slackChannelId;
1271
+ return data["id"];
1272
+ }
1273
+ async function createOwnThread(supabase, externalChannelId, dashboardChannelId, ts, text) {
1274
+ const { data, error } = await supabase.from("threads").upsert(
1275
+ {
1276
+ channel_id: dashboardChannelId,
1277
+ title: deriveThreadTitle(text),
1278
+ author: AGENT_AUTHOR,
1279
+ external_thread_id: `${externalChannelId}:${ts}`
1280
+ },
1281
+ { onConflict: "external_thread_id" }
1282
+ ).select("id").single();
1283
+ if (error || !data) throw new Error(error?.message ?? "failed to create thread");
1284
+ return data["id"];
1285
+ }
1286
+ async function ensureThreadId(supabase, externalChannelId, dashboardChannelId, parentTs) {
1287
+ const key = `${externalChannelId}:${parentTs}`;
1288
+ const { data: existing, error: selectError } = await supabase.from("threads").select("id").eq("external_thread_id", key).maybeSingle();
1289
+ if (selectError) throw new Error(selectError.message);
1290
+ if (existing) return existing["id"];
1291
+ const { data: created, error: createError } = await supabase.from("threads").upsert(
1292
+ // The unsynced parent could be anyone's message (often another bot's),
1293
+ // so keep the generic non-human placeholder rather than claiming it.
1294
+ {
1295
+ channel_id: dashboardChannelId,
1296
+ title: null,
1297
+ author: SYNCED_BOT_AUTHOR,
1298
+ external_thread_id: key
1299
+ },
1300
+ { onConflict: "external_thread_id" }
1301
+ ).select("id").single();
1302
+ if (createError || !created) {
1303
+ throw new Error(createError?.message ?? "failed to create placeholder thread");
1304
+ }
1305
+ return created["id"];
1306
+ }
1307
+
1308
+ // src/store/dashboard-post.ts
1309
+ async function postToDashboardChannel(opts) {
1310
+ const { channelId, text, threadId, title } = opts;
1311
+ const supabase = getSupabaseClient();
1312
+ if (!threadId && !channelId) {
1313
+ throw new Error("postToDashboardChannel: channelId is required to start a new thread");
1314
+ }
1315
+ const parentId = threadId ?? await createThread(supabase, channelId, text, title);
1316
+ const body = await uploadLocalImages(text);
1317
+ const { data, error } = await supabase.from("thread_replies").insert({ thread_id: parentId, author: AGENT_AUTHOR, body }).select("id").single();
1318
+ if (error || !data) {
1319
+ throw new Error(`failed to write dashboard reply: ${error?.message ?? "no row returned"}`);
1320
+ }
1321
+ return { threadId: parentId, replyId: data["id"] };
1322
+ }
1323
+ async function createThread(supabase, channelId, text, title) {
1324
+ const { data, error } = await supabase.from("threads").insert({
1325
+ channel_id: channelId,
1326
+ // An untitled thread is effectively invisible in the sidebar, so give a
1327
+ // daily report the same first-line-derived title a mirrored post gets,
1328
+ // unless the caller named the thread itself.
1329
+ title: title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(text),
1330
+ author: AGENT_AUTHOR
1331
+ }).select("id").single();
1332
+ if (error || !data) {
1333
+ throw new Error(`failed to create dashboard thread: ${error?.message ?? "no row returned"}`);
1334
+ }
1335
+ return data["id"];
1336
+ }
1337
+
626
1338
  // src/auth/device-auth.ts
627
1339
  import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "crypto";
628
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, writeFileSync } from "fs";
1340
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync, rmSync as rmSync2, writeFileSync } from "fs";
629
1341
  import { dirname, join as join2 } from "path";
630
1342
  var DEFAULT_API_URL = "https://app.flyspace.ai";
631
1343
  var EXPIRY_SKEW_MS = 6e4;
@@ -647,9 +1359,9 @@ function credentialsPath() {
647
1359
  }
648
1360
  function ensureDeviceKey(path = deviceKeyPath()) {
649
1361
  let created = false;
650
- if (!existsSync3(path)) {
1362
+ if (!existsSync4(path)) {
651
1363
  const { privateKey: privateKey2 } = generateKeyPairSync("ed25519");
652
- mkdirSync2(dirname(path), { recursive: true });
1364
+ mkdirSync3(dirname(path), { recursive: true });
653
1365
  writeFileSync(path, privateKey2.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
654
1366
  created = true;
655
1367
  }
@@ -660,7 +1372,7 @@ function ensureDeviceKey(path = deviceKeyPath()) {
660
1372
  return { privateKey, publicKeyBase64, created };
661
1373
  }
662
1374
  function loadCredentials(path = credentialsPath()) {
663
- if (!existsSync3(path)) return null;
1375
+ if (!existsSync4(path)) return null;
664
1376
  try {
665
1377
  return JSON.parse(readFileSync(path, "utf8"));
666
1378
  } catch {
@@ -668,7 +1380,7 @@ function loadCredentials(path = credentialsPath()) {
668
1380
  }
669
1381
  }
670
1382
  function saveCredentials(creds, path = credentialsPath()) {
671
- mkdirSync2(dirname(path), { recursive: true });
1383
+ mkdirSync3(dirname(path), { recursive: true });
672
1384
  writeFileSync(path, `${JSON.stringify(creds, null, 2)}
673
1385
  `, { mode: 384 });
674
1386
  }
@@ -804,7 +1516,7 @@ async function getAccessToken() {
804
1516
  // src/dashboard/host-lock.ts
805
1517
  import { execFileSync } from "child_process";
806
1518
  import { randomBytes } from "crypto";
807
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
1519
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
808
1520
  import { join as join3 } from "path";
809
1521
  function hostLockPath() {
810
1522
  return join3(paths.BASE_DATA_DIR, "host.lock");
@@ -830,7 +1542,7 @@ function readLockPid(path) {
830
1542
  }
831
1543
  function acquireHostLock() {
832
1544
  const path = hostLockPath();
833
- mkdirSync3(paths.BASE_DATA_DIR, { recursive: true });
1545
+ mkdirSync4(paths.BASE_DATA_DIR, { recursive: true });
834
1546
  const body = JSON.stringify({
835
1547
  pid: process.pid,
836
1548
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -903,14 +1615,14 @@ function handleHostDbResult(id, res) {
903
1615
  }
904
1616
  function whenConnected() {
905
1617
  if (sender) return Promise.resolve(sender);
906
- return new Promise((resolve3, reject) => {
1618
+ return new Promise((resolve4, reject) => {
907
1619
  const timer = setTimeout(() => {
908
1620
  onSender = onSender.filter((w) => w !== wake);
909
1621
  reject(new Error("Host is not connected to the Data API"));
910
1622
  }, REQUEST_TIMEOUT_MS);
911
1623
  const wake = () => {
912
1624
  clearTimeout(timer);
913
- resolve3(sender);
1625
+ resolve4(sender);
914
1626
  };
915
1627
  onSender.push(wake);
916
1628
  });
@@ -918,12 +1630,12 @@ function whenConnected() {
918
1630
  async function requestHostDb(req) {
919
1631
  const send = await whenConnected();
920
1632
  const id = randomUUID2();
921
- return new Promise((resolve3, reject) => {
1633
+ return new Promise((resolve4, reject) => {
922
1634
  const timer = setTimeout(() => {
923
1635
  pending.delete(id);
924
1636
  reject(new Error("Data API did not answer in time"));
925
1637
  }, REQUEST_TIMEOUT_MS);
926
- pending.set(id, { resolve: resolve3, reject, timer });
1638
+ pending.set(id, { resolve: resolve4, reject, timer });
927
1639
  send({ type: "db", id, req });
928
1640
  });
929
1641
  }
@@ -935,14 +1647,14 @@ function handleAttachmentUrlResult(id, url) {
935
1647
  async function requestAttachmentUrl(key) {
936
1648
  const send = await whenConnected();
937
1649
  const id = randomUUID2();
938
- return new Promise((resolve3, reject) => {
1650
+ return new Promise((resolve4, reject) => {
939
1651
  const timer = setTimeout(() => {
940
1652
  pendingUrls.delete(id);
941
1653
  reject(new Error("Data API did not answer in time"));
942
1654
  }, REQUEST_TIMEOUT_MS);
943
1655
  pendingUrls.set(id, (url) => {
944
1656
  clearTimeout(timer);
945
- resolve3(url);
1657
+ resolve4(url);
946
1658
  });
947
1659
  send({ type: "attachment-url", id, key });
948
1660
  });
@@ -955,14 +1667,14 @@ function handlePluginSvgResult(id, url) {
955
1667
  async function requestPluginSvg(workspace, svg) {
956
1668
  const send = await whenConnected();
957
1669
  const id = randomUUID2();
958
- return new Promise((resolve3, reject) => {
1670
+ return new Promise((resolve4, reject) => {
959
1671
  const timer = setTimeout(() => {
960
1672
  pendingSvgs.delete(id);
961
1673
  reject(new Error("Data API did not answer in time"));
962
1674
  }, REQUEST_TIMEOUT_MS);
963
1675
  pendingSvgs.set(id, (url) => {
964
1676
  clearTimeout(timer);
965
- resolve3(url);
1677
+ resolve4(url);
966
1678
  });
967
1679
  send({ type: "plugin-svg", id, workspace, svg });
968
1680
  });
@@ -975,14 +1687,14 @@ function handleScratchImageResult(id, url) {
975
1687
  async function requestScratchImage(workspace, filename, body) {
976
1688
  const send = await whenConnected();
977
1689
  const id = randomUUID2();
978
- return new Promise((resolve3, reject) => {
1690
+ return new Promise((resolve4, reject) => {
979
1691
  const timer = setTimeout(() => {
980
1692
  pendingImages.delete(id);
981
1693
  reject(new Error("Data API did not answer in time"));
982
1694
  }, REQUEST_TIMEOUT_MS);
983
1695
  pendingImages.set(id, (url) => {
984
1696
  clearTimeout(timer);
985
- resolve3(url);
1697
+ resolve4(url);
986
1698
  });
987
1699
  send({ type: "scratch-image", id, workspace, filename, data: body.toString("base64") });
988
1700
  });
@@ -997,14 +1709,14 @@ function handleActionResult(id, res) {
997
1709
  async function requestAction(name, input, requester) {
998
1710
  const send = await whenConnected();
999
1711
  const id = randomUUID2();
1000
- return new Promise((resolve3) => {
1712
+ return new Promise((resolve4) => {
1001
1713
  const timer = setTimeout(() => {
1002
1714
  pendingActions.delete(id);
1003
- resolve3({ error: "Data API did not answer in time" });
1715
+ resolve4({ error: "Data API did not answer in time" });
1004
1716
  }, ACTION_TIMEOUT_MS);
1005
1717
  pendingActions.set(id, (res) => {
1006
1718
  clearTimeout(timer);
1007
- resolve3(res);
1719
+ resolve4(res);
1008
1720
  });
1009
1721
  send({ type: "action", id, name, input, ...requester ? { requester } : {} });
1010
1722
  });
@@ -1019,14 +1731,14 @@ async function requestShouldRespond(transcript) {
1019
1731
  const send = await whenConnected().catch(() => null);
1020
1732
  if (!send) return false;
1021
1733
  const id = randomUUID2();
1022
- return new Promise((resolve3) => {
1734
+ return new Promise((resolve4) => {
1023
1735
  const timer = setTimeout(() => {
1024
1736
  pendingRespond.delete(id);
1025
- resolve3(false);
1737
+ resolve4(false);
1026
1738
  }, REQUEST_TIMEOUT_MS);
1027
1739
  pendingRespond.set(id, (respond) => {
1028
1740
  clearTimeout(timer);
1029
- resolve3(respond);
1741
+ resolve4(respond);
1030
1742
  });
1031
1743
  send({ type: "should-respond", id, transcript });
1032
1744
  });
@@ -1129,11 +1841,60 @@ export {
1129
1841
  slackConfigured,
1130
1842
  requireSlackBotToken,
1131
1843
  loadConfig,
1844
+ isPermissionMode,
1845
+ isLogicalCwd,
1846
+ DEFAULT_AUTO_CONTINUE_LIMIT,
1847
+ resolveAutoContinueLimit,
1848
+ resolveOwnPersona,
1849
+ workspaceAgentDefault,
1850
+ displayCwd,
1851
+ resolveLogicalCwd,
1852
+ isUnderLogicalRoot,
1853
+ ensureLogicalCwdDir,
1854
+ expandPath,
1855
+ canSeeChannel,
1856
+ refreshChannelRegistry,
1857
+ getChannelRegistry,
1858
+ getProfileChannelRegistry,
1859
+ onChannelRegistryChange,
1860
+ findChannelById,
1861
+ dmCwd,
1862
+ findChannel,
1863
+ startChannelRegistryPolling,
1864
+ isCwdUsable,
1865
+ auditChannelCwds,
1866
+ warnOnBrokenChannelCwds,
1867
+ isChannelAccessAllowed,
1868
+ resolveCwd,
1869
+ resolveChannelPermissionMode,
1870
+ resolveChannelPrompt,
1871
+ resolveModel,
1872
+ resolveEffort,
1873
+ CHANNEL_DESCRIPTION_MAX,
1874
+ normaliseChannelDescription,
1875
+ ChannelCwdError,
1876
+ createChannel,
1877
+ DefaultChannelError,
1878
+ updateChannelById,
1879
+ markChannelGreeted,
1880
+ updateChannelsMcpConnections,
1881
+ ensureChannelProvisioned,
1882
+ ensureAgentDmChannel,
1883
+ ensureGeneralChannel,
1884
+ ensureMemberDmChannel,
1885
+ AGENT_AUTHOR,
1886
+ SYNCED_BOT_AUTHOR,
1887
+ SUPPORT_BOT_AUTHOR,
1888
+ isHumanAuthor,
1132
1889
  getR2Client,
1133
1890
  getR2Bucket,
1134
1891
  sumR2PrefixBytes,
1135
1892
  SCRATCH_PREFIX,
1136
1893
  uploadLocalImages,
1894
+ deriveThreadTitle,
1895
+ syncPostToDashboard,
1896
+ resolveDashboardChannelId,
1897
+ postToDashboardChannel,
1137
1898
  DEFAULT_API_URL,
1138
1899
  AuthApiError,
1139
1900
  apiUrl,