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.
@@ -1,382 +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
- ON_BEHALF_HEADER,
6
- canReadThread,
7
- listChannels,
8
- moveThreadFully,
9
- parseThreadRef,
10
- resolveThreadOwner,
11
- shareDoc,
12
- threadPath
13
- } from "./chunk-PXZUNZ4S.js";
14
- import {
15
- AGENT_AUTHOR,
16
- getSupabaseClient,
17
- postToDashboardChannel
18
- } from "./chunk-XYS7SVWC.js";
19
-
20
- // src/mcp/servers/threads.ts
21
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
22
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
23
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
24
- var DEFAULT_SEARCH_LIMIT = 10;
25
- var MAX_SEARCH_LIMIT = 30;
26
- var SNIPPET_MAX = 300;
27
- var MAX_REPLIES = 100;
28
- function truncate(text, max) {
29
- const flat = text.replaceAll(/\s+/g, " ").trim();
30
- return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
31
- }
32
- function formatHits(hits, query) {
33
- if (!hits.length) return `No threads matching "${query}".`;
34
- return [
35
- `${hits.length} thread${hits.length === 1 ? "" : "s"} matching "${query}":`,
36
- "",
37
- ...hits.map((hit) => {
38
- const when = hit.createdAt.slice(0, 10);
39
- const title = hit.title?.trim() || "(untitled)";
40
- const snippet = truncate(hit.snippet, SNIPPET_MAX);
41
- const body = snippet && snippet !== truncate(title, SNIPPET_MAX) ? `
42
- ${snippet}` : "";
43
- return `- **${title}** \u2014 ${hit.author}, ${when}${body}
44
- id: \`${hit.id}\``;
45
- })
46
- ].join("\n");
47
- }
48
- function clampLimit(raw) {
49
- if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_SEARCH_LIMIT;
50
- return Math.min(Math.max(Math.trunc(raw), 1), MAX_SEARCH_LIMIT);
51
- }
52
- function rowsToHits(rows, channelId) {
53
- return rows.filter((row) => !channelId || row.channel_id === channelId).map((row) => ({
54
- id: row.id,
55
- channelId: row.channel_id,
56
- title: row.title,
57
- snippet: row.snippet ?? "",
58
- author: row.author ?? "unknown",
59
- createdAt: row.created_at
60
- }));
61
- }
62
- async function searchThreads(query, limit, channelId) {
63
- const matchLimit = channelId ? Math.min(limit * 5, 100) : limit;
64
- const { data, error } = await getSupabaseClient().rpc("search_threads", {
65
- q: query,
66
- match_limit: matchLimit
67
- });
68
- if (error) throw new Error(`search failed: ${error.message}`);
69
- return formatHits(rowsToHits(data ?? [], channelId).slice(0, limit), query);
70
- }
71
- function formatThread(thread, replies) {
72
- const lines = [
73
- `# ${thread.title?.trim() || "(untitled)"}`,
74
- "",
75
- `**${thread.author ?? "unknown"}** \xB7 ${thread.created_at.slice(0, 16).replace("T", " ")}`,
76
- "",
77
- thread.body?.trim() || "(no body)"
78
- ];
79
- if (replies.length) {
80
- lines.push("", `## ${replies.length} repl${replies.length === 1 ? "y" : "ies"}`, "");
81
- for (const reply of replies) {
82
- lines.push(
83
- `**${reply.author ?? "unknown"}** \xB7 ${reply.created_at.slice(0, 16).replace("T", " ")}`,
84
- "",
85
- reply.body?.trim() || "(empty)",
86
- ""
87
- );
88
- }
89
- }
90
- return lines.join("\n");
91
- }
92
- async function requesterUserId() {
93
- const handle = process.env["FLYSPACE_REQUESTER_HANDLE"];
94
- const workspace = process.env["FLYSPACE_THREADS_WORKSPACE"];
95
- if (!handle || !workspace) return null;
96
- const supabase = getSupabaseClient();
97
- const { data: ws } = await supabase.from("workspaces").select("id").eq("slug", workspace).maybeSingle();
98
- if (!ws) return null;
99
- const { data } = await supabase.from("memberships").select("user_id").eq("workspace_id", ws["id"]).ilike("handle", handle).maybeSingle();
100
- return data?.["user_id"] ?? null;
101
- }
102
- async function readThread(ref) {
103
- const threadId = parseThreadRef(ref);
104
- if (!threadId) return `Not a thread id or thread link: ${ref}`;
105
- const userId = await requesterUserId();
106
- const owner = await resolveThreadOwner(threadId, userId ?? void 0);
107
- const home = process.env["FLYSPACE_THREADS_WORKSPACE"];
108
- const allowed = !!owner && (userId ? await canReadThread(owner, userId) : !home || owner.workspace === home);
109
- if (!owner || !allowed) return `No thread with id ${threadId}.`;
110
- const supabase = getSupabaseClient();
111
- const onBehalf = (q) => userId ? q.setHeader(ON_BEHALF_HEADER, userId) : q;
112
- const { data: thread, error } = await onBehalf(
113
- supabase.from("threads").select("title, auto_title, author, created_at").eq("id", threadId)
114
- ).maybeSingle();
115
- if (error) throw new Error(`read failed: ${error.message}`);
116
- if (!thread) return `No thread with id ${threadId}.`;
117
- const { data: replies, error: repliesError } = await onBehalf(
118
- supabase.from("thread_replies").select("author, body, created_at").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: true }).limit(MAX_REPLIES)
119
- );
120
- if (repliesError) throw new Error(`read failed: ${repliesError.message}`);
121
- const [opening, ...rest] = replies ?? [];
122
- return `Link: ${threadPath(owner.workspace, owner.channelId, threadId)}
123
-
124
- ${formatThread(
125
- {
126
- title: thread.title ?? thread.auto_title,
127
- author: thread.author,
128
- body: opening?.body ?? null,
129
- created_at: thread.created_at
130
- },
131
- rest
132
- )}`;
133
- }
134
- var TOOLS = [
135
- {
136
- name: "search_threads",
137
- description: "Full-text search across this workspace's chat threads and replies. Use it to recall earlier decisions and discussions that are not in the current thread. Returns thread titles with a matching snippet and an id for read_thread.",
138
- inputSchema: {
139
- type: "object",
140
- properties: {
141
- query: { type: "string", description: "Words to search for." },
142
- channel_id: {
143
- type: "string",
144
- description: "Optional: restrict results to one channel id."
145
- },
146
- limit: {
147
- type: "number",
148
- description: `Maximum results (default ${DEFAULT_SEARCH_LIMIT}, max ${MAX_SEARCH_LIMIT}).`
149
- }
150
- },
151
- required: ["query"]
152
- }
153
- },
154
- {
155
- name: "read_thread",
156
- description: "Read one thread in full: the opening message and its replies in order. Takes an id from search_threads, or a thread link (any workspace you are a member of).",
157
- inputSchema: {
158
- type: "object",
159
- properties: {
160
- thread_id: { type: "string", description: "The thread id, or a link to the thread." }
161
- },
162
- required: ["thread_id"]
163
- }
164
- },
165
- {
166
- name: "list_channels",
167
- description: "List this workspace's dashboard channels (id, name, working directory). Use it to find a channel id for create_thread or move_thread when you only have a name.",
168
- inputSchema: { type: "object", properties: {} }
169
- },
170
- {
171
- name: "create_thread",
172
- description: "Start a new thread in a dashboard channel. Works in any channel, whether or not it has a Slack binding \u2014 use this instead of posting to Slack when you just need a Workspace thread. Returns the new thread id.",
173
- inputSchema: {
174
- type: "object",
175
- properties: {
176
- channel_id: { type: "string", description: "Target channel id (see list_channels)." },
177
- text: { type: "string", description: "The thread's opening message." },
178
- title: {
179
- type: "string",
180
- description: "Optional thread title. Without one, the title is derived from `text`."
181
- }
182
- },
183
- required: ["channel_id", "text"]
184
- }
185
- },
186
- {
187
- name: "post_reply",
188
- description: "Reply to an existing thread. Takes an id from search_threads or create_thread.",
189
- inputSchema: {
190
- type: "object",
191
- properties: {
192
- thread_id: { type: "string", description: "The thread id to reply in." },
193
- text: { type: "string", description: "The reply body." }
194
- },
195
- required: ["thread_id", "text"]
196
- }
197
- },
198
- {
199
- name: "move_thread",
200
- description: "Move a thread to a different channel.",
201
- inputSchema: {
202
- type: "object",
203
- properties: {
204
- thread_id: { type: "string", description: "The thread to move." },
205
- to_channel_id: { type: "string", description: "Destination channel id." }
206
- },
207
- required: ["thread_id", "to_channel_id"]
208
- }
209
- },
210
- {
211
- name: "share_doc",
212
- description: 'Publish a channel doc (Markdown or HTML) as a public link and return its URL, the same as "Copy public link" in the Docs pane. Re-sharing the same doc keeps the URL and updates the content.',
213
- inputSchema: {
214
- type: "object",
215
- properties: {
216
- channel_id: { type: "string", description: "The channel the doc belongs to." },
217
- path: { type: "string", description: "Doc path relative to the channel folder, e.g. docs/plan.md." },
218
- slug: { type: "string", description: "Optional custom URL: /share/<slug>." }
219
- },
220
- required: ["channel_id", "path"]
221
- }
222
- }
223
- ];
224
- var PERMISSION_TOOL = {
225
- name: "request_permission",
226
- description: "Internal: asks an admin in the thread to allow or deny a blocked tool call. Called by Claude Code itself as the permission prompt tool; never call it directly.",
227
- inputSchema: {
228
- type: "object",
229
- properties: {
230
- tool_name: { type: "string" },
231
- input: { type: "object" },
232
- tool_use_id: { type: "string" }
233
- },
234
- required: ["tool_name", "input"]
235
- }
236
- };
237
- var PERMISSION_POLL_MS = 2e3;
238
- var DEFAULT_PERMISSION_TIMEOUT_MS = 5 * 60 * 1e3;
239
- function permissionTarget() {
240
- const threadId = process.env["FLYSPACE_PERMISSION_THREAD_ID"];
241
- const channelId = process.env["FLYSPACE_PERMISSION_CHANNEL_ID"];
242
- return threadId && channelId ? { threadId, channelId } : null;
243
- }
244
- function describeToolInput(input) {
245
- const pick = input["command"] ?? input["file_path"] ?? input["path"] ?? input["url"];
246
- const text = typeof pick === "string" ? pick : JSON.stringify(input, null, 2);
247
- return text.length > 1500 ? `${text.slice(0, 1500)}\u2026` : text;
248
- }
249
- async function requestPermission(target, toolName, input, timeoutMs = Number(process.env["FLYSPACE_PERMISSION_TIMEOUT_MS"]) || DEFAULT_PERMISSION_TIMEOUT_MS) {
250
- const supabase = getSupabaseClient();
251
- const expiresAt = new Date(Date.now() + timeoutMs);
252
- const { data: request, error } = await supabase.from("permission_requests").insert({
253
- channel_id: target.channelId,
254
- thread_id: target.threadId,
255
- tool_name: toolName,
256
- input,
257
- expires_at: expiresAt.toISOString()
258
- }).select("id").single();
259
- if (error || !request) throw new Error(`failed to create permission request: ${error?.message}`);
260
- const requestId = request["id"];
261
- const prompt = `The agent wants to use **${toolName}**:
262
-
263
- \`\`\`
264
- ${describeToolInput(input)}
265
- \`\`\`
266
-
267
- [PERMISSION: ${requestId}]`;
268
- const { data: reply } = await supabase.from("thread_replies").insert({ thread_id: target.threadId, author: AGENT_AUTHOR, body: prompt }).select("id").single();
269
- const replyId = reply?.["id"] ?? null;
270
- if (replyId) await supabase.from("permission_requests").update({ reply_id: replyId }).eq("id", requestId);
271
- let status = "pending";
272
- let decidedBy = null;
273
- while (status === "pending" && Date.now() < expiresAt.getTime()) {
274
- await new Promise((r) => setTimeout(r, PERMISSION_POLL_MS));
275
- const { data } = await supabase.from("permission_requests").select("status, decided_by").eq("id", requestId).maybeSingle();
276
- status = data?.["status"] ?? "pending";
277
- decidedBy = data?.["decided_by"] ?? null;
278
- }
279
- if (status === "pending") {
280
- const { data } = await supabase.from("permission_requests").update({ status: "expired" }).eq("id", requestId).eq("status", "pending").select("status");
281
- if (data?.length) status = "expired";
282
- else {
283
- const { data: latest } = await supabase.from("permission_requests").select("status, decided_by").eq("id", requestId).maybeSingle();
284
- status = latest?.["status"] ?? "expired";
285
- decidedBy = latest?.["decided_by"] ?? null;
286
- }
287
- }
288
- const outcome = status === "allow" ? `\u2705 Allowed by @${decidedBy}` : status === "deny" ? `\u{1F6AB} Denied by @${decidedBy}` : "\u23F0 No answer in time, denied automatically";
289
- if (replyId) {
290
- await supabase.from("thread_replies").update({ body: prompt.replace(`[PERMISSION: ${requestId}]`, outcome) }).eq("id", replyId).eq("thread_id", target.threadId);
291
- }
292
- if (status === "allow") return { behavior: "allow", updatedInput: input };
293
- return {
294
- behavior: "deny",
295
- 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.`
296
- };
297
- }
298
- async function startThreadsServer() {
299
- const server = new Server(
300
- { name: "flyspace-threads", version: "1.0.0" },
301
- { capabilities: { tools: {} } }
302
- );
303
- const permission = permissionTarget();
304
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
305
- tools: permission ? [...TOOLS, PERMISSION_TOOL] : TOOLS
306
- }));
307
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
308
- const args = request.params.arguments ?? {};
309
- try {
310
- if (request.params.name === "search_threads") {
311
- const query = typeof args["query"] === "string" ? args["query"].trim() : "";
312
- if (!query) throw new Error("query is required");
313
- const channelId = typeof args["channel_id"] === "string" ? args["channel_id"] : void 0;
314
- const text = await searchThreads(query, clampLimit(args["limit"]), channelId);
315
- return { content: [{ type: "text", text }] };
316
- }
317
- if (request.params.name === "read_thread") {
318
- const threadId = typeof args["thread_id"] === "string" ? args["thread_id"].trim() : "";
319
- if (!threadId) throw new Error("thread_id is required");
320
- return { content: [{ type: "text", text: await readThread(threadId) }] };
321
- }
322
- if (request.params.name === "list_channels") {
323
- const channels = await listChannels();
324
- const text = channels.length ? channels.map((c) => `- **${c.name}** (${c.profile}) id: \`${c.id}\``).join("\n") : "No channels found.";
325
- return { content: [{ type: "text", text }] };
326
- }
327
- if (request.params.name === "create_thread") {
328
- const channelId = typeof args["channel_id"] === "string" ? args["channel_id"].trim() : "";
329
- const text = typeof args["text"] === "string" ? args["text"] : "";
330
- if (!channelId || !text) throw new Error("channel_id and text are required");
331
- const title = typeof args["title"] === "string" ? args["title"] : void 0;
332
- const { threadId } = await postToDashboardChannel({ channelId, text, title });
333
- return { content: [{ type: "text", text: `Created thread ${threadId}.` }] };
334
- }
335
- if (request.params.name === "post_reply") {
336
- const threadId = typeof args["thread_id"] === "string" ? args["thread_id"].trim() : "";
337
- const text = typeof args["text"] === "string" ? args["text"] : "";
338
- if (!threadId || !text) throw new Error("thread_id and text are required");
339
- await postToDashboardChannel({ threadId, text });
340
- return { content: [{ type: "text", text: `Replied in thread ${threadId}.` }] };
341
- }
342
- if (request.params.name === "move_thread") {
343
- const threadId = typeof args["thread_id"] === "string" ? args["thread_id"].trim() : "";
344
- const toChannelId = typeof args["to_channel_id"] === "string" ? args["to_channel_id"].trim() : "";
345
- if (!threadId || !toChannelId) throw new Error("thread_id and to_channel_id are required");
346
- const moved = await moveThreadFully(threadId, toChannelId);
347
- const text = moved === "unchanged" ? `Thread ${threadId} is already in ${toChannelId}.` : `Moved thread ${threadId} to ${moved.to.name} (${moved.to.id}); carried over ${moved.sessions} agent session(s).` + (moved.cwdChanged ? ` The channels have different working directories: files the thread created stay in ${moved.from?.cwd}.` : "");
348
- return { content: [{ type: "text", text }] };
349
- }
350
- if (request.params.name === "share_doc") {
351
- const channelId = typeof args["channel_id"] === "string" ? args["channel_id"].trim() : "";
352
- const path = typeof args["path"] === "string" ? args["path"].trim() : "";
353
- if (!channelId || !path) throw new Error("channel_id and path are required");
354
- const slug = typeof args["slug"] === "string" && args["slug"].trim() ? args["slug"].trim() : void 0;
355
- return { content: [{ type: "text", text: await shareDoc(channelId, path, slug) }] };
356
- }
357
- if (request.params.name === PERMISSION_TOOL.name && permission) {
358
- const toolName = typeof args["tool_name"] === "string" ? args["tool_name"] : "a tool";
359
- const input = args["input"] && typeof args["input"] === "object" ? args["input"] : {};
360
- const result = await requestPermission(permission, toolName, input);
361
- return { content: [{ type: "text", text: JSON.stringify(result) }] };
362
- }
363
- throw new Error(`unknown tool: ${request.params.name}`);
364
- } catch (err) {
365
- return {
366
- content: [{ type: "text", text: `Error: ${err.message}` }],
367
- isError: true
368
- };
369
- }
370
- });
371
- await server.connect(new StdioServerTransport());
372
- console.error("[flyspace-threads] ready on stdio");
373
- }
374
- export {
375
- clampLimit,
376
- formatHits,
377
- formatThread,
378
- readThread,
379
- requestPermission,
380
- rowsToHits,
381
- startThreadsServer
382
- };