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/{chunk-7W5FEG63.js → chunk-METRJ6PG.js} +1091 -972
- package/dist/chunk-PLLJ7M62.js +14799 -0
- package/dist/chunk-UZMHXV4D.js +1136 -0
- package/dist/cli.js +844 -314
- package/dist/index.js +2 -2
- package/dist/threads-BFRTS4EB.js +245 -0
- package/package.json +1 -1
- package/system.capabilities.md +2 -0
- package/dist/chunk-44WHW7NK.js +0 -178
- package/dist/chunk-XACRG7BO.js +0 -1257
- package/dist/threads-I52LSA5X.js +0 -361
|
@@ -0,0 +1,1136 @@
|
|
|
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 __export = (target, all) => {
|
|
20
|
+
for (var name in all)
|
|
21
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
22
|
+
};
|
|
23
|
+
var __copyProps = (to, from, except, desc) => {
|
|
24
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
25
|
+
for (let key of __getOwnPropNames(from))
|
|
26
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
27
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
28
|
+
}
|
|
29
|
+
return to;
|
|
30
|
+
};
|
|
31
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
32
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
33
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
34
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
35
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
36
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
37
|
+
mod
|
|
38
|
+
));
|
|
39
|
+
|
|
40
|
+
// ../api/src/store/supabase-client.ts
|
|
41
|
+
var client;
|
|
42
|
+
var factory;
|
|
43
|
+
function setSupabaseClient(replacement) {
|
|
44
|
+
client = replacement;
|
|
45
|
+
}
|
|
46
|
+
function setSupabaseClientFactory(create) {
|
|
47
|
+
factory = create;
|
|
48
|
+
}
|
|
49
|
+
function hasSupabaseCredentials() {
|
|
50
|
+
return !!process.env["SUPABASE_URL"] && !!process.env["SUPABASE_SECRET_KEY"];
|
|
51
|
+
}
|
|
52
|
+
function databaseReachable() {
|
|
53
|
+
return !!client || !!factory && hasSupabaseCredentials();
|
|
54
|
+
}
|
|
55
|
+
function getSupabaseClient() {
|
|
56
|
+
if (client) return client;
|
|
57
|
+
if (!factory) throw new Error("No Supabase client installed in this process");
|
|
58
|
+
client = factory();
|
|
59
|
+
return client;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ../api/src/profile.ts
|
|
63
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
64
|
+
var PROFILE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
65
|
+
var DEFAULT_PROFILE = "default";
|
|
66
|
+
var profileStore = new AsyncLocalStorage();
|
|
67
|
+
function runWithProfile(profile, fn) {
|
|
68
|
+
return profileStore.run(validateProfile(profile), fn);
|
|
69
|
+
}
|
|
70
|
+
function validateProfile(raw) {
|
|
71
|
+
const name = raw?.trim();
|
|
72
|
+
if (!name || name === DEFAULT_PROFILE) return DEFAULT_PROFILE;
|
|
73
|
+
if (!PROFILE_PATTERN.test(name)) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid profile name: "${name}". Use lowercase letters, digits, and hyphens (must start with a letter or digit).`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return name;
|
|
79
|
+
}
|
|
80
|
+
function getProfile() {
|
|
81
|
+
const bound = profileStore.getStore();
|
|
82
|
+
if (bound) return bound;
|
|
83
|
+
return validateProfile(process.env["FLYSPACE_WORKSPACE"]);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ../api/src/paths.ts
|
|
87
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from "fs";
|
|
88
|
+
import { homedir } from "os";
|
|
89
|
+
import { basename, join, resolve } from "path";
|
|
90
|
+
var home = homedir();
|
|
91
|
+
var XDG_CONFIG_HOME = process.env["XDG_CONFIG_HOME"] || join(home, ".config");
|
|
92
|
+
var XDG_DATA_HOME = process.env["XDG_DATA_HOME"] || join(home, ".local", "share");
|
|
93
|
+
var OWN_ROOT = resolve(import.meta.dirname, "..");
|
|
94
|
+
var paths = {
|
|
95
|
+
/** Profile-independent config root: `~/.config/flyspace`. */
|
|
96
|
+
get BASE_CONFIG_DIR() {
|
|
97
|
+
return join(XDG_CONFIG_HOME, "flyspace");
|
|
98
|
+
},
|
|
99
|
+
/** Profile-independent data root: `~/.local/share/flyspace`. */
|
|
100
|
+
get BASE_DATA_DIR() {
|
|
101
|
+
return join(XDG_DATA_HOME, "flyspace");
|
|
102
|
+
},
|
|
103
|
+
/** Where named profiles live: `~/.config/flyspace/profiles`. */
|
|
104
|
+
get PROFILES_DIR() {
|
|
105
|
+
return join(XDG_CONFIG_HOME, "flyspace", "profiles");
|
|
106
|
+
},
|
|
107
|
+
/** Config dir for the active profile. `default` uses the base dir. */
|
|
108
|
+
get CONFIG_DIR() {
|
|
109
|
+
const profile = getProfile();
|
|
110
|
+
return profile === "default" ? this.BASE_CONFIG_DIR : join(this.PROFILES_DIR, profile);
|
|
111
|
+
},
|
|
112
|
+
/** Data dir for the active profile. `default` uses the base dir. */
|
|
113
|
+
get DATA_DIR() {
|
|
114
|
+
const profile = getProfile();
|
|
115
|
+
return profile === "default" ? this.BASE_DATA_DIR : join(this.BASE_DATA_DIR, "profiles", profile);
|
|
116
|
+
},
|
|
117
|
+
get CONFIG_FILE() {
|
|
118
|
+
return join(this.CONFIG_DIR, "config.env");
|
|
119
|
+
},
|
|
120
|
+
get PROMPT_FILE() {
|
|
121
|
+
return join(this.CONFIG_DIR, "prompt.md");
|
|
122
|
+
},
|
|
123
|
+
get DB_FILE() {
|
|
124
|
+
return join(this.DATA_DIR, "flyspace.db");
|
|
125
|
+
},
|
|
126
|
+
get LOG_DIR() {
|
|
127
|
+
return join(this.DATA_DIR, "logs");
|
|
128
|
+
},
|
|
129
|
+
get UPLOADS_DIR() {
|
|
130
|
+
return join(this.DATA_DIR, "uploads");
|
|
131
|
+
},
|
|
132
|
+
/**
|
|
133
|
+
* Throwaway files the agent produces mid-turn (screenshots, rendered charts)
|
|
134
|
+
* so it has somewhere to write that isn't the shared system temp dir. Swept
|
|
135
|
+
* on startup by `sweepScratchDir()` — nothing here is expected to survive.
|
|
136
|
+
*/
|
|
137
|
+
get SCRATCH_DIR() {
|
|
138
|
+
return join(this.DATA_DIR, "scratch");
|
|
139
|
+
},
|
|
140
|
+
/**
|
|
141
|
+
* Per-channel persistent HOME for `runtime: 'container'` channels — mounted
|
|
142
|
+
* into the container as the agent's home so `--resume` survives a container
|
|
143
|
+
* exiting (each turn is a fresh `--rm` container). Unlike SCRATCH_DIR this is
|
|
144
|
+
* never swept: the Claude session files under it are the resume state.
|
|
145
|
+
* One subdirectory per container channel; see `containerHomeFor()`.
|
|
146
|
+
*/
|
|
147
|
+
get CONTAINER_HOMES_DIR() {
|
|
148
|
+
return join(this.DATA_DIR, "container-homes");
|
|
149
|
+
},
|
|
150
|
+
/**
|
|
151
|
+
* Per-channel persistent CLAUDE_CONFIG_DIR for `runtime: 'sandbox'` channels
|
|
152
|
+
* — a real host directory (sandbox-runtime confines the process to paths on
|
|
153
|
+
* disk, there is no separate container filesystem to mount into), kept out
|
|
154
|
+
* of the channel's own folder so it never shows up in the agent's Read/ls.
|
|
155
|
+
* One subdirectory per sandboxed channel; see `sandboxHomeFor()`.
|
|
156
|
+
*/
|
|
157
|
+
get SANDBOX_HOMES_DIR() {
|
|
158
|
+
return join(this.DATA_DIR, "sandbox-homes");
|
|
159
|
+
},
|
|
160
|
+
/**
|
|
161
|
+
* Root for per-channel shadow git repos (bare, one per channel) that back
|
|
162
|
+
* the version-history feature. Kept outside the channel folder itself so a
|
|
163
|
+
* channel's own `cwd` never grows a `.git` — that would collide with a repo
|
|
164
|
+
* the user links in themselves. See `src/versions`.
|
|
165
|
+
*/
|
|
166
|
+
get VERSIONS_DIR() {
|
|
167
|
+
return join(this.DATA_DIR, "versions");
|
|
168
|
+
},
|
|
169
|
+
get AUTOMATIONS_FILE() {
|
|
170
|
+
return join(this.CONFIG_DIR, "automations.yml");
|
|
171
|
+
},
|
|
172
|
+
get CHANNELS_FILE() {
|
|
173
|
+
return join(this.CONFIG_DIR, "channels.yml");
|
|
174
|
+
},
|
|
175
|
+
get DASHBOARD_SETTINGS_FILE() {
|
|
176
|
+
return join(this.CONFIG_DIR, "dashboard-settings.json");
|
|
177
|
+
},
|
|
178
|
+
/** Where the CLI's shipped files live (`system.default.md`, `hooks/`,
|
|
179
|
+
* `templates/`, its `node_modules`): packages/host in a checkout, the
|
|
180
|
+
* installed `flyspace-cli` otherwise. This module lives in packages/api, so
|
|
181
|
+
* an unbundled run (tsx, vitest) resolves to the host package next to it;
|
|
182
|
+
* the Fly images ship no host package and keep their own root. */
|
|
183
|
+
PACKAGE_ROOT: basename(OWN_ROOT) === "api" && existsSync(join(OWN_ROOT, "..", "host", "package.json")) ? resolve(OWN_ROOT, "..", "host") : OWN_ROOT,
|
|
184
|
+
/** packages/ui: the SPA source and its `dist/`. Only a checkout (or the
|
|
185
|
+
* share image) has it; the npm-installed CLI ships no UI. */
|
|
186
|
+
WEB_ROOT: resolve(OWN_ROOT, "..", "ui")
|
|
187
|
+
};
|
|
188
|
+
function ensureDirs() {
|
|
189
|
+
for (const dir of [
|
|
190
|
+
paths.CONFIG_DIR,
|
|
191
|
+
paths.DATA_DIR,
|
|
192
|
+
paths.LOG_DIR,
|
|
193
|
+
paths.UPLOADS_DIR,
|
|
194
|
+
paths.SCRATCH_DIR
|
|
195
|
+
]) {
|
|
196
|
+
if (!existsSync(dir)) {
|
|
197
|
+
mkdirSync(dir, { recursive: true });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
var SCRATCH_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
202
|
+
function sweepScratchDir(now = Date.now()) {
|
|
203
|
+
const dir = paths.SCRATCH_DIR;
|
|
204
|
+
if (!existsSync(dir)) return 0;
|
|
205
|
+
let removed = 0;
|
|
206
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
207
|
+
const path = join(dir, entry.name);
|
|
208
|
+
try {
|
|
209
|
+
if (now - statSync(path).mtimeMs < SCRATCH_MAX_AGE_MS) continue;
|
|
210
|
+
rmSync(path, { recursive: true, force: true });
|
|
211
|
+
removed++;
|
|
212
|
+
} catch {
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return removed;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ../api/src/config.ts
|
|
219
|
+
import dotenv from "dotenv";
|
|
220
|
+
import { existsSync as existsSync2 } from "fs";
|
|
221
|
+
import { resolve as resolve2 } from "path";
|
|
222
|
+
|
|
223
|
+
// ../api/src/effort.ts
|
|
224
|
+
var EFFORT_LEVELS = ["low", "medium", "high", "max"];
|
|
225
|
+
function isEffort(value) {
|
|
226
|
+
return EFFORT_LEVELS.includes(value);
|
|
227
|
+
}
|
|
228
|
+
var CLAUDE_EFFORT = {
|
|
229
|
+
low: "low",
|
|
230
|
+
medium: "medium",
|
|
231
|
+
high: "xhigh",
|
|
232
|
+
max: "max"
|
|
233
|
+
};
|
|
234
|
+
function resolveClaudeEffort(effort) {
|
|
235
|
+
return CLAUDE_EFFORT[effort];
|
|
236
|
+
}
|
|
237
|
+
var CODEX_EFFORT = {
|
|
238
|
+
low: "low",
|
|
239
|
+
medium: "medium",
|
|
240
|
+
high: "high",
|
|
241
|
+
max: "high"
|
|
242
|
+
};
|
|
243
|
+
function resolveCodexEffort(effort) {
|
|
244
|
+
return CODEX_EFFORT[effort];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ../api/src/config.ts
|
|
248
|
+
var DEFAULT_CODEX_MODEL = "";
|
|
249
|
+
function mcpStrictConfigEnabled() {
|
|
250
|
+
return process.env["MCP_STRICT_CONFIG"]?.trim() === "true";
|
|
251
|
+
}
|
|
252
|
+
function loadEnvFiles() {
|
|
253
|
+
if (existsSync2(paths.CONFIG_FILE)) {
|
|
254
|
+
dotenv.config({ path: paths.CONFIG_FILE, override: true, quiet: true });
|
|
255
|
+
}
|
|
256
|
+
const candidates = [resolve2(paths.PACKAGE_ROOT, ".env"), resolve2(process.cwd(), ".env")];
|
|
257
|
+
for (const path of new Set(candidates)) {
|
|
258
|
+
if (existsSync2(path)) {
|
|
259
|
+
dotenv.config({ path, override: false, quiet: true });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function parseBudget(raw) {
|
|
264
|
+
if (raw === void 0) return 10;
|
|
265
|
+
const n = Number.parseFloat(raw);
|
|
266
|
+
if (!Number.isFinite(n) || n <= 0) return void 0;
|
|
267
|
+
return n;
|
|
268
|
+
}
|
|
269
|
+
function parseEffort(raw) {
|
|
270
|
+
const trimmed = raw?.trim().toLowerCase();
|
|
271
|
+
return trimmed && isEffort(trimmed) ? trimmed : void 0;
|
|
272
|
+
}
|
|
273
|
+
var SLACK_ENV = ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "SLACK_SIGNING_SECRET"];
|
|
274
|
+
function slackConfigured(env = process.env) {
|
|
275
|
+
return SLACK_ENV.some((name) => env[name]?.trim());
|
|
276
|
+
}
|
|
277
|
+
function requireSlackBotToken(config) {
|
|
278
|
+
if (!config.slackBotToken) {
|
|
279
|
+
throw new Error("Slack is not configured: set SLACK_BOT_TOKEN to use Slack commands");
|
|
280
|
+
}
|
|
281
|
+
return config.slackBotToken;
|
|
282
|
+
}
|
|
283
|
+
function requireEnv(name) {
|
|
284
|
+
const value = process.env[name];
|
|
285
|
+
if (!value) {
|
|
286
|
+
throw new Error(`Missing required environment variable: ${name}`);
|
|
287
|
+
}
|
|
288
|
+
return value;
|
|
289
|
+
}
|
|
290
|
+
function loadConfig() {
|
|
291
|
+
const ownerUserId = process.env["OWNER_USER_ID"] || void 0;
|
|
292
|
+
const allowedUserIds = new Set(
|
|
293
|
+
(process.env["ALLOWED_USER_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
|
|
294
|
+
);
|
|
295
|
+
if (ownerUserId && allowedUserIds.size > 0) {
|
|
296
|
+
allowedUserIds.add(ownerUserId);
|
|
297
|
+
}
|
|
298
|
+
const autoRespondChannelIds = new Set(
|
|
299
|
+
(process.env["AUTO_RESPOND_CHANNEL_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
|
|
300
|
+
);
|
|
301
|
+
const slackEnglishOnlyExemptChannelIds = new Set(
|
|
302
|
+
(process.env["SLACK_ENGLISH_ONLY_EXEMPT_CHANNEL_IDS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean)
|
|
303
|
+
);
|
|
304
|
+
const slack = slackConfigured();
|
|
305
|
+
return {
|
|
306
|
+
slackBotToken: slack ? requireEnv("SLACK_BOT_TOKEN") : void 0,
|
|
307
|
+
slackAppToken: slack ? requireEnv("SLACK_APP_TOKEN") : void 0,
|
|
308
|
+
slackSigningSecret: slack ? requireEnv("SLACK_SIGNING_SECRET") : void 0,
|
|
309
|
+
claudeCwd: process.env["CLAUDE_CWD"] ?? process.cwd(),
|
|
310
|
+
claudeConfigDir: process.env["CLAUDE_CONFIG_DIR"] || void 0,
|
|
311
|
+
claudeCodeOauthToken: process.env["CLAUDE_CODE_OAUTH_TOKEN"] || void 0,
|
|
312
|
+
botName: process.env["BOT_NAME"] ?? "Bot",
|
|
313
|
+
allowedUserIds,
|
|
314
|
+
maxTurns: parseInt(process.env["MAX_TURNS"] ?? "10", 10),
|
|
315
|
+
model: process.env["CUSTIE_MODEL"]?.trim() || "sonnet",
|
|
316
|
+
effort: parseEffort(process.env["CUSTIE_EFFORT"]),
|
|
317
|
+
maxBudgetUsd: parseBudget(process.env["MAX_BUDGET_USD"]),
|
|
318
|
+
ownerUserId,
|
|
319
|
+
autoRespondChannelIds,
|
|
320
|
+
codexModel: process.env["CUSTIE_CODEX_MODEL"]?.trim() || DEFAULT_CODEX_MODEL,
|
|
321
|
+
slackEnglishOnly: process.env["SLACK_ENGLISH_ONLY"] === "true",
|
|
322
|
+
slackEnglishOnlyExemptChannelIds
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ../api/src/dashboard/attachment-uploader.ts
|
|
327
|
+
import { randomUUID } from "crypto";
|
|
328
|
+
import { readFile, stat } from "fs/promises";
|
|
329
|
+
import { basename as basename2 } from "path";
|
|
330
|
+
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
|
331
|
+
|
|
332
|
+
// ../api/src/store/r2-client.ts
|
|
333
|
+
import { ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
|
|
334
|
+
var client2;
|
|
335
|
+
function getR2Client() {
|
|
336
|
+
if (client2) return client2;
|
|
337
|
+
const accountId = process.env["CLOUDFLARE_R2_ACCOUNT_ID"];
|
|
338
|
+
const accessKeyId = process.env["CLOUDFLARE_R2_ACCESS_KEY_ID"];
|
|
339
|
+
const secretAccessKey = process.env["CLOUDFLARE_R2_SECRET_ACCESS_KEY"];
|
|
340
|
+
if (!accountId || !accessKeyId || !secretAccessKey) {
|
|
341
|
+
throw new Error("CLOUDFLARE_R2_* env vars not set \u2014 check .env");
|
|
342
|
+
}
|
|
343
|
+
client2 = new S3Client({
|
|
344
|
+
region: "auto",
|
|
345
|
+
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
346
|
+
credentials: { accessKeyId, secretAccessKey }
|
|
347
|
+
});
|
|
348
|
+
return client2;
|
|
349
|
+
}
|
|
350
|
+
function getR2Bucket() {
|
|
351
|
+
const bucket = process.env["CLOUDFLARE_R2_BUCKET_NAME"];
|
|
352
|
+
if (!bucket) throw new Error("CLOUDFLARE_R2_BUCKET_NAME not set \u2014 check .env");
|
|
353
|
+
return bucket;
|
|
354
|
+
}
|
|
355
|
+
async function sumR2PrefixBytes(prefix) {
|
|
356
|
+
let total = 0;
|
|
357
|
+
let token;
|
|
358
|
+
do {
|
|
359
|
+
const page = await getR2Client().send(
|
|
360
|
+
new ListObjectsV2Command({ Bucket: getR2Bucket(), Prefix: prefix, ContinuationToken: token })
|
|
361
|
+
);
|
|
362
|
+
for (const obj of page.Contents ?? []) total += obj.Size ?? 0;
|
|
363
|
+
token = page.IsTruncated ? page.NextContinuationToken : void 0;
|
|
364
|
+
} while (token);
|
|
365
|
+
return total;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ../api/src/dashboard/attachment-uploader.ts
|
|
369
|
+
var debug = process.env["DEBUG"] === "true";
|
|
370
|
+
var LOCAL_IMAGE_LINK = /!\[([^\]]*)\]\((\/[^)\s]+)\)/g;
|
|
371
|
+
var SCRATCH_VAR_IN_IMAGE_LINK = /(!\[[^\]]*\]\()\$\{?FLYSPACE_SCRATCH_DIR\}?(?=\/)/g;
|
|
372
|
+
function expandScratchDirVar(body) {
|
|
373
|
+
return body.replace(SCRATCH_VAR_IN_IMAGE_LINK, (_, prefix) => prefix + paths.SCRATCH_DIR);
|
|
374
|
+
}
|
|
375
|
+
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
376
|
+
var SCRATCH_PREFIX = "scratch";
|
|
377
|
+
var MIMETYPES = {
|
|
378
|
+
".png": "image/png",
|
|
379
|
+
".jpg": "image/jpeg",
|
|
380
|
+
".jpeg": "image/jpeg",
|
|
381
|
+
".gif": "image/gif",
|
|
382
|
+
".webp": "image/webp",
|
|
383
|
+
".avif": "image/avif"
|
|
384
|
+
};
|
|
385
|
+
function mimetypeOf(path) {
|
|
386
|
+
const dot = path.lastIndexOf(".");
|
|
387
|
+
return dot === -1 ? void 0 : MIMETYPES[path.slice(dot).toLowerCase()];
|
|
388
|
+
}
|
|
389
|
+
function sanitizeFilename(name) {
|
|
390
|
+
const cleaned = name.replace(/[/\\]/g, "_").replace(/\s+/g, "-").replace(/[^\w.-]/g, "").trim();
|
|
391
|
+
return (cleaned || "file").slice(-100);
|
|
392
|
+
}
|
|
393
|
+
function encodeKeyForUrl(key) {
|
|
394
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
395
|
+
}
|
|
396
|
+
function extractLocalImagePaths(body) {
|
|
397
|
+
const paths2 = [];
|
|
398
|
+
for (const match of body.matchAll(LOCAL_IMAGE_LINK)) {
|
|
399
|
+
const path = match[2];
|
|
400
|
+
if (path.startsWith("/api/")) continue;
|
|
401
|
+
if (!mimetypeOf(path)) continue;
|
|
402
|
+
if (!paths2.includes(path)) paths2.push(path);
|
|
403
|
+
}
|
|
404
|
+
return paths2;
|
|
405
|
+
}
|
|
406
|
+
async function uploadOne(path) {
|
|
407
|
+
const mimetype = mimetypeOf(path);
|
|
408
|
+
if (!mimetype) return null;
|
|
409
|
+
try {
|
|
410
|
+
const info = await stat(path);
|
|
411
|
+
if (!info.isFile()) return null;
|
|
412
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
413
|
+
console.error(`[attachment-uploader] ${path} is ${info.size} bytes, over the ${MAX_FILE_BYTES} limit`);
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
const key = `${SCRATCH_PREFIX}/${getProfile()}/${randomUUID()}-${sanitizeFilename(basename2(path))}`;
|
|
417
|
+
await getR2Client().send(
|
|
418
|
+
new PutObjectCommand({
|
|
419
|
+
Bucket: getR2Bucket(),
|
|
420
|
+
Key: key,
|
|
421
|
+
Body: await readFile(path),
|
|
422
|
+
ContentType: mimetype
|
|
423
|
+
})
|
|
424
|
+
);
|
|
425
|
+
if (debug) console.log(`[attachment-uploader] ${path} -> ${key} (${info.size} bytes)`);
|
|
426
|
+
return `/api/attachments/${encodeKeyForUrl(key)}`;
|
|
427
|
+
} catch (err) {
|
|
428
|
+
console.error(`[attachment-uploader] failed to upload ${path}:`, err.message);
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async function uploadLocalImages(rawBody) {
|
|
433
|
+
const body = expandScratchDirVar(rawBody);
|
|
434
|
+
const localPaths = extractLocalImagePaths(body);
|
|
435
|
+
if (localPaths.length === 0) return body;
|
|
436
|
+
const urls = /* @__PURE__ */ new Map();
|
|
437
|
+
await Promise.all(
|
|
438
|
+
localPaths.map(async (path) => {
|
|
439
|
+
const url = await uploadOne(path);
|
|
440
|
+
if (url) urls.set(path, url);
|
|
441
|
+
})
|
|
442
|
+
);
|
|
443
|
+
if (urls.size === 0) return body;
|
|
444
|
+
return body.replace(LOCAL_IMAGE_LINK, (original, alt, path) => {
|
|
445
|
+
const url = urls.get(path);
|
|
446
|
+
return url ? `` : original;
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// src/store/session-store.ts
|
|
451
|
+
import Database from "better-sqlite3";
|
|
452
|
+
var SessionStore = class {
|
|
453
|
+
db;
|
|
454
|
+
constructor(dbPath) {
|
|
455
|
+
this.db = new Database(dbPath);
|
|
456
|
+
this.db.pragma("journal_mode = WAL");
|
|
457
|
+
this.init();
|
|
458
|
+
}
|
|
459
|
+
init() {
|
|
460
|
+
this.db.exec(`
|
|
461
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
462
|
+
channel_id TEXT NOT NULL,
|
|
463
|
+
thread_ts TEXT NOT NULL,
|
|
464
|
+
session_id TEXT NOT NULL,
|
|
465
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
466
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
467
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
468
|
+
)
|
|
469
|
+
`);
|
|
470
|
+
const sessionColumns = this.db.prepare("PRAGMA table_info(sessions)").all();
|
|
471
|
+
if (!sessionColumns.some((c) => c.name === "runner")) {
|
|
472
|
+
this.db.exec(`ALTER TABLE sessions ADD COLUMN runner TEXT NOT NULL DEFAULT 'claude'`);
|
|
473
|
+
}
|
|
474
|
+
this.db.exec(`DELETE FROM sessions WHERE runner = 'opencode'`);
|
|
475
|
+
this.db.exec(`
|
|
476
|
+
CREATE TABLE IF NOT EXISTS model_overrides (
|
|
477
|
+
channel_id TEXT NOT NULL,
|
|
478
|
+
thread_ts TEXT NOT NULL,
|
|
479
|
+
model TEXT NOT NULL,
|
|
480
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
481
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
482
|
+
)
|
|
483
|
+
`);
|
|
484
|
+
this.db.exec(`
|
|
485
|
+
CREATE TABLE IF NOT EXISTS effort_overrides (
|
|
486
|
+
channel_id TEXT NOT NULL,
|
|
487
|
+
thread_ts TEXT NOT NULL,
|
|
488
|
+
effort TEXT NOT NULL,
|
|
489
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
490
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
491
|
+
)
|
|
492
|
+
`);
|
|
493
|
+
}
|
|
494
|
+
getSession(channelId, threadTs) {
|
|
495
|
+
const row = this.db.prepare("SELECT * FROM sessions WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
496
|
+
if (!row) return void 0;
|
|
497
|
+
return {
|
|
498
|
+
channelId: row.channel_id,
|
|
499
|
+
threadTs: row.thread_ts,
|
|
500
|
+
sessionId: row.session_id,
|
|
501
|
+
runner: row.runner === "codex" ? "codex" : "claude",
|
|
502
|
+
createdAt: row.created_at,
|
|
503
|
+
updatedAt: row.updated_at
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
saveSession(channelId, threadTs, sessionId, runner = "claude") {
|
|
507
|
+
this.db.prepare(
|
|
508
|
+
`INSERT INTO sessions (channel_id, thread_ts, session_id, runner)
|
|
509
|
+
VALUES (?, ?, ?, ?)
|
|
510
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
511
|
+
DO UPDATE SET session_id = excluded.session_id, runner = excluded.runner, updated_at = datetime('now')`
|
|
512
|
+
).run(channelId, threadTs, sessionId, runner);
|
|
513
|
+
}
|
|
514
|
+
/** All sessions, newest activity first. Read-only listing for the dashboard. */
|
|
515
|
+
listSessions() {
|
|
516
|
+
const rows = this.db.prepare("SELECT * FROM sessions ORDER BY updated_at DESC").all();
|
|
517
|
+
return rows.map((row) => ({
|
|
518
|
+
channelId: row.channel_id,
|
|
519
|
+
threadTs: row.thread_ts,
|
|
520
|
+
sessionId: row.session_id,
|
|
521
|
+
runner: row.runner === "codex" ? "codex" : "claude",
|
|
522
|
+
createdAt: row.created_at,
|
|
523
|
+
updatedAt: row.updated_at
|
|
524
|
+
}));
|
|
525
|
+
}
|
|
526
|
+
deleteSession(channelId, threadTs) {
|
|
527
|
+
this.db.prepare("DELETE FROM sessions WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Drop every session in a channel. Used when the channel's execution runtime
|
|
531
|
+
* changes (`channels.runtime`, 0035): the session ids here point at Claude
|
|
532
|
+
* session files stored under whichever runtime wrote them — the host's
|
|
533
|
+
* CLAUDE_CONFIG_DIR, or the container's own per-channel home — so after a
|
|
534
|
+
* switch every one of them resolves to a file the new runtime cannot see.
|
|
535
|
+
* Left in place, the next turn in each thread would `--resume` an id that
|
|
536
|
+
* does not exist there and lose the conversation in a confusing way; dropping
|
|
537
|
+
* them makes the next turn cleanly start fresh instead.
|
|
538
|
+
*
|
|
539
|
+
* Returns how many were removed, so the caller can log something meaningful.
|
|
540
|
+
*/
|
|
541
|
+
deleteSessionsForChannel(channelId) {
|
|
542
|
+
const result = this.db.prepare("DELETE FROM sessions WHERE channel_id = ?").run(channelId);
|
|
543
|
+
return result.changes;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Re-key a single thread's rows onto a different channel. `sessions`,
|
|
547
|
+
* `model_overrides` and `effort_overrides` are all keyed by (channel_id,
|
|
548
|
+
* thread_ts), so moving a thread in the dashboard without this leaves the
|
|
549
|
+
* agent unable to find its own session: the next turn would start from
|
|
550
|
+
* scratch and lose the conversation, and any `!model`/`!effort` override on
|
|
551
|
+
* the thread would silently revert.
|
|
552
|
+
*
|
|
553
|
+
* A row already sitting on the destination key wins — that means the thread
|
|
554
|
+
* has been moved back and forth and the destination row is the newer state,
|
|
555
|
+
* so the stale source row is dropped rather than overwriting it.
|
|
556
|
+
*
|
|
557
|
+
* Returns how many rows were re-keyed in each table.
|
|
558
|
+
*/
|
|
559
|
+
moveThread(fromChannelId, toChannelId, threadTs) {
|
|
560
|
+
const move = this.db.transaction(() => {
|
|
561
|
+
const counts = { sessions: 0, modelOverrides: 0, effortOverrides: 0 };
|
|
562
|
+
for (const table of ["sessions", "model_overrides", "effort_overrides"]) {
|
|
563
|
+
const updated = this.db.prepare(
|
|
564
|
+
`UPDATE OR IGNORE ${table} SET channel_id = ?
|
|
565
|
+
WHERE channel_id = ? AND thread_ts = ?`
|
|
566
|
+
).run(toChannelId, fromChannelId, threadTs);
|
|
567
|
+
this.db.prepare(`DELETE FROM ${table} WHERE channel_id = ? AND thread_ts = ?`).run(fromChannelId, threadTs);
|
|
568
|
+
if (table === "sessions") counts.sessions = updated.changes;
|
|
569
|
+
else if (table === "model_overrides") counts.modelOverrides = updated.changes;
|
|
570
|
+
else counts.effortOverrides = updated.changes;
|
|
571
|
+
}
|
|
572
|
+
return counts;
|
|
573
|
+
});
|
|
574
|
+
return move();
|
|
575
|
+
}
|
|
576
|
+
getModelOverride(channelId, threadTs) {
|
|
577
|
+
const row = this.db.prepare("SELECT model FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
578
|
+
return row?.model;
|
|
579
|
+
}
|
|
580
|
+
setModelOverride(channelId, threadTs, model) {
|
|
581
|
+
this.db.prepare(
|
|
582
|
+
`INSERT INTO model_overrides (channel_id, thread_ts, model)
|
|
583
|
+
VALUES (?, ?, ?)
|
|
584
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
585
|
+
DO UPDATE SET model = excluded.model, updated_at = datetime('now')`
|
|
586
|
+
).run(channelId, threadTs, model);
|
|
587
|
+
}
|
|
588
|
+
clearModelOverride(channelId, threadTs) {
|
|
589
|
+
this.db.prepare("DELETE FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
590
|
+
}
|
|
591
|
+
getEffortOverride(channelId, threadTs) {
|
|
592
|
+
const row = this.db.prepare("SELECT effort FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
593
|
+
return row?.effort && isEffort(row.effort) ? row.effort : void 0;
|
|
594
|
+
}
|
|
595
|
+
setEffortOverride(channelId, threadTs, effort) {
|
|
596
|
+
this.db.prepare(
|
|
597
|
+
`INSERT INTO effort_overrides (channel_id, thread_ts, effort)
|
|
598
|
+
VALUES (?, ?, ?)
|
|
599
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
600
|
+
DO UPDATE SET effort = excluded.effort, updated_at = datetime('now')`
|
|
601
|
+
).run(channelId, threadTs, effort);
|
|
602
|
+
}
|
|
603
|
+
clearEffortOverride(channelId, threadTs) {
|
|
604
|
+
this.db.prepare("DELETE FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
605
|
+
}
|
|
606
|
+
close() {
|
|
607
|
+
this.db.close();
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
// src/auth/device-auth.ts
|
|
612
|
+
import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "crypto";
|
|
613
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, writeFileSync } from "fs";
|
|
614
|
+
import { dirname, join as join2 } from "path";
|
|
615
|
+
var DEFAULT_API_URL = "https://app.flyspace.ai";
|
|
616
|
+
var EXPIRY_SKEW_MS = 6e4;
|
|
617
|
+
var AuthApiError = class extends Error {
|
|
618
|
+
constructor(message, status) {
|
|
619
|
+
super(message);
|
|
620
|
+
this.status = status;
|
|
621
|
+
this.name = "AuthApiError";
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
function apiUrl() {
|
|
625
|
+
return (process.env["FLYSPACE_API_URL"] || DEFAULT_API_URL).replace(/\/+$/, "");
|
|
626
|
+
}
|
|
627
|
+
function deviceKeyPath() {
|
|
628
|
+
return join2(paths.BASE_CONFIG_DIR, "device.key");
|
|
629
|
+
}
|
|
630
|
+
function credentialsPath() {
|
|
631
|
+
return join2(paths.BASE_CONFIG_DIR, "credentials.json");
|
|
632
|
+
}
|
|
633
|
+
function ensureDeviceKey(path = deviceKeyPath()) {
|
|
634
|
+
let created = false;
|
|
635
|
+
if (!existsSync3(path)) {
|
|
636
|
+
const { privateKey: privateKey2 } = generateKeyPairSync("ed25519");
|
|
637
|
+
mkdirSync2(dirname(path), { recursive: true });
|
|
638
|
+
writeFileSync(path, privateKey2.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
|
|
639
|
+
created = true;
|
|
640
|
+
}
|
|
641
|
+
const privateKey = createPrivateKey(readFileSync(path, "utf8"));
|
|
642
|
+
const publicKeyBase64 = createPublicKey(privateKey).export({ type: "spki", format: "der" }).toString(
|
|
643
|
+
"base64"
|
|
644
|
+
);
|
|
645
|
+
return { privateKey, publicKeyBase64, created };
|
|
646
|
+
}
|
|
647
|
+
function loadCredentials(path = credentialsPath()) {
|
|
648
|
+
if (!existsSync3(path)) return null;
|
|
649
|
+
try {
|
|
650
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
651
|
+
} catch {
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function saveCredentials(creds, path = credentialsPath()) {
|
|
656
|
+
mkdirSync2(dirname(path), { recursive: true });
|
|
657
|
+
writeFileSync(path, `${JSON.stringify(creds, null, 2)}
|
|
658
|
+
`, { mode: 384 });
|
|
659
|
+
}
|
|
660
|
+
function clearLocalAuth() {
|
|
661
|
+
rmSync2(credentialsPath(), { force: true });
|
|
662
|
+
rmSync2(deviceKeyPath(), { force: true });
|
|
663
|
+
}
|
|
664
|
+
async function post(base, path, body, token) {
|
|
665
|
+
return fetch(`${base}${path}`, {
|
|
666
|
+
method: "POST",
|
|
667
|
+
headers: {
|
|
668
|
+
"content-type": "application/json",
|
|
669
|
+
...token ? { authorization: `Bearer ${token}` } : {}
|
|
670
|
+
},
|
|
671
|
+
body: JSON.stringify(body)
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
async function readJson(res) {
|
|
675
|
+
try {
|
|
676
|
+
return await res.json();
|
|
677
|
+
} catch {
|
|
678
|
+
return {};
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
async function expectOk(res, what) {
|
|
682
|
+
const json = await readJson(res);
|
|
683
|
+
if (!res.ok) {
|
|
684
|
+
const reason = typeof json["error"] === "string" ? json["error"] : res.statusText;
|
|
685
|
+
throw new AuthApiError(`${what} failed (${res.status}): ${reason}`, res.status);
|
|
686
|
+
}
|
|
687
|
+
return json;
|
|
688
|
+
}
|
|
689
|
+
function toSlugs(value) {
|
|
690
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
691
|
+
}
|
|
692
|
+
function toGrant(json) {
|
|
693
|
+
const user = json["user"] ?? {};
|
|
694
|
+
return {
|
|
695
|
+
accessToken: String(json["access_token"]),
|
|
696
|
+
expiresIn: Number(json["expires_in"]),
|
|
697
|
+
deviceId: String(json["device_id"]),
|
|
698
|
+
userEmail: String(user["email"] ?? ""),
|
|
699
|
+
workspaces: toSlugs(json["workspaces"])
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
async function requestDeviceCode(base, input) {
|
|
703
|
+
const res = await post(base, "/api/auth/device/code", {
|
|
704
|
+
public_key: input.publicKey,
|
|
705
|
+
name: input.name,
|
|
706
|
+
platform: input.platform
|
|
707
|
+
});
|
|
708
|
+
const json = await expectOk(res, "Requesting a device code");
|
|
709
|
+
return {
|
|
710
|
+
deviceCode: String(json["device_code"]),
|
|
711
|
+
userCode: String(json["user_code"]),
|
|
712
|
+
verificationUri: String(json["verification_uri"]),
|
|
713
|
+
expiresIn: Number(json["expires_in"]),
|
|
714
|
+
interval: Number(json["interval"] ?? 5)
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
async function pollDeviceToken(base, deviceCode) {
|
|
718
|
+
const res = await post(base, "/api/auth/device/token", { device_code: deviceCode });
|
|
719
|
+
const json = await readJson(res);
|
|
720
|
+
if (res.ok) return { status: "approved", grant: toGrant(json) };
|
|
721
|
+
switch (json["error"]) {
|
|
722
|
+
case "authorization_pending":
|
|
723
|
+
return { status: "pending" };
|
|
724
|
+
case "slow_down":
|
|
725
|
+
return { status: "slow_down" };
|
|
726
|
+
case "access_denied":
|
|
727
|
+
return { status: "denied" };
|
|
728
|
+
case "expired_token":
|
|
729
|
+
return { status: "expired" };
|
|
730
|
+
default:
|
|
731
|
+
throw new AuthApiError(`Polling for approval failed (${res.status}): ${String(json["error"] ?? res.statusText)}`, res.status);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
async function refreshAccessToken(creds, privateKey) {
|
|
735
|
+
const challenge = await expectOk(
|
|
736
|
+
await post(creds.apiUrl, "/api/auth/device/challenge", { device_id: creds.deviceId }),
|
|
737
|
+
"Requesting a refresh challenge"
|
|
738
|
+
);
|
|
739
|
+
const nonce = String(challenge["nonce"]);
|
|
740
|
+
const signature = sign(null, Buffer.from(nonce), privateKey).toString("base64");
|
|
741
|
+
const json = await expectOk(
|
|
742
|
+
await post(creds.apiUrl, "/api/auth/device/refresh", { device_id: creds.deviceId, nonce, signature }),
|
|
743
|
+
"Refreshing the access token"
|
|
744
|
+
);
|
|
745
|
+
return {
|
|
746
|
+
...creds,
|
|
747
|
+
accessToken: String(json["access_token"]),
|
|
748
|
+
accessTokenExpiresAt: Date.now() + Number(json["expires_in"]) * 1e3
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
async function fetchWhoAmI(base, token) {
|
|
752
|
+
const res = await fetch(`${base}/api/auth/device/me`, { headers: { authorization: `Bearer ${token}` } });
|
|
753
|
+
const json = await expectOk(res, "Checking the session");
|
|
754
|
+
const user = json["user"] ?? {};
|
|
755
|
+
const device = json["device"] ?? {};
|
|
756
|
+
return {
|
|
757
|
+
userEmail: String(user["email"] ?? ""),
|
|
758
|
+
deviceId: String(device["id"] ?? ""),
|
|
759
|
+
deviceName: String(device["name"] ?? ""),
|
|
760
|
+
workspaces: toSlugs(json["workspaces"])
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
async function boundWorkspaces() {
|
|
764
|
+
const creds = loadCredentials();
|
|
765
|
+
if (!creds) return null;
|
|
766
|
+
try {
|
|
767
|
+
const me = await fetchWhoAmI(creds.apiUrl, await getAccessToken());
|
|
768
|
+
saveCredentials({ ...loadCredentials() ?? creds, workspaces: me.workspaces });
|
|
769
|
+
return { workspaces: me.workspaces, fresh: true };
|
|
770
|
+
} catch {
|
|
771
|
+
return { workspaces: creds.workspaces ?? [], fresh: false };
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
async function revokeDevice(base, token) {
|
|
775
|
+
await expectOk(await post(base, "/api/auth/device/revoke", {}, token), "Revoking this device");
|
|
776
|
+
}
|
|
777
|
+
async function getAccessToken() {
|
|
778
|
+
const fromEnv = process.env["FLYSPACE_TOKEN"];
|
|
779
|
+
if (fromEnv) return fromEnv;
|
|
780
|
+
const creds = loadCredentials();
|
|
781
|
+
if (!creds) return null;
|
|
782
|
+
if (creds.accessTokenExpiresAt - EXPIRY_SKEW_MS > Date.now()) return creds.accessToken;
|
|
783
|
+
const { privateKey } = ensureDeviceKey();
|
|
784
|
+
const refreshed = await refreshAccessToken(creds, privateKey);
|
|
785
|
+
saveCredentials(refreshed);
|
|
786
|
+
return refreshed.accessToken;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// src/dashboard/host-lock.ts
|
|
790
|
+
import { execFileSync } from "child_process";
|
|
791
|
+
import { randomBytes } from "crypto";
|
|
792
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
793
|
+
import { join as join3 } from "path";
|
|
794
|
+
function hostLockPath() {
|
|
795
|
+
return join3(paths.BASE_DATA_DIR, "host.lock");
|
|
796
|
+
}
|
|
797
|
+
function isLiveFlyspace(pid) {
|
|
798
|
+
try {
|
|
799
|
+
process.kill(pid, 0);
|
|
800
|
+
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
|
|
801
|
+
encoding: "utf8"
|
|
802
|
+
});
|
|
803
|
+
return command.includes("flyspace") || command.includes("host-server");
|
|
804
|
+
} catch {
|
|
805
|
+
return false;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function readLockPid(path) {
|
|
809
|
+
try {
|
|
810
|
+
const pid = Number(JSON.parse(readFileSync2(path, "utf8")).pid);
|
|
811
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
812
|
+
} catch {
|
|
813
|
+
return null;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function acquireHostLock() {
|
|
817
|
+
const path = hostLockPath();
|
|
818
|
+
mkdirSync3(paths.BASE_DATA_DIR, { recursive: true });
|
|
819
|
+
const body = JSON.stringify({
|
|
820
|
+
pid: process.pid,
|
|
821
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
822
|
+
execPath: process.argv[1] ?? ""
|
|
823
|
+
});
|
|
824
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
825
|
+
try {
|
|
826
|
+
writeFileSync2(path, body, { flag: "wx", mode: 384 });
|
|
827
|
+
const release = () => {
|
|
828
|
+
if (readLockPid(path) === process.pid) rmSync3(path, { force: true });
|
|
829
|
+
};
|
|
830
|
+
process.once("exit", release);
|
|
831
|
+
return release;
|
|
832
|
+
} catch (err) {
|
|
833
|
+
if (err.code !== "EEXIST") throw err;
|
|
834
|
+
const holder = readLockPid(path);
|
|
835
|
+
if (holder === process.pid) return () => {
|
|
836
|
+
};
|
|
837
|
+
if (holder && isLiveFlyspace(holder)) {
|
|
838
|
+
throw new Error(
|
|
839
|
+
`Another Flyspace Host is already running on this machine (pid ${holder}). Stop it first, or check for a second CLI install (\`which -a flyspace\`). Two Hosts overwrite each other's skill mirror.`
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
rmSync3(path, { force: true });
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
throw new Error(`Could not take the Host lock at ${path}`);
|
|
846
|
+
}
|
|
847
|
+
function publishHostEndpoint(port) {
|
|
848
|
+
const path = hostLockPath();
|
|
849
|
+
if (readLockPid(path) !== process.pid) return null;
|
|
850
|
+
const token = randomBytes(32).toString("hex");
|
|
851
|
+
const lock = JSON.parse(readFileSync2(path, "utf8"));
|
|
852
|
+
writeFileSync2(path, JSON.stringify({ ...lock, port, token }), { mode: 384 });
|
|
853
|
+
return token;
|
|
854
|
+
}
|
|
855
|
+
function readHostEndpoint() {
|
|
856
|
+
try {
|
|
857
|
+
const { pid, port, token } = JSON.parse(readFileSync2(hostLockPath(), "utf8"));
|
|
858
|
+
if (pid === process.pid || !Number.isInteger(port) || typeof token !== "string") return null;
|
|
859
|
+
return { port, token };
|
|
860
|
+
} catch {
|
|
861
|
+
return null;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// src/dashboard/host-db-client.ts
|
|
866
|
+
import { createClient } from "@supabase/supabase-js";
|
|
867
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
868
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
869
|
+
var pending = /* @__PURE__ */ new Map();
|
|
870
|
+
var sender = null;
|
|
871
|
+
var onSender = [];
|
|
872
|
+
function setHostDbSender(fn) {
|
|
873
|
+
sender = fn;
|
|
874
|
+
if (!fn) return;
|
|
875
|
+
const waiting = onSender;
|
|
876
|
+
onSender = [];
|
|
877
|
+
for (const wake of waiting) wake();
|
|
878
|
+
}
|
|
879
|
+
function sendAgentFailure(report) {
|
|
880
|
+
sender?.({ type: "agent-failure", ...report });
|
|
881
|
+
}
|
|
882
|
+
function handleHostDbResult(id, res) {
|
|
883
|
+
const p = pending.get(id);
|
|
884
|
+
if (!p) return;
|
|
885
|
+
pending.delete(id);
|
|
886
|
+
clearTimeout(p.timer);
|
|
887
|
+
p.resolve(res);
|
|
888
|
+
}
|
|
889
|
+
function whenConnected() {
|
|
890
|
+
if (sender) return Promise.resolve(sender);
|
|
891
|
+
return new Promise((resolve3, reject) => {
|
|
892
|
+
const timer = setTimeout(() => {
|
|
893
|
+
onSender = onSender.filter((w) => w !== wake);
|
|
894
|
+
reject(new Error("Host is not connected to the Data API"));
|
|
895
|
+
}, REQUEST_TIMEOUT_MS);
|
|
896
|
+
const wake = () => {
|
|
897
|
+
clearTimeout(timer);
|
|
898
|
+
resolve3(sender);
|
|
899
|
+
};
|
|
900
|
+
onSender.push(wake);
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
async function requestHostDb(req) {
|
|
904
|
+
const send = await whenConnected();
|
|
905
|
+
const id = randomUUID2();
|
|
906
|
+
return new Promise((resolve3, reject) => {
|
|
907
|
+
const timer = setTimeout(() => {
|
|
908
|
+
pending.delete(id);
|
|
909
|
+
reject(new Error("Data API did not answer in time"));
|
|
910
|
+
}, REQUEST_TIMEOUT_MS);
|
|
911
|
+
pending.set(id, { resolve: resolve3, reject, timer });
|
|
912
|
+
send({ type: "db", id, req });
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
var pendingUrls = /* @__PURE__ */ new Map();
|
|
916
|
+
function handleAttachmentUrlResult(id, url) {
|
|
917
|
+
pendingUrls.get(id)?.(url);
|
|
918
|
+
pendingUrls.delete(id);
|
|
919
|
+
}
|
|
920
|
+
async function requestAttachmentUrl(key) {
|
|
921
|
+
const send = await whenConnected();
|
|
922
|
+
const id = randomUUID2();
|
|
923
|
+
return new Promise((resolve3, reject) => {
|
|
924
|
+
const timer = setTimeout(() => {
|
|
925
|
+
pendingUrls.delete(id);
|
|
926
|
+
reject(new Error("Data API did not answer in time"));
|
|
927
|
+
}, REQUEST_TIMEOUT_MS);
|
|
928
|
+
pendingUrls.set(id, (url) => {
|
|
929
|
+
clearTimeout(timer);
|
|
930
|
+
resolve3(url);
|
|
931
|
+
});
|
|
932
|
+
send({ type: "attachment-url", id, key });
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
var pendingSvgs = /* @__PURE__ */ new Map();
|
|
936
|
+
function handlePluginSvgResult(id, url) {
|
|
937
|
+
pendingSvgs.get(id)?.(url);
|
|
938
|
+
pendingSvgs.delete(id);
|
|
939
|
+
}
|
|
940
|
+
async function requestPluginSvg(workspace, svg) {
|
|
941
|
+
const send = await whenConnected();
|
|
942
|
+
const id = randomUUID2();
|
|
943
|
+
return new Promise((resolve3, reject) => {
|
|
944
|
+
const timer = setTimeout(() => {
|
|
945
|
+
pendingSvgs.delete(id);
|
|
946
|
+
reject(new Error("Data API did not answer in time"));
|
|
947
|
+
}, REQUEST_TIMEOUT_MS);
|
|
948
|
+
pendingSvgs.set(id, (url) => {
|
|
949
|
+
clearTimeout(timer);
|
|
950
|
+
resolve3(url);
|
|
951
|
+
});
|
|
952
|
+
send({ type: "plugin-svg", id, workspace, svg });
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
var ACTION_TIMEOUT_MS = 15e4;
|
|
956
|
+
var pendingActions = /* @__PURE__ */ new Map();
|
|
957
|
+
function handleActionResult(id, res) {
|
|
958
|
+
pendingActions.get(id)?.(res);
|
|
959
|
+
pendingActions.delete(id);
|
|
960
|
+
}
|
|
961
|
+
async function requestAction(name, input, requester) {
|
|
962
|
+
const send = await whenConnected();
|
|
963
|
+
const id = randomUUID2();
|
|
964
|
+
return new Promise((resolve3) => {
|
|
965
|
+
const timer = setTimeout(() => {
|
|
966
|
+
pendingActions.delete(id);
|
|
967
|
+
resolve3({ error: "Data API did not answer in time" });
|
|
968
|
+
}, ACTION_TIMEOUT_MS);
|
|
969
|
+
pendingActions.set(id, (res) => {
|
|
970
|
+
clearTimeout(timer);
|
|
971
|
+
resolve3(res);
|
|
972
|
+
});
|
|
973
|
+
send({ type: "action", id, name, input, ...requester ? { requester } : {} });
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
var LOCAL_ACTION_PATH = "/internal/action";
|
|
977
|
+
var pendingRespond = /* @__PURE__ */ new Map();
|
|
978
|
+
function handleShouldRespondResult(id, respond) {
|
|
979
|
+
pendingRespond.get(id)?.(respond);
|
|
980
|
+
pendingRespond.delete(id);
|
|
981
|
+
}
|
|
982
|
+
async function requestShouldRespond(transcript) {
|
|
983
|
+
const send = await whenConnected().catch(() => null);
|
|
984
|
+
if (!send) return false;
|
|
985
|
+
const id = randomUUID2();
|
|
986
|
+
return new Promise((resolve3) => {
|
|
987
|
+
const timer = setTimeout(() => {
|
|
988
|
+
pendingRespond.delete(id);
|
|
989
|
+
resolve3(false);
|
|
990
|
+
}, REQUEST_TIMEOUT_MS);
|
|
991
|
+
pendingRespond.set(id, (respond) => {
|
|
992
|
+
clearTimeout(timer);
|
|
993
|
+
resolve3(respond);
|
|
994
|
+
});
|
|
995
|
+
send({ type: "should-respond", id, transcript });
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
var BODYLESS_STATUS = /* @__PURE__ */ new Set([101, 204, 205, 304]);
|
|
999
|
+
function dbFetch(send) {
|
|
1000
|
+
return async (input, init) => {
|
|
1001
|
+
const req = new Request(input, init);
|
|
1002
|
+
const url = new URL(req.url);
|
|
1003
|
+
const method = req.method.toUpperCase();
|
|
1004
|
+
const res = await send({
|
|
1005
|
+
method,
|
|
1006
|
+
path: `${url.pathname}${url.search}`,
|
|
1007
|
+
headers: Object.fromEntries(req.headers.entries()),
|
|
1008
|
+
body: method === "GET" || method === "HEAD" ? void 0 : await req.text()
|
|
1009
|
+
});
|
|
1010
|
+
const noBody = method === "HEAD" || BODYLESS_STATUS.has(res.status);
|
|
1011
|
+
return new Response(noBody ? null : res.body, { status: res.status, headers: res.headers });
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
var hostDbFetch = dbFetch(requestHostDb);
|
|
1015
|
+
var LOCAL_DB_PATH = "/internal/db";
|
|
1016
|
+
async function requestViaLocalHost(req) {
|
|
1017
|
+
const deadline = Date.now() + REQUEST_TIMEOUT_MS;
|
|
1018
|
+
let endpoint = readHostEndpoint();
|
|
1019
|
+
while (!endpoint && Date.now() < deadline) {
|
|
1020
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
1021
|
+
endpoint = readHostEndpoint();
|
|
1022
|
+
}
|
|
1023
|
+
if (!endpoint) throw new Error("No local Host to reach the Data API through");
|
|
1024
|
+
const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_DB_PATH}`, {
|
|
1025
|
+
method: "POST",
|
|
1026
|
+
headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
|
|
1027
|
+
body: JSON.stringify(req),
|
|
1028
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS + 5e3)
|
|
1029
|
+
});
|
|
1030
|
+
if (!res.ok) throw new Error(`Local Host DB relay answered ${res.status}`);
|
|
1031
|
+
return await res.json();
|
|
1032
|
+
}
|
|
1033
|
+
function relayChannel(topic) {
|
|
1034
|
+
const channel = {
|
|
1035
|
+
on: () => channel,
|
|
1036
|
+
subscribe: (callback) => {
|
|
1037
|
+
queueMicrotask(() => callback?.("SUBSCRIBED"));
|
|
1038
|
+
return channel;
|
|
1039
|
+
},
|
|
1040
|
+
send: async (msg) => {
|
|
1041
|
+
if (msg.type !== "broadcast" || !sender) return "error";
|
|
1042
|
+
sender({ type: "db-broadcast", topic, event: msg.event, payload: msg.payload ?? {} });
|
|
1043
|
+
return "ok";
|
|
1044
|
+
},
|
|
1045
|
+
unsubscribe: async () => "ok"
|
|
1046
|
+
};
|
|
1047
|
+
return channel;
|
|
1048
|
+
}
|
|
1049
|
+
function createHostDbClient(via = "socket") {
|
|
1050
|
+
const client3 = createClient("https://host-db.invalid", "host-device", {
|
|
1051
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
1052
|
+
global: { fetch: via === "socket" ? hostDbFetch : dbFetch(requestViaLocalHost) }
|
|
1053
|
+
});
|
|
1054
|
+
return new Proxy(client3, {
|
|
1055
|
+
get(target, prop) {
|
|
1056
|
+
if (prop === "channel") return relayChannel;
|
|
1057
|
+
if (prop === "removeChannel") return async () => "ok";
|
|
1058
|
+
const value = Reflect.get(target, prop, target);
|
|
1059
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// src/commands/supabase-via-host.ts
|
|
1065
|
+
function useHostDbWithoutCredentials() {
|
|
1066
|
+
const viaHost = !!loadCredentials() && (!hasSupabaseCredentials() || !!readHostEndpoint());
|
|
1067
|
+
if (viaHost) setSupabaseClient(createHostDbClient("local-host"));
|
|
1068
|
+
return viaHost;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
export {
|
|
1072
|
+
__require,
|
|
1073
|
+
__commonJS,
|
|
1074
|
+
__export,
|
|
1075
|
+
__toESM,
|
|
1076
|
+
setSupabaseClient,
|
|
1077
|
+
setSupabaseClientFactory,
|
|
1078
|
+
databaseReachable,
|
|
1079
|
+
getSupabaseClient,
|
|
1080
|
+
DEFAULT_PROFILE,
|
|
1081
|
+
runWithProfile,
|
|
1082
|
+
getProfile,
|
|
1083
|
+
paths,
|
|
1084
|
+
ensureDirs,
|
|
1085
|
+
sweepScratchDir,
|
|
1086
|
+
isEffort,
|
|
1087
|
+
resolveClaudeEffort,
|
|
1088
|
+
resolveCodexEffort,
|
|
1089
|
+
DEFAULT_CODEX_MODEL,
|
|
1090
|
+
mcpStrictConfigEnabled,
|
|
1091
|
+
loadEnvFiles,
|
|
1092
|
+
SLACK_ENV,
|
|
1093
|
+
slackConfigured,
|
|
1094
|
+
requireSlackBotToken,
|
|
1095
|
+
loadConfig,
|
|
1096
|
+
getR2Client,
|
|
1097
|
+
getR2Bucket,
|
|
1098
|
+
sumR2PrefixBytes,
|
|
1099
|
+
SCRATCH_PREFIX,
|
|
1100
|
+
uploadLocalImages,
|
|
1101
|
+
DEFAULT_API_URL,
|
|
1102
|
+
AuthApiError,
|
|
1103
|
+
apiUrl,
|
|
1104
|
+
deviceKeyPath,
|
|
1105
|
+
credentialsPath,
|
|
1106
|
+
ensureDeviceKey,
|
|
1107
|
+
loadCredentials,
|
|
1108
|
+
saveCredentials,
|
|
1109
|
+
clearLocalAuth,
|
|
1110
|
+
requestDeviceCode,
|
|
1111
|
+
pollDeviceToken,
|
|
1112
|
+
fetchWhoAmI,
|
|
1113
|
+
boundWorkspaces,
|
|
1114
|
+
revokeDevice,
|
|
1115
|
+
getAccessToken,
|
|
1116
|
+
acquireHostLock,
|
|
1117
|
+
publishHostEndpoint,
|
|
1118
|
+
readHostEndpoint,
|
|
1119
|
+
setHostDbSender,
|
|
1120
|
+
sendAgentFailure,
|
|
1121
|
+
handleHostDbResult,
|
|
1122
|
+
requestHostDb,
|
|
1123
|
+
handleAttachmentUrlResult,
|
|
1124
|
+
requestAttachmentUrl,
|
|
1125
|
+
handlePluginSvgResult,
|
|
1126
|
+
requestPluginSvg,
|
|
1127
|
+
handleActionResult,
|
|
1128
|
+
requestAction,
|
|
1129
|
+
LOCAL_ACTION_PATH,
|
|
1130
|
+
handleShouldRespondResult,
|
|
1131
|
+
requestShouldRespond,
|
|
1132
|
+
LOCAL_DB_PATH,
|
|
1133
|
+
createHostDbClient,
|
|
1134
|
+
useHostDbWithoutCredentials,
|
|
1135
|
+
SessionStore
|
|
1136
|
+
};
|