flyspace-cli 0.1.53 → 0.1.54
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-67WA56OD.js +1243 -0
- package/dist/chunk-ONGRYEWS.js +178 -0
- package/dist/{chunk-GX5467VC.js → chunk-ZSRDP5HJ.js} +2143 -2274
- package/dist/cli.js +367 -470
- package/dist/index.js +2 -2
- package/dist/{threads-QAVO2Z4L.js → threads-PTTZUNIJ.js} +43 -12
- package/package.json +1 -1
- package/system.capabilities.md +2 -0
- package/dist/chunk-HTFQL66T.js +0 -488
- package/dist/chunk-PIAF4FJX.js +0 -76
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-ZSRDP5HJ.js";
|
|
7
|
+
import "./chunk-67WA56OD.js";
|
|
8
8
|
export {
|
|
9
9
|
startServer
|
|
10
10
|
};
|
|
@@ -2,14 +2,19 @@
|
|
|
2
2
|
import { createRequire as __flyspaceCreateRequire } from 'node:module';
|
|
3
3
|
const require = __flyspaceCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
+
ON_BEHALF_HEADER,
|
|
6
|
+
canReadThread,
|
|
5
7
|
listChannels,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
moveThreadFully,
|
|
9
|
+
parseThreadRef,
|
|
10
|
+
resolveThreadOwner,
|
|
11
|
+
threadPath
|
|
12
|
+
} from "./chunk-ONGRYEWS.js";
|
|
8
13
|
import {
|
|
9
14
|
AGENT_AUTHOR,
|
|
10
15
|
getSupabaseClient,
|
|
11
16
|
postToDashboardChannel
|
|
12
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-67WA56OD.js";
|
|
13
18
|
|
|
14
19
|
// src/mcp/servers/threads.ts
|
|
15
20
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
@@ -83,15 +88,39 @@ function formatThread(thread, replies) {
|
|
|
83
88
|
}
|
|
84
89
|
return lines.join("\n");
|
|
85
90
|
}
|
|
86
|
-
async function
|
|
91
|
+
async function requesterUserId() {
|
|
92
|
+
const handle = process.env["FLYSPACE_REQUESTER_HANDLE"];
|
|
93
|
+
const workspace = process.env["FLYSPACE_THREADS_WORKSPACE"];
|
|
94
|
+
if (!handle || !workspace) return null;
|
|
87
95
|
const supabase = getSupabaseClient();
|
|
88
|
-
const { data:
|
|
96
|
+
const { data: ws } = await supabase.from("workspaces").select("id").eq("slug", workspace).maybeSingle();
|
|
97
|
+
if (!ws) return null;
|
|
98
|
+
const { data } = await supabase.from("memberships").select("user_id").eq("workspace_id", ws["id"]).ilike("handle", handle).maybeSingle();
|
|
99
|
+
return data?.["user_id"] ?? null;
|
|
100
|
+
}
|
|
101
|
+
async function readThread(ref) {
|
|
102
|
+
const threadId = parseThreadRef(ref);
|
|
103
|
+
if (!threadId) return `Not a thread id or thread link: ${ref}`;
|
|
104
|
+
const userId = await requesterUserId();
|
|
105
|
+
const owner = await resolveThreadOwner(threadId, userId ?? void 0);
|
|
106
|
+
const home = process.env["FLYSPACE_THREADS_WORKSPACE"];
|
|
107
|
+
const allowed = !!owner && (userId ? await canReadThread(owner, userId) : !home || owner.workspace === home);
|
|
108
|
+
if (!owner || !allowed) return `No thread with id ${threadId}.`;
|
|
109
|
+
const supabase = getSupabaseClient();
|
|
110
|
+
const onBehalf = (q) => userId ? q.setHeader(ON_BEHALF_HEADER, userId) : q;
|
|
111
|
+
const { data: thread, error } = await onBehalf(
|
|
112
|
+
supabase.from("threads").select("title, auto_title, author, created_at").eq("id", threadId)
|
|
113
|
+
).maybeSingle();
|
|
89
114
|
if (error) throw new Error(`read failed: ${error.message}`);
|
|
90
115
|
if (!thread) return `No thread with id ${threadId}.`;
|
|
91
|
-
const { data: replies, error: repliesError } = await
|
|
116
|
+
const { data: replies, error: repliesError } = await onBehalf(
|
|
117
|
+
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)
|
|
118
|
+
);
|
|
92
119
|
if (repliesError) throw new Error(`read failed: ${repliesError.message}`);
|
|
93
120
|
const [opening, ...rest] = replies ?? [];
|
|
94
|
-
return
|
|
121
|
+
return `Link: ${threadPath(owner.workspace, owner.channelId, threadId)}
|
|
122
|
+
|
|
123
|
+
${formatThread(
|
|
95
124
|
{
|
|
96
125
|
title: thread.title ?? thread.auto_title,
|
|
97
126
|
author: thread.author,
|
|
@@ -99,7 +128,7 @@ async function readThread(threadId) {
|
|
|
99
128
|
created_at: thread.created_at
|
|
100
129
|
},
|
|
101
130
|
rest
|
|
102
|
-
)
|
|
131
|
+
)}`;
|
|
103
132
|
}
|
|
104
133
|
var TOOLS = [
|
|
105
134
|
{
|
|
@@ -123,11 +152,11 @@ var TOOLS = [
|
|
|
123
152
|
},
|
|
124
153
|
{
|
|
125
154
|
name: "read_thread",
|
|
126
|
-
description: "Read one thread in full: the opening message and its replies in order. Takes an id from search_threads.",
|
|
155
|
+
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).",
|
|
127
156
|
inputSchema: {
|
|
128
157
|
type: "object",
|
|
129
158
|
properties: {
|
|
130
|
-
thread_id: { type: "string", description: "The thread id." }
|
|
159
|
+
thread_id: { type: "string", description: "The thread id, or a link to the thread." }
|
|
131
160
|
},
|
|
132
161
|
required: ["thread_id"]
|
|
133
162
|
}
|
|
@@ -300,8 +329,9 @@ async function startThreadsServer() {
|
|
|
300
329
|
const threadId = typeof args["thread_id"] === "string" ? args["thread_id"].trim() : "";
|
|
301
330
|
const toChannelId = typeof args["to_channel_id"] === "string" ? args["to_channel_id"].trim() : "";
|
|
302
331
|
if (!threadId || !toChannelId) throw new Error("thread_id and to_channel_id are required");
|
|
303
|
-
await
|
|
304
|
-
|
|
332
|
+
const moved = await moveThreadFully(threadId, toChannelId);
|
|
333
|
+
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}.` : "");
|
|
334
|
+
return { content: [{ type: "text", text }] };
|
|
305
335
|
}
|
|
306
336
|
if (request.params.name === PERMISSION_TOOL.name && permission) {
|
|
307
337
|
const toolName = typeof args["tool_name"] === "string" ? args["tool_name"] : "a tool";
|
|
@@ -324,6 +354,7 @@ export {
|
|
|
324
354
|
clampLimit,
|
|
325
355
|
formatHits,
|
|
326
356
|
formatThread,
|
|
357
|
+
readThread,
|
|
327
358
|
requestPermission,
|
|
328
359
|
rowsToHits,
|
|
329
360
|
startThreadsServer
|
package/package.json
CHANGED
package/system.capabilities.md
CHANGED
|
@@ -118,6 +118,8 @@ If you only have shell access (a background/automation callback, not the live to
|
|
|
118
118
|
You can manage scheduled automations and event-driven triggers. When users ask to add, list, remove, enable, or disable automations, use these commands via Bash:
|
|
119
119
|
|
|
120
120
|
- `flyspace automation list` — List all automations
|
|
121
|
+
- `flyspace automation show <name>` — Print one automation as JSON, including its prompt
|
|
122
|
+
- `flyspace automation edit <name> --prompt-file <path>` (or `--prompt "text"`) — Replace an automation's prompt. Run `show` first, edit the prompt in a scratch file, then pass it with `--prompt-file`
|
|
121
123
|
- `flyspace automation add --type schedule --name "name" --cron "expr" --channel "#channel" --prompt "prompt" [--timezone "tz"] [--cwd "/path"]` — Add a schedule
|
|
122
124
|
- `flyspace automation add --type trigger --name "name" --patterns "pat1,pat2" --channels "*" --cooldown 300 --prompt "prompt"` — Add a trigger
|
|
123
125
|
- `flyspace automation remove <name>` — Remove an automation
|
package/dist/chunk-HTFQL66T.js
DELETED
|
@@ -1,488 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __flyspaceCreateRequire } from 'node:module';
|
|
3
|
-
const require = __flyspaceCreateRequire(import.meta.url);
|
|
4
|
-
var __create = Object.create;
|
|
5
|
-
var __defProp = Object.defineProperty;
|
|
6
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
7
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
9
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
10
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
11
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
12
|
-
}) : x)(function(x) {
|
|
13
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
14
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
15
|
-
});
|
|
16
|
-
var __commonJS = (cb, mod) => function __require2() {
|
|
17
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
18
|
-
};
|
|
19
|
-
var __copyProps = (to, from, except, desc) => {
|
|
20
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
21
|
-
for (let key of __getOwnPropNames(from))
|
|
22
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
23
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
24
|
-
}
|
|
25
|
-
return to;
|
|
26
|
-
};
|
|
27
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
28
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
29
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
30
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
31
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
32
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
33
|
-
mod
|
|
34
|
-
));
|
|
35
|
-
|
|
36
|
-
// ../api/src/store/supabase-client.ts
|
|
37
|
-
var client;
|
|
38
|
-
var factory;
|
|
39
|
-
function setSupabaseClient(replacement) {
|
|
40
|
-
client = replacement;
|
|
41
|
-
}
|
|
42
|
-
function setSupabaseClientFactory(create) {
|
|
43
|
-
factory = create;
|
|
44
|
-
}
|
|
45
|
-
function hasSupabaseCredentials() {
|
|
46
|
-
return !!process.env["SUPABASE_URL"] && !!process.env["SUPABASE_SECRET_KEY"];
|
|
47
|
-
}
|
|
48
|
-
function databaseReachable() {
|
|
49
|
-
return !!client || !!factory && hasSupabaseCredentials();
|
|
50
|
-
}
|
|
51
|
-
function getSupabaseClient() {
|
|
52
|
-
if (client) return client;
|
|
53
|
-
if (!factory) throw new Error("No Supabase client installed in this process");
|
|
54
|
-
client = factory();
|
|
55
|
-
return client;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// ../api/src/profile.ts
|
|
59
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
60
|
-
var PROFILE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
61
|
-
var DEFAULT_PROFILE = "default";
|
|
62
|
-
var profileStore = new AsyncLocalStorage();
|
|
63
|
-
function runWithProfile(profile, fn) {
|
|
64
|
-
return profileStore.run(validateProfile(profile), fn);
|
|
65
|
-
}
|
|
66
|
-
function validateProfile(raw) {
|
|
67
|
-
const name = raw?.trim();
|
|
68
|
-
if (!name || name === DEFAULT_PROFILE) return DEFAULT_PROFILE;
|
|
69
|
-
if (!PROFILE_PATTERN.test(name)) {
|
|
70
|
-
throw new Error(
|
|
71
|
-
`Invalid profile name: "${name}". Use lowercase letters, digits, and hyphens (must start with a letter or digit).`
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
return name;
|
|
75
|
-
}
|
|
76
|
-
function getProfile() {
|
|
77
|
-
const bound = profileStore.getStore();
|
|
78
|
-
if (bound) return bound;
|
|
79
|
-
return validateProfile(process.env["FLYSPACE_WORKSPACE"]);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// ../api/src/paths.ts
|
|
83
|
-
import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from "fs";
|
|
84
|
-
import { homedir } from "os";
|
|
85
|
-
import { basename, join, resolve } from "path";
|
|
86
|
-
var home = homedir();
|
|
87
|
-
var XDG_CONFIG_HOME = process.env["XDG_CONFIG_HOME"] || join(home, ".config");
|
|
88
|
-
var XDG_DATA_HOME = process.env["XDG_DATA_HOME"] || join(home, ".local", "share");
|
|
89
|
-
var OWN_ROOT = resolve(import.meta.dirname, "..");
|
|
90
|
-
var paths = {
|
|
91
|
-
/** Profile-independent config root: `~/.config/flyspace`. */
|
|
92
|
-
get BASE_CONFIG_DIR() {
|
|
93
|
-
return join(XDG_CONFIG_HOME, "flyspace");
|
|
94
|
-
},
|
|
95
|
-
/** Profile-independent data root: `~/.local/share/flyspace`. */
|
|
96
|
-
get BASE_DATA_DIR() {
|
|
97
|
-
return join(XDG_DATA_HOME, "flyspace");
|
|
98
|
-
},
|
|
99
|
-
/** Where named profiles live: `~/.config/flyspace/profiles`. */
|
|
100
|
-
get PROFILES_DIR() {
|
|
101
|
-
return join(XDG_CONFIG_HOME, "flyspace", "profiles");
|
|
102
|
-
},
|
|
103
|
-
/** Config dir for the active profile. `default` uses the base dir. */
|
|
104
|
-
get CONFIG_DIR() {
|
|
105
|
-
const profile = getProfile();
|
|
106
|
-
return profile === "default" ? this.BASE_CONFIG_DIR : join(this.PROFILES_DIR, profile);
|
|
107
|
-
},
|
|
108
|
-
/** Data dir for the active profile. `default` uses the base dir. */
|
|
109
|
-
get DATA_DIR() {
|
|
110
|
-
const profile = getProfile();
|
|
111
|
-
return profile === "default" ? this.BASE_DATA_DIR : join(this.BASE_DATA_DIR, "profiles", profile);
|
|
112
|
-
},
|
|
113
|
-
get CONFIG_FILE() {
|
|
114
|
-
return join(this.CONFIG_DIR, "config.env");
|
|
115
|
-
},
|
|
116
|
-
get PROMPT_FILE() {
|
|
117
|
-
return join(this.CONFIG_DIR, "prompt.md");
|
|
118
|
-
},
|
|
119
|
-
get DB_FILE() {
|
|
120
|
-
return join(this.DATA_DIR, "flyspace.db");
|
|
121
|
-
},
|
|
122
|
-
get LOG_DIR() {
|
|
123
|
-
return join(this.DATA_DIR, "logs");
|
|
124
|
-
},
|
|
125
|
-
get UPLOADS_DIR() {
|
|
126
|
-
return join(this.DATA_DIR, "uploads");
|
|
127
|
-
},
|
|
128
|
-
/**
|
|
129
|
-
* Throwaway files the agent produces mid-turn (screenshots, rendered charts)
|
|
130
|
-
* so it has somewhere to write that isn't the shared system temp dir. Swept
|
|
131
|
-
* on startup by `sweepScratchDir()` — nothing here is expected to survive.
|
|
132
|
-
*/
|
|
133
|
-
get SCRATCH_DIR() {
|
|
134
|
-
return join(this.DATA_DIR, "scratch");
|
|
135
|
-
},
|
|
136
|
-
/**
|
|
137
|
-
* Per-channel persistent HOME for `runtime: 'container'` channels — mounted
|
|
138
|
-
* into the container as the agent's home so `--resume` survives a container
|
|
139
|
-
* exiting (each turn is a fresh `--rm` container). Unlike SCRATCH_DIR this is
|
|
140
|
-
* never swept: the Claude session files under it are the resume state.
|
|
141
|
-
* One subdirectory per container channel; see `containerHomeFor()`.
|
|
142
|
-
*/
|
|
143
|
-
get CONTAINER_HOMES_DIR() {
|
|
144
|
-
return join(this.DATA_DIR, "container-homes");
|
|
145
|
-
},
|
|
146
|
-
/**
|
|
147
|
-
* Per-channel persistent CLAUDE_CONFIG_DIR for `runtime: 'sandbox'` channels
|
|
148
|
-
* — a real host directory (sandbox-runtime confines the process to paths on
|
|
149
|
-
* disk, there is no separate container filesystem to mount into), kept out
|
|
150
|
-
* of the channel's own folder so it never shows up in the agent's Read/ls.
|
|
151
|
-
* One subdirectory per sandboxed channel; see `sandboxHomeFor()`.
|
|
152
|
-
*/
|
|
153
|
-
get SANDBOX_HOMES_DIR() {
|
|
154
|
-
return join(this.DATA_DIR, "sandbox-homes");
|
|
155
|
-
},
|
|
156
|
-
/**
|
|
157
|
-
* Root for per-channel shadow git repos (bare, one per channel) that back
|
|
158
|
-
* the version-history feature. Kept outside the channel folder itself so a
|
|
159
|
-
* channel's own `cwd` never grows a `.git` — that would collide with a repo
|
|
160
|
-
* the user links in themselves. See `src/versions`.
|
|
161
|
-
*/
|
|
162
|
-
get VERSIONS_DIR() {
|
|
163
|
-
return join(this.DATA_DIR, "versions");
|
|
164
|
-
},
|
|
165
|
-
get AUTOMATIONS_FILE() {
|
|
166
|
-
return join(this.CONFIG_DIR, "automations.yml");
|
|
167
|
-
},
|
|
168
|
-
get CHANNELS_FILE() {
|
|
169
|
-
return join(this.CONFIG_DIR, "channels.yml");
|
|
170
|
-
},
|
|
171
|
-
get DASHBOARD_SETTINGS_FILE() {
|
|
172
|
-
return join(this.CONFIG_DIR, "dashboard-settings.json");
|
|
173
|
-
},
|
|
174
|
-
/** Where the CLI's shipped files live (`system.default.md`, `hooks/`,
|
|
175
|
-
* `templates/`, its `node_modules`): packages/host in a checkout, the
|
|
176
|
-
* installed `flyspace-cli` otherwise. This module lives in packages/api, so
|
|
177
|
-
* an unbundled run (tsx, vitest) resolves to the host package next to it;
|
|
178
|
-
* the Fly images ship no host package and keep their own root. */
|
|
179
|
-
PACKAGE_ROOT: basename(OWN_ROOT) === "api" && existsSync(join(OWN_ROOT, "..", "host", "package.json")) ? resolve(OWN_ROOT, "..", "host") : OWN_ROOT,
|
|
180
|
-
/** packages/ui: the SPA source and its `dist/`. Only a checkout (or the
|
|
181
|
-
* share image) has it; the npm-installed CLI ships no UI. */
|
|
182
|
-
WEB_ROOT: resolve(OWN_ROOT, "..", "ui")
|
|
183
|
-
};
|
|
184
|
-
function ensureDirs() {
|
|
185
|
-
for (const dir of [
|
|
186
|
-
paths.CONFIG_DIR,
|
|
187
|
-
paths.DATA_DIR,
|
|
188
|
-
paths.LOG_DIR,
|
|
189
|
-
paths.UPLOADS_DIR,
|
|
190
|
-
paths.SCRATCH_DIR
|
|
191
|
-
]) {
|
|
192
|
-
if (!existsSync(dir)) {
|
|
193
|
-
mkdirSync(dir, { recursive: true });
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
var SCRATCH_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
198
|
-
function sweepScratchDir(now = Date.now()) {
|
|
199
|
-
const dir = paths.SCRATCH_DIR;
|
|
200
|
-
if (!existsSync(dir)) return 0;
|
|
201
|
-
let removed = 0;
|
|
202
|
-
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
203
|
-
const path = join(dir, entry.name);
|
|
204
|
-
try {
|
|
205
|
-
if (now - statSync(path).mtimeMs < SCRATCH_MAX_AGE_MS) continue;
|
|
206
|
-
rmSync(path, { recursive: true, force: true });
|
|
207
|
-
removed++;
|
|
208
|
-
} catch {
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
return removed;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// ../api/src/store/authors.ts
|
|
215
|
-
var AGENT_AUTHOR = "agent";
|
|
216
|
-
var SYNCED_BOT_AUTHOR = "Bot";
|
|
217
|
-
var LEGACY_BOT_AUTHOR = "Custie";
|
|
218
|
-
var SUPPORT_BOT_AUTHOR = "Flyspace Support";
|
|
219
|
-
var NON_HUMAN_AUTHORS = new Set(
|
|
220
|
-
[AGENT_AUTHOR, SYNCED_BOT_AUTHOR, LEGACY_BOT_AUTHOR, SUPPORT_BOT_AUTHOR].map((a) => a.toLowerCase())
|
|
221
|
-
);
|
|
222
|
-
function isHumanAuthor(author) {
|
|
223
|
-
return !NON_HUMAN_AUTHORS.has(author.toLowerCase());
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// ../api/src/dashboard/attachment-uploader.ts
|
|
227
|
-
import { randomUUID } from "crypto";
|
|
228
|
-
import { readFile, stat } from "fs/promises";
|
|
229
|
-
import { basename as basename2 } from "path";
|
|
230
|
-
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
|
231
|
-
|
|
232
|
-
// ../api/src/store/r2-client.ts
|
|
233
|
-
import { ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
|
|
234
|
-
var client2;
|
|
235
|
-
function getR2Client() {
|
|
236
|
-
if (client2) return client2;
|
|
237
|
-
const accountId = process.env["CLOUDFLARE_R2_ACCOUNT_ID"];
|
|
238
|
-
const accessKeyId = process.env["CLOUDFLARE_R2_ACCESS_KEY_ID"];
|
|
239
|
-
const secretAccessKey = process.env["CLOUDFLARE_R2_SECRET_ACCESS_KEY"];
|
|
240
|
-
if (!accountId || !accessKeyId || !secretAccessKey) {
|
|
241
|
-
throw new Error("CLOUDFLARE_R2_* env vars not set \u2014 check .env");
|
|
242
|
-
}
|
|
243
|
-
client2 = new S3Client({
|
|
244
|
-
region: "auto",
|
|
245
|
-
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
246
|
-
credentials: { accessKeyId, secretAccessKey }
|
|
247
|
-
});
|
|
248
|
-
return client2;
|
|
249
|
-
}
|
|
250
|
-
function getR2Bucket() {
|
|
251
|
-
const bucket = process.env["CLOUDFLARE_R2_BUCKET_NAME"];
|
|
252
|
-
if (!bucket) throw new Error("CLOUDFLARE_R2_BUCKET_NAME not set \u2014 check .env");
|
|
253
|
-
return bucket;
|
|
254
|
-
}
|
|
255
|
-
async function sumR2PrefixBytes(prefix) {
|
|
256
|
-
let total = 0;
|
|
257
|
-
let token;
|
|
258
|
-
do {
|
|
259
|
-
const page = await getR2Client().send(
|
|
260
|
-
new ListObjectsV2Command({ Bucket: getR2Bucket(), Prefix: prefix, ContinuationToken: token })
|
|
261
|
-
);
|
|
262
|
-
for (const obj of page.Contents ?? []) total += obj.Size ?? 0;
|
|
263
|
-
token = page.IsTruncated ? page.NextContinuationToken : void 0;
|
|
264
|
-
} while (token);
|
|
265
|
-
return total;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// ../api/src/dashboard/attachment-uploader.ts
|
|
269
|
-
var debug = process.env["DEBUG"] === "true";
|
|
270
|
-
var LOCAL_IMAGE_LINK = /!\[([^\]]*)\]\((\/[^)\s]+)\)/g;
|
|
271
|
-
var SCRATCH_VAR_IN_IMAGE_LINK = /(!\[[^\]]*\]\()\$\{?FLYSPACE_SCRATCH_DIR\}?(?=\/)/g;
|
|
272
|
-
function expandScratchDirVar(body) {
|
|
273
|
-
return body.replace(SCRATCH_VAR_IN_IMAGE_LINK, (_, prefix) => prefix + paths.SCRATCH_DIR);
|
|
274
|
-
}
|
|
275
|
-
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
276
|
-
var SCRATCH_PREFIX = "scratch";
|
|
277
|
-
var MIMETYPES = {
|
|
278
|
-
".png": "image/png",
|
|
279
|
-
".jpg": "image/jpeg",
|
|
280
|
-
".jpeg": "image/jpeg",
|
|
281
|
-
".gif": "image/gif",
|
|
282
|
-
".webp": "image/webp",
|
|
283
|
-
".avif": "image/avif"
|
|
284
|
-
};
|
|
285
|
-
function mimetypeOf(path) {
|
|
286
|
-
const dot = path.lastIndexOf(".");
|
|
287
|
-
return dot === -1 ? void 0 : MIMETYPES[path.slice(dot).toLowerCase()];
|
|
288
|
-
}
|
|
289
|
-
function sanitizeFilename(name) {
|
|
290
|
-
const cleaned = name.replace(/[/\\]/g, "_").replace(/\s+/g, "-").replace(/[^\w.-]/g, "").trim();
|
|
291
|
-
return (cleaned || "file").slice(-100);
|
|
292
|
-
}
|
|
293
|
-
function encodeKeyForUrl(key) {
|
|
294
|
-
return key.split("/").map(encodeURIComponent).join("/");
|
|
295
|
-
}
|
|
296
|
-
function extractLocalImagePaths(body) {
|
|
297
|
-
const paths2 = [];
|
|
298
|
-
for (const match of body.matchAll(LOCAL_IMAGE_LINK)) {
|
|
299
|
-
const path = match[2];
|
|
300
|
-
if (path.startsWith("/api/")) continue;
|
|
301
|
-
if (!mimetypeOf(path)) continue;
|
|
302
|
-
if (!paths2.includes(path)) paths2.push(path);
|
|
303
|
-
}
|
|
304
|
-
return paths2;
|
|
305
|
-
}
|
|
306
|
-
async function uploadOne(path) {
|
|
307
|
-
const mimetype = mimetypeOf(path);
|
|
308
|
-
if (!mimetype) return null;
|
|
309
|
-
try {
|
|
310
|
-
const info = await stat(path);
|
|
311
|
-
if (!info.isFile()) return null;
|
|
312
|
-
if (info.size > MAX_FILE_BYTES) {
|
|
313
|
-
console.error(`[attachment-uploader] ${path} is ${info.size} bytes, over the ${MAX_FILE_BYTES} limit`);
|
|
314
|
-
return null;
|
|
315
|
-
}
|
|
316
|
-
const key = `${SCRATCH_PREFIX}/${getProfile()}/${randomUUID()}-${sanitizeFilename(basename2(path))}`;
|
|
317
|
-
await getR2Client().send(
|
|
318
|
-
new PutObjectCommand({
|
|
319
|
-
Bucket: getR2Bucket(),
|
|
320
|
-
Key: key,
|
|
321
|
-
Body: await readFile(path),
|
|
322
|
-
ContentType: mimetype
|
|
323
|
-
})
|
|
324
|
-
);
|
|
325
|
-
if (debug) console.log(`[attachment-uploader] ${path} -> ${key} (${info.size} bytes)`);
|
|
326
|
-
return `/api/attachments/${encodeKeyForUrl(key)}`;
|
|
327
|
-
} catch (err) {
|
|
328
|
-
console.error(`[attachment-uploader] failed to upload ${path}:`, err.message);
|
|
329
|
-
return null;
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
async function uploadLocalImages(rawBody) {
|
|
333
|
-
const body = expandScratchDirVar(rawBody);
|
|
334
|
-
const localPaths = extractLocalImagePaths(body);
|
|
335
|
-
if (localPaths.length === 0) return body;
|
|
336
|
-
const urls = /* @__PURE__ */ new Map();
|
|
337
|
-
await Promise.all(
|
|
338
|
-
localPaths.map(async (path) => {
|
|
339
|
-
const url = await uploadOne(path);
|
|
340
|
-
if (url) urls.set(path, url);
|
|
341
|
-
})
|
|
342
|
-
);
|
|
343
|
-
if (urls.size === 0) return body;
|
|
344
|
-
return body.replace(LOCAL_IMAGE_LINK, (original, alt, path) => {
|
|
345
|
-
const url = urls.get(path);
|
|
346
|
-
return url ? `` : original;
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// src/store/dashboard-sync.ts
|
|
351
|
-
var TITLE_MAX_LENGTH = 80;
|
|
352
|
-
function deriveThreadTitle(text) {
|
|
353
|
-
const firstLine = text.split("\n").find((line) => line.trim().length > 0);
|
|
354
|
-
if (!firstLine) return null;
|
|
355
|
-
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();
|
|
356
|
-
if (!cleaned) return null;
|
|
357
|
-
return cleaned.length > TITLE_MAX_LENGTH ? `${cleaned.slice(0, TITLE_MAX_LENGTH).trim()}\u2026` : cleaned;
|
|
358
|
-
}
|
|
359
|
-
async function syncPostToDashboard(opts) {
|
|
360
|
-
const { channelId, ts, threadTs, text } = opts;
|
|
361
|
-
if (!databaseReachable()) {
|
|
362
|
-
console.warn("[dashboard-sync] Supabase not configured \u2014 skipping dashboard sync");
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
try {
|
|
366
|
-
const supabase = getSupabaseClient();
|
|
367
|
-
const dashboardChannelId = await resolveDashboardChannelId(supabase, channelId);
|
|
368
|
-
const threadId = threadTs ? await ensureThreadId(supabase, channelId, dashboardChannelId, threadTs) : await createOwnThread(supabase, channelId, dashboardChannelId, ts, text);
|
|
369
|
-
const { error } = await supabase.from("thread_replies").upsert(
|
|
370
|
-
{
|
|
371
|
-
thread_id: threadId,
|
|
372
|
-
// This mirror only ever runs for the bot's own posts (automation
|
|
373
|
-
// output, `flyspace slack post`), so the author is the agent itself —
|
|
374
|
-
// labelling it anything else makes the chat agent count it as a
|
|
375
|
-
// second human and stop replying without an explicit mention.
|
|
376
|
-
author: AGENT_AUTHOR,
|
|
377
|
-
body: await uploadLocalImages(text),
|
|
378
|
-
external_thread_replies_id: `${channelId}:${ts}`
|
|
379
|
-
},
|
|
380
|
-
{ onConflict: "external_thread_replies_id" }
|
|
381
|
-
);
|
|
382
|
-
if (error) {
|
|
383
|
-
console.warn(`[dashboard-sync] failed to write reply: ${error.message}`);
|
|
384
|
-
}
|
|
385
|
-
} catch (err) {
|
|
386
|
-
console.warn(
|
|
387
|
-
`[dashboard-sync] sync failed: ${err instanceof Error ? err.message : String(err)}`
|
|
388
|
-
);
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
async function resolveDashboardChannelId(supabase, slackChannelId) {
|
|
392
|
-
const { data, error } = await supabase.from("channels").select("id").eq("external_channel_id", slackChannelId).maybeSingle();
|
|
393
|
-
if (error || !data) return slackChannelId;
|
|
394
|
-
return data["id"];
|
|
395
|
-
}
|
|
396
|
-
async function createOwnThread(supabase, externalChannelId, dashboardChannelId, ts, text) {
|
|
397
|
-
const { data, error } = await supabase.from("threads").upsert(
|
|
398
|
-
{
|
|
399
|
-
channel_id: dashboardChannelId,
|
|
400
|
-
title: deriveThreadTitle(text),
|
|
401
|
-
author: AGENT_AUTHOR,
|
|
402
|
-
external_thread_id: `${externalChannelId}:${ts}`
|
|
403
|
-
},
|
|
404
|
-
{ onConflict: "external_thread_id" }
|
|
405
|
-
).select("id").single();
|
|
406
|
-
if (error || !data) throw new Error(error?.message ?? "failed to create thread");
|
|
407
|
-
return data["id"];
|
|
408
|
-
}
|
|
409
|
-
async function ensureThreadId(supabase, externalChannelId, dashboardChannelId, parentTs) {
|
|
410
|
-
const key = `${externalChannelId}:${parentTs}`;
|
|
411
|
-
const { data: existing, error: selectError } = await supabase.from("threads").select("id").eq("external_thread_id", key).maybeSingle();
|
|
412
|
-
if (selectError) throw new Error(selectError.message);
|
|
413
|
-
if (existing) return existing["id"];
|
|
414
|
-
const { data: created, error: createError } = await supabase.from("threads").upsert(
|
|
415
|
-
// The unsynced parent could be anyone's message (often another bot's),
|
|
416
|
-
// so keep the generic non-human placeholder rather than claiming it.
|
|
417
|
-
{
|
|
418
|
-
channel_id: dashboardChannelId,
|
|
419
|
-
title: null,
|
|
420
|
-
author: SYNCED_BOT_AUTHOR,
|
|
421
|
-
external_thread_id: key
|
|
422
|
-
},
|
|
423
|
-
{ onConflict: "external_thread_id" }
|
|
424
|
-
).select("id").single();
|
|
425
|
-
if (createError || !created) {
|
|
426
|
-
throw new Error(createError?.message ?? "failed to create placeholder thread");
|
|
427
|
-
}
|
|
428
|
-
return created["id"];
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// src/store/dashboard-post.ts
|
|
432
|
-
async function postToDashboardChannel(opts) {
|
|
433
|
-
const { channelId, text, threadId, title } = opts;
|
|
434
|
-
const supabase = getSupabaseClient();
|
|
435
|
-
if (!threadId && !channelId) {
|
|
436
|
-
throw new Error("postToDashboardChannel: channelId is required to start a new thread");
|
|
437
|
-
}
|
|
438
|
-
const parentId = threadId ?? await createThread(supabase, channelId, text, title);
|
|
439
|
-
const body = await uploadLocalImages(text);
|
|
440
|
-
const { data, error } = await supabase.from("thread_replies").insert({ thread_id: parentId, author: AGENT_AUTHOR, body }).select("id").single();
|
|
441
|
-
if (error || !data) {
|
|
442
|
-
throw new Error(`failed to write dashboard reply: ${error?.message ?? "no row returned"}`);
|
|
443
|
-
}
|
|
444
|
-
return { threadId: parentId, replyId: data["id"] };
|
|
445
|
-
}
|
|
446
|
-
async function createThread(supabase, channelId, text, title) {
|
|
447
|
-
const { data, error } = await supabase.from("threads").insert({
|
|
448
|
-
channel_id: channelId,
|
|
449
|
-
// An untitled thread is effectively invisible in the sidebar, so give a
|
|
450
|
-
// daily report the same first-line-derived title a mirrored post gets,
|
|
451
|
-
// unless the caller named the thread itself.
|
|
452
|
-
title: title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(text),
|
|
453
|
-
author: AGENT_AUTHOR
|
|
454
|
-
}).select("id").single();
|
|
455
|
-
if (error || !data) {
|
|
456
|
-
throw new Error(`failed to create dashboard thread: ${error?.message ?? "no row returned"}`);
|
|
457
|
-
}
|
|
458
|
-
return data["id"];
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
export {
|
|
462
|
-
__require,
|
|
463
|
-
__commonJS,
|
|
464
|
-
__toESM,
|
|
465
|
-
setSupabaseClient,
|
|
466
|
-
setSupabaseClientFactory,
|
|
467
|
-
hasSupabaseCredentials,
|
|
468
|
-
databaseReachable,
|
|
469
|
-
getSupabaseClient,
|
|
470
|
-
DEFAULT_PROFILE,
|
|
471
|
-
runWithProfile,
|
|
472
|
-
getProfile,
|
|
473
|
-
paths,
|
|
474
|
-
ensureDirs,
|
|
475
|
-
sweepScratchDir,
|
|
476
|
-
AGENT_AUTHOR,
|
|
477
|
-
SYNCED_BOT_AUTHOR,
|
|
478
|
-
SUPPORT_BOT_AUTHOR,
|
|
479
|
-
isHumanAuthor,
|
|
480
|
-
getR2Client,
|
|
481
|
-
getR2Bucket,
|
|
482
|
-
sumR2PrefixBytes,
|
|
483
|
-
SCRATCH_PREFIX,
|
|
484
|
-
uploadLocalImages,
|
|
485
|
-
syncPostToDashboard,
|
|
486
|
-
resolveDashboardChannelId,
|
|
487
|
-
postToDashboardChannel
|
|
488
|
-
};
|