flyspace-cli 0.1.60 → 0.1.61

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.
@@ -16,6 +16,10 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
16
16
  var __commonJS = (cb, mod) => function __require2() {
17
17
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
18
  };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
19
23
  var __copyProps = (to, from, except, desc) => {
20
24
  if (from && typeof from === "object" || typeof from === "function") {
21
25
  for (let key of __getOwnPropNames(from))
@@ -319,559 +323,6 @@ function loadConfig() {
319
323
  };
320
324
  }
321
325
 
322
- // ../api/src/channels.ts
323
- import { createHash } from "crypto";
324
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, realpathSync, statSync as statSync2 } from "fs";
325
- import { homedir as homedir2 } from "os";
326
- import { isAbsolute, relative, resolve as resolve3, sep } from "path";
327
- function isPermissionMode(value) {
328
- return value === "bypass" || value === "ask";
329
- }
330
- function isLogicalCwd(p) {
331
- return /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(p);
332
- }
333
- function logicalRoot() {
334
- return process.env["FLYSPACE_ROOT"] || resolve3(homedir2(), "Flyspace");
335
- }
336
- var workspaceRoots = /* @__PURE__ */ new Map();
337
- var workspacePermissionModes = /* @__PURE__ */ new Map();
338
- var workspaceAutoContinueLimits = /* @__PURE__ */ new Map();
339
- var DEFAULT_AUTO_CONTINUE_LIMIT = 3;
340
- async function refreshWorkspaceAutoContinueLimits() {
341
- const { data, error } = await getSupabaseClient().from("workspaces").select("slug, auto_continue_limit");
342
- if (error) return;
343
- workspaceAutoContinueLimits = new Map(
344
- (data ?? []).filter((w) => typeof w.auto_continue_limit === "number").map((w) => [w.slug, w.auto_continue_limit])
345
- );
346
- }
347
- function resolveAutoContinueLimit(channelId) {
348
- const channel = channelId ? findChannel(channelId) : void 0;
349
- return workspaceAutoContinueLimits.get(channel?.profile ?? getProfile()) ?? DEFAULT_AUTO_CONTINUE_LIMIT;
350
- }
351
- var workspaceOwnPersona = /* @__PURE__ */ new Set();
352
- async function refreshWorkspaceOwnPersona() {
353
- const { data, error } = await getSupabaseClient().from("workspaces").select("slug, own_persona");
354
- if (error) return;
355
- workspaceOwnPersona = new Set(
356
- (data ?? []).filter((w) => w.own_persona === true).map((w) => w.slug)
357
- );
358
- }
359
- function resolveOwnPersona(channelId) {
360
- const channel = channelId ? findChannel(channelId) : void 0;
361
- return workspaceOwnPersona.has(channel?.profile ?? getProfile());
362
- }
363
- async function refreshWorkspacePermissionModes() {
364
- const { data, error } = await getSupabaseClient().from("workspaces").select("slug, permission_mode");
365
- if (error) return;
366
- workspacePermissionModes = new Map(
367
- (data ?? []).filter((w) => isPermissionMode(w.permission_mode)).map((w) => [w.slug, w.permission_mode])
368
- );
369
- }
370
- async function refreshWorkspaceRoots() {
371
- const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
372
- if (error) return;
373
- workspaceRoots = new Map(
374
- (data ?? []).filter((w) => w.root_path).map((w) => [w.slug, expandPath(w.root_path)])
375
- );
376
- }
377
- function resolveLogicalCwd(p) {
378
- const [slug, name] = p.split("/");
379
- const root = workspaceRoots.get(slug);
380
- return root ? resolve3(root, name) : resolve3(logicalRoot(), p);
381
- }
382
- function isUnderLogicalRoot(cwd) {
383
- return [logicalRoot(), ...workspaceRoots.values()].some((r) => cwd.startsWith(r + sep));
384
- }
385
- function toLogicalCwd(cwd) {
386
- const fromRoot = relative(logicalRoot(), cwd).split(sep).join("/");
387
- if (isLogicalCwd(fromRoot)) return fromRoot;
388
- for (const [slug, root] of workspaceRoots) {
389
- const name = relative(root, cwd);
390
- if (isLogicalCwd(`${slug}/${name}`)) return `${slug}/${name}`;
391
- }
392
- return cwd;
393
- }
394
- function ensureLogicalCwdDir(cwd) {
395
- if (!isUnderLogicalRoot(cwd) || existsSync3(cwd)) return;
396
- mkdirSync2(cwd, { recursive: true });
397
- }
398
- function expandPath(p) {
399
- let expanded = p;
400
- if (expanded === "~") {
401
- expanded = homedir2();
402
- } else if (expanded.startsWith("~/")) {
403
- expanded = resolve3(homedir2(), expanded.slice(2));
404
- }
405
- return isAbsolute(expanded) ? expanded : resolve3(expanded);
406
- }
407
- function normaliseMemberEmails(raw) {
408
- if (!Array.isArray(raw)) return [];
409
- const seen = /* @__PURE__ */ new Set();
410
- for (const v of raw) {
411
- if (typeof v !== "string") continue;
412
- const email = v.trim().toLowerCase();
413
- if (email) seen.add(email);
414
- }
415
- return [...seen];
416
- }
417
- function canSeeChannel(channel, viewer) {
418
- if (channel.visibility === "public") return true;
419
- if (viewer?.role === "admin" && !channel.dmKey) return true;
420
- const email = viewer?.email?.trim().toLowerCase();
421
- return !!email && channel.memberEmails.includes(email);
422
- }
423
- function rowToChannel(row) {
424
- return {
425
- id: row.id,
426
- name: row.name,
427
- categoryId: row.category_id,
428
- cwd: isLogicalCwd(row.cwd) ? resolveLogicalCwd(row.cwd) : expandPath(row.cwd),
429
- externalChannelId: row.external_channel_id,
430
- model: row.model,
431
- effort: row.effort && isEffort(row.effort) ? row.effort : null,
432
- prompt: row.prompt?.trim() || null,
433
- topicCategories: normaliseTopicCategories(row.topic_categories),
434
- // A uuid[] arrives as a real array; anything else (an older row read
435
- // through a cached client, a hand-edited value) reads as "no MCP", which
436
- // is the safe direction for a list that decides which credentials a run
437
- // can reach.
438
- mcpConnections: Array.isArray(row.mcp_connections) ? row.mcp_connections.filter((id) => typeof id === "string") : [],
439
- access: row.access ?? void 0,
440
- visibility: row.visibility === "public" ? "public" : "private",
441
- memberEmails: normaliseMemberEmails(row.member_emails),
442
- // The CHECK constraint (0035, extended by 0070 for 'sandbox') means the
443
- // stored value is always one of these three, so this narrowing is
444
- // unreachable in practice and exists to satisfy the type. Note it cannot
445
- // degrade *safely* the way `mcpConnections` does: an unreadable value here
446
- // would drop a channel back to the unisolated runtime, which is why the
447
- // constraint is the real guarantee and this is only a type-level
448
- // fallback.
449
- runtime: row.runtime === "container" ? "container" : row.runtime === "sandbox" ? "sandbox" : "host",
450
- // Same shape and same defensive read as `mcpConnections`: anything that
451
- // isn't a clean string array reads as "no mounts", which exposes less
452
- // rather than more.
453
- mounts: Array.isArray(row.mounts) ? row.mounts.filter((p) => typeof p === "string").map(expandPath) : [],
454
- permissionMode: isPermissionMode(row.permission_mode) ? row.permission_mode : null,
455
- position: row.position,
456
- automations: row.automations ?? void 0,
457
- agentName: row.agent_name,
458
- dmKey: row.dm_key,
459
- isDefault: row.is_default === true,
460
- profile: row.profile,
461
- archivedAt: row.archived_at,
462
- greetedAt: row.greeted_at,
463
- createdAt: row.created_at,
464
- updatedAt: row.updated_at
465
- };
466
- }
467
- var registry = [];
468
- var byId = /* @__PURE__ */ new Map();
469
- var byExternalId = /* @__PURE__ */ new Map();
470
- var changeListeners = /* @__PURE__ */ new Set();
471
- var lastSnapshot;
472
- function indexRegistry(list) {
473
- registry = list;
474
- byId = new Map(list.map((c) => [c.id, c]));
475
- byExternalId = new Map(
476
- list.filter((c) => !!c.externalChannelId).map((c) => [c.externalChannelId, c])
477
- );
478
- }
479
- async function refreshChannelRegistry() {
480
- const rootsBefore = JSON.stringify([...workspaceRoots]);
481
- await Promise.all([
482
- refreshWorkspaceRoots(),
483
- refreshWorkspacePermissionModes(),
484
- refreshWorkspaceOwnPersona(),
485
- refreshWorkspaceAutoContinueLimits()
486
- ]);
487
- if (JSON.stringify([...workspaceRoots]) !== rootsBefore) lastSnapshot = void 0;
488
- const { data, error } = await getSupabaseClient().from("channels").select("*").order("position", { ascending: true });
489
- if (error) {
490
- console.error("[channels] refreshChannelRegistry failed:", error.message);
491
- return;
492
- }
493
- const rows = data ?? [];
494
- const snapshot = JSON.stringify(
495
- rows,
496
- (key, value) => key === "updated_at" || key === "created_at" ? void 0 : value
497
- );
498
- if (snapshot === lastSnapshot) return;
499
- lastSnapshot = snapshot;
500
- indexRegistry(rows.map(rowToChannel));
501
- for (const cb of changeListeners) {
502
- try {
503
- cb();
504
- } catch (err) {
505
- console.error("[channels] onChannelRegistryChange listener failed:", err);
506
- }
507
- }
508
- }
509
- function getChannelRegistry() {
510
- return registry;
511
- }
512
- function getProfileChannelRegistry() {
513
- const profile = getProfile();
514
- return registry.filter((ch) => ch.profile === profile);
515
- }
516
- function onChannelRegistryChange(cb) {
517
- changeListeners.add(cb);
518
- return () => changeListeners.delete(cb);
519
- }
520
- function findChannelById(id) {
521
- return byId.get(id);
522
- }
523
- function findChannelByExternalId(externalId) {
524
- return byExternalId.get(externalId);
525
- }
526
- function agentDmKey(agentName, userId) {
527
- return `agent:${agentName}:${userId}`;
528
- }
529
- function dmCwd(dmKey, profile = getProfile()) {
530
- return `${profile}/dm-${createHash("sha256").update(dmKey).digest("hex").slice(0, 24)}`;
531
- }
532
- function findChannelByAgentName(agentName, userId) {
533
- const dmKey = agentDmKey(agentName, userId);
534
- return getProfileChannelRegistry().find((c) => c.agentName === agentName && c.dmKey === dmKey);
535
- }
536
- function findChannel(ref) {
537
- if (!ref) return void 0;
538
- return byId.get(ref) ?? byExternalId.get(ref) ?? registry.find((c) => c.name === ref || c.name === ref.replace(/^#/, ""));
539
- }
540
- var DEFAULT_POLL_INTERVAL_MS = 2e4;
541
- var pollTimer;
542
- var realtimeChannel;
543
- function startChannelRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
544
- stopChannelRegistryPolling();
545
- pollTimer = setInterval(() => void refreshChannelRegistry(), intervalMs);
546
- try {
547
- realtimeChannel = getSupabaseClient().channel("channels-registry").on(
548
- "postgres_changes",
549
- { event: "*", schema: "public", table: "channels" },
550
- () => void refreshChannelRegistry()
551
- ).subscribe();
552
- } catch (err) {
553
- console.warn(
554
- "[channels] realtime subscribe failed \u2014 falling back to polling only:",
555
- err.message
556
- );
557
- }
558
- return stopChannelRegistryPolling;
559
- }
560
- function stopChannelRegistryPolling() {
561
- if (pollTimer) clearInterval(pollTimer);
562
- pollTimer = void 0;
563
- if (realtimeChannel) {
564
- void getSupabaseClient().removeChannel(realtimeChannel);
565
- realtimeChannel = void 0;
566
- }
567
- }
568
- function isCwdUsable(cwd) {
569
- try {
570
- return existsSync3(cwd) && statSync2(cwd).isDirectory();
571
- } catch {
572
- return false;
573
- }
574
- }
575
- function auditChannelCwds(list = registry) {
576
- return list.filter((ch) => ch.cwd && !isCwdUsable(ch.cwd));
577
- }
578
- function warnOnBrokenChannelCwds(list = registry) {
579
- const broken = auditChannelCwds(list);
580
- for (const ch of broken) {
581
- console.warn(
582
- `[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.`
583
- );
584
- }
585
- return broken;
586
- }
587
- function resolveChannelCwd(channelId) {
588
- if (!channelId) return void 0;
589
- const entry = findChannel(channelId);
590
- if (!entry?.cwd) return void 0;
591
- if (!isCwdUsable(entry.cwd)) {
592
- console.warn(
593
- `[channels] ${channelId}: cwd "${entry.cwd}" does not exist \u2014 falling back to CLAUDE_CWD`
594
- );
595
- return void 0;
596
- }
597
- return entry.cwd;
598
- }
599
- function isChannelAccessAllowed(channelId, userId) {
600
- if (!channelId) return false;
601
- const access = findChannel(channelId)?.access;
602
- if (!access) return false;
603
- if (typeof access === "string") {
604
- return access === "open" || access === "*" || access === "all";
605
- }
606
- return !!userId && access.includes(userId);
607
- }
608
- function resolveCwd(explicitCwd, channelId, fallback) {
609
- if (explicitCwd) return explicitCwd;
610
- return resolveChannelCwd(channelId) ?? fallback;
611
- }
612
- function resolveChannelModel(channelId) {
613
- if (!channelId) return void 0;
614
- return findChannel(channelId)?.model?.trim() || void 0;
615
- }
616
- function resolveChannelEffort(channelId) {
617
- if (!channelId) return void 0;
618
- return findChannel(channelId)?.effort ?? void 0;
619
- }
620
- function resolveChannelPermissionMode(channelId) {
621
- const channel = channelId ? findChannel(channelId) : void 0;
622
- return channel?.permissionMode ?? workspacePermissionModes.get(channel?.profile ?? getProfile()) ?? "bypass";
623
- }
624
- function resolveChannelPrompt(channelId) {
625
- if (!channelId) return void 0;
626
- return findChannel(channelId)?.prompt?.trim() || void 0;
627
- }
628
- function resolveModel(explicitModel, channelId, fallback) {
629
- if (explicitModel?.trim()) return explicitModel.trim();
630
- return resolveChannelModel(channelId) ?? fallback;
631
- }
632
- function resolveEffort(explicitEffort, channelId, fallback) {
633
- if (explicitEffort) return explicitEffort;
634
- return resolveChannelEffort(channelId) ?? fallback;
635
- }
636
- function normaliseTopicCategories(value) {
637
- if (!Array.isArray(value)) return [];
638
- const out = [];
639
- for (const v of value) {
640
- const t = typeof v === "string" ? v.trim() : "";
641
- if (t && !out.includes(t)) out.push(t);
642
- }
643
- return out;
644
- }
645
- function toRow(input) {
646
- const row = {};
647
- if (input.name !== void 0) row["name"] = input.name;
648
- if (input.cwd !== void 0) row["cwd"] = isLogicalCwd(input.cwd) ? input.cwd : toLogicalCwd(expandPath(input.cwd));
649
- if (input.categoryId !== void 0) row["category_id"] = input.categoryId;
650
- if (input.externalChannelId !== void 0) row["external_channel_id"] = input.externalChannelId;
651
- if (input.model !== void 0) row["model"] = input.model;
652
- if (input.effort !== void 0) row["effort"] = input.effort;
653
- if (input.prompt !== void 0) row["prompt"] = input.prompt?.trim() || null;
654
- if (input.topicCategories !== void 0) {
655
- const list = normaliseTopicCategories(input.topicCategories);
656
- row["topic_categories"] = list.length ? list : null;
657
- }
658
- if (input.access !== void 0) row["access"] = input.access;
659
- if (input.visibility !== void 0) row["visibility"] = input.visibility;
660
- if (input.memberEmails !== void 0) {
661
- row["member_emails"] = normaliseMemberEmails(input.memberEmails);
662
- }
663
- if (input.runtime !== void 0) row["runtime"] = input.runtime;
664
- if (input.mounts !== void 0) {
665
- row["mounts"] = input.mounts.map((p) => p.trim()).filter(Boolean).map(expandPath);
666
- }
667
- if (input.permissionMode !== void 0) row["permission_mode"] = input.permissionMode;
668
- if (input.position !== void 0) row["position"] = input.position;
669
- if (input.automations !== void 0) row["automations"] = input.automations;
670
- if (input.agentName !== void 0) row["agent_name"] = input.agentName;
671
- if (input.dmKey !== void 0) row["dm_key"] = input.dmKey;
672
- if (input.isDefault !== void 0) row["is_default"] = input.isDefault;
673
- if (input.mcpConnections !== void 0) row["mcp_connections"] = input.mcpConnections;
674
- if (input.archivedAt !== void 0) row["archived_at"] = input.archivedAt;
675
- return row;
676
- }
677
- var ChannelCwdError = class extends Error {
678
- constructor(message) {
679
- super(message);
680
- this.name = "ChannelCwdError";
681
- }
682
- };
683
- function realpathOrSelf(p) {
684
- try {
685
- return realpathSync(p);
686
- } catch {
687
- return p;
688
- }
689
- }
690
- async function assertCwdInWorkspace(profile, cwd) {
691
- if (isLogicalCwd(cwd)) {
692
- if (cwd.split("/")[0] !== profile) {
693
- throw new ChannelCwdError(`Folder "${cwd}" belongs to another workspace.`);
694
- }
695
- return cwd;
696
- }
697
- const logical = relative(logicalRoot(), cwd).split(sep).join("/");
698
- if (isLogicalCwd(logical)) return assertCwdInWorkspace(profile, logical);
699
- const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
700
- if (error) throw new Error(error.message);
701
- const workspaces = data ?? [];
702
- const ownRoot = workspaces.find((w) => w.slug === profile)?.root_path;
703
- const home2 = ownRoot?.match(/^(\/Users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/)?.[1];
704
- const absolute = home2 && (cwd === "~" || cwd.startsWith("~/")) ? resolve3(home2, cwd.slice(2)) : expandPath(cwd);
705
- const path = realpathOrSelf(absolute);
706
- const roots = workspaces.filter((w) => w.root_path).map((w) => ({ slug: w.slug, root: realpathOrSelf(expandPath(w.root_path)) }));
707
- const owner = roots.filter(({ root }) => path === root || path.startsWith(root + sep)).sort((a, b) => b.root.length - a.root.length)[0];
708
- if (owner ? owner.slug !== profile : roots.some((r) => r.slug === profile)) {
709
- throw new ChannelCwdError(
710
- owner ? `Folder "${cwd}" belongs to the "${owner.slug}" workspace.` : `Folder "${cwd}" is outside this workspace's folder.`
711
- );
712
- }
713
- return absolute;
714
- }
715
- async function createChannel(input) {
716
- input = { ...input, cwd: await assertCwdInWorkspace(getProfile(), input.cwd) };
717
- const { data, error } = await getSupabaseClient().from("channels").insert({ ...toRow(input), profile: getProfile() }).select().single();
718
- if (error) throw new Error(error.message);
719
- const channel = rowToChannel(data);
720
- if (channel.cwd && !isLogicalCwd(input.cwd) && !isCwdUsable(channel.cwd)) {
721
- try {
722
- mkdirSync2(channel.cwd, { recursive: true });
723
- } catch (err) {
724
- console.error(`[channels] failed to create cwd for "${channel.name}":`, err.message);
725
- }
726
- }
727
- await refreshChannelRegistry();
728
- return channel;
729
- }
730
- var DefaultChannelError = class extends Error {
731
- constructor() {
732
- super("The default channel must stay public and cannot be renamed or archived.");
733
- this.name = "DefaultChannelError";
734
- }
735
- };
736
- async function updateChannelById(id, patch) {
737
- const existing = findChannelById(id);
738
- if (existing?.isDefault && (patch.visibility === "private" || patch.archivedAt || patch.isDefault === false || patch.name !== void 0 && patch.name.trim() !== existing.name)) {
739
- throw new DefaultChannelError();
740
- }
741
- if (patch.cwd !== void 0 && existing && patch.cwd === existing.cwd) {
742
- const { cwd: _unchanged, ...rest } = patch;
743
- patch = rest;
744
- }
745
- if (patch.cwd !== void 0) {
746
- patch = { ...patch, cwd: await assertCwdInWorkspace(existing?.profile ?? getProfile(), patch.cwd) };
747
- }
748
- const { data, error } = await getSupabaseClient().from("channels").update({ ...toRow(patch), updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
749
- if (error) throw new Error(error.message);
750
- await refreshChannelRegistry();
751
- return rowToChannel(data);
752
- }
753
- async function markChannelGreeted(id) {
754
- const { data, error } = await getSupabaseClient().from("channels").update({ greeted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).is("greeted_at", null).select("id");
755
- if (error) throw new Error(error.message);
756
- await refreshChannelRegistry();
757
- return (data ?? []).length > 0;
758
- }
759
- async function updateChannelsMcpConnections(updates) {
760
- if (!updates.length) return;
761
- const supabase = getSupabaseClient();
762
- for (const update of updates) {
763
- const { error } = await supabase.from("channels").update({ mcp_connections: update.mcpConnections, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", update.id);
764
- if (error) throw new Error(`Failed to update channel ${update.id}: ${error.message}`);
765
- }
766
- await refreshChannelRegistry();
767
- }
768
- function defaultFallbackCwd() {
769
- return process.env["CLAUDE_CWD"] ?? process.cwd();
770
- }
771
- async function ensureChannelProvisioned(externalChannelId, opts = {}) {
772
- const existing = findChannelByExternalId(externalChannelId);
773
- if (existing) {
774
- if (existing.profile !== getProfile()) return null;
775
- if (existing.name === externalChannelId && opts.name && opts.name !== externalChannelId) {
776
- try {
777
- return await updateChannelById(existing.id, { name: opts.name });
778
- } catch (err) {
779
- console.error(`[channels] failed to heal name for ${externalChannelId}:`, err);
780
- return existing;
781
- }
782
- }
783
- return existing;
784
- }
785
- try {
786
- const created = await createChannel({
787
- name: opts.name ?? externalChannelId,
788
- cwd: opts.fallbackCwd ?? defaultFallbackCwd(),
789
- externalChannelId
790
- });
791
- console.log(`[channels] auto-provisioned a new channel for Slack channel ${externalChannelId}`);
792
- return created;
793
- } catch (err) {
794
- await refreshChannelRegistry();
795
- const raced = findChannelByExternalId(externalChannelId);
796
- if (raced) return raced.profile === getProfile() ? raced : null;
797
- throw err;
798
- }
799
- }
800
- async function ensureAgentDmChannel(agentName, viewer, opts) {
801
- const existing = findChannelByAgentName(agentName, viewer.userId);
802
- if (existing) {
803
- return existing.name === opts.name ? existing : updateChannelById(existing.id, { name: opts.name });
804
- }
805
- const dmKey = agentDmKey(agentName, viewer.userId);
806
- try {
807
- return await createChannel({
808
- name: opts.name,
809
- cwd: dmCwd(dmKey),
810
- visibility: "private",
811
- memberEmails: [viewer.email],
812
- agentName,
813
- dmKey
814
- });
815
- } catch (err) {
816
- await refreshChannelRegistry();
817
- const raced = findChannelByAgentName(agentName, viewer.userId);
818
- if (raced) return raced;
819
- throw err;
820
- }
821
- }
822
- async function ensureGeneralChannel() {
823
- const find = () => getProfileChannelRegistry().find((c) => c.isDefault);
824
- const existing = find();
825
- if (existing) return existing;
826
- try {
827
- return await createChannel({
828
- name: "general",
829
- cwd: `${getProfile()}/general`,
830
- visibility: "public",
831
- isDefault: true
832
- });
833
- } catch (err) {
834
- await refreshChannelRegistry();
835
- const raced = find();
836
- if (raced) return raced;
837
- throw err;
838
- }
839
- }
840
- async function ensureMemberDmChannel(a, b) {
841
- const dmKey = [a.userId, b.userId].sort().join(":");
842
- const find = () => [...getProfileChannelRegistry()].find((c) => c.dmKey === dmKey && c.profile === getProfile());
843
- const existing = find();
844
- if (existing) return existing;
845
- try {
846
- return await createChannel({
847
- name: `${a.handle}, ${b.handle}`,
848
- // Hash the whole key: a prefix of the sorted ids is just the first user's
849
- // id, which put every DM that user sorts first in into one shared folder.
850
- cwd: dmCwd(dmKey),
851
- visibility: "private",
852
- memberEmails: [a.email, b.email],
853
- dmKey
854
- });
855
- } catch (err) {
856
- await refreshChannelRegistry();
857
- const raced = find();
858
- if (raced) return raced;
859
- throw err;
860
- }
861
- }
862
-
863
- // ../api/src/store/authors.ts
864
- var AGENT_AUTHOR = "agent";
865
- var SYNCED_BOT_AUTHOR = "Bot";
866
- var LEGACY_BOT_AUTHOR = "Custie";
867
- var SUPPORT_BOT_AUTHOR = "Flyspace Support";
868
- var NON_HUMAN_AUTHORS = new Set(
869
- [AGENT_AUTHOR, SYNCED_BOT_AUTHOR, LEGACY_BOT_AUTHOR, SUPPORT_BOT_AUTHOR].map((a) => a.toLowerCase())
870
- );
871
- function isHumanAuthor(author) {
872
- return !NON_HUMAN_AUTHORS.has(author.toLowerCase());
873
- }
874
-
875
326
  // ../api/src/dashboard/attachment-uploader.ts
876
327
  import { randomUUID } from "crypto";
877
328
  import { readFile, stat } from "fs/promises";
@@ -996,117 +447,6 @@ async function uploadLocalImages(rawBody) {
996
447
  });
997
448
  }
998
449
 
999
- // src/store/dashboard-sync.ts
1000
- var TITLE_MAX_LENGTH = 80;
1001
- function deriveThreadTitle(text) {
1002
- const firstLine = text.split("\n").find((line) => line.trim().length > 0);
1003
- if (!firstLine) return null;
1004
- 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();
1005
- if (!cleaned) return null;
1006
- return cleaned.length > TITLE_MAX_LENGTH ? `${cleaned.slice(0, TITLE_MAX_LENGTH).trim()}\u2026` : cleaned;
1007
- }
1008
- async function syncPostToDashboard(opts) {
1009
- const { channelId, ts, threadTs, text } = opts;
1010
- if (!databaseReachable()) {
1011
- console.warn("[dashboard-sync] Supabase not configured \u2014 skipping dashboard sync");
1012
- return;
1013
- }
1014
- try {
1015
- const supabase = getSupabaseClient();
1016
- const dashboardChannelId = await resolveDashboardChannelId(supabase, channelId);
1017
- const threadId = threadTs ? await ensureThreadId(supabase, channelId, dashboardChannelId, threadTs) : await createOwnThread(supabase, channelId, dashboardChannelId, ts, text);
1018
- const { error } = await supabase.from("thread_replies").upsert(
1019
- {
1020
- thread_id: threadId,
1021
- // This mirror only ever runs for the bot's own posts (automation
1022
- // output, `flyspace slack post`), so the author is the agent itself —
1023
- // labelling it anything else makes the chat agent count it as a
1024
- // second human and stop replying without an explicit mention.
1025
- author: AGENT_AUTHOR,
1026
- body: await uploadLocalImages(text),
1027
- external_thread_replies_id: `${channelId}:${ts}`
1028
- },
1029
- { onConflict: "external_thread_replies_id" }
1030
- );
1031
- if (error) {
1032
- console.warn(`[dashboard-sync] failed to write reply: ${error.message}`);
1033
- }
1034
- } catch (err) {
1035
- console.warn(
1036
- `[dashboard-sync] sync failed: ${err instanceof Error ? err.message : String(err)}`
1037
- );
1038
- }
1039
- }
1040
- async function resolveDashboardChannelId(supabase, slackChannelId) {
1041
- const { data, error } = await supabase.from("channels").select("id").eq("external_channel_id", slackChannelId).maybeSingle();
1042
- if (error || !data) return slackChannelId;
1043
- return data["id"];
1044
- }
1045
- async function createOwnThread(supabase, externalChannelId, dashboardChannelId, ts, text) {
1046
- const { data, error } = await supabase.from("threads").upsert(
1047
- {
1048
- channel_id: dashboardChannelId,
1049
- title: deriveThreadTitle(text),
1050
- author: AGENT_AUTHOR,
1051
- external_thread_id: `${externalChannelId}:${ts}`
1052
- },
1053
- { onConflict: "external_thread_id" }
1054
- ).select("id").single();
1055
- if (error || !data) throw new Error(error?.message ?? "failed to create thread");
1056
- return data["id"];
1057
- }
1058
- async function ensureThreadId(supabase, externalChannelId, dashboardChannelId, parentTs) {
1059
- const key = `${externalChannelId}:${parentTs}`;
1060
- const { data: existing, error: selectError } = await supabase.from("threads").select("id").eq("external_thread_id", key).maybeSingle();
1061
- if (selectError) throw new Error(selectError.message);
1062
- if (existing) return existing["id"];
1063
- const { data: created, error: createError } = await supabase.from("threads").upsert(
1064
- // The unsynced parent could be anyone's message (often another bot's),
1065
- // so keep the generic non-human placeholder rather than claiming it.
1066
- {
1067
- channel_id: dashboardChannelId,
1068
- title: null,
1069
- author: SYNCED_BOT_AUTHOR,
1070
- external_thread_id: key
1071
- },
1072
- { onConflict: "external_thread_id" }
1073
- ).select("id").single();
1074
- if (createError || !created) {
1075
- throw new Error(createError?.message ?? "failed to create placeholder thread");
1076
- }
1077
- return created["id"];
1078
- }
1079
-
1080
- // src/store/dashboard-post.ts
1081
- async function postToDashboardChannel(opts) {
1082
- const { channelId, text, threadId, title } = opts;
1083
- const supabase = getSupabaseClient();
1084
- if (!threadId && !channelId) {
1085
- throw new Error("postToDashboardChannel: channelId is required to start a new thread");
1086
- }
1087
- const parentId = threadId ?? await createThread(supabase, channelId, text, title);
1088
- const body = await uploadLocalImages(text);
1089
- const { data, error } = await supabase.from("thread_replies").insert({ thread_id: parentId, author: AGENT_AUTHOR, body }).select("id").single();
1090
- if (error || !data) {
1091
- throw new Error(`failed to write dashboard reply: ${error?.message ?? "no row returned"}`);
1092
- }
1093
- return { threadId: parentId, replyId: data["id"] };
1094
- }
1095
- async function createThread(supabase, channelId, text, title) {
1096
- const { data, error } = await supabase.from("threads").insert({
1097
- channel_id: channelId,
1098
- // An untitled thread is effectively invisible in the sidebar, so give a
1099
- // daily report the same first-line-derived title a mirrored post gets,
1100
- // unless the caller named the thread itself.
1101
- title: title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(text),
1102
- author: AGENT_AUTHOR
1103
- }).select("id").single();
1104
- if (error || !data) {
1105
- throw new Error(`failed to create dashboard thread: ${error?.message ?? "no row returned"}`);
1106
- }
1107
- return data["id"];
1108
- }
1109
-
1110
450
  // src/store/session-store.ts
1111
451
  import Database from "better-sqlite3";
1112
452
  var SessionStore = class {
@@ -1270,7 +610,7 @@ var SessionStore = class {
1270
610
 
1271
611
  // src/auth/device-auth.ts
1272
612
  import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "crypto";
1273
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync, rmSync as rmSync2, writeFileSync } from "fs";
613
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, writeFileSync } from "fs";
1274
614
  import { dirname, join as join2 } from "path";
1275
615
  var DEFAULT_API_URL = "https://app.flyspace.ai";
1276
616
  var EXPIRY_SKEW_MS = 6e4;
@@ -1292,9 +632,9 @@ function credentialsPath() {
1292
632
  }
1293
633
  function ensureDeviceKey(path = deviceKeyPath()) {
1294
634
  let created = false;
1295
- if (!existsSync4(path)) {
635
+ if (!existsSync3(path)) {
1296
636
  const { privateKey: privateKey2 } = generateKeyPairSync("ed25519");
1297
- mkdirSync3(dirname(path), { recursive: true });
637
+ mkdirSync2(dirname(path), { recursive: true });
1298
638
  writeFileSync(path, privateKey2.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
1299
639
  created = true;
1300
640
  }
@@ -1305,7 +645,7 @@ function ensureDeviceKey(path = deviceKeyPath()) {
1305
645
  return { privateKey, publicKeyBase64, created };
1306
646
  }
1307
647
  function loadCredentials(path = credentialsPath()) {
1308
- if (!existsSync4(path)) return null;
648
+ if (!existsSync3(path)) return null;
1309
649
  try {
1310
650
  return JSON.parse(readFileSync(path, "utf8"));
1311
651
  } catch {
@@ -1313,7 +653,7 @@ function loadCredentials(path = credentialsPath()) {
1313
653
  }
1314
654
  }
1315
655
  function saveCredentials(creds, path = credentialsPath()) {
1316
- mkdirSync3(dirname(path), { recursive: true });
656
+ mkdirSync2(dirname(path), { recursive: true });
1317
657
  writeFileSync(path, `${JSON.stringify(creds, null, 2)}
1318
658
  `, { mode: 384 });
1319
659
  }
@@ -1449,7 +789,7 @@ async function getAccessToken() {
1449
789
  // src/dashboard/host-lock.ts
1450
790
  import { execFileSync } from "child_process";
1451
791
  import { randomBytes } from "crypto";
1452
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
792
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
1453
793
  import { join as join3 } from "path";
1454
794
  function hostLockPath() {
1455
795
  return join3(paths.BASE_DATA_DIR, "host.lock");
@@ -1475,7 +815,7 @@ function readLockPid(path) {
1475
815
  }
1476
816
  function acquireHostLock() {
1477
817
  const path = hostLockPath();
1478
- mkdirSync4(paths.BASE_DATA_DIR, { recursive: true });
818
+ mkdirSync3(paths.BASE_DATA_DIR, { recursive: true });
1479
819
  const body = JSON.stringify({
1480
820
  pid: process.pid,
1481
821
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -1548,14 +888,14 @@ function handleHostDbResult(id, res) {
1548
888
  }
1549
889
  function whenConnected() {
1550
890
  if (sender) return Promise.resolve(sender);
1551
- return new Promise((resolve4, reject) => {
891
+ return new Promise((resolve3, reject) => {
1552
892
  const timer = setTimeout(() => {
1553
893
  onSender = onSender.filter((w) => w !== wake);
1554
894
  reject(new Error("Host is not connected to the Data API"));
1555
895
  }, REQUEST_TIMEOUT_MS);
1556
896
  const wake = () => {
1557
897
  clearTimeout(timer);
1558
- resolve4(sender);
898
+ resolve3(sender);
1559
899
  };
1560
900
  onSender.push(wake);
1561
901
  });
@@ -1563,12 +903,12 @@ function whenConnected() {
1563
903
  async function requestHostDb(req) {
1564
904
  const send = await whenConnected();
1565
905
  const id = randomUUID2();
1566
- return new Promise((resolve4, reject) => {
906
+ return new Promise((resolve3, reject) => {
1567
907
  const timer = setTimeout(() => {
1568
908
  pending.delete(id);
1569
909
  reject(new Error("Data API did not answer in time"));
1570
910
  }, REQUEST_TIMEOUT_MS);
1571
- pending.set(id, { resolve: resolve4, reject, timer });
911
+ pending.set(id, { resolve: resolve3, reject, timer });
1572
912
  send({ type: "db", id, req });
1573
913
  });
1574
914
  }
@@ -1580,14 +920,14 @@ function handleAttachmentUrlResult(id, url) {
1580
920
  async function requestAttachmentUrl(key) {
1581
921
  const send = await whenConnected();
1582
922
  const id = randomUUID2();
1583
- return new Promise((resolve4, reject) => {
923
+ return new Promise((resolve3, reject) => {
1584
924
  const timer = setTimeout(() => {
1585
925
  pendingUrls.delete(id);
1586
926
  reject(new Error("Data API did not answer in time"));
1587
927
  }, REQUEST_TIMEOUT_MS);
1588
928
  pendingUrls.set(id, (url) => {
1589
929
  clearTimeout(timer);
1590
- resolve4(url);
930
+ resolve3(url);
1591
931
  });
1592
932
  send({ type: "attachment-url", id, key });
1593
933
  });
@@ -1600,39 +940,40 @@ function handlePluginSvgResult(id, url) {
1600
940
  async function requestPluginSvg(workspace, svg) {
1601
941
  const send = await whenConnected();
1602
942
  const id = randomUUID2();
1603
- return new Promise((resolve4, reject) => {
943
+ return new Promise((resolve3, reject) => {
1604
944
  const timer = setTimeout(() => {
1605
945
  pendingSvgs.delete(id);
1606
946
  reject(new Error("Data API did not answer in time"));
1607
947
  }, REQUEST_TIMEOUT_MS);
1608
948
  pendingSvgs.set(id, (url) => {
1609
949
  clearTimeout(timer);
1610
- resolve4(url);
950
+ resolve3(url);
1611
951
  });
1612
952
  send({ type: "plugin-svg", id, workspace, svg });
1613
953
  });
1614
954
  }
1615
- var pendingShares = /* @__PURE__ */ new Map();
1616
- function handleDocShareResult(id, res) {
1617
- pendingShares.get(id)?.(res);
1618
- pendingShares.delete(id);
955
+ var ACTION_TIMEOUT_MS = 15e4;
956
+ var pendingActions = /* @__PURE__ */ new Map();
957
+ function handleActionResult(id, res) {
958
+ pendingActions.get(id)?.(res);
959
+ pendingActions.delete(id);
1619
960
  }
1620
- async function requestDocShare(channelId, path, slug) {
961
+ async function requestAction(name, input, requester) {
1621
962
  const send = await whenConnected();
1622
963
  const id = randomUUID2();
1623
- return new Promise((resolve4) => {
964
+ return new Promise((resolve3) => {
1624
965
  const timer = setTimeout(() => {
1625
- pendingShares.delete(id);
1626
- resolve4({ error: "Data API did not answer in time" });
1627
- }, 15e4);
1628
- pendingShares.set(id, (res) => {
966
+ pendingActions.delete(id);
967
+ resolve3({ error: "Data API did not answer in time" });
968
+ }, ACTION_TIMEOUT_MS);
969
+ pendingActions.set(id, (res) => {
1629
970
  clearTimeout(timer);
1630
- resolve4(res);
971
+ resolve3(res);
1631
972
  });
1632
- send({ type: "doc-share", id, channelId, path, ...slug ? { slug } : {} });
973
+ send({ type: "action", id, name, input, ...requester ? { requester } : {} });
1633
974
  });
1634
975
  }
1635
- var LOCAL_DOC_SHARE_PATH = "/internal/doc-share";
976
+ var LOCAL_ACTION_PATH = "/internal/action";
1636
977
  var pendingRespond = /* @__PURE__ */ new Map();
1637
978
  function handleShouldRespondResult(id, respond) {
1638
979
  pendingRespond.get(id)?.(respond);
@@ -1642,14 +983,14 @@ async function requestShouldRespond(transcript) {
1642
983
  const send = await whenConnected().catch(() => null);
1643
984
  if (!send) return false;
1644
985
  const id = randomUUID2();
1645
- return new Promise((resolve4) => {
986
+ return new Promise((resolve3) => {
1646
987
  const timer = setTimeout(() => {
1647
988
  pendingRespond.delete(id);
1648
- resolve4(false);
989
+ resolve3(false);
1649
990
  }, REQUEST_TIMEOUT_MS);
1650
991
  pendingRespond.set(id, (respond) => {
1651
992
  clearTimeout(timer);
1652
- resolve4(respond);
993
+ resolve3(respond);
1653
994
  });
1654
995
  send({ type: "should-respond", id, transcript });
1655
996
  });
@@ -1730,6 +1071,7 @@ function useHostDbWithoutCredentials() {
1730
1071
  export {
1731
1072
  __require,
1732
1073
  __commonJS,
1074
+ __export,
1733
1075
  __toESM,
1734
1076
  setSupabaseClient,
1735
1077
  setSupabaseClientFactory,
@@ -1751,55 +1093,11 @@ export {
1751
1093
  slackConfigured,
1752
1094
  requireSlackBotToken,
1753
1095
  loadConfig,
1754
- isPermissionMode,
1755
- isLogicalCwd,
1756
- DEFAULT_AUTO_CONTINUE_LIMIT,
1757
- resolveAutoContinueLimit,
1758
- resolveOwnPersona,
1759
- resolveLogicalCwd,
1760
- isUnderLogicalRoot,
1761
- ensureLogicalCwdDir,
1762
- expandPath,
1763
- canSeeChannel,
1764
- refreshChannelRegistry,
1765
- getChannelRegistry,
1766
- getProfileChannelRegistry,
1767
- onChannelRegistryChange,
1768
- findChannelById,
1769
- dmCwd,
1770
- findChannel,
1771
- startChannelRegistryPolling,
1772
- isCwdUsable,
1773
- auditChannelCwds,
1774
- warnOnBrokenChannelCwds,
1775
- isChannelAccessAllowed,
1776
- resolveCwd,
1777
- resolveChannelPermissionMode,
1778
- resolveChannelPrompt,
1779
- resolveModel,
1780
- resolveEffort,
1781
- ChannelCwdError,
1782
- createChannel,
1783
- DefaultChannelError,
1784
- updateChannelById,
1785
- markChannelGreeted,
1786
- updateChannelsMcpConnections,
1787
- ensureChannelProvisioned,
1788
- ensureAgentDmChannel,
1789
- ensureGeneralChannel,
1790
- ensureMemberDmChannel,
1791
- AGENT_AUTHOR,
1792
- SYNCED_BOT_AUTHOR,
1793
- SUPPORT_BOT_AUTHOR,
1794
- isHumanAuthor,
1795
1096
  getR2Client,
1796
1097
  getR2Bucket,
1797
1098
  sumR2PrefixBytes,
1798
1099
  SCRATCH_PREFIX,
1799
1100
  uploadLocalImages,
1800
- syncPostToDashboard,
1801
- resolveDashboardChannelId,
1802
- postToDashboardChannel,
1803
1101
  DEFAULT_API_URL,
1804
1102
  AuthApiError,
1805
1103
  apiUrl,
@@ -1826,9 +1124,9 @@ export {
1826
1124
  requestAttachmentUrl,
1827
1125
  handlePluginSvgResult,
1828
1126
  requestPluginSvg,
1829
- handleDocShareResult,
1830
- requestDocShare,
1831
- LOCAL_DOC_SHARE_PATH,
1127
+ handleActionResult,
1128
+ requestAction,
1129
+ LOCAL_ACTION_PATH,
1832
1130
  handleShouldRespondResult,
1833
1131
  requestShouldRespond,
1834
1132
  LOCAL_DB_PATH,