flyspace-cli 0.1.52 → 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-ZBOOJCDU.js → chunk-ZSRDP5HJ.js} +2072 -2167
- package/dist/cli.js +916 -564
- 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
|
@@ -0,0 +1,1243 @@
|
|
|
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/channels.ts
|
|
215
|
+
import { createHash } from "crypto";
|
|
216
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, realpathSync, statSync as statSync2 } from "fs";
|
|
217
|
+
import { homedir as homedir2 } from "os";
|
|
218
|
+
import { isAbsolute, relative, resolve as resolve2, sep } from "path";
|
|
219
|
+
|
|
220
|
+
// ../api/src/effort.ts
|
|
221
|
+
var EFFORT_LEVELS = ["low", "medium", "high", "max"];
|
|
222
|
+
function isEffort(value) {
|
|
223
|
+
return EFFORT_LEVELS.includes(value);
|
|
224
|
+
}
|
|
225
|
+
var CLAUDE_EFFORT = {
|
|
226
|
+
low: "low",
|
|
227
|
+
medium: "medium",
|
|
228
|
+
high: "xhigh",
|
|
229
|
+
max: "max"
|
|
230
|
+
};
|
|
231
|
+
function resolveClaudeEffort(effort) {
|
|
232
|
+
return CLAUDE_EFFORT[effort];
|
|
233
|
+
}
|
|
234
|
+
var CODEX_EFFORT = {
|
|
235
|
+
low: "low",
|
|
236
|
+
medium: "medium",
|
|
237
|
+
high: "high",
|
|
238
|
+
max: "high"
|
|
239
|
+
};
|
|
240
|
+
function resolveCodexEffort(effort) {
|
|
241
|
+
return CODEX_EFFORT[effort];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ../api/src/channels.ts
|
|
245
|
+
function isPermissionMode(value) {
|
|
246
|
+
return value === "bypass" || value === "ask";
|
|
247
|
+
}
|
|
248
|
+
function isLogicalCwd(p) {
|
|
249
|
+
return /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(p);
|
|
250
|
+
}
|
|
251
|
+
function logicalRoot() {
|
|
252
|
+
return process.env["FLYSPACE_ROOT"] || resolve2(homedir2(), "Flyspace");
|
|
253
|
+
}
|
|
254
|
+
var workspaceRoots = /* @__PURE__ */ new Map();
|
|
255
|
+
var workspacePermissionModes = /* @__PURE__ */ new Map();
|
|
256
|
+
var workspaceAutoContinueLimits = /* @__PURE__ */ new Map();
|
|
257
|
+
var DEFAULT_AUTO_CONTINUE_LIMIT = 3;
|
|
258
|
+
async function refreshWorkspaceAutoContinueLimits() {
|
|
259
|
+
const { data, error } = await getSupabaseClient().from("workspaces").select("slug, auto_continue_limit");
|
|
260
|
+
if (error) return;
|
|
261
|
+
workspaceAutoContinueLimits = new Map(
|
|
262
|
+
(data ?? []).filter((w) => typeof w.auto_continue_limit === "number").map((w) => [w.slug, w.auto_continue_limit])
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
function resolveAutoContinueLimit(channelId) {
|
|
266
|
+
const channel = channelId ? findChannel(channelId) : void 0;
|
|
267
|
+
return workspaceAutoContinueLimits.get(channel?.profile ?? getProfile()) ?? DEFAULT_AUTO_CONTINUE_LIMIT;
|
|
268
|
+
}
|
|
269
|
+
async function refreshWorkspacePermissionModes() {
|
|
270
|
+
const { data, error } = await getSupabaseClient().from("workspaces").select("slug, permission_mode");
|
|
271
|
+
if (error) return;
|
|
272
|
+
workspacePermissionModes = new Map(
|
|
273
|
+
(data ?? []).filter((w) => isPermissionMode(w.permission_mode)).map((w) => [w.slug, w.permission_mode])
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
async function refreshWorkspaceRoots() {
|
|
277
|
+
const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
|
|
278
|
+
if (error) return;
|
|
279
|
+
workspaceRoots = new Map(
|
|
280
|
+
(data ?? []).filter((w) => w.root_path).map((w) => [w.slug, expandPath(w.root_path)])
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
function resolveLogicalCwd(p) {
|
|
284
|
+
const [slug, name] = p.split("/");
|
|
285
|
+
const root = workspaceRoots.get(slug);
|
|
286
|
+
return root ? resolve2(root, name) : resolve2(logicalRoot(), p);
|
|
287
|
+
}
|
|
288
|
+
function isUnderLogicalRoot(cwd) {
|
|
289
|
+
return [logicalRoot(), ...workspaceRoots.values()].some((r) => cwd.startsWith(r + sep));
|
|
290
|
+
}
|
|
291
|
+
function toLogicalCwd(cwd) {
|
|
292
|
+
const fromRoot = relative(logicalRoot(), cwd).split(sep).join("/");
|
|
293
|
+
if (isLogicalCwd(fromRoot)) return fromRoot;
|
|
294
|
+
for (const [slug, root] of workspaceRoots) {
|
|
295
|
+
const name = relative(root, cwd);
|
|
296
|
+
if (isLogicalCwd(`${slug}/${name}`)) return `${slug}/${name}`;
|
|
297
|
+
}
|
|
298
|
+
return cwd;
|
|
299
|
+
}
|
|
300
|
+
function ensureLogicalCwdDir(cwd) {
|
|
301
|
+
if (!isUnderLogicalRoot(cwd) || existsSync2(cwd)) return;
|
|
302
|
+
mkdirSync2(cwd, { recursive: true });
|
|
303
|
+
}
|
|
304
|
+
function expandPath(p) {
|
|
305
|
+
let expanded = p;
|
|
306
|
+
if (expanded === "~") {
|
|
307
|
+
expanded = homedir2();
|
|
308
|
+
} else if (expanded.startsWith("~/")) {
|
|
309
|
+
expanded = resolve2(homedir2(), expanded.slice(2));
|
|
310
|
+
}
|
|
311
|
+
return isAbsolute(expanded) ? expanded : resolve2(expanded);
|
|
312
|
+
}
|
|
313
|
+
function normaliseMemberEmails(raw) {
|
|
314
|
+
if (!Array.isArray(raw)) return [];
|
|
315
|
+
const seen = /* @__PURE__ */ new Set();
|
|
316
|
+
for (const v of raw) {
|
|
317
|
+
if (typeof v !== "string") continue;
|
|
318
|
+
const email = v.trim().toLowerCase();
|
|
319
|
+
if (email) seen.add(email);
|
|
320
|
+
}
|
|
321
|
+
return [...seen];
|
|
322
|
+
}
|
|
323
|
+
function canSeeChannel(channel, viewer) {
|
|
324
|
+
if (channel.visibility === "public") return true;
|
|
325
|
+
if (viewer?.role === "admin" && !channel.dmKey) return true;
|
|
326
|
+
const email = viewer?.email?.trim().toLowerCase();
|
|
327
|
+
return !!email && channel.memberEmails.includes(email);
|
|
328
|
+
}
|
|
329
|
+
function rowToChannel(row) {
|
|
330
|
+
return {
|
|
331
|
+
id: row.id,
|
|
332
|
+
name: row.name,
|
|
333
|
+
categoryId: row.category_id,
|
|
334
|
+
cwd: isLogicalCwd(row.cwd) ? resolveLogicalCwd(row.cwd) : expandPath(row.cwd),
|
|
335
|
+
externalChannelId: row.external_channel_id,
|
|
336
|
+
model: row.model,
|
|
337
|
+
effort: row.effort && isEffort(row.effort) ? row.effort : null,
|
|
338
|
+
prompt: row.prompt?.trim() || null,
|
|
339
|
+
topicCategories: normaliseTopicCategories(row.topic_categories),
|
|
340
|
+
// A uuid[] arrives as a real array; anything else (an older row read
|
|
341
|
+
// through a cached client, a hand-edited value) reads as "no MCP", which
|
|
342
|
+
// is the safe direction for a list that decides which credentials a run
|
|
343
|
+
// can reach.
|
|
344
|
+
mcpConnections: Array.isArray(row.mcp_connections) ? row.mcp_connections.filter((id) => typeof id === "string") : [],
|
|
345
|
+
access: row.access ?? void 0,
|
|
346
|
+
visibility: row.visibility === "public" ? "public" : "private",
|
|
347
|
+
memberEmails: normaliseMemberEmails(row.member_emails),
|
|
348
|
+
// The CHECK constraint (0035, extended by 0070 for 'sandbox') means the
|
|
349
|
+
// stored value is always one of these three, so this narrowing is
|
|
350
|
+
// unreachable in practice and exists to satisfy the type. Note it cannot
|
|
351
|
+
// degrade *safely* the way `mcpConnections` does: an unreadable value here
|
|
352
|
+
// would drop a channel back to the unisolated runtime, which is why the
|
|
353
|
+
// constraint is the real guarantee and this is only a type-level
|
|
354
|
+
// fallback.
|
|
355
|
+
runtime: row.runtime === "container" ? "container" : row.runtime === "sandbox" ? "sandbox" : "host",
|
|
356
|
+
// Same shape and same defensive read as `mcpConnections`: anything that
|
|
357
|
+
// isn't a clean string array reads as "no mounts", which exposes less
|
|
358
|
+
// rather than more.
|
|
359
|
+
mounts: Array.isArray(row.mounts) ? row.mounts.filter((p) => typeof p === "string").map(expandPath) : [],
|
|
360
|
+
permissionMode: isPermissionMode(row.permission_mode) ? row.permission_mode : null,
|
|
361
|
+
position: row.position,
|
|
362
|
+
automations: row.automations ?? void 0,
|
|
363
|
+
agentName: row.agent_name,
|
|
364
|
+
dmKey: row.dm_key,
|
|
365
|
+
isDefault: row.is_default === true,
|
|
366
|
+
profile: row.profile,
|
|
367
|
+
archivedAt: row.archived_at,
|
|
368
|
+
greetedAt: row.greeted_at,
|
|
369
|
+
createdAt: row.created_at,
|
|
370
|
+
updatedAt: row.updated_at
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
var registry = [];
|
|
374
|
+
var byId = /* @__PURE__ */ new Map();
|
|
375
|
+
var byExternalId = /* @__PURE__ */ new Map();
|
|
376
|
+
var changeListeners = /* @__PURE__ */ new Set();
|
|
377
|
+
var lastSnapshot;
|
|
378
|
+
function indexRegistry(list) {
|
|
379
|
+
registry = list;
|
|
380
|
+
byId = new Map(list.map((c) => [c.id, c]));
|
|
381
|
+
byExternalId = new Map(
|
|
382
|
+
list.filter((c) => !!c.externalChannelId).map((c) => [c.externalChannelId, c])
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
async function refreshChannelRegistry() {
|
|
386
|
+
const rootsBefore = JSON.stringify([...workspaceRoots]);
|
|
387
|
+
await Promise.all([
|
|
388
|
+
refreshWorkspaceRoots(),
|
|
389
|
+
refreshWorkspacePermissionModes(),
|
|
390
|
+
refreshWorkspaceAutoContinueLimits()
|
|
391
|
+
]);
|
|
392
|
+
if (JSON.stringify([...workspaceRoots]) !== rootsBefore) lastSnapshot = void 0;
|
|
393
|
+
const { data, error } = await getSupabaseClient().from("channels").select("*").order("position", { ascending: true });
|
|
394
|
+
if (error) {
|
|
395
|
+
console.error("[channels] refreshChannelRegistry failed:", error.message);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const rows = data ?? [];
|
|
399
|
+
const snapshot = JSON.stringify(
|
|
400
|
+
rows,
|
|
401
|
+
(key, value) => key === "updated_at" || key === "created_at" ? void 0 : value
|
|
402
|
+
);
|
|
403
|
+
if (snapshot === lastSnapshot) return;
|
|
404
|
+
lastSnapshot = snapshot;
|
|
405
|
+
indexRegistry(rows.map(rowToChannel));
|
|
406
|
+
for (const cb of changeListeners) {
|
|
407
|
+
try {
|
|
408
|
+
cb();
|
|
409
|
+
} catch (err) {
|
|
410
|
+
console.error("[channels] onChannelRegistryChange listener failed:", err);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function getChannelRegistry() {
|
|
415
|
+
return registry;
|
|
416
|
+
}
|
|
417
|
+
function getProfileChannelRegistry() {
|
|
418
|
+
const profile = getProfile();
|
|
419
|
+
return registry.filter((ch) => ch.profile === profile);
|
|
420
|
+
}
|
|
421
|
+
function onChannelRegistryChange(cb) {
|
|
422
|
+
changeListeners.add(cb);
|
|
423
|
+
return () => changeListeners.delete(cb);
|
|
424
|
+
}
|
|
425
|
+
function findChannelById(id) {
|
|
426
|
+
return byId.get(id);
|
|
427
|
+
}
|
|
428
|
+
function findChannelByExternalId(externalId) {
|
|
429
|
+
return byExternalId.get(externalId);
|
|
430
|
+
}
|
|
431
|
+
function agentDmKey(agentName, userId) {
|
|
432
|
+
return `agent:${agentName}:${userId}`;
|
|
433
|
+
}
|
|
434
|
+
function dmCwd(dmKey, profile = getProfile()) {
|
|
435
|
+
return `${profile}/dm-${createHash("sha256").update(dmKey).digest("hex").slice(0, 24)}`;
|
|
436
|
+
}
|
|
437
|
+
function findChannelByAgentName(agentName, userId) {
|
|
438
|
+
const dmKey = agentDmKey(agentName, userId);
|
|
439
|
+
return getProfileChannelRegistry().find((c) => c.agentName === agentName && c.dmKey === dmKey);
|
|
440
|
+
}
|
|
441
|
+
function findChannel(ref) {
|
|
442
|
+
if (!ref) return void 0;
|
|
443
|
+
return byId.get(ref) ?? byExternalId.get(ref) ?? registry.find((c) => c.name === ref || c.name === ref.replace(/^#/, ""));
|
|
444
|
+
}
|
|
445
|
+
var DEFAULT_POLL_INTERVAL_MS = 2e4;
|
|
446
|
+
var pollTimer;
|
|
447
|
+
var realtimeChannel;
|
|
448
|
+
function startChannelRegistryPolling(intervalMs = DEFAULT_POLL_INTERVAL_MS) {
|
|
449
|
+
stopChannelRegistryPolling();
|
|
450
|
+
pollTimer = setInterval(() => void refreshChannelRegistry(), intervalMs);
|
|
451
|
+
try {
|
|
452
|
+
realtimeChannel = getSupabaseClient().channel("channels-registry").on(
|
|
453
|
+
"postgres_changes",
|
|
454
|
+
{ event: "*", schema: "public", table: "channels" },
|
|
455
|
+
() => void refreshChannelRegistry()
|
|
456
|
+
).subscribe();
|
|
457
|
+
} catch (err) {
|
|
458
|
+
console.warn(
|
|
459
|
+
"[channels] realtime subscribe failed \u2014 falling back to polling only:",
|
|
460
|
+
err.message
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
return stopChannelRegistryPolling;
|
|
464
|
+
}
|
|
465
|
+
function stopChannelRegistryPolling() {
|
|
466
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
467
|
+
pollTimer = void 0;
|
|
468
|
+
if (realtimeChannel) {
|
|
469
|
+
void getSupabaseClient().removeChannel(realtimeChannel);
|
|
470
|
+
realtimeChannel = void 0;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function isCwdUsable(cwd) {
|
|
474
|
+
try {
|
|
475
|
+
return existsSync2(cwd) && statSync2(cwd).isDirectory();
|
|
476
|
+
} catch {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function auditChannelCwds(list = registry) {
|
|
481
|
+
return list.filter((ch) => ch.cwd && !isCwdUsable(ch.cwd));
|
|
482
|
+
}
|
|
483
|
+
function warnOnBrokenChannelCwds(list = registry) {
|
|
484
|
+
const broken = auditChannelCwds(list);
|
|
485
|
+
for (const ch of broken) {
|
|
486
|
+
console.warn(
|
|
487
|
+
`[channels] "${ch.name}" (${ch.id}): cwd "${ch.cwd}" does not exist \u2014 the agent will fall back to CLAUDE_CWD. Fix it in the channel's settings.`
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
return broken;
|
|
491
|
+
}
|
|
492
|
+
function resolveChannelCwd(channelId) {
|
|
493
|
+
if (!channelId) return void 0;
|
|
494
|
+
const entry = findChannel(channelId);
|
|
495
|
+
if (!entry?.cwd) return void 0;
|
|
496
|
+
if (!isCwdUsable(entry.cwd)) {
|
|
497
|
+
console.warn(
|
|
498
|
+
`[channels] ${channelId}: cwd "${entry.cwd}" does not exist \u2014 falling back to CLAUDE_CWD`
|
|
499
|
+
);
|
|
500
|
+
return void 0;
|
|
501
|
+
}
|
|
502
|
+
return entry.cwd;
|
|
503
|
+
}
|
|
504
|
+
function isChannelAccessAllowed(channelId, userId) {
|
|
505
|
+
if (!channelId) return false;
|
|
506
|
+
const access = findChannel(channelId)?.access;
|
|
507
|
+
if (!access) return false;
|
|
508
|
+
if (typeof access === "string") {
|
|
509
|
+
return access === "open" || access === "*" || access === "all";
|
|
510
|
+
}
|
|
511
|
+
return !!userId && access.includes(userId);
|
|
512
|
+
}
|
|
513
|
+
function resolveCwd(explicitCwd, channelId, fallback) {
|
|
514
|
+
if (explicitCwd) return explicitCwd;
|
|
515
|
+
return resolveChannelCwd(channelId) ?? fallback;
|
|
516
|
+
}
|
|
517
|
+
function resolveChannelModel(channelId) {
|
|
518
|
+
if (!channelId) return void 0;
|
|
519
|
+
return findChannel(channelId)?.model?.trim() || void 0;
|
|
520
|
+
}
|
|
521
|
+
function resolveChannelEffort(channelId) {
|
|
522
|
+
if (!channelId) return void 0;
|
|
523
|
+
return findChannel(channelId)?.effort ?? void 0;
|
|
524
|
+
}
|
|
525
|
+
function resolveChannelPermissionMode(channelId) {
|
|
526
|
+
const channel = channelId ? findChannel(channelId) : void 0;
|
|
527
|
+
return channel?.permissionMode ?? workspacePermissionModes.get(channel?.profile ?? getProfile()) ?? "bypass";
|
|
528
|
+
}
|
|
529
|
+
function resolveChannelPrompt(channelId) {
|
|
530
|
+
if (!channelId) return void 0;
|
|
531
|
+
return findChannel(channelId)?.prompt?.trim() || void 0;
|
|
532
|
+
}
|
|
533
|
+
function resolveModel(explicitModel, channelId, fallback) {
|
|
534
|
+
if (explicitModel?.trim()) return explicitModel.trim();
|
|
535
|
+
return resolveChannelModel(channelId) ?? fallback;
|
|
536
|
+
}
|
|
537
|
+
function resolveEffort(explicitEffort, channelId, fallback) {
|
|
538
|
+
if (explicitEffort) return explicitEffort;
|
|
539
|
+
return resolveChannelEffort(channelId) ?? fallback;
|
|
540
|
+
}
|
|
541
|
+
function normaliseTopicCategories(value) {
|
|
542
|
+
if (!Array.isArray(value)) return [];
|
|
543
|
+
const out = [];
|
|
544
|
+
for (const v of value) {
|
|
545
|
+
const t = typeof v === "string" ? v.trim() : "";
|
|
546
|
+
if (t && !out.includes(t)) out.push(t);
|
|
547
|
+
}
|
|
548
|
+
return out;
|
|
549
|
+
}
|
|
550
|
+
function toRow(input) {
|
|
551
|
+
const row = {};
|
|
552
|
+
if (input.name !== void 0) row["name"] = input.name;
|
|
553
|
+
if (input.cwd !== void 0) row["cwd"] = isLogicalCwd(input.cwd) ? input.cwd : toLogicalCwd(expandPath(input.cwd));
|
|
554
|
+
if (input.categoryId !== void 0) row["category_id"] = input.categoryId;
|
|
555
|
+
if (input.externalChannelId !== void 0) row["external_channel_id"] = input.externalChannelId;
|
|
556
|
+
if (input.model !== void 0) row["model"] = input.model;
|
|
557
|
+
if (input.effort !== void 0) row["effort"] = input.effort;
|
|
558
|
+
if (input.prompt !== void 0) row["prompt"] = input.prompt?.trim() || null;
|
|
559
|
+
if (input.topicCategories !== void 0) {
|
|
560
|
+
const list = normaliseTopicCategories(input.topicCategories);
|
|
561
|
+
row["topic_categories"] = list.length ? list : null;
|
|
562
|
+
}
|
|
563
|
+
if (input.access !== void 0) row["access"] = input.access;
|
|
564
|
+
if (input.visibility !== void 0) row["visibility"] = input.visibility;
|
|
565
|
+
if (input.memberEmails !== void 0) {
|
|
566
|
+
row["member_emails"] = normaliseMemberEmails(input.memberEmails);
|
|
567
|
+
}
|
|
568
|
+
if (input.runtime !== void 0) row["runtime"] = input.runtime;
|
|
569
|
+
if (input.mounts !== void 0) {
|
|
570
|
+
row["mounts"] = input.mounts.map((p) => p.trim()).filter(Boolean).map(expandPath);
|
|
571
|
+
}
|
|
572
|
+
if (input.permissionMode !== void 0) row["permission_mode"] = input.permissionMode;
|
|
573
|
+
if (input.position !== void 0) row["position"] = input.position;
|
|
574
|
+
if (input.automations !== void 0) row["automations"] = input.automations;
|
|
575
|
+
if (input.agentName !== void 0) row["agent_name"] = input.agentName;
|
|
576
|
+
if (input.dmKey !== void 0) row["dm_key"] = input.dmKey;
|
|
577
|
+
if (input.isDefault !== void 0) row["is_default"] = input.isDefault;
|
|
578
|
+
if (input.mcpConnections !== void 0) row["mcp_connections"] = input.mcpConnections;
|
|
579
|
+
if (input.archivedAt !== void 0) row["archived_at"] = input.archivedAt;
|
|
580
|
+
return row;
|
|
581
|
+
}
|
|
582
|
+
var ChannelCwdError = class extends Error {
|
|
583
|
+
constructor(message) {
|
|
584
|
+
super(message);
|
|
585
|
+
this.name = "ChannelCwdError";
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
function realpathOrSelf(p) {
|
|
589
|
+
try {
|
|
590
|
+
return realpathSync(p);
|
|
591
|
+
} catch {
|
|
592
|
+
return p;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
async function assertCwdInWorkspace(profile, cwd) {
|
|
596
|
+
if (isLogicalCwd(cwd)) {
|
|
597
|
+
if (cwd.split("/")[0] !== profile) {
|
|
598
|
+
throw new ChannelCwdError(`Folder "${cwd}" belongs to another workspace.`);
|
|
599
|
+
}
|
|
600
|
+
return cwd;
|
|
601
|
+
}
|
|
602
|
+
const logical = relative(logicalRoot(), cwd).split(sep).join("/");
|
|
603
|
+
if (isLogicalCwd(logical)) return assertCwdInWorkspace(profile, logical);
|
|
604
|
+
const { data, error } = await getSupabaseClient().from("workspaces").select("slug, root_path");
|
|
605
|
+
if (error) throw new Error(error.message);
|
|
606
|
+
const workspaces = data ?? [];
|
|
607
|
+
const ownRoot = workspaces.find((w) => w.slug === profile)?.root_path;
|
|
608
|
+
const home2 = ownRoot?.match(/^(\/Users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/)?.[1];
|
|
609
|
+
const absolute = home2 && (cwd === "~" || cwd.startsWith("~/")) ? resolve2(home2, cwd.slice(2)) : expandPath(cwd);
|
|
610
|
+
const path = realpathOrSelf(absolute);
|
|
611
|
+
const roots = workspaces.filter((w) => w.root_path).map((w) => ({ slug: w.slug, root: realpathOrSelf(expandPath(w.root_path)) }));
|
|
612
|
+
const owner = roots.filter(({ root }) => path === root || path.startsWith(root + sep)).sort((a, b) => b.root.length - a.root.length)[0];
|
|
613
|
+
if (owner ? owner.slug !== profile : roots.some((r) => r.slug === profile)) {
|
|
614
|
+
throw new ChannelCwdError(
|
|
615
|
+
owner ? `Folder "${cwd}" belongs to the "${owner.slug}" workspace.` : `Folder "${cwd}" is outside this workspace's folder.`
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
return absolute;
|
|
619
|
+
}
|
|
620
|
+
async function createChannel(input) {
|
|
621
|
+
input = { ...input, cwd: await assertCwdInWorkspace(getProfile(), input.cwd) };
|
|
622
|
+
const { data, error } = await getSupabaseClient().from("channels").insert({ ...toRow(input), profile: getProfile() }).select().single();
|
|
623
|
+
if (error) throw new Error(error.message);
|
|
624
|
+
const channel = rowToChannel(data);
|
|
625
|
+
if (channel.cwd && !isLogicalCwd(input.cwd) && !isCwdUsable(channel.cwd)) {
|
|
626
|
+
try {
|
|
627
|
+
mkdirSync2(channel.cwd, { recursive: true });
|
|
628
|
+
} catch (err) {
|
|
629
|
+
console.error(`[channels] failed to create cwd for "${channel.name}":`, err.message);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
await refreshChannelRegistry();
|
|
633
|
+
return channel;
|
|
634
|
+
}
|
|
635
|
+
var DefaultChannelError = class extends Error {
|
|
636
|
+
constructor() {
|
|
637
|
+
super("The default channel must stay public and cannot be renamed or archived.");
|
|
638
|
+
this.name = "DefaultChannelError";
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
async function updateChannelById(id, patch) {
|
|
642
|
+
const existing = findChannelById(id);
|
|
643
|
+
if (existing?.isDefault && (patch.visibility === "private" || patch.archivedAt || patch.isDefault === false || patch.name !== void 0 && patch.name.trim() !== existing.name)) {
|
|
644
|
+
throw new DefaultChannelError();
|
|
645
|
+
}
|
|
646
|
+
if (patch.cwd !== void 0 && existing && patch.cwd === existing.cwd) {
|
|
647
|
+
const { cwd: _unchanged, ...rest } = patch;
|
|
648
|
+
patch = rest;
|
|
649
|
+
}
|
|
650
|
+
if (patch.cwd !== void 0) {
|
|
651
|
+
patch = { ...patch, cwd: await assertCwdInWorkspace(existing?.profile ?? getProfile(), patch.cwd) };
|
|
652
|
+
}
|
|
653
|
+
const { data, error } = await getSupabaseClient().from("channels").update({ ...toRow(patch), updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
|
|
654
|
+
if (error) throw new Error(error.message);
|
|
655
|
+
await refreshChannelRegistry();
|
|
656
|
+
return rowToChannel(data);
|
|
657
|
+
}
|
|
658
|
+
async function markChannelGreeted(id) {
|
|
659
|
+
const { data, error } = await getSupabaseClient().from("channels").update({ greeted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).is("greeted_at", null).select("id");
|
|
660
|
+
if (error) throw new Error(error.message);
|
|
661
|
+
await refreshChannelRegistry();
|
|
662
|
+
return (data ?? []).length > 0;
|
|
663
|
+
}
|
|
664
|
+
async function updateChannelsMcpConnections(updates) {
|
|
665
|
+
if (!updates.length) return;
|
|
666
|
+
const supabase = getSupabaseClient();
|
|
667
|
+
for (const update of updates) {
|
|
668
|
+
const { error } = await supabase.from("channels").update({ mcp_connections: update.mcpConnections, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", update.id);
|
|
669
|
+
if (error) throw new Error(`Failed to update channel ${update.id}: ${error.message}`);
|
|
670
|
+
}
|
|
671
|
+
await refreshChannelRegistry();
|
|
672
|
+
}
|
|
673
|
+
function defaultFallbackCwd() {
|
|
674
|
+
return process.env["CLAUDE_CWD"] ?? process.cwd();
|
|
675
|
+
}
|
|
676
|
+
async function ensureChannelProvisioned(externalChannelId, opts = {}) {
|
|
677
|
+
const existing = findChannelByExternalId(externalChannelId);
|
|
678
|
+
if (existing) {
|
|
679
|
+
if (existing.profile !== getProfile()) return null;
|
|
680
|
+
if (existing.name === externalChannelId && opts.name && opts.name !== externalChannelId) {
|
|
681
|
+
try {
|
|
682
|
+
return await updateChannelById(existing.id, { name: opts.name });
|
|
683
|
+
} catch (err) {
|
|
684
|
+
console.error(`[channels] failed to heal name for ${externalChannelId}:`, err);
|
|
685
|
+
return existing;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return existing;
|
|
689
|
+
}
|
|
690
|
+
try {
|
|
691
|
+
const created = await createChannel({
|
|
692
|
+
name: opts.name ?? externalChannelId,
|
|
693
|
+
cwd: opts.fallbackCwd ?? defaultFallbackCwd(),
|
|
694
|
+
externalChannelId
|
|
695
|
+
});
|
|
696
|
+
console.log(`[channels] auto-provisioned a new channel for Slack channel ${externalChannelId}`);
|
|
697
|
+
return created;
|
|
698
|
+
} catch (err) {
|
|
699
|
+
await refreshChannelRegistry();
|
|
700
|
+
const raced = findChannelByExternalId(externalChannelId);
|
|
701
|
+
if (raced) return raced.profile === getProfile() ? raced : null;
|
|
702
|
+
throw err;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
async function ensureAgentDmChannel(agentName, viewer, opts) {
|
|
706
|
+
const existing = findChannelByAgentName(agentName, viewer.userId);
|
|
707
|
+
if (existing) {
|
|
708
|
+
return existing.name === opts.name ? existing : updateChannelById(existing.id, { name: opts.name });
|
|
709
|
+
}
|
|
710
|
+
const dmKey = agentDmKey(agentName, viewer.userId);
|
|
711
|
+
try {
|
|
712
|
+
return await createChannel({
|
|
713
|
+
name: opts.name,
|
|
714
|
+
cwd: dmCwd(dmKey),
|
|
715
|
+
visibility: "private",
|
|
716
|
+
memberEmails: [viewer.email],
|
|
717
|
+
agentName,
|
|
718
|
+
dmKey
|
|
719
|
+
});
|
|
720
|
+
} catch (err) {
|
|
721
|
+
await refreshChannelRegistry();
|
|
722
|
+
const raced = findChannelByAgentName(agentName, viewer.userId);
|
|
723
|
+
if (raced) return raced;
|
|
724
|
+
throw err;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
async function ensureGeneralChannel() {
|
|
728
|
+
const find = () => getProfileChannelRegistry().find((c) => c.isDefault);
|
|
729
|
+
const existing = find();
|
|
730
|
+
if (existing) return existing;
|
|
731
|
+
try {
|
|
732
|
+
return await createChannel({
|
|
733
|
+
name: "general",
|
|
734
|
+
cwd: `${getProfile()}/general`,
|
|
735
|
+
visibility: "public",
|
|
736
|
+
isDefault: true
|
|
737
|
+
});
|
|
738
|
+
} catch (err) {
|
|
739
|
+
await refreshChannelRegistry();
|
|
740
|
+
const raced = find();
|
|
741
|
+
if (raced) return raced;
|
|
742
|
+
throw err;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
async function ensureMemberDmChannel(a, b) {
|
|
746
|
+
const dmKey = [a.userId, b.userId].sort().join(":");
|
|
747
|
+
const find = () => [...getProfileChannelRegistry()].find((c) => c.dmKey === dmKey && c.profile === getProfile());
|
|
748
|
+
const existing = find();
|
|
749
|
+
if (existing) return existing;
|
|
750
|
+
try {
|
|
751
|
+
return await createChannel({
|
|
752
|
+
name: `${a.handle}, ${b.handle}`,
|
|
753
|
+
// Hash the whole key: a prefix of the sorted ids is just the first user's
|
|
754
|
+
// id, which put every DM that user sorts first in into one shared folder.
|
|
755
|
+
cwd: dmCwd(dmKey),
|
|
756
|
+
visibility: "private",
|
|
757
|
+
memberEmails: [a.email, b.email],
|
|
758
|
+
dmKey
|
|
759
|
+
});
|
|
760
|
+
} catch (err) {
|
|
761
|
+
await refreshChannelRegistry();
|
|
762
|
+
const raced = find();
|
|
763
|
+
if (raced) return raced;
|
|
764
|
+
throw err;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// ../api/src/store/authors.ts
|
|
769
|
+
var AGENT_AUTHOR = "agent";
|
|
770
|
+
var SYNCED_BOT_AUTHOR = "Bot";
|
|
771
|
+
var LEGACY_BOT_AUTHOR = "Custie";
|
|
772
|
+
var SUPPORT_BOT_AUTHOR = "Flyspace Support";
|
|
773
|
+
var NON_HUMAN_AUTHORS = new Set(
|
|
774
|
+
[AGENT_AUTHOR, SYNCED_BOT_AUTHOR, LEGACY_BOT_AUTHOR, SUPPORT_BOT_AUTHOR].map((a) => a.toLowerCase())
|
|
775
|
+
);
|
|
776
|
+
function isHumanAuthor(author) {
|
|
777
|
+
return !NON_HUMAN_AUTHORS.has(author.toLowerCase());
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// ../api/src/dashboard/attachment-uploader.ts
|
|
781
|
+
import { randomUUID } from "crypto";
|
|
782
|
+
import { readFile, stat } from "fs/promises";
|
|
783
|
+
import { basename as basename2 } from "path";
|
|
784
|
+
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
|
785
|
+
|
|
786
|
+
// ../api/src/store/r2-client.ts
|
|
787
|
+
import { ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
|
|
788
|
+
var client2;
|
|
789
|
+
function getR2Client() {
|
|
790
|
+
if (client2) return client2;
|
|
791
|
+
const accountId = process.env["CLOUDFLARE_R2_ACCOUNT_ID"];
|
|
792
|
+
const accessKeyId = process.env["CLOUDFLARE_R2_ACCESS_KEY_ID"];
|
|
793
|
+
const secretAccessKey = process.env["CLOUDFLARE_R2_SECRET_ACCESS_KEY"];
|
|
794
|
+
if (!accountId || !accessKeyId || !secretAccessKey) {
|
|
795
|
+
throw new Error("CLOUDFLARE_R2_* env vars not set \u2014 check .env");
|
|
796
|
+
}
|
|
797
|
+
client2 = new S3Client({
|
|
798
|
+
region: "auto",
|
|
799
|
+
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
800
|
+
credentials: { accessKeyId, secretAccessKey }
|
|
801
|
+
});
|
|
802
|
+
return client2;
|
|
803
|
+
}
|
|
804
|
+
function getR2Bucket() {
|
|
805
|
+
const bucket = process.env["CLOUDFLARE_R2_BUCKET_NAME"];
|
|
806
|
+
if (!bucket) throw new Error("CLOUDFLARE_R2_BUCKET_NAME not set \u2014 check .env");
|
|
807
|
+
return bucket;
|
|
808
|
+
}
|
|
809
|
+
async function sumR2PrefixBytes(prefix) {
|
|
810
|
+
let total = 0;
|
|
811
|
+
let token;
|
|
812
|
+
do {
|
|
813
|
+
const page = await getR2Client().send(
|
|
814
|
+
new ListObjectsV2Command({ Bucket: getR2Bucket(), Prefix: prefix, ContinuationToken: token })
|
|
815
|
+
);
|
|
816
|
+
for (const obj of page.Contents ?? []) total += obj.Size ?? 0;
|
|
817
|
+
token = page.IsTruncated ? page.NextContinuationToken : void 0;
|
|
818
|
+
} while (token);
|
|
819
|
+
return total;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// ../api/src/dashboard/attachment-uploader.ts
|
|
823
|
+
var debug = process.env["DEBUG"] === "true";
|
|
824
|
+
var LOCAL_IMAGE_LINK = /!\[([^\]]*)\]\((\/[^)\s]+)\)/g;
|
|
825
|
+
var SCRATCH_VAR_IN_IMAGE_LINK = /(!\[[^\]]*\]\()\$\{?FLYSPACE_SCRATCH_DIR\}?(?=\/)/g;
|
|
826
|
+
function expandScratchDirVar(body) {
|
|
827
|
+
return body.replace(SCRATCH_VAR_IN_IMAGE_LINK, (_, prefix) => prefix + paths.SCRATCH_DIR);
|
|
828
|
+
}
|
|
829
|
+
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
830
|
+
var SCRATCH_PREFIX = "scratch";
|
|
831
|
+
var MIMETYPES = {
|
|
832
|
+
".png": "image/png",
|
|
833
|
+
".jpg": "image/jpeg",
|
|
834
|
+
".jpeg": "image/jpeg",
|
|
835
|
+
".gif": "image/gif",
|
|
836
|
+
".webp": "image/webp",
|
|
837
|
+
".avif": "image/avif"
|
|
838
|
+
};
|
|
839
|
+
function mimetypeOf(path) {
|
|
840
|
+
const dot = path.lastIndexOf(".");
|
|
841
|
+
return dot === -1 ? void 0 : MIMETYPES[path.slice(dot).toLowerCase()];
|
|
842
|
+
}
|
|
843
|
+
function sanitizeFilename(name) {
|
|
844
|
+
const cleaned = name.replace(/[/\\]/g, "_").replace(/\s+/g, "-").replace(/[^\w.-]/g, "").trim();
|
|
845
|
+
return (cleaned || "file").slice(-100);
|
|
846
|
+
}
|
|
847
|
+
function encodeKeyForUrl(key) {
|
|
848
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
849
|
+
}
|
|
850
|
+
function extractLocalImagePaths(body) {
|
|
851
|
+
const paths2 = [];
|
|
852
|
+
for (const match of body.matchAll(LOCAL_IMAGE_LINK)) {
|
|
853
|
+
const path = match[2];
|
|
854
|
+
if (path.startsWith("/api/")) continue;
|
|
855
|
+
if (!mimetypeOf(path)) continue;
|
|
856
|
+
if (!paths2.includes(path)) paths2.push(path);
|
|
857
|
+
}
|
|
858
|
+
return paths2;
|
|
859
|
+
}
|
|
860
|
+
async function uploadOne(path) {
|
|
861
|
+
const mimetype = mimetypeOf(path);
|
|
862
|
+
if (!mimetype) return null;
|
|
863
|
+
try {
|
|
864
|
+
const info = await stat(path);
|
|
865
|
+
if (!info.isFile()) return null;
|
|
866
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
867
|
+
console.error(`[attachment-uploader] ${path} is ${info.size} bytes, over the ${MAX_FILE_BYTES} limit`);
|
|
868
|
+
return null;
|
|
869
|
+
}
|
|
870
|
+
const key = `${SCRATCH_PREFIX}/${getProfile()}/${randomUUID()}-${sanitizeFilename(basename2(path))}`;
|
|
871
|
+
await getR2Client().send(
|
|
872
|
+
new PutObjectCommand({
|
|
873
|
+
Bucket: getR2Bucket(),
|
|
874
|
+
Key: key,
|
|
875
|
+
Body: await readFile(path),
|
|
876
|
+
ContentType: mimetype
|
|
877
|
+
})
|
|
878
|
+
);
|
|
879
|
+
if (debug) console.log(`[attachment-uploader] ${path} -> ${key} (${info.size} bytes)`);
|
|
880
|
+
return `/api/attachments/${encodeKeyForUrl(key)}`;
|
|
881
|
+
} catch (err) {
|
|
882
|
+
console.error(`[attachment-uploader] failed to upload ${path}:`, err.message);
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
async function uploadLocalImages(rawBody) {
|
|
887
|
+
const body = expandScratchDirVar(rawBody);
|
|
888
|
+
const localPaths = extractLocalImagePaths(body);
|
|
889
|
+
if (localPaths.length === 0) return body;
|
|
890
|
+
const urls = /* @__PURE__ */ new Map();
|
|
891
|
+
await Promise.all(
|
|
892
|
+
localPaths.map(async (path) => {
|
|
893
|
+
const url = await uploadOne(path);
|
|
894
|
+
if (url) urls.set(path, url);
|
|
895
|
+
})
|
|
896
|
+
);
|
|
897
|
+
if (urls.size === 0) return body;
|
|
898
|
+
return body.replace(LOCAL_IMAGE_LINK, (original, alt, path) => {
|
|
899
|
+
const url = urls.get(path);
|
|
900
|
+
return url ? `` : original;
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// src/store/dashboard-sync.ts
|
|
905
|
+
var TITLE_MAX_LENGTH = 80;
|
|
906
|
+
function deriveThreadTitle(text) {
|
|
907
|
+
const firstLine = text.split("\n").find((line) => line.trim().length > 0);
|
|
908
|
+
if (!firstLine) return null;
|
|
909
|
+
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();
|
|
910
|
+
if (!cleaned) return null;
|
|
911
|
+
return cleaned.length > TITLE_MAX_LENGTH ? `${cleaned.slice(0, TITLE_MAX_LENGTH).trim()}\u2026` : cleaned;
|
|
912
|
+
}
|
|
913
|
+
async function syncPostToDashboard(opts) {
|
|
914
|
+
const { channelId, ts, threadTs, text } = opts;
|
|
915
|
+
if (!databaseReachable()) {
|
|
916
|
+
console.warn("[dashboard-sync] Supabase not configured \u2014 skipping dashboard sync");
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
try {
|
|
920
|
+
const supabase = getSupabaseClient();
|
|
921
|
+
const dashboardChannelId = await resolveDashboardChannelId(supabase, channelId);
|
|
922
|
+
const threadId = threadTs ? await ensureThreadId(supabase, channelId, dashboardChannelId, threadTs) : await createOwnThread(supabase, channelId, dashboardChannelId, ts, text);
|
|
923
|
+
const { error } = await supabase.from("thread_replies").upsert(
|
|
924
|
+
{
|
|
925
|
+
thread_id: threadId,
|
|
926
|
+
// This mirror only ever runs for the bot's own posts (automation
|
|
927
|
+
// output, `flyspace slack post`), so the author is the agent itself —
|
|
928
|
+
// labelling it anything else makes the chat agent count it as a
|
|
929
|
+
// second human and stop replying without an explicit mention.
|
|
930
|
+
author: AGENT_AUTHOR,
|
|
931
|
+
body: await uploadLocalImages(text),
|
|
932
|
+
external_thread_replies_id: `${channelId}:${ts}`
|
|
933
|
+
},
|
|
934
|
+
{ onConflict: "external_thread_replies_id" }
|
|
935
|
+
);
|
|
936
|
+
if (error) {
|
|
937
|
+
console.warn(`[dashboard-sync] failed to write reply: ${error.message}`);
|
|
938
|
+
}
|
|
939
|
+
} catch (err) {
|
|
940
|
+
console.warn(
|
|
941
|
+
`[dashboard-sync] sync failed: ${err instanceof Error ? err.message : String(err)}`
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
async function resolveDashboardChannelId(supabase, slackChannelId) {
|
|
946
|
+
const { data, error } = await supabase.from("channels").select("id").eq("external_channel_id", slackChannelId).maybeSingle();
|
|
947
|
+
if (error || !data) return slackChannelId;
|
|
948
|
+
return data["id"];
|
|
949
|
+
}
|
|
950
|
+
async function createOwnThread(supabase, externalChannelId, dashboardChannelId, ts, text) {
|
|
951
|
+
const { data, error } = await supabase.from("threads").upsert(
|
|
952
|
+
{
|
|
953
|
+
channel_id: dashboardChannelId,
|
|
954
|
+
title: deriveThreadTitle(text),
|
|
955
|
+
author: AGENT_AUTHOR,
|
|
956
|
+
external_thread_id: `${externalChannelId}:${ts}`
|
|
957
|
+
},
|
|
958
|
+
{ onConflict: "external_thread_id" }
|
|
959
|
+
).select("id").single();
|
|
960
|
+
if (error || !data) throw new Error(error?.message ?? "failed to create thread");
|
|
961
|
+
return data["id"];
|
|
962
|
+
}
|
|
963
|
+
async function ensureThreadId(supabase, externalChannelId, dashboardChannelId, parentTs) {
|
|
964
|
+
const key = `${externalChannelId}:${parentTs}`;
|
|
965
|
+
const { data: existing, error: selectError } = await supabase.from("threads").select("id").eq("external_thread_id", key).maybeSingle();
|
|
966
|
+
if (selectError) throw new Error(selectError.message);
|
|
967
|
+
if (existing) return existing["id"];
|
|
968
|
+
const { data: created, error: createError } = await supabase.from("threads").upsert(
|
|
969
|
+
// The unsynced parent could be anyone's message (often another bot's),
|
|
970
|
+
// so keep the generic non-human placeholder rather than claiming it.
|
|
971
|
+
{
|
|
972
|
+
channel_id: dashboardChannelId,
|
|
973
|
+
title: null,
|
|
974
|
+
author: SYNCED_BOT_AUTHOR,
|
|
975
|
+
external_thread_id: key
|
|
976
|
+
},
|
|
977
|
+
{ onConflict: "external_thread_id" }
|
|
978
|
+
).select("id").single();
|
|
979
|
+
if (createError || !created) {
|
|
980
|
+
throw new Error(createError?.message ?? "failed to create placeholder thread");
|
|
981
|
+
}
|
|
982
|
+
return created["id"];
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// src/store/dashboard-post.ts
|
|
986
|
+
async function postToDashboardChannel(opts) {
|
|
987
|
+
const { channelId, text, threadId, title } = opts;
|
|
988
|
+
const supabase = getSupabaseClient();
|
|
989
|
+
if (!threadId && !channelId) {
|
|
990
|
+
throw new Error("postToDashboardChannel: channelId is required to start a new thread");
|
|
991
|
+
}
|
|
992
|
+
const parentId = threadId ?? await createThread(supabase, channelId, text, title);
|
|
993
|
+
const body = await uploadLocalImages(text);
|
|
994
|
+
const { data, error } = await supabase.from("thread_replies").insert({ thread_id: parentId, author: AGENT_AUTHOR, body }).select("id").single();
|
|
995
|
+
if (error || !data) {
|
|
996
|
+
throw new Error(`failed to write dashboard reply: ${error?.message ?? "no row returned"}`);
|
|
997
|
+
}
|
|
998
|
+
return { threadId: parentId, replyId: data["id"] };
|
|
999
|
+
}
|
|
1000
|
+
async function createThread(supabase, channelId, text, title) {
|
|
1001
|
+
const { data, error } = await supabase.from("threads").insert({
|
|
1002
|
+
channel_id: channelId,
|
|
1003
|
+
// An untitled thread is effectively invisible in the sidebar, so give a
|
|
1004
|
+
// daily report the same first-line-derived title a mirrored post gets,
|
|
1005
|
+
// unless the caller named the thread itself.
|
|
1006
|
+
title: title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(text),
|
|
1007
|
+
author: AGENT_AUTHOR
|
|
1008
|
+
}).select("id").single();
|
|
1009
|
+
if (error || !data) {
|
|
1010
|
+
throw new Error(`failed to create dashboard thread: ${error?.message ?? "no row returned"}`);
|
|
1011
|
+
}
|
|
1012
|
+
return data["id"];
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// src/store/session-store.ts
|
|
1016
|
+
import Database from "better-sqlite3";
|
|
1017
|
+
var SessionStore = class {
|
|
1018
|
+
db;
|
|
1019
|
+
constructor(dbPath) {
|
|
1020
|
+
this.db = new Database(dbPath);
|
|
1021
|
+
this.db.pragma("journal_mode = WAL");
|
|
1022
|
+
this.init();
|
|
1023
|
+
}
|
|
1024
|
+
init() {
|
|
1025
|
+
this.db.exec(`
|
|
1026
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
1027
|
+
channel_id TEXT NOT NULL,
|
|
1028
|
+
thread_ts TEXT NOT NULL,
|
|
1029
|
+
session_id TEXT NOT NULL,
|
|
1030
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1031
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1032
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
1033
|
+
)
|
|
1034
|
+
`);
|
|
1035
|
+
const sessionColumns = this.db.prepare("PRAGMA table_info(sessions)").all();
|
|
1036
|
+
if (!sessionColumns.some((c) => c.name === "runner")) {
|
|
1037
|
+
this.db.exec(`ALTER TABLE sessions ADD COLUMN runner TEXT NOT NULL DEFAULT 'claude'`);
|
|
1038
|
+
}
|
|
1039
|
+
this.db.exec(`DELETE FROM sessions WHERE runner = 'opencode'`);
|
|
1040
|
+
this.db.exec(`
|
|
1041
|
+
CREATE TABLE IF NOT EXISTS model_overrides (
|
|
1042
|
+
channel_id TEXT NOT NULL,
|
|
1043
|
+
thread_ts TEXT NOT NULL,
|
|
1044
|
+
model TEXT NOT NULL,
|
|
1045
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1046
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
1047
|
+
)
|
|
1048
|
+
`);
|
|
1049
|
+
this.db.exec(`
|
|
1050
|
+
CREATE TABLE IF NOT EXISTS effort_overrides (
|
|
1051
|
+
channel_id TEXT NOT NULL,
|
|
1052
|
+
thread_ts TEXT NOT NULL,
|
|
1053
|
+
effort TEXT NOT NULL,
|
|
1054
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1055
|
+
PRIMARY KEY (channel_id, thread_ts)
|
|
1056
|
+
)
|
|
1057
|
+
`);
|
|
1058
|
+
}
|
|
1059
|
+
getSession(channelId, threadTs) {
|
|
1060
|
+
const row = this.db.prepare("SELECT * FROM sessions WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
1061
|
+
if (!row) return void 0;
|
|
1062
|
+
return {
|
|
1063
|
+
channelId: row.channel_id,
|
|
1064
|
+
threadTs: row.thread_ts,
|
|
1065
|
+
sessionId: row.session_id,
|
|
1066
|
+
runner: row.runner === "codex" ? "codex" : "claude",
|
|
1067
|
+
createdAt: row.created_at,
|
|
1068
|
+
updatedAt: row.updated_at
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
saveSession(channelId, threadTs, sessionId, runner = "claude") {
|
|
1072
|
+
this.db.prepare(
|
|
1073
|
+
`INSERT INTO sessions (channel_id, thread_ts, session_id, runner)
|
|
1074
|
+
VALUES (?, ?, ?, ?)
|
|
1075
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
1076
|
+
DO UPDATE SET session_id = excluded.session_id, runner = excluded.runner, updated_at = datetime('now')`
|
|
1077
|
+
).run(channelId, threadTs, sessionId, runner);
|
|
1078
|
+
}
|
|
1079
|
+
/** All sessions, newest activity first. Read-only listing for the dashboard. */
|
|
1080
|
+
listSessions() {
|
|
1081
|
+
const rows = this.db.prepare("SELECT * FROM sessions ORDER BY updated_at DESC").all();
|
|
1082
|
+
return rows.map((row) => ({
|
|
1083
|
+
channelId: row.channel_id,
|
|
1084
|
+
threadTs: row.thread_ts,
|
|
1085
|
+
sessionId: row.session_id,
|
|
1086
|
+
runner: row.runner === "codex" ? "codex" : "claude",
|
|
1087
|
+
createdAt: row.created_at,
|
|
1088
|
+
updatedAt: row.updated_at
|
|
1089
|
+
}));
|
|
1090
|
+
}
|
|
1091
|
+
deleteSession(channelId, threadTs) {
|
|
1092
|
+
this.db.prepare("DELETE FROM sessions WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Drop every session in a channel. Used when the channel's execution runtime
|
|
1096
|
+
* changes (`channels.runtime`, 0035): the session ids here point at Claude
|
|
1097
|
+
* session files stored under whichever runtime wrote them — the host's
|
|
1098
|
+
* CLAUDE_CONFIG_DIR, or the container's own per-channel home — so after a
|
|
1099
|
+
* switch every one of them resolves to a file the new runtime cannot see.
|
|
1100
|
+
* Left in place, the next turn in each thread would `--resume` an id that
|
|
1101
|
+
* does not exist there and lose the conversation in a confusing way; dropping
|
|
1102
|
+
* them makes the next turn cleanly start fresh instead.
|
|
1103
|
+
*
|
|
1104
|
+
* Returns how many were removed, so the caller can log something meaningful.
|
|
1105
|
+
*/
|
|
1106
|
+
deleteSessionsForChannel(channelId) {
|
|
1107
|
+
const result = this.db.prepare("DELETE FROM sessions WHERE channel_id = ?").run(channelId);
|
|
1108
|
+
return result.changes;
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Re-key a single thread's rows onto a different channel. `sessions`,
|
|
1112
|
+
* `model_overrides` and `effort_overrides` are all keyed by (channel_id,
|
|
1113
|
+
* thread_ts), so moving a thread in the dashboard without this leaves the
|
|
1114
|
+
* agent unable to find its own session: the next turn would start from
|
|
1115
|
+
* scratch and lose the conversation, and any `!model`/`!effort` override on
|
|
1116
|
+
* the thread would silently revert.
|
|
1117
|
+
*
|
|
1118
|
+
* A row already sitting on the destination key wins — that means the thread
|
|
1119
|
+
* has been moved back and forth and the destination row is the newer state,
|
|
1120
|
+
* so the stale source row is dropped rather than overwriting it.
|
|
1121
|
+
*
|
|
1122
|
+
* Returns how many rows were re-keyed in each table.
|
|
1123
|
+
*/
|
|
1124
|
+
moveThread(fromChannelId, toChannelId, threadTs) {
|
|
1125
|
+
const move = this.db.transaction(() => {
|
|
1126
|
+
const counts = { sessions: 0, modelOverrides: 0, effortOverrides: 0 };
|
|
1127
|
+
for (const table of ["sessions", "model_overrides", "effort_overrides"]) {
|
|
1128
|
+
const updated = this.db.prepare(
|
|
1129
|
+
`UPDATE OR IGNORE ${table} SET channel_id = ?
|
|
1130
|
+
WHERE channel_id = ? AND thread_ts = ?`
|
|
1131
|
+
).run(toChannelId, fromChannelId, threadTs);
|
|
1132
|
+
this.db.prepare(`DELETE FROM ${table} WHERE channel_id = ? AND thread_ts = ?`).run(fromChannelId, threadTs);
|
|
1133
|
+
if (table === "sessions") counts.sessions = updated.changes;
|
|
1134
|
+
else if (table === "model_overrides") counts.modelOverrides = updated.changes;
|
|
1135
|
+
else counts.effortOverrides = updated.changes;
|
|
1136
|
+
}
|
|
1137
|
+
return counts;
|
|
1138
|
+
});
|
|
1139
|
+
return move();
|
|
1140
|
+
}
|
|
1141
|
+
getModelOverride(channelId, threadTs) {
|
|
1142
|
+
const row = this.db.prepare("SELECT model FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
1143
|
+
return row?.model;
|
|
1144
|
+
}
|
|
1145
|
+
setModelOverride(channelId, threadTs, model) {
|
|
1146
|
+
this.db.prepare(
|
|
1147
|
+
`INSERT INTO model_overrides (channel_id, thread_ts, model)
|
|
1148
|
+
VALUES (?, ?, ?)
|
|
1149
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
1150
|
+
DO UPDATE SET model = excluded.model, updated_at = datetime('now')`
|
|
1151
|
+
).run(channelId, threadTs, model);
|
|
1152
|
+
}
|
|
1153
|
+
clearModelOverride(channelId, threadTs) {
|
|
1154
|
+
this.db.prepare("DELETE FROM model_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
1155
|
+
}
|
|
1156
|
+
getEffortOverride(channelId, threadTs) {
|
|
1157
|
+
const row = this.db.prepare("SELECT effort FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").get(channelId, threadTs);
|
|
1158
|
+
return row?.effort && isEffort(row.effort) ? row.effort : void 0;
|
|
1159
|
+
}
|
|
1160
|
+
setEffortOverride(channelId, threadTs, effort) {
|
|
1161
|
+
this.db.prepare(
|
|
1162
|
+
`INSERT INTO effort_overrides (channel_id, thread_ts, effort)
|
|
1163
|
+
VALUES (?, ?, ?)
|
|
1164
|
+
ON CONFLICT (channel_id, thread_ts)
|
|
1165
|
+
DO UPDATE SET effort = excluded.effort, updated_at = datetime('now')`
|
|
1166
|
+
).run(channelId, threadTs, effort);
|
|
1167
|
+
}
|
|
1168
|
+
clearEffortOverride(channelId, threadTs) {
|
|
1169
|
+
this.db.prepare("DELETE FROM effort_overrides WHERE channel_id = ? AND thread_ts = ?").run(channelId, threadTs);
|
|
1170
|
+
}
|
|
1171
|
+
close() {
|
|
1172
|
+
this.db.close();
|
|
1173
|
+
}
|
|
1174
|
+
};
|
|
1175
|
+
|
|
1176
|
+
export {
|
|
1177
|
+
__require,
|
|
1178
|
+
__commonJS,
|
|
1179
|
+
__toESM,
|
|
1180
|
+
setSupabaseClient,
|
|
1181
|
+
setSupabaseClientFactory,
|
|
1182
|
+
hasSupabaseCredentials,
|
|
1183
|
+
databaseReachable,
|
|
1184
|
+
getSupabaseClient,
|
|
1185
|
+
DEFAULT_PROFILE,
|
|
1186
|
+
runWithProfile,
|
|
1187
|
+
getProfile,
|
|
1188
|
+
paths,
|
|
1189
|
+
ensureDirs,
|
|
1190
|
+
sweepScratchDir,
|
|
1191
|
+
isEffort,
|
|
1192
|
+
resolveClaudeEffort,
|
|
1193
|
+
resolveCodexEffort,
|
|
1194
|
+
isPermissionMode,
|
|
1195
|
+
isLogicalCwd,
|
|
1196
|
+
DEFAULT_AUTO_CONTINUE_LIMIT,
|
|
1197
|
+
resolveAutoContinueLimit,
|
|
1198
|
+
resolveLogicalCwd,
|
|
1199
|
+
isUnderLogicalRoot,
|
|
1200
|
+
ensureLogicalCwdDir,
|
|
1201
|
+
expandPath,
|
|
1202
|
+
canSeeChannel,
|
|
1203
|
+
refreshChannelRegistry,
|
|
1204
|
+
getChannelRegistry,
|
|
1205
|
+
getProfileChannelRegistry,
|
|
1206
|
+
onChannelRegistryChange,
|
|
1207
|
+
findChannelById,
|
|
1208
|
+
dmCwd,
|
|
1209
|
+
findChannel,
|
|
1210
|
+
startChannelRegistryPolling,
|
|
1211
|
+
isCwdUsable,
|
|
1212
|
+
auditChannelCwds,
|
|
1213
|
+
warnOnBrokenChannelCwds,
|
|
1214
|
+
isChannelAccessAllowed,
|
|
1215
|
+
resolveCwd,
|
|
1216
|
+
resolveChannelPermissionMode,
|
|
1217
|
+
resolveChannelPrompt,
|
|
1218
|
+
resolveModel,
|
|
1219
|
+
resolveEffort,
|
|
1220
|
+
ChannelCwdError,
|
|
1221
|
+
createChannel,
|
|
1222
|
+
DefaultChannelError,
|
|
1223
|
+
updateChannelById,
|
|
1224
|
+
markChannelGreeted,
|
|
1225
|
+
updateChannelsMcpConnections,
|
|
1226
|
+
ensureChannelProvisioned,
|
|
1227
|
+
ensureAgentDmChannel,
|
|
1228
|
+
ensureGeneralChannel,
|
|
1229
|
+
ensureMemberDmChannel,
|
|
1230
|
+
AGENT_AUTHOR,
|
|
1231
|
+
SYNCED_BOT_AUTHOR,
|
|
1232
|
+
SUPPORT_BOT_AUTHOR,
|
|
1233
|
+
isHumanAuthor,
|
|
1234
|
+
getR2Client,
|
|
1235
|
+
getR2Bucket,
|
|
1236
|
+
sumR2PrefixBytes,
|
|
1237
|
+
SCRATCH_PREFIX,
|
|
1238
|
+
uploadLocalImages,
|
|
1239
|
+
syncPostToDashboard,
|
|
1240
|
+
resolveDashboardChannelId,
|
|
1241
|
+
postToDashboardChannel,
|
|
1242
|
+
SessionStore
|
|
1243
|
+
};
|