flyspace-cli 0.1.59 → 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.
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@ import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
3
  const require = __flyspaceCreateRequire(import.meta.url);
4
4
  import {
5
5
  startServer
6
- } from "./chunk-7W5FEG63.js";
7
- import "./chunk-XACRG7BO.js";
6
+ } from "./chunk-METRJ6PG.js";
7
+ import "./chunk-UZMHXV4D.js";
8
8
  export {
9
9
  startServer
10
10
  };
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
+ const require = __flyspaceCreateRequire(import.meta.url);
4
+ import {
5
+ ACTIONS,
6
+ actionInputJsonSchema,
7
+ callAction,
8
+ checkPermissionAction,
9
+ createThreadAction,
10
+ listChannelsAction,
11
+ moveThreadAction,
12
+ postReplyAction,
13
+ readThreadAction,
14
+ requestPermissionAction,
15
+ searchThreadsAction,
16
+ shareDoc,
17
+ shareDocAction
18
+ } from "./chunk-PLLJ7M62.js";
19
+ import {
20
+ SessionStore,
21
+ paths,
22
+ uploadLocalImages
23
+ } from "./chunk-UZMHXV4D.js";
24
+
25
+ // src/mcp/servers/threads.ts
26
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
27
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
28
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
29
+ var DEFAULT_SEARCH_LIMIT = 10;
30
+ var MAX_SEARCH_LIMIT = 30;
31
+ var SNIPPET_MAX = 300;
32
+ function truncate(text, max) {
33
+ const flat = text.replaceAll(/\s+/g, " ").trim();
34
+ return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
35
+ }
36
+ function formatHits(hits, query) {
37
+ if (!hits.length) return `No threads matching "${query}".`;
38
+ return [
39
+ `${hits.length} thread${hits.length === 1 ? "" : "s"} matching "${query}":`,
40
+ "",
41
+ ...hits.map((hit) => {
42
+ const when = hit.createdAt.slice(0, 10);
43
+ const title = hit.title?.trim() || "(untitled)";
44
+ const snippet = truncate(hit.snippet, SNIPPET_MAX);
45
+ const body = snippet && snippet !== truncate(title, SNIPPET_MAX) ? `
46
+ ${snippet}` : "";
47
+ return `- **${title}** \u2014 ${hit.author}, ${when}${body}
48
+ id: \`${hit.id}\``;
49
+ })
50
+ ].join("\n");
51
+ }
52
+ function clampLimit(raw) {
53
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_SEARCH_LIMIT;
54
+ return Math.min(Math.max(Math.trunc(raw), 1), MAX_SEARCH_LIMIT);
55
+ }
56
+ function rowsToHits(rows, channelId) {
57
+ return rows.filter((row) => !channelId || row.channel_id === channelId).map((row) => ({
58
+ id: row.id,
59
+ channelId: row.channel_id,
60
+ title: row.title,
61
+ snippet: row.snippet ?? "",
62
+ author: row.author ?? "unknown",
63
+ createdAt: row.created_at
64
+ }));
65
+ }
66
+ function formatThread(thread, replies) {
67
+ const lines = [
68
+ `# ${thread.title?.trim() || "(untitled)"}`,
69
+ "",
70
+ `**${thread.author ?? "unknown"}** \xB7 ${thread.created_at.slice(0, 16).replace("T", " ")}`,
71
+ "",
72
+ thread.body?.trim() || "(no body)"
73
+ ];
74
+ if (replies.length) {
75
+ lines.push("", `## ${replies.length} repl${replies.length === 1 ? "y" : "ies"}`, "");
76
+ for (const reply of replies) {
77
+ lines.push(
78
+ `**${reply.author ?? "unknown"}** \xB7 ${reply.created_at.slice(0, 16).replace("T", " ")}`,
79
+ "",
80
+ reply.body?.trim() || "(empty)",
81
+ ""
82
+ );
83
+ }
84
+ }
85
+ return lines.join("\n");
86
+ }
87
+ function requester() {
88
+ const env = process.env;
89
+ return {
90
+ ...env["FLYSPACE_THREADS_WORKSPACE"] ? { workspace: env["FLYSPACE_THREADS_WORKSPACE"] } : {},
91
+ ...env["FLYSPACE_REQUESTER_HANDLE"] ? { handle: env["FLYSPACE_REQUESTER_HANDLE"] } : {}
92
+ };
93
+ }
94
+ async function readThread(ref) {
95
+ const thread = await callAction(readThreadAction, { thread_id: ref }, requester());
96
+ if (!thread) return `No thread with id ${ref}.`;
97
+ const [opening, ...rest] = thread.replies;
98
+ return `Link: ${thread.link}
99
+
100
+ ${formatThread({ ...thread, body: opening?.body ?? null }, rest)}`;
101
+ }
102
+ var TOOLS = ACTIONS.filter(
103
+ (a) => a !== checkPermissionAction && a !== requestPermissionAction
104
+ ).map(toTool);
105
+ var PERMISSION_TOOL = toTool(requestPermissionAction);
106
+ function toTool(action) {
107
+ return {
108
+ name: action.name,
109
+ description: action.description,
110
+ inputSchema: actionInputJsonSchema(action)
111
+ };
112
+ }
113
+ var PERMISSION_POLL_MS = 2e3;
114
+ var DEFAULT_PERMISSION_TIMEOUT_MS = 5 * 60 * 1e3;
115
+ function permissionTarget() {
116
+ const threadId = process.env["FLYSPACE_PERMISSION_THREAD_ID"];
117
+ const channelId = process.env["FLYSPACE_PERMISSION_CHANNEL_ID"];
118
+ return threadId && channelId ? { threadId, channelId } : null;
119
+ }
120
+ async function requestPermission(target, toolName, input, timeoutMs = Number(process.env["FLYSPACE_PERMISSION_TIMEOUT_MS"]) || DEFAULT_PERMISSION_TIMEOUT_MS) {
121
+ const who = { ...requester(), ...target, permissionTimeoutMs: timeoutMs };
122
+ const { requestId } = await callAction(
123
+ requestPermissionAction,
124
+ { tool_name: toolName, input },
125
+ who
126
+ );
127
+ let status = "pending";
128
+ const giveUpAt = Date.now() + timeoutMs + 3e4;
129
+ while (status === "pending" && Date.now() < giveUpAt) {
130
+ await new Promise((r) => setTimeout(r, PERMISSION_POLL_MS));
131
+ status = (await callAction(checkPermissionAction, { request_id: requestId }, who).catch(() => null))?.status ?? status;
132
+ }
133
+ if (status === "allow") return { behavior: "allow", updatedInput: input };
134
+ return {
135
+ behavior: "deny",
136
+ message: status === "deny" ? `An admin denied ${toolName}. Do not retry it; find another way or explain what you needed.` : `Nobody answered the permission prompt for ${toolName} in time, so it was denied.`
137
+ };
138
+ }
139
+ async function moveThread(threadId, toChannelId) {
140
+ const store = new SessionStore(paths.DB_FILE);
141
+ try {
142
+ const moved = await callAction(moveThreadAction, {
143
+ thread_id: threadId,
144
+ to_channel_id: toChannelId
145
+ });
146
+ if (moved === "unchanged") return `Thread ${threadId} is already in ${toChannelId}.`;
147
+ const counts = moved.from ? store.moveThread(`chat:${moved.from.id}`, `chat:${moved.to.id}`, threadId) : { sessions: 0 };
148
+ return `Moved thread ${threadId} to ${moved.to.name} (${moved.to.id}); carried over ${counts.sessions} agent session(s).` + (moved.from && moved.from.cwd !== moved.to.cwd ? ` The channels have different working directories: files the thread created stay in ${moved.from.cwd}.` : "");
149
+ } finally {
150
+ store.close();
151
+ }
152
+ }
153
+ var str = (v) => typeof v === "string" ? v : void 0;
154
+ async function callTool(name, args, permission) {
155
+ switch (name) {
156
+ case searchThreadsAction.name: {
157
+ const query = str(args["query"])?.trim() ?? "";
158
+ const rows = await callAction(searchThreadsAction, {
159
+ query,
160
+ limit: clampLimit(args["limit"]),
161
+ ...str(args["channel_id"]) ? { channel_id: str(args["channel_id"]) } : {}
162
+ });
163
+ return formatHits(rowsToHits(rows), query);
164
+ }
165
+ case readThreadAction.name:
166
+ return readThread(str(args["thread_id"])?.trim() ?? "");
167
+ case listChannelsAction.name: {
168
+ const channels = await callAction(listChannelsAction, {});
169
+ return channels.length ? channels.map((c) => `- **${c.name}** (${c.profile}) id: \`${c.id}\``).join("\n") : "No channels found.";
170
+ }
171
+ case createThreadAction.name: {
172
+ const text = await uploadLocalImages(str(args["text"]) ?? "");
173
+ const title = str(args["title"]);
174
+ const { threadId } = await callAction(createThreadAction, {
175
+ channel_id: str(args["channel_id"]) ?? "",
176
+ text,
177
+ ...title ? { title } : {}
178
+ });
179
+ return `Created thread ${threadId}.`;
180
+ }
181
+ case postReplyAction.name: {
182
+ const text = await uploadLocalImages(str(args["text"]) ?? "");
183
+ const { threadId } = await callAction(postReplyAction, {
184
+ thread_id: str(args["thread_id"]) ?? "",
185
+ text
186
+ });
187
+ return `Replied in thread ${threadId}.`;
188
+ }
189
+ case moveThreadAction.name:
190
+ return moveThread(
191
+ str(args["thread_id"])?.trim() ?? "",
192
+ str(args["to_channel_id"])?.trim() ?? ""
193
+ );
194
+ case shareDocAction.name: {
195
+ const channelId = str(args["channel_id"])?.trim() ?? "";
196
+ const path = str(args["path"])?.trim() ?? "";
197
+ if (!channelId || !path) throw new Error("channel_id and path are required");
198
+ return shareDoc(channelId, path, str(args["slug"])?.trim() || void 0);
199
+ }
200
+ case requestPermissionAction.name: {
201
+ if (!permission) break;
202
+ const input = args["input"] && typeof args["input"] === "object" ? args["input"] : {};
203
+ return JSON.stringify(
204
+ await requestPermission(permission, str(args["tool_name"]) ?? "a tool", input)
205
+ );
206
+ }
207
+ }
208
+ throw new Error(`unknown tool: ${name}`);
209
+ }
210
+ async function startThreadsServer() {
211
+ const server = new Server(
212
+ { name: "flyspace-threads", version: "1.0.0" },
213
+ { capabilities: { tools: {} } }
214
+ );
215
+ const permission = permissionTarget();
216
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
217
+ tools: permission ? [...TOOLS, PERMISSION_TOOL] : TOOLS
218
+ }));
219
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
220
+ try {
221
+ const text = await callTool(
222
+ request.params.name,
223
+ request.params.arguments ?? {},
224
+ permission
225
+ );
226
+ return { content: [{ type: "text", text }] };
227
+ } catch (err) {
228
+ return {
229
+ content: [{ type: "text", text: `Error: ${err.message}` }],
230
+ isError: true
231
+ };
232
+ }
233
+ });
234
+ await server.connect(new StdioServerTransport());
235
+ console.error("[flyspace-threads] ready on stdio");
236
+ }
237
+ export {
238
+ clampLimit,
239
+ formatHits,
240
+ formatThread,
241
+ readThread,
242
+ requestPermission,
243
+ rowsToHits,
244
+ startThreadsServer
245
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flyspace-cli",
3
- "version": "0.1.59",
3
+ "version": "0.1.61",
4
4
  "description": "AI-native headless community OS",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "private": false,
@@ -111,6 +111,8 @@ The Flyspace dashboard is your primary surface, and it does NOT require a Slack
111
111
 
112
112
  If you only have shell access (a background/automation callback, not the live tool list), use `flyspace chat post --channel <c> [--thread <id>] --text <t> [--title <t>]` instead — same underlying write path. `flyspace chat channels` / `flyspace chat threads <channel>` are the read-side CLI equivalents.
113
113
 
114
+ To publish a doc in the channel folder as a public link (same as the Docs pane's "Copy public link"), run `flyspace docs share <path> --channel <channel-id> [--slug <name>]` (or the threads MCP tool `share_doc`); it prints the URL. Re-sharing a doc keeps its URL and updates the snapshot.
115
+
114
116
  **Do not fall back to `flyspace slack post` to create a Workspace thread.** That only works because a Slack-bound channel mirrors the post back into the dashboard — it silently does nothing useful in a channel with no Slack binding, and duplicates the message in one that has both.
115
117
 
116
118
  ## Automation Management
@@ -1,178 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __flyspaceCreateRequire } from 'node:module';
3
- const require = __flyspaceCreateRequire(import.meta.url);
4
- import {
5
- SessionStore,
6
- canSeeChannel,
7
- getSupabaseClient,
8
- paths
9
- } from "./chunk-XACRG7BO.js";
10
-
11
- // src/store/chat-admin-store.ts
12
- async function listChannels(profile) {
13
- let query = getSupabaseClient().from("channels").select("id, name, profile, cwd");
14
- if (profile) query = query.eq("profile", profile);
15
- const { data, error } = await query.order("name");
16
- if (error) throw new Error(`listChannels: ${error.message}`);
17
- return (data ?? []).map((row) => ({
18
- id: row["id"],
19
- name: row["name"],
20
- profile: row["profile"],
21
- cwd: row["cwd"]
22
- }));
23
- }
24
- async function resolveChannel(nameOrId, profile) {
25
- const channels = await listChannels(profile);
26
- const byId = channels.find((c) => c.id === nameOrId);
27
- if (byId) return byId;
28
- const wanted = nameOrId.replace(/^#/, "").toLowerCase();
29
- const matches = channels.filter((c) => c.name.toLowerCase() === wanted);
30
- if (matches.length === 1) return matches[0];
31
- if (matches.length > 1) {
32
- const detail = matches.map((c) => `${c.name} (${c.profile}) ${c.id}`).join("\n ");
33
- throw new Error(`"${nameOrId}" matches ${matches.length} channels \u2014 pass an id:
34
- ${detail}`);
35
- }
36
- throw new Error(`No channel matching "${nameOrId}". Run "flyspace chat channels".`);
37
- }
38
- async function listThreads(channelId, limit = 20) {
39
- const { data, error } = await getSupabaseClient().from("threads").select("id, channel_id, title, author, updated_at, thread_replies(count)").eq("channel_id", channelId).order("updated_at", { ascending: false }).limit(limit);
40
- if (error) throw new Error(`listThreads(${channelId}): ${error.message}`);
41
- return (data ?? []).map(rowToThread);
42
- }
43
- async function getThread(threadId) {
44
- const { data, error } = await getSupabaseClient().from("threads").select("id, channel_id, title, author, updated_at, thread_replies(count)").eq("id", threadId).maybeSingle();
45
- if (error) throw new Error(`getThread(${threadId}): ${error.message}`);
46
- return data ? rowToThread(data) : void 0;
47
- }
48
- async function firstReplyBody(threadId) {
49
- const { data, error } = await getSupabaseClient().from("thread_replies").select("body").eq("thread_id", threadId).order("created_at").limit(1).maybeSingle();
50
- if (error) throw new Error(`firstReplyBody(${threadId}): ${error.message}`);
51
- return data?.body;
52
- }
53
- async function moveThread(threadId, toChannelId) {
54
- const supabase = getSupabaseClient();
55
- const { error } = await supabase.from("threads").update({ channel_id: toChannelId }).eq("id", threadId);
56
- if (error) throw new Error(`moveThread(${threadId}): ${error.message}`);
57
- const { error: notifyError } = await supabase.from("notifications").update({ channel_id: toChannelId }).eq("thread_id", threadId);
58
- if (notifyError) throw new Error(`moveThread(${threadId}) notifications: ${notifyError.message}`);
59
- }
60
- function rowToThread(row) {
61
- const counts = row["thread_replies"];
62
- return {
63
- id: row["id"],
64
- channelId: row["channel_id"],
65
- title: row["title"] ?? null,
66
- author: row["author"],
67
- replies: counts?.[0]?.count ?? 0,
68
- updatedAt: row["updated_at"]
69
- };
70
- }
71
-
72
- // src/store/thread-move.ts
73
- async function moveThreadFully(threadId, toChannelId) {
74
- const thread = await getThread(threadId);
75
- if (!thread) throw new Error(`No thread with id ${threadId}.`);
76
- if (thread.channelId === toChannelId) return "unchanged";
77
- const channels = await listChannels();
78
- const to = channels.find((c) => c.id === toChannelId);
79
- if (!to) throw new Error(`No channel with id ${toChannelId}.`);
80
- const from = channels.find((c) => c.id === thread.channelId);
81
- const store = new SessionStore(paths.DB_FILE);
82
- try {
83
- await moveThread(thread.id, to.id);
84
- const counts = store.moveThread(`chat:${thread.channelId}`, `chat:${to.id}`, thread.id);
85
- return { from, to, ...counts, cwdChanged: !!from && from.cwd !== to.cwd };
86
- } finally {
87
- store.close();
88
- }
89
- }
90
-
91
- // ../api/src/dashboard/thread-access.ts
92
- var ON_BEHALF_HEADER = "x-flyspace-on-behalf-of";
93
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
94
- function parseThreadRef(input) {
95
- const raw = input.trim();
96
- if (UUID.test(raw)) return raw.toLowerCase();
97
- let url;
98
- try {
99
- url = new URL(raw, "http://ref.invalid");
100
- } catch {
101
- return null;
102
- }
103
- const fromPath = /(?:^|\/)chat\/[^/]+\/([^/]+)\/?$/.exec(url.pathname)?.[1];
104
- if (fromPath && UUID.test(fromPath)) return fromPath.toLowerCase();
105
- const fromQuery = url.searchParams.get("t");
106
- return fromQuery && UUID.test(fromQuery) ? fromQuery.toLowerCase() : null;
107
- }
108
- function readingFor(query, userId) {
109
- return userId ? query.setHeader(ON_BEHALF_HEADER, userId) : query;
110
- }
111
- async function resolveThreadOwner(threadId, onBehalfOf) {
112
- if (!UUID.test(threadId)) return null;
113
- const db = getSupabaseClient();
114
- const { data: thread, error } = await readingFor(
115
- db.from("threads").select("id, channel_id").eq("id", threadId),
116
- onBehalfOf
117
- ).maybeSingle();
118
- if (error) throw new Error(`resolveThreadOwner: ${error.message}`);
119
- const channelId = thread?.channel_id;
120
- if (!channelId) return null;
121
- const { data: channel, error: channelError } = await readingFor(
122
- db.from("channels").select("profile, visibility, dm_key, member_emails").eq(UUID.test(channelId) ? "id" : "external_channel_id", channelId),
123
- onBehalfOf
124
- ).maybeSingle();
125
- if (channelError) throw new Error(`resolveThreadOwner: ${channelError.message}`);
126
- const row = channel;
127
- if (!row?.profile) return null;
128
- const { data: workspace, error: workspaceError } = await readingFor(
129
- db.from("workspaces").select("id").eq("slug", row.profile),
130
- onBehalfOf
131
- ).maybeSingle();
132
- if (workspaceError) throw new Error(`resolveThreadOwner: ${workspaceError.message}`);
133
- const workspaceId = workspace?.id;
134
- if (!workspaceId) return null;
135
- return {
136
- threadId,
137
- channelId,
138
- workspace: row.profile,
139
- workspaceId,
140
- channel: {
141
- // Same default as rowToChannel: anything not explicitly public is private.
142
- visibility: row.visibility === "public" ? "public" : "private",
143
- dmKey: row.dm_key,
144
- memberEmails: Array.isArray(row.member_emails) ? row.member_emails.filter((e) => typeof e === "string").map((e) => e.trim().toLowerCase()) : []
145
- }
146
- };
147
- }
148
- async function canReadThread(owner, userId) {
149
- if (!UUID.test(userId)) return false;
150
- const { data, error } = await readingFor(
151
- getSupabaseClient().from("memberships").select("email, role").eq("workspace_id", owner.workspaceId).eq("user_id", userId),
152
- userId
153
- ).maybeSingle();
154
- if (error) throw new Error(`canReadThread: ${error.message}`);
155
- const membership = data;
156
- if (!membership) return false;
157
- return canSeeChannel(owner.channel, {
158
- email: membership.email ?? void 0,
159
- role: membership.role
160
- });
161
- }
162
- function threadPath(workspace, channelId, threadId) {
163
- return `/${encodeURIComponent(workspace)}/chat/${encodeURIComponent(channelId)}/${threadId}`;
164
- }
165
-
166
- export {
167
- listChannels,
168
- resolveChannel,
169
- listThreads,
170
- getThread,
171
- firstReplyBody,
172
- moveThreadFully,
173
- ON_BEHALF_HEADER,
174
- parseThreadRef,
175
- resolveThreadOwner,
176
- canReadThread,
177
- threadPath
178
- };