flyspace-cli 0.1.60 → 0.1.62
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/{chunk-SIR6PTDT.js → chunk-BDUA5N6B.js} +1088 -384
- package/dist/chunk-PLLJ7M62.js +14799 -0
- package/dist/{chunk-XYS7SVWC.js → chunk-UZMHXV4D.js} +40 -742
- package/dist/cli.js +675 -120
- package/dist/index.js +2 -2
- package/dist/threads-BFRTS4EB.js +245 -0
- package/package.json +1 -1
- package/dist/chunk-PXZUNZ4S.js +0 -230
- package/dist/threads-QQRWT3OM.js +0 -382
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-
|
|
7
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-BDUA5N6B.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
package/dist/chunk-PXZUNZ4S.js
DELETED
|
@@ -1,230 +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
|
-
LOCAL_DOC_SHARE_PATH,
|
|
6
|
-
SessionStore,
|
|
7
|
-
canSeeChannel,
|
|
8
|
-
getSupabaseClient,
|
|
9
|
-
loadEnvFiles,
|
|
10
|
-
paths,
|
|
11
|
-
readHostEndpoint,
|
|
12
|
-
useHostDbWithoutCredentials
|
|
13
|
-
} from "./chunk-XYS7SVWC.js";
|
|
14
|
-
|
|
15
|
-
// src/store/chat-admin-store.ts
|
|
16
|
-
async function listChannels(profile) {
|
|
17
|
-
let query = getSupabaseClient().from("channels").select("id, name, profile, cwd");
|
|
18
|
-
if (profile) query = query.eq("profile", profile);
|
|
19
|
-
const { data, error } = await query.order("name");
|
|
20
|
-
if (error) throw new Error(`listChannels: ${error.message}`);
|
|
21
|
-
return (data ?? []).map((row) => ({
|
|
22
|
-
id: row["id"],
|
|
23
|
-
name: row["name"],
|
|
24
|
-
profile: row["profile"],
|
|
25
|
-
cwd: row["cwd"]
|
|
26
|
-
}));
|
|
27
|
-
}
|
|
28
|
-
async function resolveChannel(nameOrId, profile) {
|
|
29
|
-
const channels = await listChannels(profile);
|
|
30
|
-
const byId = channels.find((c) => c.id === nameOrId);
|
|
31
|
-
if (byId) return byId;
|
|
32
|
-
const wanted = nameOrId.replace(/^#/, "").toLowerCase();
|
|
33
|
-
const matches = channels.filter((c) => c.name.toLowerCase() === wanted);
|
|
34
|
-
if (matches.length === 1) return matches[0];
|
|
35
|
-
if (matches.length > 1) {
|
|
36
|
-
const detail = matches.map((c) => `${c.name} (${c.profile}) ${c.id}`).join("\n ");
|
|
37
|
-
throw new Error(`"${nameOrId}" matches ${matches.length} channels \u2014 pass an id:
|
|
38
|
-
${detail}`);
|
|
39
|
-
}
|
|
40
|
-
throw new Error(`No channel matching "${nameOrId}". Run "flyspace chat channels".`);
|
|
41
|
-
}
|
|
42
|
-
async function listThreads(channelId, limit = 20) {
|
|
43
|
-
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);
|
|
44
|
-
if (error) throw new Error(`listThreads(${channelId}): ${error.message}`);
|
|
45
|
-
return (data ?? []).map(rowToThread);
|
|
46
|
-
}
|
|
47
|
-
async function getThread(threadId) {
|
|
48
|
-
const { data, error } = await getSupabaseClient().from("threads").select("id, channel_id, title, author, updated_at, thread_replies(count)").eq("id", threadId).maybeSingle();
|
|
49
|
-
if (error) throw new Error(`getThread(${threadId}): ${error.message}`);
|
|
50
|
-
return data ? rowToThread(data) : void 0;
|
|
51
|
-
}
|
|
52
|
-
async function firstReplyBody(threadId) {
|
|
53
|
-
const { data, error } = await getSupabaseClient().from("thread_replies").select("body").eq("thread_id", threadId).order("created_at").limit(1).maybeSingle();
|
|
54
|
-
if (error) throw new Error(`firstReplyBody(${threadId}): ${error.message}`);
|
|
55
|
-
return data?.body;
|
|
56
|
-
}
|
|
57
|
-
async function moveThread(threadId, toChannelId) {
|
|
58
|
-
const supabase = getSupabaseClient();
|
|
59
|
-
const { error } = await supabase.from("threads").update({ channel_id: toChannelId }).eq("id", threadId);
|
|
60
|
-
if (error) throw new Error(`moveThread(${threadId}): ${error.message}`);
|
|
61
|
-
const { error: notifyError } = await supabase.from("notifications").update({ channel_id: toChannelId }).eq("thread_id", threadId);
|
|
62
|
-
if (notifyError) throw new Error(`moveThread(${threadId}) notifications: ${notifyError.message}`);
|
|
63
|
-
}
|
|
64
|
-
function rowToThread(row) {
|
|
65
|
-
const counts = row["thread_replies"];
|
|
66
|
-
return {
|
|
67
|
-
id: row["id"],
|
|
68
|
-
channelId: row["channel_id"],
|
|
69
|
-
title: row["title"] ?? null,
|
|
70
|
-
author: row["author"],
|
|
71
|
-
replies: counts?.[0]?.count ?? 0,
|
|
72
|
-
updatedAt: row["updated_at"]
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// src/store/thread-move.ts
|
|
77
|
-
async function moveThreadFully(threadId, toChannelId) {
|
|
78
|
-
const thread = await getThread(threadId);
|
|
79
|
-
if (!thread) throw new Error(`No thread with id ${threadId}.`);
|
|
80
|
-
if (thread.channelId === toChannelId) return "unchanged";
|
|
81
|
-
const channels = await listChannels();
|
|
82
|
-
const to = channels.find((c) => c.id === toChannelId);
|
|
83
|
-
if (!to) throw new Error(`No channel with id ${toChannelId}.`);
|
|
84
|
-
const from = channels.find((c) => c.id === thread.channelId);
|
|
85
|
-
const store = new SessionStore(paths.DB_FILE);
|
|
86
|
-
try {
|
|
87
|
-
await moveThread(thread.id, to.id);
|
|
88
|
-
const counts = store.moveThread(`chat:${thread.channelId}`, `chat:${to.id}`, thread.id);
|
|
89
|
-
return { from, to, ...counts, cwdChanged: !!from && from.cwd !== to.cwd };
|
|
90
|
-
} finally {
|
|
91
|
-
store.close();
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// src/commands/docs.ts
|
|
96
|
-
import { isAbsolute, normalize, relative } from "path";
|
|
97
|
-
var USAGE = `
|
|
98
|
-
Usage: flyspace docs share <path> --channel <name-or-id> [--slug <name>]
|
|
99
|
-
|
|
100
|
-
Publish a channel doc (Markdown or HTML) as a public link and print its URL,
|
|
101
|
-
the same as "Copy public link" in the Docs pane. Re-sharing keeps the URL.
|
|
102
|
-
|
|
103
|
-
<path> Relative to the channel folder (absolute paths are read
|
|
104
|
-
relative to the current directory, which the agent runs in)
|
|
105
|
-
--slug <name> Custom URL: /share/<name>
|
|
106
|
-
`;
|
|
107
|
-
function getArg(args, flag) {
|
|
108
|
-
const idx = args.indexOf(flag);
|
|
109
|
-
return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : void 0;
|
|
110
|
-
}
|
|
111
|
-
async function runDocsCmd(args) {
|
|
112
|
-
const [sub, rawPath] = args;
|
|
113
|
-
if (sub !== "share" || !rawPath || rawPath.startsWith("--")) {
|
|
114
|
-
console.log(USAGE);
|
|
115
|
-
if (sub && sub !== "-h" && sub !== "--help") process.exitCode = 1;
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
const channelRef = getArg(args, "--channel");
|
|
119
|
-
if (!channelRef) throw new Error("--channel is required");
|
|
120
|
-
loadEnvFiles();
|
|
121
|
-
useHostDbWithoutCredentials();
|
|
122
|
-
const channel = await resolveChannel(channelRef);
|
|
123
|
-
console.log(await shareDoc(channel.id, rawPath, getArg(args, "--slug")));
|
|
124
|
-
}
|
|
125
|
-
async function shareDoc(channelId, rawPath, slug) {
|
|
126
|
-
const path = normalize(isAbsolute(rawPath) ? relative(process.cwd(), rawPath) : rawPath);
|
|
127
|
-
if (path.startsWith("..") || isAbsolute(path)) throw new Error(`${rawPath} is outside the channel folder`);
|
|
128
|
-
const endpoint = readHostEndpoint();
|
|
129
|
-
if (!endpoint) throw new Error("No Flyspace Host is running on this machine.");
|
|
130
|
-
const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_DOC_SHARE_PATH}`, {
|
|
131
|
-
method: "POST",
|
|
132
|
-
headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
|
|
133
|
-
body: JSON.stringify({ channelId, path, ...slug ? { slug } : {} }),
|
|
134
|
-
signal: AbortSignal.timeout(18e4)
|
|
135
|
-
});
|
|
136
|
-
const body = await res.json().catch(() => ({}));
|
|
137
|
-
if (!body.url) throw new Error(`Share failed: ${body.error ?? `Host answered ${res.status}`}`);
|
|
138
|
-
return body.url;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// ../api/src/dashboard/thread-access.ts
|
|
142
|
-
var ON_BEHALF_HEADER = "x-flyspace-on-behalf-of";
|
|
143
|
-
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
144
|
-
function parseThreadRef(input) {
|
|
145
|
-
const raw = input.trim();
|
|
146
|
-
if (UUID.test(raw)) return raw.toLowerCase();
|
|
147
|
-
let url;
|
|
148
|
-
try {
|
|
149
|
-
url = new URL(raw, "http://ref.invalid");
|
|
150
|
-
} catch {
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
const fromPath = /(?:^|\/)chat\/[^/]+\/([^/]+)\/?$/.exec(url.pathname)?.[1];
|
|
154
|
-
if (fromPath && UUID.test(fromPath)) return fromPath.toLowerCase();
|
|
155
|
-
const fromQuery = url.searchParams.get("t");
|
|
156
|
-
return fromQuery && UUID.test(fromQuery) ? fromQuery.toLowerCase() : null;
|
|
157
|
-
}
|
|
158
|
-
function readingFor(query, userId) {
|
|
159
|
-
return userId ? query.setHeader(ON_BEHALF_HEADER, userId) : query;
|
|
160
|
-
}
|
|
161
|
-
async function resolveThreadOwner(threadId, onBehalfOf) {
|
|
162
|
-
if (!UUID.test(threadId)) return null;
|
|
163
|
-
const db = getSupabaseClient();
|
|
164
|
-
const { data: thread, error } = await readingFor(
|
|
165
|
-
db.from("threads").select("id, channel_id").eq("id", threadId),
|
|
166
|
-
onBehalfOf
|
|
167
|
-
).maybeSingle();
|
|
168
|
-
if (error) throw new Error(`resolveThreadOwner: ${error.message}`);
|
|
169
|
-
const channelId = thread?.channel_id;
|
|
170
|
-
if (!channelId) return null;
|
|
171
|
-
const { data: channel, error: channelError } = await readingFor(
|
|
172
|
-
db.from("channels").select("profile, visibility, dm_key, member_emails").eq(UUID.test(channelId) ? "id" : "external_channel_id", channelId),
|
|
173
|
-
onBehalfOf
|
|
174
|
-
).maybeSingle();
|
|
175
|
-
if (channelError) throw new Error(`resolveThreadOwner: ${channelError.message}`);
|
|
176
|
-
const row = channel;
|
|
177
|
-
if (!row?.profile) return null;
|
|
178
|
-
const { data: workspace, error: workspaceError } = await readingFor(
|
|
179
|
-
db.from("workspaces").select("id").eq("slug", row.profile),
|
|
180
|
-
onBehalfOf
|
|
181
|
-
).maybeSingle();
|
|
182
|
-
if (workspaceError) throw new Error(`resolveThreadOwner: ${workspaceError.message}`);
|
|
183
|
-
const workspaceId = workspace?.id;
|
|
184
|
-
if (!workspaceId) return null;
|
|
185
|
-
return {
|
|
186
|
-
threadId,
|
|
187
|
-
channelId,
|
|
188
|
-
workspace: row.profile,
|
|
189
|
-
workspaceId,
|
|
190
|
-
channel: {
|
|
191
|
-
// Same default as rowToChannel: anything not explicitly public is private.
|
|
192
|
-
visibility: row.visibility === "public" ? "public" : "private",
|
|
193
|
-
dmKey: row.dm_key,
|
|
194
|
-
memberEmails: Array.isArray(row.member_emails) ? row.member_emails.filter((e) => typeof e === "string").map((e) => e.trim().toLowerCase()) : []
|
|
195
|
-
}
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
async function canReadThread(owner, userId) {
|
|
199
|
-
if (!UUID.test(userId)) return false;
|
|
200
|
-
const { data, error } = await readingFor(
|
|
201
|
-
getSupabaseClient().from("memberships").select("email, role").eq("workspace_id", owner.workspaceId).eq("user_id", userId),
|
|
202
|
-
userId
|
|
203
|
-
).maybeSingle();
|
|
204
|
-
if (error) throw new Error(`canReadThread: ${error.message}`);
|
|
205
|
-
const membership = data;
|
|
206
|
-
if (!membership) return false;
|
|
207
|
-
return canSeeChannel(owner.channel, {
|
|
208
|
-
email: membership.email ?? void 0,
|
|
209
|
-
role: membership.role
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
function threadPath(workspace, channelId, threadId) {
|
|
213
|
-
return `/${encodeURIComponent(workspace)}/chat/${encodeURIComponent(channelId)}/${threadId}`;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
export {
|
|
217
|
-
listChannels,
|
|
218
|
-
resolveChannel,
|
|
219
|
-
listThreads,
|
|
220
|
-
getThread,
|
|
221
|
-
firstReplyBody,
|
|
222
|
-
moveThreadFully,
|
|
223
|
-
runDocsCmd,
|
|
224
|
-
shareDoc,
|
|
225
|
-
ON_BEHALF_HEADER,
|
|
226
|
-
parseThreadRef,
|
|
227
|
-
resolveThreadOwner,
|
|
228
|
-
canReadThread,
|
|
229
|
-
threadPath
|
|
230
|
-
};
|