flyspace-cli 0.1.48 → 0.1.50
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-F5CXKDZV.js → chunk-HTFQL66T.js} +5 -7
- package/dist/{chunk-2V33REYC.js → chunk-NR5FHLR2.js} +184 -96
- package/dist/{chunk-ETFEQSMF.js → chunk-PIAF4FJX.js} +1 -1
- package/dist/cli.js +854 -248
- package/dist/index.js +2 -2
- package/dist/{threads-S4L5QX7T.js → threads-QAVO2Z4L.js} +89 -4
- package/package.json +1 -1
- package/system.capabilities.md +5 -4
package/dist/cli.js
CHANGED
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
disableFeatureFlag,
|
|
53
53
|
displayNameFor,
|
|
54
54
|
docsAccessPromptNote,
|
|
55
|
+
effectiveModel,
|
|
55
56
|
enableFeatureFlag,
|
|
56
57
|
ensureAgentDmChannel,
|
|
57
58
|
ensureGeneralChannel,
|
|
@@ -83,6 +84,7 @@ import {
|
|
|
83
84
|
getWorkspaceBySlug,
|
|
84
85
|
getWorkspaceByStripeCustomerId,
|
|
85
86
|
getWorkspaceGreetedAt,
|
|
87
|
+
getWorkspacePermissionMode,
|
|
86
88
|
getWorkspacePlanStatus,
|
|
87
89
|
installUsageRecording,
|
|
88
90
|
isAllowedModel,
|
|
@@ -94,6 +96,7 @@ import {
|
|
|
94
96
|
isLockedPlan,
|
|
95
97
|
isLogicalCwd,
|
|
96
98
|
isMemoryType,
|
|
99
|
+
isPermissionMode,
|
|
97
100
|
isUnderLogicalRoot,
|
|
98
101
|
isUuid,
|
|
99
102
|
isValidSkillName,
|
|
@@ -130,6 +133,7 @@ import {
|
|
|
130
133
|
markWorkspaceProjectsSetup,
|
|
131
134
|
markdownToBlocks,
|
|
132
135
|
mcpStrictConfigEnabled,
|
|
136
|
+
mentionedUserIds,
|
|
133
137
|
mimetypeSizeLimit,
|
|
134
138
|
modelLabel,
|
|
135
139
|
pinnedClaudeConfigDir,
|
|
@@ -144,6 +148,7 @@ import {
|
|
|
144
148
|
resetWorkspaceOnboarding,
|
|
145
149
|
resetWorkspacePrompt,
|
|
146
150
|
resolveChannelId,
|
|
151
|
+
resolveChannelPermissionMode,
|
|
147
152
|
resolveChannelPrompt,
|
|
148
153
|
resolveCwd,
|
|
149
154
|
resolveFeatureFlags,
|
|
@@ -166,6 +171,7 @@ import {
|
|
|
166
171
|
setMemoryAutoPaused,
|
|
167
172
|
setOutputStyleDefault,
|
|
168
173
|
setWorkspaceArchived,
|
|
174
|
+
setWorkspacePermissionMode,
|
|
169
175
|
setWorkspaceStripeSubscription,
|
|
170
176
|
slackConfigured,
|
|
171
177
|
startAutomationRegistryPolling,
|
|
@@ -191,7 +197,7 @@ import {
|
|
|
191
197
|
warnOnBrokenChannelCwds,
|
|
192
198
|
workspaceSkillsDir,
|
|
193
199
|
writeSkillFile
|
|
194
|
-
} from "./chunk-
|
|
200
|
+
} from "./chunk-NR5FHLR2.js";
|
|
195
201
|
import {
|
|
196
202
|
firstReplyBody,
|
|
197
203
|
getThread,
|
|
@@ -199,7 +205,7 @@ import {
|
|
|
199
205
|
listThreads,
|
|
200
206
|
moveThread,
|
|
201
207
|
resolveChannel
|
|
202
|
-
} from "./chunk-
|
|
208
|
+
} from "./chunk-PIAF4FJX.js";
|
|
203
209
|
import {
|
|
204
210
|
AGENT_AUTHOR,
|
|
205
211
|
DEFAULT_PROFILE,
|
|
@@ -224,7 +230,7 @@ import {
|
|
|
224
230
|
sumR2PrefixBytes,
|
|
225
231
|
syncPostToDashboard,
|
|
226
232
|
uploadLocalImages
|
|
227
|
-
} from "./chunk-
|
|
233
|
+
} from "./chunk-HTFQL66T.js";
|
|
228
234
|
|
|
229
235
|
// ../../node_modules/.pnpm/delayed-stream@1.0.0/node_modules/delayed-stream/lib/delayed_stream.js
|
|
230
236
|
var require_delayed_stream = __commonJS({
|
|
@@ -11914,9 +11920,9 @@ var require_axios = __commonJS({
|
|
|
11914
11920
|
var { toString } = Object.prototype;
|
|
11915
11921
|
var { getPrototypeOf } = Object;
|
|
11916
11922
|
var { iterator, toStringTag } = Symbol;
|
|
11917
|
-
var kindOf = /* @__PURE__ */ ((
|
|
11923
|
+
var kindOf = /* @__PURE__ */ ((cache8) => (thing) => {
|
|
11918
11924
|
const str = toString.call(thing);
|
|
11919
|
-
return
|
|
11925
|
+
return cache8[str] || (cache8[str] = str.slice(8, -1).toLowerCase());
|
|
11920
11926
|
})(/* @__PURE__ */ Object.create(null));
|
|
11921
11927
|
var kindOfTest = (type) => {
|
|
11922
11928
|
type = type.toLowerCase();
|
|
@@ -19492,7 +19498,7 @@ async function runAuthCmd(args) {
|
|
|
19492
19498
|
|
|
19493
19499
|
// ../api/src/version.ts
|
|
19494
19500
|
import { readFileSync as readFileSync8 } from "fs";
|
|
19495
|
-
var CLI_VERSION = true ? "0.1.
|
|
19501
|
+
var CLI_VERSION = true ? "0.1.50" : devVersion();
|
|
19496
19502
|
function isOlderVersion(a, b) {
|
|
19497
19503
|
const parse = (v) => v.replace(/^v/, "").split("-")[0].split(".").map(Number);
|
|
19498
19504
|
const [pa, pb] = [parse(a), parse(b)];
|
|
@@ -20120,7 +20126,7 @@ function npmEnv(target) {
|
|
|
20120
20126
|
return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
|
|
20121
20127
|
}
|
|
20122
20128
|
async function runUpgrade() {
|
|
20123
|
-
const current = "0.1.
|
|
20129
|
+
const current = "0.1.50";
|
|
20124
20130
|
console.log(`Current version: ${current}`);
|
|
20125
20131
|
console.log("Checking for updates...\n");
|
|
20126
20132
|
try {
|
|
@@ -20899,6 +20905,7 @@ function resolveChannelConfig(channelId) {
|
|
|
20899
20905
|
effort: channel?.effort ?? defaultEffort(),
|
|
20900
20906
|
runtime: channel?.runtime ?? "host",
|
|
20901
20907
|
mounts: channel?.mounts ?? [],
|
|
20908
|
+
permissionMode: resolveChannelPermissionMode(channelId),
|
|
20902
20909
|
prompt: channel?.prompt?.trim() || void 0,
|
|
20903
20910
|
codexModel: profileEnv("CUSTIE_CODEX_MODEL")?.trim() || DEFAULT_CODEX_MODEL,
|
|
20904
20911
|
claudeConfigDir: profileClaudeConfigDir(),
|
|
@@ -21342,11 +21349,67 @@ function clearKnownWorkspacesCache() {
|
|
|
21342
21349
|
warned = false;
|
|
21343
21350
|
}
|
|
21344
21351
|
|
|
21352
|
+
// ../api/src/store/workspace-domain-store.ts
|
|
21353
|
+
async function getWorkspaceDomain(workspaceId) {
|
|
21354
|
+
const { data, error: error2 } = await getSupabaseClient().from("workspace_domains").select("workspace_id, hostname, cf_hostname_id, status, verified_at").eq("workspace_id", workspaceId).maybeSingle();
|
|
21355
|
+
if (error2) throw new Error(`getWorkspaceDomain(${workspaceId}): ${error2.message}`);
|
|
21356
|
+
return data ?? null;
|
|
21357
|
+
}
|
|
21358
|
+
async function insertWorkspaceDomain(row) {
|
|
21359
|
+
const { error: error2 } = await getSupabaseClient().from("workspace_domains").insert(row);
|
|
21360
|
+
if (error2) throw new Error(`insertWorkspaceDomain(${row.hostname}): ${error2.message}`);
|
|
21361
|
+
invalidateCustomDomainCache();
|
|
21362
|
+
}
|
|
21363
|
+
async function updateWorkspaceDomainStatus(workspaceId, status) {
|
|
21364
|
+
const { error: error2 } = await getSupabaseClient().from("workspace_domains").update({ status, ...status === "active" ? { verified_at: (/* @__PURE__ */ new Date()).toISOString() } : {} }).eq("workspace_id", workspaceId);
|
|
21365
|
+
if (error2) throw new Error(`updateWorkspaceDomainStatus(${workspaceId}): ${error2.message}`);
|
|
21366
|
+
invalidateCustomDomainCache();
|
|
21367
|
+
}
|
|
21368
|
+
async function deleteWorkspaceDomain(workspaceId) {
|
|
21369
|
+
const { error: error2 } = await getSupabaseClient().from("workspace_domains").delete().eq("workspace_id", workspaceId);
|
|
21370
|
+
if (error2) throw new Error(`deleteWorkspaceDomain(${workspaceId}): ${error2.message}`);
|
|
21371
|
+
invalidateCustomDomainCache();
|
|
21372
|
+
}
|
|
21373
|
+
var CACHE_TTL_MS = 6e4;
|
|
21374
|
+
var cache3 = null;
|
|
21375
|
+
var refreshing = false;
|
|
21376
|
+
function invalidateCustomDomainCache() {
|
|
21377
|
+
cache3 = null;
|
|
21378
|
+
}
|
|
21379
|
+
async function refreshCustomDomainCache() {
|
|
21380
|
+
if (refreshing) return;
|
|
21381
|
+
refreshing = true;
|
|
21382
|
+
try {
|
|
21383
|
+
const { data, error: error2 } = await getSupabaseClient().from("workspace_domains").select("hostname, workspaces(slug)").eq("status", "active");
|
|
21384
|
+
if (error2) throw new Error(error2.message);
|
|
21385
|
+
const map = /* @__PURE__ */ new Map();
|
|
21386
|
+
for (const row of data ?? []) {
|
|
21387
|
+
if (row.workspaces?.slug) map.set(row.hostname, row.workspaces.slug);
|
|
21388
|
+
}
|
|
21389
|
+
cache3 = { map, fetchedAt: Date.now() };
|
|
21390
|
+
} catch (err) {
|
|
21391
|
+
console.error("[custom-domains] cache refresh failed:", err);
|
|
21392
|
+
} finally {
|
|
21393
|
+
refreshing = false;
|
|
21394
|
+
}
|
|
21395
|
+
}
|
|
21396
|
+
function customDomainSlug(host) {
|
|
21397
|
+
const name = host?.trim().toLowerCase().replace(/:\d+$/, "");
|
|
21398
|
+
if (!name) return null;
|
|
21399
|
+
if ((!cache3 || Date.now() - cache3.fetchedAt > CACHE_TTL_MS) && databaseReachable()) {
|
|
21400
|
+
void refreshCustomDomainCache();
|
|
21401
|
+
}
|
|
21402
|
+
return cache3?.map.get(name) ?? null;
|
|
21403
|
+
}
|
|
21404
|
+
|
|
21345
21405
|
// ../api/src/dashboard/cors.ts
|
|
21346
21406
|
function allowedOrigins() {
|
|
21347
21407
|
return (process.env["DASHBOARD_ALLOWED_ORIGINS"] ?? "").split(",").map((o) => o.trim().replace(/\/+$/, "")).filter(Boolean);
|
|
21348
21408
|
}
|
|
21349
21409
|
function isAllowedOrigin(origin) {
|
|
21410
|
+
if (origin.startsWith("https://") && customDomainSlug(origin.slice("https://".length))) {
|
|
21411
|
+
return true;
|
|
21412
|
+
}
|
|
21350
21413
|
return allowedOrigins().some((entry) => {
|
|
21351
21414
|
if (!entry.includes("://*.")) return entry === origin;
|
|
21352
21415
|
const [scheme, suffix] = entry.split("://*.");
|
|
@@ -21402,6 +21465,8 @@ function subdomainLabel(host) {
|
|
|
21402
21465
|
return label2;
|
|
21403
21466
|
}
|
|
21404
21467
|
function profileFromHost(host, known) {
|
|
21468
|
+
const custom = customDomainSlug(bareHost(host) ?? void 0);
|
|
21469
|
+
if (custom) return known.includes(custom) ? custom : null;
|
|
21405
21470
|
const label2 = subdomainLabel(host);
|
|
21406
21471
|
if (!label2) return null;
|
|
21407
21472
|
const bare = label2.startsWith("api-") ? label2.slice(4) : label2.startsWith("dev-") ? label2.slice(4) : label2;
|
|
@@ -21831,7 +21896,8 @@ async function startWorkspaceTrial(workspace, plan, ownerEmail) {
|
|
|
21831
21896
|
plan,
|
|
21832
21897
|
stripeCustomerId: customer.id,
|
|
21833
21898
|
stripeSubscriptionId: subscription.id,
|
|
21834
|
-
planStatus: "trialing"
|
|
21899
|
+
planStatus: "trialing",
|
|
21900
|
+
trialEndsAt: subscription.trial_end ? new Date(subscription.trial_end * 1e3).toISOString() : null
|
|
21835
21901
|
});
|
|
21836
21902
|
}
|
|
21837
21903
|
|
|
@@ -22406,7 +22472,8 @@ async function handleSubscriptionUpdated(subscription) {
|
|
|
22406
22472
|
if (!workspace) return;
|
|
22407
22473
|
const planStatus = planStatusFor(subscription.status);
|
|
22408
22474
|
if (!planStatus) return;
|
|
22409
|
-
|
|
22475
|
+
const trialEndsAt = subscription.trial_end ? new Date(subscription.trial_end * 1e3).toISOString() : null;
|
|
22476
|
+
await updateWorkspacePlanStatus(workspace.id, planStatus, trialEndsAt);
|
|
22410
22477
|
}
|
|
22411
22478
|
async function handleCardAdded(session) {
|
|
22412
22479
|
if (session.mode !== "setup" || !session.setup_intent || !session.customer) return;
|
|
@@ -22576,7 +22643,7 @@ async function syncChannel(client2, channelId, channelName, own, oldest) {
|
|
|
22576
22643
|
(m) => m.ts && m.text !== void 0 && !(m.subtype && SKIP_SUBTYPES.has(m.subtype))
|
|
22577
22644
|
);
|
|
22578
22645
|
const userIds = [...new Set(parents.map((m) => m.user).filter((v) => Boolean(v)))];
|
|
22579
|
-
await ensureUsersCached(client2, userIds);
|
|
22646
|
+
await ensureUsersCached(client2, [...userIds, ...parents.flatMap(mentionedUserIds)]);
|
|
22580
22647
|
await syncSlackAvatars(userIds);
|
|
22581
22648
|
let threadCount = 0;
|
|
22582
22649
|
let replyCount = 0;
|
|
@@ -23655,6 +23722,34 @@ async function runSlackCmd(args) {
|
|
|
23655
23722
|
}
|
|
23656
23723
|
}
|
|
23657
23724
|
|
|
23725
|
+
// ../core/src/bridge-protocol.ts
|
|
23726
|
+
var HOST_SOCKET_PATH = "/internal/host-socket";
|
|
23727
|
+
var DEFAULT_DATA_API_PORT = 4757;
|
|
23728
|
+
var CALL_TIMEOUT_MS = 15e3;
|
|
23729
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
23730
|
+
var HEARTBEAT_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 2.5;
|
|
23731
|
+
var LOCAL_RELAY_PATH = "/internal/agent-call";
|
|
23732
|
+
var RELAYED_METHODS = [
|
|
23733
|
+
"onChatMessage",
|
|
23734
|
+
"isAgentThinking",
|
|
23735
|
+
"getAgentActivities",
|
|
23736
|
+
"getBackgroundTasks",
|
|
23737
|
+
"cancelAgentRun",
|
|
23738
|
+
"regenerateAgentRun",
|
|
23739
|
+
"listAgentRuns",
|
|
23740
|
+
"wakeAgentRun"
|
|
23741
|
+
];
|
|
23742
|
+
function encodeWireMessage(msg) {
|
|
23743
|
+
return JSON.stringify(msg);
|
|
23744
|
+
}
|
|
23745
|
+
function parseWireMessage(raw) {
|
|
23746
|
+
try {
|
|
23747
|
+
return JSON.parse(String(raw));
|
|
23748
|
+
} catch {
|
|
23749
|
+
return null;
|
|
23750
|
+
}
|
|
23751
|
+
}
|
|
23752
|
+
|
|
23658
23753
|
// src/commands/chat.ts
|
|
23659
23754
|
var USAGE4 = `
|
|
23660
23755
|
Usage: flyspace chat <subcommand> [options]
|
|
@@ -23665,6 +23760,8 @@ var USAGE4 = `
|
|
|
23665
23760
|
move <thread-id> --to <channel> Move a thread to another channel
|
|
23666
23761
|
post --channel <c> --text <t> Start a new thread, or reply with --thread
|
|
23667
23762
|
[--thread <id>] [--title <t>]
|
|
23763
|
+
wake --thread <id> --text <t> Post a background task's result AND start a
|
|
23764
|
+
new agent turn on the thread to act on it
|
|
23668
23765
|
|
|
23669
23766
|
Options:
|
|
23670
23767
|
--to <name-or-id> Destination channel for "move"
|
|
@@ -23774,7 +23871,7 @@ async function runPost(args) {
|
|
|
23774
23871
|
);
|
|
23775
23872
|
}
|
|
23776
23873
|
const channelId = threadArg ? void 0 : (await resolveChannel(channelArg, getArg3(args, "--profile-name"))).id;
|
|
23777
|
-
const threadId = await postToDashboardChannel({
|
|
23874
|
+
const { threadId } = await postToDashboardChannel({
|
|
23778
23875
|
channelId,
|
|
23779
23876
|
threadId: threadArg,
|
|
23780
23877
|
text,
|
|
@@ -23782,6 +23879,28 @@ async function runPost(args) {
|
|
|
23782
23879
|
});
|
|
23783
23880
|
console.log(threadArg ? `Replied in thread ${threadId}.` : `Posted new thread ${threadId}.`);
|
|
23784
23881
|
}
|
|
23882
|
+
async function runWake(args) {
|
|
23883
|
+
const threadId = getArg3(args, "--thread");
|
|
23884
|
+
const text = getArg3(args, "--text");
|
|
23885
|
+
if (!threadId || !text) throw new Error("Usage: flyspace chat wake --thread <id> --text <t>");
|
|
23886
|
+
const { replyId } = await postToDashboardChannel({ threadId, text });
|
|
23887
|
+
const endpoint = readHostEndpoint();
|
|
23888
|
+
if (!endpoint) {
|
|
23889
|
+
console.log(`Replied in thread ${threadId}, but no Host is running to wake the agent.`);
|
|
23890
|
+
return;
|
|
23891
|
+
}
|
|
23892
|
+
const res = await fetch(`http://127.0.0.1:${endpoint.port}${LOCAL_RELAY_PATH}`, {
|
|
23893
|
+
method: "POST",
|
|
23894
|
+
headers: { authorization: `Bearer ${endpoint.token}`, "content-type": "application/json" },
|
|
23895
|
+
body: JSON.stringify({ method: "wakeAgentRun", profile: getProfile(), args: [threadId, replyId, text] }),
|
|
23896
|
+
signal: AbortSignal.timeout(3e4)
|
|
23897
|
+
});
|
|
23898
|
+
if (!res.ok) throw new Error(`Replied in thread ${threadId}, but the Host answered ${res.status}`);
|
|
23899
|
+
const { value } = await res.json();
|
|
23900
|
+
console.log(
|
|
23901
|
+
value ? `Replied in thread ${threadId} and woke the agent.` : `Replied in thread ${threadId}; wake refused (too many wakes in a row without a human message).`
|
|
23902
|
+
);
|
|
23903
|
+
}
|
|
23785
23904
|
async function runChatCmd(args) {
|
|
23786
23905
|
loadEnvFiles();
|
|
23787
23906
|
useHostDbWithoutCredentials();
|
|
@@ -23800,6 +23919,9 @@ async function runChatCmd(args) {
|
|
|
23800
23919
|
case "post":
|
|
23801
23920
|
await runPost(rest);
|
|
23802
23921
|
break;
|
|
23922
|
+
case "wake":
|
|
23923
|
+
await runWake(rest);
|
|
23924
|
+
break;
|
|
23803
23925
|
case "-h":
|
|
23804
23926
|
case "--help":
|
|
23805
23927
|
case void 0:
|
|
@@ -24074,7 +24196,7 @@ async function runMcpCmd(args) {
|
|
|
24074
24196
|
loadEnvFiles();
|
|
24075
24197
|
switch (server) {
|
|
24076
24198
|
case "threads": {
|
|
24077
|
-
const { startThreadsServer } = await import("./threads-
|
|
24199
|
+
const { startThreadsServer } = await import("./threads-QAVO2Z4L.js");
|
|
24078
24200
|
await startThreadsServer();
|
|
24079
24201
|
return;
|
|
24080
24202
|
}
|
|
@@ -24262,7 +24384,93 @@ var requireDocsAccess = async (c, next) => {
|
|
|
24262
24384
|
};
|
|
24263
24385
|
|
|
24264
24386
|
// ../api/src/dashboard/api.ts
|
|
24265
|
-
import { Hono as
|
|
24387
|
+
import { Hono as Hono35 } from "hono";
|
|
24388
|
+
|
|
24389
|
+
// ../api/src/dashboard/supabase-server-client.ts
|
|
24390
|
+
import { createServerClient, parseCookieHeader, serializeCookieHeader } from "@supabase/ssr";
|
|
24391
|
+
|
|
24392
|
+
// ../api/src/dashboard/scoped-auth-cookies.ts
|
|
24393
|
+
import { stringFromBase64URL } from "@supabase/ssr";
|
|
24394
|
+
var SESSION_NAME = /^(sb-.+-auth-token)(?:\.\d+)?$/;
|
|
24395
|
+
var SCOPE_MARK = "fsw_";
|
|
24396
|
+
var SCOPE_END = "__";
|
|
24397
|
+
function hostLabel(host) {
|
|
24398
|
+
return host.toLowerCase().replace(/:\d+$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
24399
|
+
}
|
|
24400
|
+
var scopePrefix = (label2) => `${SCOPE_MARK}${label2}${SCOPE_END}`;
|
|
24401
|
+
function sessionUserId(cookies) {
|
|
24402
|
+
const base = cookies.map((c) => SESSION_NAME.exec(c.name)?.[1]).find(Boolean);
|
|
24403
|
+
if (!base) return null;
|
|
24404
|
+
const whole = cookies.find((c) => c.name === base)?.value;
|
|
24405
|
+
const raw = whole ?? cookies.filter((c) => c.name.startsWith(`${base}.`)).sort((a, b) => Number(a.name.split(".").pop()) - Number(b.name.split(".").pop())).map((c) => c.value).join("");
|
|
24406
|
+
if (!raw) return null;
|
|
24407
|
+
try {
|
|
24408
|
+
const json = raw.startsWith("base64-") ? stringFromBase64URL(raw.slice(7)) : raw;
|
|
24409
|
+
const id = JSON.parse(json).user?.id;
|
|
24410
|
+
return typeof id === "string" ? id : null;
|
|
24411
|
+
} catch {
|
|
24412
|
+
return null;
|
|
24413
|
+
}
|
|
24414
|
+
}
|
|
24415
|
+
var isScoped = (name) => name.startsWith(SCOPE_MARK);
|
|
24416
|
+
function readScopedCookies(all, label2) {
|
|
24417
|
+
const prefix = scopePrefix(label2);
|
|
24418
|
+
const own = all.filter((c) => c.name.startsWith(prefix)).map((c) => ({ name: c.name.slice(prefix.length), value: c.value }));
|
|
24419
|
+
return own.length ? own : all.filter((c) => !isScoped(c.name));
|
|
24420
|
+
}
|
|
24421
|
+
function routeCookieWrites(all, label2, writes) {
|
|
24422
|
+
const prefix = scopePrefix(label2);
|
|
24423
|
+
const hasOwn = all.some((c) => c.name.startsWith(prefix));
|
|
24424
|
+
const incoming = sessionUserId(writes.filter((c) => c.value !== ""));
|
|
24425
|
+
const shared = sessionUserId(all.filter((c) => !isScoped(c.name)));
|
|
24426
|
+
const toScoped = hasOwn || incoming !== null && shared !== null && incoming !== shared;
|
|
24427
|
+
return writes.map(
|
|
24428
|
+
(c) => toScoped ? { name: prefix + c.name, value: c.value, scoped: true } : { ...c, scoped: false }
|
|
24429
|
+
);
|
|
24430
|
+
}
|
|
24431
|
+
|
|
24432
|
+
// ../api/src/dashboard/supabase-server-client.ts
|
|
24433
|
+
var REQUEST_TIMEOUT_MS2 = 5e3;
|
|
24434
|
+
function fetchWithTimeout(input2, init2) {
|
|
24435
|
+
return fetch(input2, { ...init2, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2) });
|
|
24436
|
+
}
|
|
24437
|
+
function createRequestSupabaseClient(c) {
|
|
24438
|
+
const url = process.env["SUPABASE_URL"];
|
|
24439
|
+
const key = process.env["VITE_SUPABASE_PUBLISHABLE_KEY"];
|
|
24440
|
+
if (!url || !key) {
|
|
24441
|
+
throw new Error("SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_KEY not set \u2014 check .env");
|
|
24442
|
+
}
|
|
24443
|
+
const origin = c.req.header("Origin");
|
|
24444
|
+
const label2 = hostLabel(
|
|
24445
|
+
(origin ? URL.parse(origin)?.host : void 0) ?? c.req.header("X-Forwarded-Host") ?? c.req.header("Host") ?? ""
|
|
24446
|
+
);
|
|
24447
|
+
const rawCookies = () => parseCookieHeader(c.req.header("Cookie") ?? "").map(({ name, value }) => ({
|
|
24448
|
+
name,
|
|
24449
|
+
value: value ?? ""
|
|
24450
|
+
}));
|
|
24451
|
+
return createServerClient(url, key, {
|
|
24452
|
+
global: { fetch: fetchWithTimeout },
|
|
24453
|
+
cookies: {
|
|
24454
|
+
// `parseCookieHeader` types `value` as optional; the client requires a
|
|
24455
|
+
// string, and a valueless cookie is the same as an empty one here.
|
|
24456
|
+
getAll: () => readScopedCookies(rawCookies(), label2),
|
|
24457
|
+
setAll: (cookies) => {
|
|
24458
|
+
const domain = process.env["AUTH_COOKIE_DOMAIN"]?.trim();
|
|
24459
|
+
const overrides = {
|
|
24460
|
+
...domain ? { domain } : {},
|
|
24461
|
+
...crossOriginShell(c) ? { sameSite: "none", secure: true } : {}
|
|
24462
|
+
};
|
|
24463
|
+
const routed = routeCookieWrites(rawCookies(), label2, cookies);
|
|
24464
|
+
cookies.forEach(({ options }, i) => {
|
|
24465
|
+
const { name, value } = routed[i];
|
|
24466
|
+
c.header("Set-Cookie", serializeCookieHeader(name, value, { ...options, ...overrides }), {
|
|
24467
|
+
append: true
|
|
24468
|
+
});
|
|
24469
|
+
});
|
|
24470
|
+
}
|
|
24471
|
+
}
|
|
24472
|
+
});
|
|
24473
|
+
}
|
|
24266
24474
|
|
|
24267
24475
|
// ../api/src/dashboard/public-share-routes.ts
|
|
24268
24476
|
import { existsSync as existsSync17, readFileSync as readFileSync17, statSync as statSync3 } from "fs";
|
|
@@ -24744,7 +24952,7 @@ var LAYOUT = {
|
|
|
24744
24952
|
};
|
|
24745
24953
|
var PLAIN_LOGO = 0.84;
|
|
24746
24954
|
var PLATE_RADIUS = 0.18;
|
|
24747
|
-
var
|
|
24955
|
+
var cache4 = /* @__PURE__ */ new Map();
|
|
24748
24956
|
function decodeLogo(logo) {
|
|
24749
24957
|
if (!logo?.startsWith("data:image/")) return null;
|
|
24750
24958
|
const comma = logo.indexOf(",");
|
|
@@ -24811,12 +25019,12 @@ async function renderAppIcon({
|
|
|
24811
25019
|
plain ? "plain" : "badged",
|
|
24812
25020
|
logo ? createHash2("sha1").update(logo).digest("hex").slice(0, 12) : transparent ? "stock-transparent" : "stock"
|
|
24813
25021
|
].join(":");
|
|
24814
|
-
const hit =
|
|
25022
|
+
const hit = cache4.get(key);
|
|
24815
25023
|
if (hit) return hit;
|
|
24816
25024
|
const out = logo && await composeIcon(logo, size, maskable, plain).catch(() => null) || // No workspace logo to lead with — the stock mark is still the best icon,
|
|
24817
25025
|
// either on its usual dark plate or, for a favicon, trimmed and bare.
|
|
24818
25026
|
(transparent ? await renderBadge(size) : await sharp2(readFileSync16(MARK_FILE)).resize(size, size, { fit: "cover" }).png().toBuffer());
|
|
24819
|
-
|
|
25027
|
+
cache4.set(key, out);
|
|
24820
25028
|
return out;
|
|
24821
25029
|
}
|
|
24822
25030
|
async function composeIcon(logo, size, maskable, plain) {
|
|
@@ -25686,7 +25894,7 @@ function backdrop(input2, hasLogo) {
|
|
|
25686
25894
|
`<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}"><defs><pattern id="grid" width="56" height="56" patternUnits="userSpaceOnUse"><path d="M56 0H0V56" fill="none" stroke="${gridStroke}" stroke-opacity="0.035" stroke-width="1"/></pattern>` + glowDefs + `</defs><rect width="${WIDTH}" height="${HEIGHT}" fill="${palette.bg}"/><rect width="${WIDTH}" height="${HEIGHT}" fill="url(#grid)"/>` + glowRect + initialChip + nameText + title + description + `<text x="${PAD}" y="${FOOTER_BASELINE}" font-family="${SANS}" font-size="21" fill="${palette.muted}">Powered by Flyspace</text>` + published + `</svg>`
|
|
25687
25895
|
);
|
|
25688
25896
|
}
|
|
25689
|
-
var
|
|
25897
|
+
var cache5 = /* @__PURE__ */ new Map();
|
|
25690
25898
|
var CACHE_MAX = 64;
|
|
25691
25899
|
function cacheKey(input2) {
|
|
25692
25900
|
const parts = [
|
|
@@ -25701,13 +25909,13 @@ function cacheKey(input2) {
|
|
|
25701
25909
|
}
|
|
25702
25910
|
async function renderShareOgImage(input2) {
|
|
25703
25911
|
const key = cacheKey(input2);
|
|
25704
|
-
const hit =
|
|
25912
|
+
const hit = cache5.get(key);
|
|
25705
25913
|
if (hit) return hit;
|
|
25706
25914
|
const chip = input2.workspaceName?.trim() ? await renderLogoChip(decodeLogo(input2.logo)) : null;
|
|
25707
25915
|
const composed = sharp3(backdrop(input2, !!chip));
|
|
25708
25916
|
const out = await (chip ? composed.composite([{ input: chip, left: PAD, top: LOGO_TOP }]) : composed).png({ compressionLevel: 9 }).toBuffer();
|
|
25709
|
-
if (
|
|
25710
|
-
|
|
25917
|
+
if (cache5.size >= CACHE_MAX) cache5.delete(cache5.keys().next().value);
|
|
25918
|
+
cache5.set(key, out);
|
|
25711
25919
|
return out;
|
|
25712
25920
|
}
|
|
25713
25921
|
|
|
@@ -26304,92 +26512,6 @@ function createGuestRouter() {
|
|
|
26304
26512
|
// ../api/src/dashboard/auth-routes.ts
|
|
26305
26513
|
import { Hono as Hono9 } from "hono";
|
|
26306
26514
|
|
|
26307
|
-
// ../api/src/dashboard/supabase-server-client.ts
|
|
26308
|
-
import { createServerClient, parseCookieHeader, serializeCookieHeader } from "@supabase/ssr";
|
|
26309
|
-
|
|
26310
|
-
// ../api/src/dashboard/scoped-auth-cookies.ts
|
|
26311
|
-
import { stringFromBase64URL } from "@supabase/ssr";
|
|
26312
|
-
var SESSION_NAME = /^(sb-.+-auth-token)(?:\.\d+)?$/;
|
|
26313
|
-
var SCOPE_MARK = "fsw_";
|
|
26314
|
-
var SCOPE_END = "__";
|
|
26315
|
-
function hostLabel(host) {
|
|
26316
|
-
return host.toLowerCase().replace(/:\d+$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
26317
|
-
}
|
|
26318
|
-
var scopePrefix = (label2) => `${SCOPE_MARK}${label2}${SCOPE_END}`;
|
|
26319
|
-
function sessionUserId(cookies) {
|
|
26320
|
-
const base = cookies.map((c) => SESSION_NAME.exec(c.name)?.[1]).find(Boolean);
|
|
26321
|
-
if (!base) return null;
|
|
26322
|
-
const whole = cookies.find((c) => c.name === base)?.value;
|
|
26323
|
-
const raw = whole ?? cookies.filter((c) => c.name.startsWith(`${base}.`)).sort((a, b) => Number(a.name.split(".").pop()) - Number(b.name.split(".").pop())).map((c) => c.value).join("");
|
|
26324
|
-
if (!raw) return null;
|
|
26325
|
-
try {
|
|
26326
|
-
const json = raw.startsWith("base64-") ? stringFromBase64URL(raw.slice(7)) : raw;
|
|
26327
|
-
const id = JSON.parse(json).user?.id;
|
|
26328
|
-
return typeof id === "string" ? id : null;
|
|
26329
|
-
} catch {
|
|
26330
|
-
return null;
|
|
26331
|
-
}
|
|
26332
|
-
}
|
|
26333
|
-
var isScoped = (name) => name.startsWith(SCOPE_MARK);
|
|
26334
|
-
function readScopedCookies(all, label2) {
|
|
26335
|
-
const prefix = scopePrefix(label2);
|
|
26336
|
-
const own = all.filter((c) => c.name.startsWith(prefix)).map((c) => ({ name: c.name.slice(prefix.length), value: c.value }));
|
|
26337
|
-
return own.length ? own : all.filter((c) => !isScoped(c.name));
|
|
26338
|
-
}
|
|
26339
|
-
function routeCookieWrites(all, label2, writes) {
|
|
26340
|
-
const prefix = scopePrefix(label2);
|
|
26341
|
-
const hasOwn = all.some((c) => c.name.startsWith(prefix));
|
|
26342
|
-
const incoming = sessionUserId(writes.filter((c) => c.value !== ""));
|
|
26343
|
-
const shared = sessionUserId(all.filter((c) => !isScoped(c.name)));
|
|
26344
|
-
const toScoped = hasOwn || incoming !== null && shared !== null && incoming !== shared;
|
|
26345
|
-
return writes.map(
|
|
26346
|
-
(c) => toScoped ? { name: prefix + c.name, value: c.value, scoped: true } : { ...c, scoped: false }
|
|
26347
|
-
);
|
|
26348
|
-
}
|
|
26349
|
-
|
|
26350
|
-
// ../api/src/dashboard/supabase-server-client.ts
|
|
26351
|
-
var REQUEST_TIMEOUT_MS2 = 5e3;
|
|
26352
|
-
function fetchWithTimeout(input2, init2) {
|
|
26353
|
-
return fetch(input2, { ...init2, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2) });
|
|
26354
|
-
}
|
|
26355
|
-
function createRequestSupabaseClient(c) {
|
|
26356
|
-
const url = process.env["SUPABASE_URL"];
|
|
26357
|
-
const key = process.env["VITE_SUPABASE_PUBLISHABLE_KEY"];
|
|
26358
|
-
if (!url || !key) {
|
|
26359
|
-
throw new Error("SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_KEY not set \u2014 check .env");
|
|
26360
|
-
}
|
|
26361
|
-
const origin = c.req.header("Origin");
|
|
26362
|
-
const label2 = hostLabel(
|
|
26363
|
-
(origin ? URL.parse(origin)?.host : void 0) ?? c.req.header("X-Forwarded-Host") ?? c.req.header("Host") ?? ""
|
|
26364
|
-
);
|
|
26365
|
-
const rawCookies = () => parseCookieHeader(c.req.header("Cookie") ?? "").map(({ name, value }) => ({
|
|
26366
|
-
name,
|
|
26367
|
-
value: value ?? ""
|
|
26368
|
-
}));
|
|
26369
|
-
return createServerClient(url, key, {
|
|
26370
|
-
global: { fetch: fetchWithTimeout },
|
|
26371
|
-
cookies: {
|
|
26372
|
-
// `parseCookieHeader` types `value` as optional; the client requires a
|
|
26373
|
-
// string, and a valueless cookie is the same as an empty one here.
|
|
26374
|
-
getAll: () => readScopedCookies(rawCookies(), label2),
|
|
26375
|
-
setAll: (cookies) => {
|
|
26376
|
-
const domain = process.env["AUTH_COOKIE_DOMAIN"]?.trim();
|
|
26377
|
-
const overrides = {
|
|
26378
|
-
...domain ? { domain } : {},
|
|
26379
|
-
...crossOriginShell(c) ? { sameSite: "none", secure: true } : {}
|
|
26380
|
-
};
|
|
26381
|
-
const routed = routeCookieWrites(rawCookies(), label2, cookies);
|
|
26382
|
-
cookies.forEach(({ options }, i) => {
|
|
26383
|
-
const { name, value } = routed[i];
|
|
26384
|
-
c.header("Set-Cookie", serializeCookieHeader(name, value, { ...options, ...overrides }), {
|
|
26385
|
-
append: true
|
|
26386
|
-
});
|
|
26387
|
-
});
|
|
26388
|
-
}
|
|
26389
|
-
}
|
|
26390
|
-
});
|
|
26391
|
-
}
|
|
26392
|
-
|
|
26393
26515
|
// ../api/src/dashboard/auth-context.ts
|
|
26394
26516
|
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
26395
26517
|
import { isAuthApiError, isAuthRetryableFetchError } from "@supabase/supabase-js";
|
|
@@ -26402,7 +26524,7 @@ function onboardingPending(ctx) {
|
|
|
26402
26524
|
return pending2;
|
|
26403
26525
|
}
|
|
26404
26526
|
var inFlight3 = /* @__PURE__ */ new Map();
|
|
26405
|
-
var
|
|
26527
|
+
var CACHE_TTL_MS2 = 3e4;
|
|
26406
26528
|
var resolved = /* @__PURE__ */ new Map();
|
|
26407
26529
|
function invalidateAuthContextCache() {
|
|
26408
26530
|
resolved.clear();
|
|
@@ -26436,7 +26558,7 @@ async function resolveAuthContextCached(c, opts) {
|
|
|
26436
26558
|
const inflight = inFlight3.get(key);
|
|
26437
26559
|
if (inflight) return inflight;
|
|
26438
26560
|
const promise = resolveAuthContextUncached(c).then((value) => {
|
|
26439
|
-
resolved.set(key, { value, expires: Date.now() +
|
|
26561
|
+
resolved.set(key, { value, expires: Date.now() + CACHE_TTL_MS2 });
|
|
26440
26562
|
return value;
|
|
26441
26563
|
}).finally(() => inFlight3.delete(key));
|
|
26442
26564
|
inFlight3.set(key, promise);
|
|
@@ -26499,18 +26621,18 @@ import { GetObjectCommand as GetObjectCommand2 } from "@aws-sdk/client-s3";
|
|
|
26499
26621
|
import { getSignedUrl as getSignedUrl2 } from "@aws-sdk/s3-request-presigner";
|
|
26500
26622
|
var TTL_SECONDS = 24 * 60 * 60;
|
|
26501
26623
|
var REUSE_MS = 20 * 60 * 60 * 1e3;
|
|
26502
|
-
var
|
|
26624
|
+
var cache6 = /* @__PURE__ */ new Map();
|
|
26503
26625
|
async function signAvatarUrl(key) {
|
|
26504
26626
|
const now = Date.now();
|
|
26505
|
-
const hit =
|
|
26627
|
+
const hit = cache6.get(key);
|
|
26506
26628
|
if (hit && now - hit.signedAt < REUSE_MS) return hit.url;
|
|
26507
|
-
for (const [k, v] of
|
|
26629
|
+
for (const [k, v] of cache6) if (now - v.signedAt >= REUSE_MS) cache6.delete(k);
|
|
26508
26630
|
const url = await getSignedUrl2(
|
|
26509
26631
|
getR2Client(),
|
|
26510
26632
|
new GetObjectCommand2({ Bucket: getR2Bucket(), Key: key }),
|
|
26511
26633
|
{ expiresIn: TTL_SECONDS }
|
|
26512
26634
|
);
|
|
26513
|
-
|
|
26635
|
+
cache6.set(key, { url, signedAt: now });
|
|
26514
26636
|
return url;
|
|
26515
26637
|
}
|
|
26516
26638
|
|
|
@@ -26882,32 +27004,6 @@ function createUploadsRouter() {
|
|
|
26882
27004
|
return app;
|
|
26883
27005
|
}
|
|
26884
27006
|
|
|
26885
|
-
// ../core/src/bridge-protocol.ts
|
|
26886
|
-
var HOST_SOCKET_PATH = "/internal/host-socket";
|
|
26887
|
-
var DEFAULT_DATA_API_PORT = 4757;
|
|
26888
|
-
var CALL_TIMEOUT_MS = 15e3;
|
|
26889
|
-
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
26890
|
-
var HEARTBEAT_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 2.5;
|
|
26891
|
-
var LOCAL_RELAY_PATH = "/internal/agent-call";
|
|
26892
|
-
var RELAYED_METHODS = [
|
|
26893
|
-
"onChatMessage",
|
|
26894
|
-
"isAgentThinking",
|
|
26895
|
-
"getAgentActivities",
|
|
26896
|
-
"cancelAgentRun",
|
|
26897
|
-
"regenerateAgentRun",
|
|
26898
|
-
"listAgentRuns"
|
|
26899
|
-
];
|
|
26900
|
-
function encodeWireMessage(msg) {
|
|
26901
|
-
return JSON.stringify(msg);
|
|
26902
|
-
}
|
|
26903
|
-
function parseWireMessage(raw) {
|
|
26904
|
-
try {
|
|
26905
|
-
return JSON.parse(String(raw));
|
|
26906
|
-
} catch {
|
|
26907
|
-
return null;
|
|
26908
|
-
}
|
|
26909
|
-
}
|
|
26910
|
-
|
|
26911
27007
|
// ../api/src/dashboard/slack-format.ts
|
|
26912
27008
|
import { nameToEmoji } from "gemoji";
|
|
26913
27009
|
var SLACK_EMOJI_ALIASES = {
|
|
@@ -26918,7 +27014,10 @@ function emojifyShortcode(code) {
|
|
|
26918
27014
|
return nameToEmoji[name] ?? SLACK_EMOJI_ALIASES[name] ?? code;
|
|
26919
27015
|
}
|
|
26920
27016
|
function resolveSlackTokens(text) {
|
|
26921
|
-
return text.replace(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g, (_m, id
|
|
27017
|
+
return text.replace(/<@([A-Z0-9]+)(?:\|([^>]*))?>/g, (_m, id, label2) => {
|
|
27018
|
+
const name = getLocalCache().displayNameFor(id);
|
|
27019
|
+
return `@${name === id && label2 ? label2 : name}`;
|
|
27020
|
+
}).replace(/<#([A-Z0-9]+)\|([^>]+)>/g, (_m, _id, name) => `#${name}`).replace(/<#([A-Z0-9]+)>/g, (_m, id) => `#${getLocalCache().lookupChannelById(id)?.name ?? id}`).replace(/<!channel>/g, "@channel").replace(/<!here>/g, "@here").replace(/<!everyone>/g, "@everyone").replace(/<!subteam\^[A-Z0-9]+\|@?([^>]+)>/g, "@$1").replace(/<mailto:([^|>]+)\|([^>]+)>/g, (_m, addr, label2) => `[${label2}](mailto:${addr})`).replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g, (_m, url, label2) => `[${label2}](${url})`).replace(/:[a-z0-9_+-]+:/gi, emojifyShortcode);
|
|
26922
27021
|
}
|
|
26923
27022
|
function slackMrkdwnToMarkdown(text) {
|
|
26924
27023
|
return resolveSlackTokens(text).replace(/(?<![\w*])\*(?!\*)(\S(?:[^*\n]*?\S)?)\*(?!\*)(?![\w*])/g, "**$1**").replace(/(?<![\w~])~(?!~)(\S(?:[^~\n]*?\S)?)~(?!~)(?![\w~])/g, "~~$1~~").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
@@ -28238,14 +28337,19 @@ async function relevantThreadsPage(supabase, handle, channelIds, opts) {
|
|
|
28238
28337
|
import { createHash as createHash8 } from "crypto";
|
|
28239
28338
|
|
|
28240
28339
|
// ../api/src/store/thread-translation-store.ts
|
|
28241
|
-
|
|
28340
|
+
var TABLES = {
|
|
28341
|
+
reply: { table: "thread_reply_translations", idColumn: "reply_id" },
|
|
28342
|
+
title: { table: "thread_title_translations", idColumn: "thread_id" }
|
|
28343
|
+
};
|
|
28344
|
+
async function getThreadTranslations(lang, keys, kind = "reply") {
|
|
28345
|
+
const { table, idColumn } = TABLES[kind];
|
|
28242
28346
|
const found = /* @__PURE__ */ new Map();
|
|
28243
28347
|
if (keys.length === 0) return found;
|
|
28244
|
-
const clauses = keys.map((k) => `and(
|
|
28245
|
-
const { data, error: error2 } = await getSupabaseClient().from(
|
|
28348
|
+
const clauses = keys.map((k) => `and(${idColumn}.eq.${k.replyId},body_hash.eq.${k.bodyHash})`).join(",");
|
|
28349
|
+
const { data, error: error2 } = await getSupabaseClient().from(table).select(`${idColumn}, body, passthrough`).eq("lang", lang).or(clauses);
|
|
28246
28350
|
if (error2) throw new Error(`getThreadTranslations(${lang}): ${error2.message}`);
|
|
28247
28351
|
for (const row of data ?? []) {
|
|
28248
|
-
const replyId = row[
|
|
28352
|
+
const replyId = row[idColumn];
|
|
28249
28353
|
found.set(replyId, {
|
|
28250
28354
|
replyId,
|
|
28251
28355
|
body: row["body"],
|
|
@@ -28254,21 +28358,41 @@ async function getThreadTranslations(lang, keys) {
|
|
|
28254
28358
|
}
|
|
28255
28359
|
return found;
|
|
28256
28360
|
}
|
|
28257
|
-
async function putThreadTranslations(lang, rows) {
|
|
28361
|
+
async function putThreadTranslations(lang, rows, kind = "reply") {
|
|
28258
28362
|
if (rows.length === 0) return;
|
|
28259
|
-
const {
|
|
28363
|
+
const { table, idColumn } = TABLES[kind];
|
|
28364
|
+
const { error: error2 } = await getSupabaseClient().from(table).upsert(
|
|
28260
28365
|
rows.map((r) => ({
|
|
28261
|
-
|
|
28366
|
+
[idColumn]: r.replyId,
|
|
28262
28367
|
lang,
|
|
28263
28368
|
body_hash: r.bodyHash,
|
|
28264
28369
|
body: r.body,
|
|
28265
28370
|
passthrough: r.passthrough
|
|
28266
28371
|
})),
|
|
28267
|
-
{ onConflict:
|
|
28372
|
+
{ onConflict: `${idColumn},lang,body_hash` }
|
|
28268
28373
|
);
|
|
28269
28374
|
if (error2) throw new Error(`putThreadTranslations(${lang}): ${error2.message}`);
|
|
28270
28375
|
}
|
|
28271
28376
|
|
|
28377
|
+
// ../api/src/store/translation-usage-store.ts
|
|
28378
|
+
function today() {
|
|
28379
|
+
return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
28380
|
+
}
|
|
28381
|
+
async function getTranslationTokensToday(workspaceId) {
|
|
28382
|
+
const { data, error: error2 } = await getSupabaseClient().from("translation_usage").select("tokens").eq("workspace_id", workspaceId).eq("day", today()).maybeSingle();
|
|
28383
|
+
if (error2) throw new Error(`getTranslationTokensToday: ${error2.message}`);
|
|
28384
|
+
return Number(data?.tokens ?? 0);
|
|
28385
|
+
}
|
|
28386
|
+
async function addTranslationTokens(workspaceId, tokens2) {
|
|
28387
|
+
if (tokens2 <= 0) return;
|
|
28388
|
+
const { error: error2 } = await getSupabaseClient().rpc("add_translation_usage", {
|
|
28389
|
+
p_workspace_id: workspaceId,
|
|
28390
|
+
p_day: today(),
|
|
28391
|
+
p_tokens: tokens2
|
|
28392
|
+
});
|
|
28393
|
+
if (error2) throw new Error(`addTranslationTokens: ${error2.message}`);
|
|
28394
|
+
}
|
|
28395
|
+
|
|
28272
28396
|
// ../api/src/dashboard/thread-translate.ts
|
|
28273
28397
|
var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
|
|
28274
28398
|
var TRANSLATION_MODEL2 = "openai/gpt-oss-120b";
|
|
@@ -28277,6 +28401,16 @@ var BATCH_CHAR_BUDGET = 16e3;
|
|
|
28277
28401
|
var CONTEXT_MESSAGES = 4;
|
|
28278
28402
|
var MAX_MESSAGE_CHARS = 12e3;
|
|
28279
28403
|
var MAX_OUTPUT_TOKENS2 = 32768;
|
|
28404
|
+
var DAILY_TOKEN_LIMIT = Number(process.env["TRANSLATION_DAILY_TOKEN_LIMIT"] ?? 2e6);
|
|
28405
|
+
var TranslationLimitError = class extends Error {
|
|
28406
|
+
constructor() {
|
|
28407
|
+
super("daily translation limit reached");
|
|
28408
|
+
}
|
|
28409
|
+
};
|
|
28410
|
+
function glossaryFor(glossary, bodies) {
|
|
28411
|
+
const text = bodies.join("\n").toLowerCase();
|
|
28412
|
+
return glossary.filter((g) => text.includes(g.term.toLowerCase()));
|
|
28413
|
+
}
|
|
28280
28414
|
var BY_CODE2 = new Map(TRANSLATION_LANGUAGES.map((l) => [l.code, l]));
|
|
28281
28415
|
function isTranslatableLanguage2(lang) {
|
|
28282
28416
|
return BY_CODE2.has(lang);
|
|
@@ -28292,6 +28426,7 @@ function systemPrompt2(languageName2) {
|
|
|
28292
28426
|
You receive a JSON object with two keys:
|
|
28293
28427
|
- "context": earlier messages, for reference only. NEVER translate these and never mention them in your output.
|
|
28294
28428
|
- "translate": the messages to translate, each with an "n" and a "body".
|
|
28429
|
+
- "glossary" (optional): terms specific to this group. Follow each entry's "note"; an entry with an empty note is kept exactly as written.
|
|
28295
28430
|
|
|
28296
28431
|
Reply with ONLY a JSON object of this exact shape, one entry per message in "translate", in the same order:
|
|
28297
28432
|
{"messages":[{"n":1,"body":"...","already_target":false}]}
|
|
@@ -28329,14 +28464,18 @@ function batchMessages(messages) {
|
|
|
28329
28464
|
if (current.length > 0) batches.push(current);
|
|
28330
28465
|
return batches;
|
|
28331
28466
|
}
|
|
28332
|
-
async function translateBatch(batch, context, lang) {
|
|
28467
|
+
async function translateBatch(batch, context, lang, scope) {
|
|
28333
28468
|
const language = BY_CODE2.get(lang);
|
|
28334
28469
|
if (!language) throw new Error(`unsupported translation language: ${lang}`);
|
|
28335
28470
|
const apiKey = process.env["GROQ_API_KEY"];
|
|
28336
28471
|
if (!apiKey) throw new Error("GROQ_API_KEY is not configured");
|
|
28337
28472
|
const payload = {
|
|
28338
28473
|
context: context.map((m) => ({ author: m.author, body: clip(m.body) })),
|
|
28339
|
-
translate: batch.map((m, i) => ({ n: i + 1, author: m.author, body: clip(m.body) }))
|
|
28474
|
+
translate: batch.map((m, i) => ({ n: i + 1, author: m.author, body: clip(m.body) })),
|
|
28475
|
+
glossary: glossaryFor(
|
|
28476
|
+
scope.glossary,
|
|
28477
|
+
batch.map((m) => m.body)
|
|
28478
|
+
)
|
|
28340
28479
|
};
|
|
28341
28480
|
const res = await fetch(GROQ_API_URL6, {
|
|
28342
28481
|
method: "POST",
|
|
@@ -28354,6 +28493,9 @@ async function translateBatch(batch, context, lang) {
|
|
|
28354
28493
|
});
|
|
28355
28494
|
if (!res.ok) throw new Error(`translation model returned ${res.status}`);
|
|
28356
28495
|
const data = await res.json();
|
|
28496
|
+
await addTranslationTokens(scope.workspaceId, data.usage?.total_tokens ?? 0).catch(
|
|
28497
|
+
(err) => console.error("Translation usage not recorded:", err)
|
|
28498
|
+
);
|
|
28357
28499
|
const choice = data.choices?.[0];
|
|
28358
28500
|
if (choice?.finish_reason === "length") {
|
|
28359
28501
|
throw new Error("the translation ran past the model output limit");
|
|
@@ -28382,52 +28524,121 @@ async function translateBatch(batch, context, lang) {
|
|
|
28382
28524
|
});
|
|
28383
28525
|
}
|
|
28384
28526
|
var inFlight4 = /* @__PURE__ */ new Map();
|
|
28385
|
-
async function
|
|
28527
|
+
async function translateCached(lang, scope, messages, contextFor) {
|
|
28386
28528
|
if (!BY_CODE2.has(lang)) throw new Error(`unsupported translation language: ${lang}`);
|
|
28387
28529
|
if (messages.length === 0) return [];
|
|
28388
|
-
const
|
|
28389
|
-
const
|
|
28530
|
+
const keyed = messages.map((m) => ({ ...m, hash: translationHash2(m.author, m.body) }));
|
|
28531
|
+
const shape = createHash8("sha256").update(keyed.map((m) => `${m.kind}:${m.id}:${m.hash}`).join("\n")).digest("hex");
|
|
28532
|
+
const key = `${lang}:${shape}`;
|
|
28390
28533
|
const running2 = inFlight4.get(key);
|
|
28391
28534
|
if (running2) return running2;
|
|
28392
28535
|
const job = (async () => {
|
|
28393
|
-
const
|
|
28394
|
-
|
|
28395
|
-
|
|
28396
|
-
|
|
28397
|
-
|
|
28398
|
-
|
|
28536
|
+
const kinds = ["reply", "title"];
|
|
28537
|
+
const cachedByKind = new Map(
|
|
28538
|
+
await Promise.all(
|
|
28539
|
+
kinds.map(
|
|
28540
|
+
async (kind) => [
|
|
28541
|
+
kind,
|
|
28542
|
+
await getThreadTranslations(
|
|
28543
|
+
lang,
|
|
28544
|
+
keyed.filter((m) => m.kind === kind).map((m) => ({ replyId: m.id, bodyHash: m.hash })),
|
|
28545
|
+
kind
|
|
28546
|
+
)
|
|
28547
|
+
]
|
|
28548
|
+
)
|
|
28549
|
+
)
|
|
28550
|
+
);
|
|
28551
|
+
const cachedOf = (m) => cachedByKind.get(m.kind)?.get(m.id);
|
|
28552
|
+
const missing = keyed.filter((m) => !cachedOf(m));
|
|
28399
28553
|
const fresh = /* @__PURE__ */ new Map();
|
|
28554
|
+
const freshKey = (m) => `${m.kind}:${m.id}`;
|
|
28400
28555
|
if (missing.length > 0) {
|
|
28401
|
-
|
|
28556
|
+
if (await getTranslationTokensToday(scope.workspaceId) >= DAILY_TOKEN_LIMIT) {
|
|
28557
|
+
throw new TranslationLimitError();
|
|
28558
|
+
}
|
|
28402
28559
|
const batches = batchMessages(missing);
|
|
28403
28560
|
const results = await Promise.all(
|
|
28404
|
-
batches.map((batch) =>
|
|
28405
|
-
const first = index.get(batch[0].id) ?? 0;
|
|
28406
|
-
const context = messages.slice(Math.max(0, first - CONTEXT_MESSAGES), first);
|
|
28407
|
-
return translateBatch(batch, context, lang);
|
|
28408
|
-
})
|
|
28561
|
+
batches.map((batch) => translateBatch(batch, contextFor(batch[0]), lang, scope))
|
|
28409
28562
|
);
|
|
28410
|
-
|
|
28411
|
-
|
|
28412
|
-
|
|
28413
|
-
|
|
28414
|
-
|
|
28415
|
-
|
|
28416
|
-
|
|
28417
|
-
|
|
28418
|
-
|
|
28419
|
-
|
|
28563
|
+
batches.forEach(
|
|
28564
|
+
(batch, b) => batch.forEach((m, i) => fresh.set(freshKey(m), results[b][i]))
|
|
28565
|
+
);
|
|
28566
|
+
await Promise.all(
|
|
28567
|
+
kinds.map(
|
|
28568
|
+
(kind) => putThreadTranslations(
|
|
28569
|
+
lang,
|
|
28570
|
+
missing.filter((m) => m.kind === kind).map((m) => {
|
|
28571
|
+
const r = fresh.get(freshKey(m));
|
|
28572
|
+
return {
|
|
28573
|
+
replyId: m.id,
|
|
28574
|
+
bodyHash: m.hash,
|
|
28575
|
+
body: r.body,
|
|
28576
|
+
passthrough: r.passthrough
|
|
28577
|
+
};
|
|
28578
|
+
}),
|
|
28579
|
+
kind
|
|
28580
|
+
)
|
|
28581
|
+
)
|
|
28420
28582
|
);
|
|
28421
28583
|
}
|
|
28422
|
-
return
|
|
28423
|
-
const hit =
|
|
28584
|
+
return keyed.map((m) => {
|
|
28585
|
+
const hit = cachedOf(m);
|
|
28424
28586
|
if (hit) return { id: m.id, body: hit.body, passthrough: hit.passthrough };
|
|
28425
|
-
return fresh.get(m
|
|
28587
|
+
return fresh.get(freshKey(m)) ?? { id: m.id, body: m.body, passthrough: true };
|
|
28426
28588
|
});
|
|
28427
28589
|
})().finally(() => inFlight4.delete(key));
|
|
28428
28590
|
inFlight4.set(key, job);
|
|
28429
28591
|
return job;
|
|
28430
28592
|
}
|
|
28593
|
+
async function translateThread(lang, scope, messages) {
|
|
28594
|
+
const index = new Map(messages.map((m, i) => [m.id, i]));
|
|
28595
|
+
return translateCached(
|
|
28596
|
+
lang,
|
|
28597
|
+
scope,
|
|
28598
|
+
messages.map((m) => ({ ...m, kind: "reply" })),
|
|
28599
|
+
(first) => {
|
|
28600
|
+
const at = index.get(first.id) ?? 0;
|
|
28601
|
+
return messages.slice(Math.max(0, at - CONTEXT_MESSAGES), at);
|
|
28602
|
+
}
|
|
28603
|
+
);
|
|
28604
|
+
}
|
|
28605
|
+
async function translateTopics(lang, scope, topics) {
|
|
28606
|
+
const sources = [];
|
|
28607
|
+
for (const t of topics) {
|
|
28608
|
+
if (t.title) sources.push({ id: t.threadId, author: t.author, body: t.title, kind: "title" });
|
|
28609
|
+
if (t.opening) sources.push({ ...t.opening, kind: "reply" });
|
|
28610
|
+
}
|
|
28611
|
+
const out = await translateCached(lang, scope, sources, () => []);
|
|
28612
|
+
const byKey = new Map(out.map((r, i) => [`${sources[i].kind}:${r.id}`, r]));
|
|
28613
|
+
const shown = (r) => r && !r.passthrough ? r.body : null;
|
|
28614
|
+
return topics.map((t) => ({
|
|
28615
|
+
id: t.threadId,
|
|
28616
|
+
title: shown(byKey.get(`title:${t.threadId}`)),
|
|
28617
|
+
preview: t.opening ? shown(byKey.get(`reply:${t.opening.id}`)) : null
|
|
28618
|
+
}));
|
|
28619
|
+
}
|
|
28620
|
+
|
|
28621
|
+
// ../api/src/store/channel-glossary-store.ts
|
|
28622
|
+
function toTerms(raw) {
|
|
28623
|
+
if (!Array.isArray(raw)) return [];
|
|
28624
|
+
return raw.flatMap(
|
|
28625
|
+
(t) => t && typeof t.term === "string" && t.term.trim() ? [{ term: t.term.trim(), note: typeof t.note === "string" ? t.note.trim() : "" }] : []
|
|
28626
|
+
);
|
|
28627
|
+
}
|
|
28628
|
+
async function getChannelGlossaries(channelIds) {
|
|
28629
|
+
const found = /* @__PURE__ */ new Map();
|
|
28630
|
+
if (channelIds.length === 0) return found;
|
|
28631
|
+
const { data, error: error2 } = await getSupabaseClient().from("channel_glossary").select("channel_id, terms, scanned_at").in("channel_id", [...new Set(channelIds)]);
|
|
28632
|
+
if (error2) throw new Error(`getChannelGlossaries: ${error2.message}`);
|
|
28633
|
+
for (const row of data ?? []) {
|
|
28634
|
+
found.set(row.channel_id, {
|
|
28635
|
+
channelId: row.channel_id,
|
|
28636
|
+
terms: toTerms(row.terms),
|
|
28637
|
+
scannedAt: row.scanned_at
|
|
28638
|
+
});
|
|
28639
|
+
}
|
|
28640
|
+
return found;
|
|
28641
|
+
}
|
|
28431
28642
|
|
|
28432
28643
|
// ../api/src/dashboard/chat-routes.ts
|
|
28433
28644
|
function isNonEmptyString(v) {
|
|
@@ -28494,6 +28705,7 @@ var THREADS_PAGE_SIZE_MAX = 100;
|
|
|
28494
28705
|
var REPLIES_PAGE_SIZE = 50;
|
|
28495
28706
|
var REPLIES_PAGE_SIZE_MAX = 200;
|
|
28496
28707
|
var TRANSLATABLE_REPLIES_MAX = 400;
|
|
28708
|
+
var TOPICS_TRANSLATION_MAX = 50;
|
|
28497
28709
|
var BOARD_PAGE_SIZE = 50;
|
|
28498
28710
|
var BOARD_PAGE_SIZE_MAX = 100;
|
|
28499
28711
|
function ownChannelIds(c) {
|
|
@@ -28627,6 +28839,7 @@ function createChatRouter(agent = {}) {
|
|
|
28627
28839
|
onChatMessage: onMessage,
|
|
28628
28840
|
isAgentThinking,
|
|
28629
28841
|
getAgentActivities,
|
|
28842
|
+
getBackgroundTasks,
|
|
28630
28843
|
cancelAgentRun,
|
|
28631
28844
|
regenerateAgentRun,
|
|
28632
28845
|
listAgentRuns
|
|
@@ -28650,7 +28863,8 @@ function createChatRouter(agent = {}) {
|
|
|
28650
28863
|
"/threads/:id/agent-status",
|
|
28651
28864
|
async (c) => c.json({
|
|
28652
28865
|
thinking: await isAgentThinking?.(c.req.param("id")) ?? false,
|
|
28653
|
-
activities: await getAgentActivities?.(c.req.param("id")) ?? []
|
|
28866
|
+
activities: await getAgentActivities?.(c.req.param("id")) ?? [],
|
|
28867
|
+
background: await getBackgroundTasks?.(c.req.param("id")) ?? []
|
|
28654
28868
|
})
|
|
28655
28869
|
);
|
|
28656
28870
|
app.get("/agent-runs", async (c) => c.json({ threadIds: await listAgentRuns?.() ?? [] }));
|
|
@@ -28884,13 +29098,56 @@ function createChatRouter(agent = {}) {
|
|
|
28884
29098
|
(r) => ({ id: r.id, author: r.author, body: slackMrkdwnToMarkdown(r.body) })
|
|
28885
29099
|
);
|
|
28886
29100
|
try {
|
|
28887
|
-
|
|
29101
|
+
const glossary = (await getChannelGlossaries([channelId])).get(channelId)?.terms ?? [];
|
|
29102
|
+
const scope = { workspaceId: c.get("auth").workspaceId, glossary };
|
|
29103
|
+
return c.json({ lang, messages: await translateThread(lang, scope, messages) });
|
|
28888
29104
|
} catch (err) {
|
|
29105
|
+
if (err instanceof TranslationLimitError) return c.json({ error: err.message }, 429);
|
|
28889
29106
|
const message = err instanceof Error ? err.message : "translation failed";
|
|
28890
29107
|
console.error(`Thread translation failed (${id} \u2192 ${lang}):`, err);
|
|
28891
29108
|
return c.json({ error: message }, 502);
|
|
28892
29109
|
}
|
|
28893
29110
|
});
|
|
29111
|
+
app.post("/topics/translation/:lang", async (c) => {
|
|
29112
|
+
const lang = canonicalLanguage(c.req.param("lang"));
|
|
29113
|
+
if (!isTranslatableLanguage2(lang)) return c.json({ error: "unsupported language" }, 400);
|
|
29114
|
+
const body = await c.req.json().catch(() => null);
|
|
29115
|
+
const ids = Array.isArray(body?.ids) ? [...new Set(body.ids.filter((v) => typeof v === "string"))] : [];
|
|
29116
|
+
if (ids.length === 0) return c.json({ lang, topics: [] });
|
|
29117
|
+
if (ids.length > TOPICS_TRANSLATION_MAX) return c.json({ error: "too many topics" }, 400);
|
|
29118
|
+
const threads = await getSupabaseClient().from("threads").select("id, channel_id, author, title, auto_title").in("id", ids);
|
|
29119
|
+
if (threads.error) return c.json({ error: threads.error.message }, 500);
|
|
29120
|
+
const visible = await globalChannelMeta(c);
|
|
29121
|
+
const rows = (threads.data ?? []).filter((t) => visible.has(t.channel_id));
|
|
29122
|
+
const openings = await Promise.all(
|
|
29123
|
+
rows.map(
|
|
29124
|
+
(t) => getSupabaseClient().from("thread_replies").select("id, author, body").eq("thread_id", t.id).is("archived_at", null).order("created_at", { ascending: true }).limit(1).maybeSingle()
|
|
29125
|
+
)
|
|
29126
|
+
);
|
|
29127
|
+
try {
|
|
29128
|
+
const glossaries = await getChannelGlossaries(rows.map((t) => t.channel_id));
|
|
29129
|
+
const glossary = [...glossaries.values()].flatMap((g) => g.terms);
|
|
29130
|
+
const topics = await translateTopics(
|
|
29131
|
+
lang,
|
|
29132
|
+
{ workspaceId: c.get("auth").workspaceId, glossary },
|
|
29133
|
+
rows.map((t, i) => {
|
|
29134
|
+
const o = openings[i]?.data;
|
|
29135
|
+
return {
|
|
29136
|
+
threadId: t.id,
|
|
29137
|
+
author: t.author,
|
|
29138
|
+
title: t.title || t.auto_title,
|
|
29139
|
+
// Normalised like the thread view, so this shares its cache rows.
|
|
29140
|
+
opening: o ? { id: o.id, author: o.author, body: slackMrkdwnToMarkdown(o.body) } : null
|
|
29141
|
+
};
|
|
29142
|
+
})
|
|
29143
|
+
);
|
|
29144
|
+
return c.json({ lang, topics });
|
|
29145
|
+
} catch (err) {
|
|
29146
|
+
if (err instanceof TranslationLimitError) return c.json({ error: err.message }, 429);
|
|
29147
|
+
console.error(`Topic translation failed (\u2192 ${lang}):`, err);
|
|
29148
|
+
return c.json({ error: err instanceof Error ? err.message : "translation failed" }, 502);
|
|
29149
|
+
}
|
|
29150
|
+
});
|
|
28894
29151
|
app.patch("/threads/:id/board-status", async (c) => {
|
|
28895
29152
|
const id = c.req.param("id");
|
|
28896
29153
|
const input2 = await c.req.json().catch(() => null);
|
|
@@ -29906,15 +30163,149 @@ function createSearchRouter() {
|
|
|
29906
30163
|
return app;
|
|
29907
30164
|
}
|
|
29908
30165
|
|
|
29909
|
-
// ../api/src/dashboard/
|
|
30166
|
+
// ../api/src/dashboard/domain-routes.ts
|
|
29910
30167
|
import { Hono as Hono17 } from "hono";
|
|
30168
|
+
var FALLBACK_ORIGIN = "custom.flyspace.ai";
|
|
30169
|
+
function isValidCustomHostname(hostname2) {
|
|
30170
|
+
if (hostname2.length > 253 || hostname2.endsWith(".flyspace.ai") || hostname2 === "flyspace.ai") {
|
|
30171
|
+
return false;
|
|
30172
|
+
}
|
|
30173
|
+
const labels = hostname2.split(".");
|
|
30174
|
+
if (labels.length < 2) return false;
|
|
30175
|
+
return labels.every((l) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(l));
|
|
30176
|
+
}
|
|
30177
|
+
async function cloudflare(method, path, body) {
|
|
30178
|
+
const token = process.env["CLOUDFLARE_SAAS_API_TOKEN"];
|
|
30179
|
+
const zone = process.env["CLOUDFLARE_SAAS_ZONE_ID"];
|
|
30180
|
+
if (!token || !zone) {
|
|
30181
|
+
throw new Error("CLOUDFLARE_SAAS_API_TOKEN / CLOUDFLARE_SAAS_ZONE_ID not set");
|
|
30182
|
+
}
|
|
30183
|
+
const res = await fetch(`https://api.cloudflare.com/client/v4/zones/${zone}/custom_hostnames${path}`, {
|
|
30184
|
+
method,
|
|
30185
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
30186
|
+
...body ? { body: JSON.stringify(body) } : {},
|
|
30187
|
+
signal: AbortSignal.timeout(1e4)
|
|
30188
|
+
});
|
|
30189
|
+
const json = await res.json();
|
|
30190
|
+
if (!json.success) {
|
|
30191
|
+
throw new Error(`Cloudflare ${method} ${path || "/"}: ${json.errors?.[0]?.message ?? res.status}`);
|
|
30192
|
+
}
|
|
30193
|
+
return json.result;
|
|
30194
|
+
}
|
|
30195
|
+
function statusFrom(cf) {
|
|
30196
|
+
if (cf.status === "active" && cf.ssl?.status === "active") return "active";
|
|
30197
|
+
if ((cf.ssl?.validation_errors?.length ?? 0) > 0 || cf.status === "deleted") return "failed";
|
|
30198
|
+
return "pending";
|
|
30199
|
+
}
|
|
30200
|
+
async function syncAuthRedirectAllowlist(hostname2, present) {
|
|
30201
|
+
const token = process.env["SUPABASE_ACCESS_TOKEN"];
|
|
30202
|
+
const ref = URL.parse(process.env["SUPABASE_URL"] ?? "")?.hostname.split(".")[0];
|
|
30203
|
+
if (!token || !ref) {
|
|
30204
|
+
console.warn("[custom-domains] SUPABASE_ACCESS_TOKEN not set; redirect allowlist not updated");
|
|
30205
|
+
return;
|
|
30206
|
+
}
|
|
30207
|
+
try {
|
|
30208
|
+
const base = `https://api.supabase.com/v1/projects/${ref}/config/auth`;
|
|
30209
|
+
const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
|
|
30210
|
+
const current = await (await fetch(base, { headers })).json();
|
|
30211
|
+
const entry = `https://${hostname2}/**`;
|
|
30212
|
+
const list = (current.uri_allow_list ?? "").split(",").map((u) => u.trim()).filter(Boolean);
|
|
30213
|
+
const next = present ? [.../* @__PURE__ */ new Set([...list, entry])] : list.filter((u) => u !== entry);
|
|
30214
|
+
if (next.join(",") === list.join(",")) return;
|
|
30215
|
+
const res = await fetch(base, {
|
|
30216
|
+
method: "PATCH",
|
|
30217
|
+
headers,
|
|
30218
|
+
body: JSON.stringify({ uri_allow_list: next.join(",") })
|
|
30219
|
+
});
|
|
30220
|
+
if (!res.ok) throw new Error(`PATCH config/auth: ${res.status}`);
|
|
30221
|
+
} catch (err) {
|
|
30222
|
+
console.error("[custom-domains] redirect allowlist update failed:", err);
|
|
30223
|
+
}
|
|
30224
|
+
}
|
|
30225
|
+
function view(row, dcv) {
|
|
30226
|
+
return {
|
|
30227
|
+
hostname: row.hostname,
|
|
30228
|
+
status: row.status,
|
|
30229
|
+
verifiedAt: row.verified_at,
|
|
30230
|
+
records: [
|
|
30231
|
+
{ type: "CNAME", name: row.hostname, value: FALLBACK_ORIGIN },
|
|
30232
|
+
...dcv.map((r) => ({ type: "TXT", name: r.txt_name, value: r.txt_value }))
|
|
30233
|
+
]
|
|
30234
|
+
};
|
|
30235
|
+
}
|
|
30236
|
+
function createDomainRouter() {
|
|
30237
|
+
const app = new Hono17();
|
|
30238
|
+
app.use("*", async (c, next) => {
|
|
30239
|
+
const auth = c.get("auth");
|
|
30240
|
+
if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
30241
|
+
await next();
|
|
30242
|
+
});
|
|
30243
|
+
app.get("/", async (c) => {
|
|
30244
|
+
const auth = c.get("auth");
|
|
30245
|
+
const row = await getWorkspaceDomain(auth.workspaceId);
|
|
30246
|
+
if (!row) return c.json({ domain: null });
|
|
30247
|
+
let dcv = [];
|
|
30248
|
+
if (row.status !== "active") {
|
|
30249
|
+
const cf = await cloudflare("GET", `/${row.cf_hostname_id}`);
|
|
30250
|
+
if (cf) {
|
|
30251
|
+
dcv = cf.ssl?.validation_records ?? [];
|
|
30252
|
+
const status = statusFrom(cf);
|
|
30253
|
+
if (status !== row.status) {
|
|
30254
|
+
await updateWorkspaceDomainStatus(auth.workspaceId, status);
|
|
30255
|
+
row.status = status;
|
|
30256
|
+
if (status === "active") await syncAuthRedirectAllowlist(row.hostname, true);
|
|
30257
|
+
}
|
|
30258
|
+
}
|
|
30259
|
+
}
|
|
30260
|
+
return c.json({ domain: view(row, dcv) });
|
|
30261
|
+
});
|
|
30262
|
+
app.post("/", async (c) => {
|
|
30263
|
+
const auth = c.get("auth");
|
|
30264
|
+
const { hostname: hostname2 } = await c.req.json().catch(() => ({})) ?? {};
|
|
30265
|
+
const name = hostname2?.trim().toLowerCase() ?? "";
|
|
30266
|
+
if (!isValidCustomHostname(name)) return c.json({ error: "not a usable hostname" }, 400);
|
|
30267
|
+
if (await getWorkspaceDomain(auth.workspaceId)) {
|
|
30268
|
+
return c.json({ error: "this workspace already has a domain; remove it first" }, 409);
|
|
30269
|
+
}
|
|
30270
|
+
const cf = await cloudflare("POST", "", { hostname: name, ssl: { method: "txt", type: "dv" } });
|
|
30271
|
+
if (!cf) return c.json({ error: "Cloudflare returned no hostname" }, 502);
|
|
30272
|
+
try {
|
|
30273
|
+
await insertWorkspaceDomain({ workspace_id: auth.workspaceId, hostname: name, cf_hostname_id: cf.id });
|
|
30274
|
+
} catch (err) {
|
|
30275
|
+
await cloudflare("DELETE", `/${cf.id}`).catch(() => {
|
|
30276
|
+
});
|
|
30277
|
+
throw err;
|
|
30278
|
+
}
|
|
30279
|
+
return c.json({
|
|
30280
|
+
domain: view(
|
|
30281
|
+
{ workspace_id: auth.workspaceId, hostname: name, cf_hostname_id: cf.id, status: "pending", verified_at: null },
|
|
30282
|
+
cf.ssl?.validation_records ?? []
|
|
30283
|
+
)
|
|
30284
|
+
});
|
|
30285
|
+
});
|
|
30286
|
+
app.delete("/", async (c) => {
|
|
30287
|
+
const auth = c.get("auth");
|
|
30288
|
+
const row = await getWorkspaceDomain(auth.workspaceId);
|
|
30289
|
+
if (!row) return c.json({ error: "no domain configured" }, 404);
|
|
30290
|
+
await cloudflare("DELETE", `/${row.cf_hostname_id}`).catch((err) => {
|
|
30291
|
+
if (!String(err).includes("not found")) throw err;
|
|
30292
|
+
});
|
|
30293
|
+
await deleteWorkspaceDomain(auth.workspaceId);
|
|
30294
|
+
await syncAuthRedirectAllowlist(row.hostname, false);
|
|
30295
|
+
return c.json({ ok: true });
|
|
30296
|
+
});
|
|
30297
|
+
return app;
|
|
30298
|
+
}
|
|
30299
|
+
|
|
30300
|
+
// ../api/src/dashboard/feature-flags-routes.ts
|
|
30301
|
+
import { Hono as Hono18 } from "hono";
|
|
29911
30302
|
async function isFeatureEnabled(c, flagId) {
|
|
29912
30303
|
const auth = c.get("auth");
|
|
29913
30304
|
const enabled = await listEnabledFeatureFlags(auth.workspaceId);
|
|
29914
30305
|
return resolveFeatureFlags(enabled, isDevHost(c))[flagId];
|
|
29915
30306
|
}
|
|
29916
30307
|
function createFeatureFlagsRouter() {
|
|
29917
|
-
const app = new
|
|
30308
|
+
const app = new Hono18();
|
|
29918
30309
|
app.get("/", async (c) => {
|
|
29919
30310
|
const auth = c.get("auth");
|
|
29920
30311
|
const devHost = isDevHost(c);
|
|
@@ -29940,14 +30331,14 @@ function createFeatureFlagsRouter() {
|
|
|
29940
30331
|
}
|
|
29941
30332
|
|
|
29942
30333
|
// ../api/src/dashboard/transcribe-routes.ts
|
|
29943
|
-
import { Hono as
|
|
30334
|
+
import { Hono as Hono19 } from "hono";
|
|
29944
30335
|
var GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
|
|
29945
30336
|
var MODEL = "whisper-large-v3-turbo";
|
|
29946
30337
|
var MAX_AUDIO_BYTES = 5 * 1024 * 1024;
|
|
29947
30338
|
var MAX_PROMPT_CHARS = 400;
|
|
29948
30339
|
var NO_SPEECH_THRESHOLD = 0.6;
|
|
29949
30340
|
function createTranscribeRouter() {
|
|
29950
|
-
const app = new
|
|
30341
|
+
const app = new Hono19();
|
|
29951
30342
|
app.post("/transcribe", async (c) => {
|
|
29952
30343
|
if (!await isFeatureEnabled(c, "dictation"))
|
|
29953
30344
|
return c.json({ error: "feature not enabled" }, 403);
|
|
@@ -29986,7 +30377,7 @@ function createTranscribeRouter() {
|
|
|
29986
30377
|
}
|
|
29987
30378
|
|
|
29988
30379
|
// ../api/src/dashboard/autocomplete-routes.ts
|
|
29989
|
-
import { Hono as
|
|
30380
|
+
import { Hono as Hono20 } from "hono";
|
|
29990
30381
|
var GROQ_API_URL8 = "https://api.groq.com/openai/v1/chat/completions";
|
|
29991
30382
|
var MODEL2 = "openai/gpt-oss-120b";
|
|
29992
30383
|
var MAX_REPLY_CHARS = 4e3;
|
|
@@ -29997,7 +30388,7 @@ Base it on the agent's last reply: answer a question it asked, approve or pick a
|
|
|
29997
30388
|
Keep it short (under 15 words), in the language the user writes in. No greetings, thanks or filler.
|
|
29998
30389
|
Output ONLY the message text, no quotes or explanation. If there is no clear next step, output nothing.`;
|
|
29999
30390
|
function createAutocompleteRouter() {
|
|
30000
|
-
const app = new
|
|
30391
|
+
const app = new Hono20();
|
|
30001
30392
|
app.post("/autocomplete", async (c) => {
|
|
30002
30393
|
if (!await isFeatureEnabled(c, "autocomplete"))
|
|
30003
30394
|
return c.json({ error: "feature not enabled" }, 403);
|
|
@@ -30062,7 +30453,7 @@ ${last.body.slice(-MAX_REPLY_CHARS)}`;
|
|
|
30062
30453
|
|
|
30063
30454
|
// ../api/src/dashboard/avatars-routes.ts
|
|
30064
30455
|
import { createHash as createHash9, randomUUID as randomUUID4 } from "crypto";
|
|
30065
|
-
import { Hono as
|
|
30456
|
+
import { Hono as Hono21 } from "hono";
|
|
30066
30457
|
import sharp5 from "sharp";
|
|
30067
30458
|
import { PutObjectCommand as PutObjectCommand4, DeleteObjectCommand as DeleteObjectCommand3 } from "@aws-sdk/client-s3";
|
|
30068
30459
|
var AVATAR_SIZE = 192;
|
|
@@ -30115,7 +30506,7 @@ function avatarKeyPrefix() {
|
|
|
30115
30506
|
return `${KEY_PREFIX2}/${getProfile()}/`;
|
|
30116
30507
|
}
|
|
30117
30508
|
function createAvatarsRouter() {
|
|
30118
|
-
const app = new
|
|
30509
|
+
const app = new Hono21();
|
|
30119
30510
|
app.get("/avatars/slack", async (c) => {
|
|
30120
30511
|
const ctx = await resolveAuthContext(c);
|
|
30121
30512
|
if (!ctx) return c.json({ error: "not signed in" }, 401);
|
|
@@ -30164,7 +30555,7 @@ function createAvatarsRouter() {
|
|
|
30164
30555
|
}
|
|
30165
30556
|
|
|
30166
30557
|
// ../api/src/dashboard/members-routes.ts
|
|
30167
|
-
import { Hono as
|
|
30558
|
+
import { Hono as Hono22 } from "hono";
|
|
30168
30559
|
function inviteLinkFor(c, token) {
|
|
30169
30560
|
const url = new URL("/auth/invite", callbackUrl(c));
|
|
30170
30561
|
url.searchParams.set("token", token);
|
|
@@ -30172,7 +30563,7 @@ function inviteLinkFor(c, token) {
|
|
|
30172
30563
|
}
|
|
30173
30564
|
var EMAIL_RE2 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
30174
30565
|
function createMembersRouter() {
|
|
30175
|
-
const members = new
|
|
30566
|
+
const members = new Hono22();
|
|
30176
30567
|
members.get("/", async (c) => {
|
|
30177
30568
|
const ctx = await resolveAuthContext(c);
|
|
30178
30569
|
if (ctx?.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
@@ -30395,7 +30786,7 @@ function createMembersRouter() {
|
|
|
30395
30786
|
}
|
|
30396
30787
|
|
|
30397
30788
|
// ../api/src/dashboard/notifications-routes.ts
|
|
30398
|
-
import { Hono as
|
|
30789
|
+
import { Hono as Hono23 } from "hono";
|
|
30399
30790
|
|
|
30400
30791
|
// ../api/src/store/notification-store.ts
|
|
30401
30792
|
function rowToNotification(row) {
|
|
@@ -30463,7 +30854,7 @@ async function markAllRead(channelIds, userId) {
|
|
|
30463
30854
|
|
|
30464
30855
|
// ../api/src/dashboard/notifications-routes.ts
|
|
30465
30856
|
function createNotificationsRouter() {
|
|
30466
|
-
const notifications = new
|
|
30857
|
+
const notifications = new Hono23();
|
|
30467
30858
|
notifications.get("/", async (c) => {
|
|
30468
30859
|
const auth = c.get("auth");
|
|
30469
30860
|
const channelIds = getProfileChannelRegistry().filter((ch) => canSeeChannel(ch, auth)).map((ch) => ch.id);
|
|
@@ -30490,7 +30881,7 @@ function createNotificationsRouter() {
|
|
|
30490
30881
|
return notifications;
|
|
30491
30882
|
}
|
|
30492
30883
|
function createThreadReadRouter() {
|
|
30493
|
-
const threads = new
|
|
30884
|
+
const threads = new Hono23();
|
|
30494
30885
|
threads.post("/threads/:threadId/read", async (c) => {
|
|
30495
30886
|
const { userId } = c.get("auth");
|
|
30496
30887
|
const threadId = c.req.param("threadId");
|
|
@@ -30502,7 +30893,7 @@ function createThreadReadRouter() {
|
|
|
30502
30893
|
}
|
|
30503
30894
|
|
|
30504
30895
|
// ../api/src/dashboard/push-routes.ts
|
|
30505
|
-
import { Hono as
|
|
30896
|
+
import { Hono as Hono24 } from "hono";
|
|
30506
30897
|
|
|
30507
30898
|
// ../api/src/push/send.ts
|
|
30508
30899
|
import webpush from "web-push";
|
|
@@ -30605,7 +30996,7 @@ async function pushToUser(userId, payload) {
|
|
|
30605
30996
|
|
|
30606
30997
|
// ../api/src/dashboard/push-routes.ts
|
|
30607
30998
|
function createPushRouter() {
|
|
30608
|
-
const push = new
|
|
30999
|
+
const push = new Hono24();
|
|
30609
31000
|
push.get("/key", (c) => c.json({ publicKey: getVapidPublicKey() }));
|
|
30610
31001
|
push.post("/subscribe", async (c) => {
|
|
30611
31002
|
const { userId } = c.get("auth");
|
|
@@ -30636,7 +31027,7 @@ function createPushRouter() {
|
|
|
30636
31027
|
}
|
|
30637
31028
|
|
|
30638
31029
|
// ../api/src/dashboard/mcp-oauth-routes.ts
|
|
30639
|
-
import { Hono as
|
|
31030
|
+
import { Hono as Hono25 } from "hono";
|
|
30640
31031
|
|
|
30641
31032
|
// ../api/src/mcp/crypto.ts
|
|
30642
31033
|
import { createCipheriv, createDecipheriv, randomBytes as randomBytes7, timingSafeEqual } from "crypto";
|
|
@@ -31151,7 +31542,7 @@ function backToDashboard(c, to, params) {
|
|
|
31151
31542
|
return c.redirect(`${target.pathname}${target.search}`);
|
|
31152
31543
|
}
|
|
31153
31544
|
function createMcpOAuthRouter() {
|
|
31154
|
-
const app = new
|
|
31545
|
+
const app = new Hono25();
|
|
31155
31546
|
app.get("/oauth/:provider/start", async (c) => {
|
|
31156
31547
|
const auth = c.get("auth");
|
|
31157
31548
|
if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
@@ -31278,7 +31669,7 @@ function createMcpOAuthRouter() {
|
|
|
31278
31669
|
}
|
|
31279
31670
|
|
|
31280
31671
|
// ../api/src/dashboard/mcp-routes.ts
|
|
31281
|
-
import { Hono as
|
|
31672
|
+
import { Hono as Hono26 } from "hono";
|
|
31282
31673
|
|
|
31283
31674
|
// ../api/src/mcp/transport.ts
|
|
31284
31675
|
var KINDS = ["inherit", "npx", "local", "http", "sse"];
|
|
@@ -31408,7 +31799,7 @@ function bindingsByConnection() {
|
|
|
31408
31799
|
return map;
|
|
31409
31800
|
}
|
|
31410
31801
|
function createMcpRouter() {
|
|
31411
|
-
const app = new
|
|
31802
|
+
const app = new Hono26();
|
|
31412
31803
|
app.get("/providers", async (c) => {
|
|
31413
31804
|
const denied = requireAdmin(c.get("auth"));
|
|
31414
31805
|
if (denied) return c.json({ error: denied }, 403);
|
|
@@ -31824,8 +32215,40 @@ async function buildThreadUsage(threadTs) {
|
|
|
31824
32215
|
}
|
|
31825
32216
|
}
|
|
31826
32217
|
|
|
32218
|
+
// ../api/src/dashboard/permission-routes.ts
|
|
32219
|
+
import { Hono as Hono27 } from "hono";
|
|
32220
|
+
function createPermissionRequestsRouter() {
|
|
32221
|
+
const app = new Hono27();
|
|
32222
|
+
app.post("/:id", async (c) => {
|
|
32223
|
+
const auth = c.get("auth");
|
|
32224
|
+
if (auth.role !== "admin") return c.json({ error: "only an admin can answer this" }, 403);
|
|
32225
|
+
const body = await c.req.json().catch(() => ({}));
|
|
32226
|
+
if (body.decision !== "allow" && body.decision !== "deny") {
|
|
32227
|
+
return c.json({ error: "decision must be 'allow' or 'deny'" }, 400);
|
|
32228
|
+
}
|
|
32229
|
+
const supabase = getSupabaseClient();
|
|
32230
|
+
const { data: request } = await supabase.from("permission_requests").select("channel_id, status, expires_at").eq("id", c.req.param("id")).maybeSingle();
|
|
32231
|
+
const ownChannels = new Set(getProfileChannelRegistry().map((ch) => ch.id));
|
|
32232
|
+
if (!request || !ownChannels.has(request["channel_id"])) {
|
|
32233
|
+
return c.json({ error: "not found" }, 404);
|
|
32234
|
+
}
|
|
32235
|
+
if (request["status"] !== "pending" || Date.parse(request["expires_at"]) < Date.now()) {
|
|
32236
|
+
return c.json({ status: request["status"] === "pending" ? "expired" : request["status"] }, 409);
|
|
32237
|
+
}
|
|
32238
|
+
const { data, error: error2 } = await supabase.from("permission_requests").update({
|
|
32239
|
+
status: body.decision,
|
|
32240
|
+
decided_by: auth.handle,
|
|
32241
|
+
decided_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
32242
|
+
}).eq("id", c.req.param("id")).eq("status", "pending").select("status");
|
|
32243
|
+
if (error2) return c.json({ error: error2.message }, 500);
|
|
32244
|
+
if (!data?.length) return c.json({ error: "already answered" }, 409);
|
|
32245
|
+
return c.json({ status: body.decision });
|
|
32246
|
+
});
|
|
32247
|
+
return app;
|
|
32248
|
+
}
|
|
32249
|
+
|
|
31827
32250
|
// ../api/src/dashboard/channel-greeting.ts
|
|
31828
|
-
import { Hono as
|
|
32251
|
+
import { Hono as Hono28 } from "hono";
|
|
31829
32252
|
function eligible(ch) {
|
|
31830
32253
|
return !!ch && !ch.isDefault && !ch.dmKey && !ch.agentName && !ch.archivedAt;
|
|
31831
32254
|
}
|
|
@@ -31854,7 +32277,7 @@ function introOpening(channelName) {
|
|
|
31854
32277
|
return `Welcome to #${channelName}. I'm reading this project's folder, docs, skills and automations to work out how I can help here. Below you'll find a short intro and a few first steps you can click to try.`;
|
|
31855
32278
|
}
|
|
31856
32279
|
function createChannelGreetingRouter(agent) {
|
|
31857
|
-
const app = new
|
|
32280
|
+
const app = new Hono28();
|
|
31858
32281
|
app.get("/:id/greeting", async (c) => {
|
|
31859
32282
|
const ctx = await resolveAuthContext(c);
|
|
31860
32283
|
const ch = findChannelById(c.req.param("id"));
|
|
@@ -31912,7 +32335,7 @@ async function ensureIntroThread(ch) {
|
|
|
31912
32335
|
}
|
|
31913
32336
|
|
|
31914
32337
|
// ../api/src/dashboard/channel-suggest.ts
|
|
31915
|
-
import { Hono as
|
|
32338
|
+
import { Hono as Hono29 } from "hono";
|
|
31916
32339
|
var CATEGORY_MAX_CHARS = 16;
|
|
31917
32340
|
var CATEGORY_MAX_ITEMS = 30;
|
|
31918
32341
|
var PROMPT_MAX_CHARS = 4e3;
|
|
@@ -31960,7 +32383,7 @@ function parseSuggestion(field, raw) {
|
|
|
31960
32383
|
return items.length ? items.slice(0, CATEGORY_MAX_ITEMS).join("\n") : null;
|
|
31961
32384
|
}
|
|
31962
32385
|
function createChannelSuggestRouter(agent) {
|
|
31963
|
-
const router = new
|
|
32386
|
+
const router = new Hono29();
|
|
31964
32387
|
router.post("/:id/suggest", async (c) => {
|
|
31965
32388
|
const channel = findChannel(c.req.param("id"));
|
|
31966
32389
|
if (!channel || !canSeeChannel(channel, c.get("auth"))) {
|
|
@@ -31998,7 +32421,7 @@ function createChannelSuggestRouter(agent) {
|
|
|
31998
32421
|
}
|
|
31999
32422
|
|
|
32000
32423
|
// ../api/src/dashboard/channel-members-routes.ts
|
|
32001
|
-
import { Hono as
|
|
32424
|
+
import { Hono as Hono30 } from "hono";
|
|
32002
32425
|
async function isChannelAdmin(ctx, channelId) {
|
|
32003
32426
|
if (ctx.role === "admin") return true;
|
|
32004
32427
|
const membership = await getMembershipByUserId(ctx.workspaceId, ctx.userId);
|
|
@@ -32007,7 +32430,7 @@ async function isChannelAdmin(ctx, channelId) {
|
|
|
32007
32430
|
return members.some((m) => m.membershipId === membership.id && m.role === "channel_admin");
|
|
32008
32431
|
}
|
|
32009
32432
|
function createChannelMembersRouter() {
|
|
32010
|
-
const router = new
|
|
32433
|
+
const router = new Hono30();
|
|
32011
32434
|
router.get("/:id/members", async (c) => {
|
|
32012
32435
|
const ctx = await resolveAuthContext(c);
|
|
32013
32436
|
if (!ctx) return c.json({ error: "workspace access required" }, 403);
|
|
@@ -32077,7 +32500,7 @@ function createChannelMembersRouter() {
|
|
|
32077
32500
|
}
|
|
32078
32501
|
|
|
32079
32502
|
// ../api/src/dashboard/memories-routes.ts
|
|
32080
|
-
import { Hono as
|
|
32503
|
+
import { Hono as Hono31 } from "hono";
|
|
32081
32504
|
async function readPatch(c) {
|
|
32082
32505
|
const body = await c.req.json().catch(() => ({}));
|
|
32083
32506
|
const patch = {};
|
|
@@ -32105,7 +32528,7 @@ var requireAgentMemory = async (c, next) => {
|
|
|
32105
32528
|
await next();
|
|
32106
32529
|
};
|
|
32107
32530
|
function createMemoriesRouter() {
|
|
32108
|
-
const router = new
|
|
32531
|
+
const router = new Hono31();
|
|
32109
32532
|
for (const path of [
|
|
32110
32533
|
"/:id/memories",
|
|
32111
32534
|
"/:id/memories/*",
|
|
@@ -32178,7 +32601,7 @@ function createMemoriesRouter() {
|
|
|
32178
32601
|
return router;
|
|
32179
32602
|
}
|
|
32180
32603
|
function createScopedMemoriesRouter() {
|
|
32181
|
-
const router = new
|
|
32604
|
+
const router = new Hono31();
|
|
32182
32605
|
router.use("*", requireAgentMemory);
|
|
32183
32606
|
const workspace = (c) => ({
|
|
32184
32607
|
scope: "workspace",
|
|
@@ -32238,7 +32661,7 @@ function createScopedMemoriesRouter() {
|
|
|
32238
32661
|
}
|
|
32239
32662
|
|
|
32240
32663
|
// ../api/src/dashboard/session-import-routes.ts
|
|
32241
|
-
import { Hono as
|
|
32664
|
+
import { Hono as Hono32 } from "hono";
|
|
32242
32665
|
var MAX_FOLDERS2 = 20;
|
|
32243
32666
|
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
32244
32667
|
var IMPORT_RANGES = ["all", "7d", "latest5"];
|
|
@@ -32344,7 +32767,7 @@ async function syncSession(agent, channelId, session, author, existing) {
|
|
|
32344
32767
|
return messages.length;
|
|
32345
32768
|
}
|
|
32346
32769
|
function createSessionImportRouter(agent) {
|
|
32347
|
-
const app = new
|
|
32770
|
+
const app = new Hono32();
|
|
32348
32771
|
const scanFolders = async () => {
|
|
32349
32772
|
const scan = await ask(agent, { op: "scan", slug: getProfile() });
|
|
32350
32773
|
return scan && importableFolders(scan.folders, getProfileChannelRegistry());
|
|
@@ -32622,6 +33045,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32622
33045
|
effort: ch.effort ?? void 0,
|
|
32623
33046
|
prompt: ch.prompt ?? void 0,
|
|
32624
33047
|
topicCategories: ch.topicCategories,
|
|
33048
|
+
permissionMode: ch.permissionMode,
|
|
32625
33049
|
access: ch.access,
|
|
32626
33050
|
visibility: ch.visibility,
|
|
32627
33051
|
memberEmails: ch.memberEmails,
|
|
@@ -32632,7 +33056,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32632
33056
|
}));
|
|
32633
33057
|
return c.json({
|
|
32634
33058
|
channels: list,
|
|
32635
|
-
defaultModel: defaultModel(),
|
|
33059
|
+
defaultModel: effectiveModel(defaultModel(), agent.getHostPinnedModel?.(getProfile()) ?? null),
|
|
32636
33060
|
defaultEffort: defaultEffort() ?? null,
|
|
32637
33061
|
defaultCwd: getProfile()
|
|
32638
33062
|
});
|
|
@@ -32685,7 +33109,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32685
33109
|
});
|
|
32686
33110
|
return c.json({
|
|
32687
33111
|
...auto,
|
|
32688
|
-
defaultModel: defaultModel(),
|
|
33112
|
+
defaultModel: effectiveModel(defaultModel(), agent.getHostPinnedModel?.(getProfile()) ?? null),
|
|
32689
33113
|
schedules: auto.schedules.map((s) => ({
|
|
32690
33114
|
...withRun(s),
|
|
32691
33115
|
channelLabel: s.channel ? channelLabel(s.channel) : "Workspace"
|
|
@@ -32759,6 +33183,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32759
33183
|
});
|
|
32760
33184
|
api.route("/tts", createTtsRouter());
|
|
32761
33185
|
api.route("/feature-flags", createFeatureFlagsRouter());
|
|
33186
|
+
api.route("/domain", createDomainRouter());
|
|
32762
33187
|
api.route("/members", createMembersRouter());
|
|
32763
33188
|
api.route("/notifications", createNotificationsRouter());
|
|
32764
33189
|
api.route("/push", createPushRouter());
|
|
@@ -32777,6 +33202,21 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32777
33202
|
await setAllowGuestAccess(auth.workspaceId, body.allowGuestAccess);
|
|
32778
33203
|
return c.json({ allowGuestAccess: body.allowGuestAccess });
|
|
32779
33204
|
});
|
|
33205
|
+
api.get("/permission-mode", async (c) => {
|
|
33206
|
+
const auth = c.get("auth");
|
|
33207
|
+
return c.json({ permissionMode: await getWorkspacePermissionMode(auth.workspaceId) });
|
|
33208
|
+
});
|
|
33209
|
+
api.put("/permission-mode", async (c) => {
|
|
33210
|
+
const auth = c.get("auth");
|
|
33211
|
+
if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
33212
|
+
const body = await c.req.json().catch(() => ({}));
|
|
33213
|
+
if (!isPermissionMode(body.permissionMode)) {
|
|
33214
|
+
return c.json({ error: "permissionMode must be 'bypass' or 'ask'" }, 400);
|
|
33215
|
+
}
|
|
33216
|
+
await setWorkspacePermissionMode(auth.workspaceId, body.permissionMode);
|
|
33217
|
+
return c.json({ permissionMode: body.permissionMode });
|
|
33218
|
+
});
|
|
33219
|
+
api.route("/permission-requests", createPermissionRequestsRouter());
|
|
32780
33220
|
api.route("/mcp", createMcpOAuthRouter());
|
|
32781
33221
|
api.route("/mcp", createMcpRouter());
|
|
32782
33222
|
api.get("/agent-pause", async (c) => {
|
|
@@ -32904,7 +33344,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
32904
33344
|
// ../api/src/dashboard/device-auth-routes.ts
|
|
32905
33345
|
import { verify } from "crypto";
|
|
32906
33346
|
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
32907
|
-
import { Hono as
|
|
33347
|
+
import { Hono as Hono33 } from "hono";
|
|
32908
33348
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
32909
33349
|
function cleanText(value, max) {
|
|
32910
33350
|
if (typeof value !== "string") return null;
|
|
@@ -32952,7 +33392,7 @@ async function boundWorkspaceIds(publicKey, userId) {
|
|
|
32952
33392
|
return new Set(existing ? (await listDeviceWorkspaces(existing)).map((w) => w.id) : []);
|
|
32953
33393
|
}
|
|
32954
33394
|
function createDeviceAuthRouter() {
|
|
32955
|
-
const app = new
|
|
33395
|
+
const app = new Hono33();
|
|
32956
33396
|
app.post("/code", async (c) => {
|
|
32957
33397
|
const body = await readBody(c);
|
|
32958
33398
|
const publicKey = typeof body["public_key"] === "string" ? body["public_key"] : "";
|
|
@@ -33271,7 +33711,7 @@ var workspaceRef = () => ({ kind: "workspace" });
|
|
|
33271
33711
|
var channelRef = (c) => ({ kind: "channel", channelId: c.req.param("id") });
|
|
33272
33712
|
|
|
33273
33713
|
// ../api/src/dashboard/output-styles-routes.ts
|
|
33274
|
-
import { Hono as
|
|
33714
|
+
import { Hono as Hono34 } from "hono";
|
|
33275
33715
|
function requireAdmin3(auth) {
|
|
33276
33716
|
return auth?.role === "admin" ? null : "admin access required";
|
|
33277
33717
|
}
|
|
@@ -33291,7 +33731,7 @@ function failure(c, err) {
|
|
|
33291
33731
|
return c.json({ error: message }, err instanceof OutputStyleConflictError ? 409 : 500);
|
|
33292
33732
|
}
|
|
33293
33733
|
function createOutputStylesRouter() {
|
|
33294
|
-
const app = new
|
|
33734
|
+
const app = new Hono34();
|
|
33295
33735
|
app.get("/", (c) => {
|
|
33296
33736
|
const auth = c.get("auth");
|
|
33297
33737
|
const denied = requireAdmin3(auth);
|
|
@@ -33383,7 +33823,7 @@ function createOutputStylesRouter() {
|
|
|
33383
33823
|
return app;
|
|
33384
33824
|
}
|
|
33385
33825
|
async function handleOutputStylesRequest(req) {
|
|
33386
|
-
const app = new
|
|
33826
|
+
const app = new Hono34();
|
|
33387
33827
|
app.use("*", async (c, next) => {
|
|
33388
33828
|
c.set("auth", { role: "admin" });
|
|
33389
33829
|
await next();
|
|
@@ -33403,8 +33843,25 @@ async function handleOutputStylesRequest(req) {
|
|
|
33403
33843
|
import { streamSSE } from "hono/streaming";
|
|
33404
33844
|
|
|
33405
33845
|
// ../api/src/dashboard/api.ts
|
|
33846
|
+
async function viewerProfile(c, known) {
|
|
33847
|
+
if (!c.req.header("Cookie")) return null;
|
|
33848
|
+
const {
|
|
33849
|
+
data: { user }
|
|
33850
|
+
} = await createRequestSupabaseClient(c).auth.getUser().catch(() => ({ data: { user: null } }));
|
|
33851
|
+
if (!user?.email) return null;
|
|
33852
|
+
const [memberships, workspaces] = await Promise.all([
|
|
33853
|
+
listMembershipsByEmail(user.email),
|
|
33854
|
+
listWorkspaces()
|
|
33855
|
+
]);
|
|
33856
|
+
const slugById = new Map(workspaces.map((w) => [w.id, w.slug]));
|
|
33857
|
+
for (const m of memberships) {
|
|
33858
|
+
const slug = slugById.get(m.workspaceId);
|
|
33859
|
+
if (slug && known.includes(slug)) return slug;
|
|
33860
|
+
}
|
|
33861
|
+
return null;
|
|
33862
|
+
}
|
|
33406
33863
|
function createGatedRouter(agent, register) {
|
|
33407
|
-
const api = new
|
|
33864
|
+
const api = new Hono35();
|
|
33408
33865
|
api.use("*", async (c, next) => {
|
|
33409
33866
|
const known = await listKnownWorkspaces();
|
|
33410
33867
|
const fromHost = profileFromHost(trustedHost(c), known);
|
|
@@ -33413,7 +33870,9 @@ function createGatedRouter(agent, register) {
|
|
|
33413
33870
|
if (known.includes(requested)) return runWithProfile(requested, () => next());
|
|
33414
33871
|
if (!fromHost) return c.json({ error: `unknown profile: ${requested}` }, 400);
|
|
33415
33872
|
}
|
|
33416
|
-
|
|
33873
|
+
if (fromHost) return runWithProfile(fromHost, () => next());
|
|
33874
|
+
const viewer = await viewerProfile(c, known);
|
|
33875
|
+
return viewer ? runWithProfile(viewer, () => next()) : next();
|
|
33417
33876
|
});
|
|
33418
33877
|
api.route("/auth/device", createDeviceAuthRouter());
|
|
33419
33878
|
api.route("/auth", createAuthRouter());
|
|
@@ -33457,7 +33916,7 @@ import sharp7 from "sharp";
|
|
|
33457
33916
|
|
|
33458
33917
|
// src/dashboard/channels-routes.ts
|
|
33459
33918
|
import { existsSync as existsSync22, mkdirSync as mkdirSync10 } from "fs";
|
|
33460
|
-
import { Hono as
|
|
33919
|
+
import { Hono as Hono36 } from "hono";
|
|
33461
33920
|
function coerceAccess(raw) {
|
|
33462
33921
|
if (raw === "open" || raw === "*" || raw === "all") return raw;
|
|
33463
33922
|
if (Array.isArray(raw) && raw.every((v) => typeof v === "string")) return raw;
|
|
@@ -33469,6 +33928,10 @@ function coerceVisibility(raw) {
|
|
|
33469
33928
|
function coerceRuntime(raw) {
|
|
33470
33929
|
return raw === "host" || raw === "container" || raw === "sandbox" ? raw : void 0;
|
|
33471
33930
|
}
|
|
33931
|
+
function coercePermissionMode(raw) {
|
|
33932
|
+
if (raw === null || raw === "") return null;
|
|
33933
|
+
return isPermissionMode(raw) ? raw : void 0;
|
|
33934
|
+
}
|
|
33472
33935
|
function coerceEffort(raw) {
|
|
33473
33936
|
return typeof raw === "string" && isEffort(raw) ? raw : void 0;
|
|
33474
33937
|
}
|
|
@@ -33517,6 +33980,7 @@ function toResponse3(channel) {
|
|
|
33517
33980
|
memberEmails: channel.memberEmails,
|
|
33518
33981
|
runtime: channel.runtime,
|
|
33519
33982
|
mounts: channel.mounts,
|
|
33983
|
+
permissionMode: channel.permissionMode,
|
|
33520
33984
|
agentName: channel.agentName,
|
|
33521
33985
|
dmKey: channel.dmKey,
|
|
33522
33986
|
isDefault: channel.isDefault,
|
|
@@ -33524,7 +33988,7 @@ function toResponse3(channel) {
|
|
|
33524
33988
|
};
|
|
33525
33989
|
}
|
|
33526
33990
|
function createChannelWriteRouter() {
|
|
33527
|
-
const app = new
|
|
33991
|
+
const app = new Hono36();
|
|
33528
33992
|
app.post("/", async (c) => {
|
|
33529
33993
|
const body = await c.req.json().catch(() => ({}));
|
|
33530
33994
|
const name = typeof body["name"] === "string" ? body["name"].trim() : "";
|
|
@@ -33578,7 +34042,8 @@ function createChannelWriteRouter() {
|
|
|
33578
34042
|
visibility: coerceVisibility(body["visibility"]),
|
|
33579
34043
|
memberEmails: coerceMemberEmails(body["memberEmails"]),
|
|
33580
34044
|
runtime: coerceRuntime(body["runtime"]),
|
|
33581
|
-
mounts: coerceMounts(body["mounts"])
|
|
34045
|
+
mounts: coerceMounts(body["mounts"]),
|
|
34046
|
+
permissionMode: coercePermissionMode(body["permissionMode"])
|
|
33582
34047
|
});
|
|
33583
34048
|
ensureCwdDir(cwd);
|
|
33584
34049
|
dropSessionsIfRuntimeChanged(id, existing.runtime, channel.runtime);
|
|
@@ -33633,6 +34098,7 @@ function createChannelWriteRouter() {
|
|
|
33633
34098
|
if (r) patch.runtime = r;
|
|
33634
34099
|
}
|
|
33635
34100
|
if ("mounts" in body) patch.mounts = coerceMounts(body["mounts"]);
|
|
34101
|
+
if ("permissionMode" in body) patch.permissionMode = coercePermissionMode(body["permissionMode"]);
|
|
33636
34102
|
if (typeof body["archived"] === "boolean") {
|
|
33637
34103
|
patch.archivedAt = body["archived"] ? (/* @__PURE__ */ new Date()).toISOString() : null;
|
|
33638
34104
|
}
|
|
@@ -33667,7 +34133,7 @@ import {
|
|
|
33667
34133
|
} from "fs";
|
|
33668
34134
|
import { Readable } from "stream";
|
|
33669
34135
|
import { basename as basename8, dirname as dirname8, extname, join as join23, relative, resolve as resolve5, sep } from "path";
|
|
33670
|
-
import { Hono as
|
|
34136
|
+
import { Hono as Hono37 } from "hono";
|
|
33671
34137
|
import { streamSSE as streamSSE2 } from "hono/streaming";
|
|
33672
34138
|
|
|
33673
34139
|
// src/dashboard/docs-watcher.ts
|
|
@@ -34154,8 +34620,9 @@ function writeMcpConfigFile(config) {
|
|
|
34154
34620
|
cleanup: () => rmSync6(dir, { recursive: true, force: true })
|
|
34155
34621
|
};
|
|
34156
34622
|
}
|
|
34157
|
-
async function withMcpConfig(profile, connectionIds, fn) {
|
|
34623
|
+
async function withMcpConfig(profile, connectionIds, fn, extraServers = {}) {
|
|
34158
34624
|
const { config, skipped } = await buildMcpConfig(profile, connectionIds);
|
|
34625
|
+
Object.assign(config.mcpServers, extraServers);
|
|
34159
34626
|
if (!Object.keys(config.mcpServers).length && !mcpStrictConfigEnabled()) {
|
|
34160
34627
|
return fn(void 0, skipped);
|
|
34161
34628
|
}
|
|
@@ -34642,6 +35109,44 @@ ${recent.map((m) => `${m.author}: ${m.body}`).join("\n")}`;
|
|
|
34642
35109
|
}
|
|
34643
35110
|
}
|
|
34644
35111
|
|
|
35112
|
+
// src/dashboard/background-tasks.ts
|
|
35113
|
+
import { execFile as execFile2 } from "child_process";
|
|
35114
|
+
import { promisify as promisify2 } from "util";
|
|
35115
|
+
var execFileAsync = promisify2(execFile2);
|
|
35116
|
+
var WAKE_THREAD_RE = /chat wake\b.*?--thread[ =]['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/;
|
|
35117
|
+
function parseEtime(etime) {
|
|
35118
|
+
const [days, rest] = etime.includes("-") ? etime.split("-") : ["0", etime];
|
|
35119
|
+
const parts = rest.split(":").map(Number);
|
|
35120
|
+
while (parts.length < 3) parts.unshift(0);
|
|
35121
|
+
const [h, m, s] = parts;
|
|
35122
|
+
return Number(days) * 86400 + h * 3600 + m * 60 + s;
|
|
35123
|
+
}
|
|
35124
|
+
function parseBackgroundTasks(psOutput, now = Date.now()) {
|
|
35125
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
35126
|
+
for (const line of psOutput.split("\n")) {
|
|
35127
|
+
const m = /^\s*(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
35128
|
+
if (!m) continue;
|
|
35129
|
+
const [, pid, etime, command] = m;
|
|
35130
|
+
if (/^\S*node\b/.test(command)) continue;
|
|
35131
|
+
const threadId = WAKE_THREAD_RE.exec(command)?.[1];
|
|
35132
|
+
if (!threadId) continue;
|
|
35133
|
+
const list = byThread.get(threadId) ?? [];
|
|
35134
|
+
list.push({ pid: Number(pid), startedAt: now - parseEtime(etime) * 1e3 });
|
|
35135
|
+
byThread.set(threadId, list);
|
|
35136
|
+
}
|
|
35137
|
+
return byThread;
|
|
35138
|
+
}
|
|
35139
|
+
async function scanBackgroundTasks() {
|
|
35140
|
+
try {
|
|
35141
|
+
const { stdout } = await execFileAsync("ps", ["-axo", "pid=,etime=,command="], {
|
|
35142
|
+
maxBuffer: 16 * 1024 * 1024
|
|
35143
|
+
});
|
|
35144
|
+
return parseBackgroundTasks(stdout);
|
|
35145
|
+
} catch {
|
|
35146
|
+
return /* @__PURE__ */ new Map();
|
|
35147
|
+
}
|
|
35148
|
+
}
|
|
35149
|
+
|
|
34645
35150
|
// src/dashboard/attachment-downloader.ts
|
|
34646
35151
|
import { writeFile } from "fs/promises";
|
|
34647
35152
|
import { join as join22 } from "path";
|
|
@@ -34758,6 +35263,8 @@ function guardDocMentions(body, root) {
|
|
|
34758
35263
|
}
|
|
34759
35264
|
|
|
34760
35265
|
// src/dashboard/chat-agent.ts
|
|
35266
|
+
var PERMISSION_SERVER = "flyspace_permission";
|
|
35267
|
+
var PERMISSION_PROMPT_TOOL = `mcp__${PERMISSION_SERVER}__request_permission`;
|
|
34761
35268
|
var CLASSIFIER_CONTEXT_SIZE = 10;
|
|
34762
35269
|
var DEFAULT_SESSION_COMPACT_THRESHOLD_TOKENS = 14e4;
|
|
34763
35270
|
var DEFAULT_RECENT_VERBATIM_TOKENS = 2e4;
|
|
@@ -34800,6 +35307,8 @@ function loadChatAgentConfig() {
|
|
|
34800
35307
|
};
|
|
34801
35308
|
}
|
|
34802
35309
|
var RETRY_DELAY_MS = 3e3;
|
|
35310
|
+
var MAX_CONSECUTIVE_WAKES = 5;
|
|
35311
|
+
var BACKGROUND_SWEEP_MS = 6e4;
|
|
34803
35312
|
var MISSED_MESSAGE_WINDOW_MS = 24 * 60 * 60 * 1e3;
|
|
34804
35313
|
var MISSED_MESSAGE_THREAD_LIMIT = 100;
|
|
34805
35314
|
var delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
@@ -34862,6 +35371,17 @@ var ChatAgent = class {
|
|
|
34862
35371
|
* never re-runs a message that is queued, in flight, or was deliberately
|
|
34863
35372
|
* left unanswered by the ambient classifier. */
|
|
34864
35373
|
seenReplies = /* @__PURE__ */ new Set();
|
|
35374
|
+
/** threadId → wakes since the last human message. Capped at
|
|
35375
|
+
* `MAX_CONSECUTIVE_WAKES` so a woken turn that launches another background
|
|
35376
|
+
* job (which wakes it again, and so on) can't loop forever unattended. */
|
|
35377
|
+
consecutiveWakes = /* @__PURE__ */ new Map();
|
|
35378
|
+
/** threadId → when its last wake arrived, so the sweep can tell a job that
|
|
35379
|
+
* reported back from one that died silently. */
|
|
35380
|
+
lastWakeAt = /* @__PURE__ */ new Map();
|
|
35381
|
+
/** threadId → background jobs seen waiting on it, and the profile that owns
|
|
35382
|
+
* the thread (the sweep runs outside any request's profile binding). */
|
|
35383
|
+
watchedTasks = /* @__PURE__ */ new Map();
|
|
35384
|
+
backgroundSweep;
|
|
34865
35385
|
/** Workspace roots (workspaces.root_path) for path-prefix stripping in
|
|
34866
35386
|
* activity labels. Fetched once per process — roots change ~never, and a
|
|
34867
35387
|
* restart picks up edits. */
|
|
@@ -34899,6 +35419,7 @@ var ChatAgent = class {
|
|
|
34899
35419
|
handleMessage(msg) {
|
|
34900
35420
|
if (msg.author === AGENT_AUTHOR) return;
|
|
34901
35421
|
this.seenReplies.add(msg.replyId);
|
|
35422
|
+
if (!msg.resumed && !msg.woken) this.consecutiveWakes.delete(msg.threadId);
|
|
34902
35423
|
this.queue.enqueue(msg.threadId, () => this.maybeRun(msg));
|
|
34903
35424
|
void this.maybeSupersede(msg);
|
|
34904
35425
|
}
|
|
@@ -34933,6 +35454,68 @@ var ChatAgent = class {
|
|
|
34933
35454
|
this.supersedingReplies.add(msg.replyId);
|
|
34934
35455
|
run5.abort.abort();
|
|
34935
35456
|
}
|
|
35457
|
+
/**
|
|
35458
|
+
* A background task the agent launched in an earlier turn has finished and
|
|
35459
|
+
* reported back via `flyspace chat wake` (its result is already posted as
|
|
35460
|
+
* reply `replyId`). Each turn is a one-shot CLI process, so nothing else is
|
|
35461
|
+
* left to notice the task ending: this queues a new turn on the thread,
|
|
35462
|
+
* which resumes the same session with the result as its prompt. Goes
|
|
35463
|
+
* through the per-thread queue like any message, so it waits for an
|
|
35464
|
+
* in-flight run instead of racing it. Returns false when refused: the
|
|
35465
|
+
* consecutive-wake cap was hit, or no human ever spoke in the thread.
|
|
35466
|
+
*/
|
|
35467
|
+
async wake(threadId, replyId, text) {
|
|
35468
|
+
const wakes = this.consecutiveWakes.get(threadId) ?? 0;
|
|
35469
|
+
if (wakes >= MAX_CONSECUTIVE_WAKES) {
|
|
35470
|
+
console.log(`[chat-agent] wake refused, cap of ${MAX_CONSECUTIVE_WAKES} reached. thread=${threadId}`);
|
|
35471
|
+
return false;
|
|
35472
|
+
}
|
|
35473
|
+
const { data } = await this.supabase().from("thread_replies").select("author").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: false }).limit(50);
|
|
35474
|
+
const asker = (data ?? []).find((r) => isHumanAuthor(r.author));
|
|
35475
|
+
if (!asker) return false;
|
|
35476
|
+
this.consecutiveWakes.set(threadId, wakes + 1);
|
|
35477
|
+
this.lastWakeAt.set(threadId, Date.now());
|
|
35478
|
+
console.log(`[chat-agent] woken by background task. thread=${threadId}`);
|
|
35479
|
+
this.handleMessage({ threadId, replyId, author: asker.author, body: text, woken: true });
|
|
35480
|
+
return true;
|
|
35481
|
+
}
|
|
35482
|
+
/** Background jobs still waiting to wake this thread (the "waiting on a
|
|
35483
|
+
* background task" status). */
|
|
35484
|
+
async backgroundTasks(threadId) {
|
|
35485
|
+
return (await scanBackgroundTasks()).get(threadId) ?? [];
|
|
35486
|
+
}
|
|
35487
|
+
/** After a run, start watching any job it left behind, so one that dies
|
|
35488
|
+
* without calling `chat wake` (killed, machine rebooted) still brings the
|
|
35489
|
+
* agent back instead of leaving the thread waiting forever. */
|
|
35490
|
+
async watchBackgroundTasks(threadId, profile) {
|
|
35491
|
+
const tasks = await this.backgroundTasks(threadId);
|
|
35492
|
+
if (tasks.length === 0) return;
|
|
35493
|
+
this.watchedTasks.set(threadId, { profile, firstSeen: Date.now(), tasks });
|
|
35494
|
+
this.backgroundSweep ??= setInterval(() => void this.sweepBackgroundTasks(), BACKGROUND_SWEEP_MS);
|
|
35495
|
+
this.backgroundSweep.unref?.();
|
|
35496
|
+
}
|
|
35497
|
+
async sweepBackgroundTasks() {
|
|
35498
|
+
const live = await scanBackgroundTasks();
|
|
35499
|
+
for (const [threadId, watched] of this.watchedTasks) {
|
|
35500
|
+
const tasks = live.get(threadId);
|
|
35501
|
+
if (tasks?.length) {
|
|
35502
|
+
watched.tasks = tasks;
|
|
35503
|
+
continue;
|
|
35504
|
+
}
|
|
35505
|
+
this.watchedTasks.delete(threadId);
|
|
35506
|
+
if ((this.lastWakeAt.get(threadId) ?? 0) >= watched.firstSeen) continue;
|
|
35507
|
+
console.log(`[chat-agent] background task ended without waking. thread=${threadId}`);
|
|
35508
|
+
const text = "Background task ended without reporting a result (it may have been killed or the machine restarted).";
|
|
35509
|
+
await runWithProfile(watched.profile, async () => {
|
|
35510
|
+
const { replyId } = await postToDashboardChannel({ threadId, text });
|
|
35511
|
+
await this.wake(threadId, replyId, text);
|
|
35512
|
+
}).catch((err) => console.error("[chat-agent] background wake failed:", err.message));
|
|
35513
|
+
}
|
|
35514
|
+
if (this.watchedTasks.size === 0 && this.backgroundSweep) {
|
|
35515
|
+
clearInterval(this.backgroundSweep);
|
|
35516
|
+
this.backgroundSweep = void 0;
|
|
35517
|
+
}
|
|
35518
|
+
}
|
|
34936
35519
|
/**
|
|
34937
35520
|
* Picks up messages nobody answered. `handleMessage` is fire-and-forget and
|
|
34938
35521
|
* every bit of run state lives in this process, so a message is silently
|
|
@@ -35007,7 +35590,7 @@ var ChatAgent = class {
|
|
|
35007
35590
|
async maybeRun(msg) {
|
|
35008
35591
|
const superseding = this.supersedingReplies.delete(msg.replyId);
|
|
35009
35592
|
if (await this.isPausedForThread(msg.threadId)) return;
|
|
35010
|
-
if (superseding || msg.resumed) {
|
|
35593
|
+
if (superseding || msg.resumed || msg.woken) {
|
|
35011
35594
|
await this.run(msg);
|
|
35012
35595
|
return;
|
|
35013
35596
|
}
|
|
@@ -35314,6 +35897,10 @@ var ChatAgent = class {
|
|
|
35314
35897
|
...isHumanAuthor(msg.author) ? { senderHandle: msg.author } : {}
|
|
35315
35898
|
});
|
|
35316
35899
|
if (memory.enabled) channelConfig = { ...channelConfig, disableAutoMemory: true };
|
|
35900
|
+
channelConfig = {
|
|
35901
|
+
...channelConfig,
|
|
35902
|
+
permissionThread: { threadId: msg.threadId, channelId: thread.channel_id }
|
|
35903
|
+
};
|
|
35317
35904
|
if (memory.memoryPrompt) channelConfig = { ...channelConfig, memoryPrompt: memory.memoryPrompt };
|
|
35318
35905
|
const store = this.openSessionStore();
|
|
35319
35906
|
try {
|
|
@@ -35335,6 +35922,9 @@ var ChatAgent = class {
|
|
|
35335
35922
|
const body = msg.resumed ? `[note: nobody sent a new message. The agent process restarted after your last reply in this thread, quoted below, which left work unfinished. Anything you had running or meant to do next may have died with it. Check what actually got done (a background job may also still be running, or have finished), then complete what is left and report the result. If there turns out to be nothing left to do, say so in one line. Do not promise another follow-up, and do not apologise for the gap.]
|
|
35336
35923
|
|
|
35337
35924
|
[your last reply]
|
|
35925
|
+
${msg.body}` : msg.woken ? `[background task finished]
|
|
35926
|
+
[note: nobody sent a new message. A background task you launched earlier in this thread has finished and reported the result below (it is already posted in the thread, so do not repeat it). Carry on with whatever was meant to happen next, then report. If nothing is left to do, say so in one line.]
|
|
35927
|
+
|
|
35338
35928
|
${msg.body}` : msg.body;
|
|
35339
35929
|
const barePrompt = header + interruptionNote + recoveryNote + body + buildFilesPromptSection(attachments);
|
|
35340
35930
|
let resumableSessionId = session?.runner === activeRunner ? session.sessionId : void 0;
|
|
@@ -35565,6 +36155,7 @@ ${msg.body}` : msg.body;
|
|
|
35565
36155
|
store.close();
|
|
35566
36156
|
this.activeRuns.delete(msg.threadId);
|
|
35567
36157
|
notifyThinking(false);
|
|
36158
|
+
void this.watchBackgroundTasks(msg.threadId, owningProfile);
|
|
35568
36159
|
}
|
|
35569
36160
|
}
|
|
35570
36161
|
/**
|
|
@@ -35704,6 +36295,16 @@ ${msg.body}` : msg.body;
|
|
|
35704
36295
|
async tryAsk(channelConfig, prompt, sessionId, onActivity, signal, usageContext) {
|
|
35705
36296
|
const name = subAgentName(channelConfig.agentName);
|
|
35706
36297
|
const agentPersona = name ? readAgentPersona(channelConfig.claudeConfigDir, channelConfig.cwd, name) : void 0;
|
|
36298
|
+
const permissionServer = channelConfig.permissionMode === "ask" && channelConfig.runtime === "host" && channelConfig.permissionThread ? {
|
|
36299
|
+
[PERMISSION_SERVER]: {
|
|
36300
|
+
command: "flyspace",
|
|
36301
|
+
args: ["mcp", "threads"],
|
|
36302
|
+
env: {
|
|
36303
|
+
FLYSPACE_PERMISSION_THREAD_ID: channelConfig.permissionThread.threadId,
|
|
36304
|
+
FLYSPACE_PERMISSION_CHANNEL_ID: channelConfig.permissionThread.channelId
|
|
36305
|
+
}
|
|
36306
|
+
}
|
|
36307
|
+
} : void 0;
|
|
35707
36308
|
try {
|
|
35708
36309
|
return await withMcpConfig(
|
|
35709
36310
|
channelConfig.profile,
|
|
@@ -35717,6 +36318,8 @@ ${msg.body}` : msg.body;
|
|
|
35717
36318
|
effort: channelConfig.effort,
|
|
35718
36319
|
runtime: channelConfig.runtime,
|
|
35719
36320
|
mounts: channelConfig.mounts,
|
|
36321
|
+
permissionMode: channelConfig.permissionMode,
|
|
36322
|
+
...permissionServer ? { permissionPromptTool: PERMISSION_PROMPT_TOOL } : {},
|
|
35720
36323
|
maxBudgetUsd: this.config.maxBudgetUsd,
|
|
35721
36324
|
agentPersona,
|
|
35722
36325
|
channelPrompt: channelConfig.prompt,
|
|
@@ -35732,7 +36335,8 @@ ${msg.body}` : msg.body;
|
|
|
35732
36335
|
channelConfig.claudeConfigDir,
|
|
35733
36336
|
sessionId,
|
|
35734
36337
|
channelConfig.claudeCodeOauthToken
|
|
35735
|
-
)
|
|
36338
|
+
),
|
|
36339
|
+
permissionServer ?? {}
|
|
35736
36340
|
);
|
|
35737
36341
|
} catch (err) {
|
|
35738
36342
|
console.error("[chat-agent] ask failed:", err.message);
|
|
@@ -36050,14 +36654,14 @@ async function exportDocAsArtifact(channelId, docPath) {
|
|
|
36050
36654
|
if (!abs) throw new Error(`doc not found: ${docPath}`);
|
|
36051
36655
|
const content = readFileSync21(abs, "utf8");
|
|
36052
36656
|
const title = extractTitle(abs, "md");
|
|
36053
|
-
const
|
|
36657
|
+
const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
36054
36658
|
const prompt = `Publish the document at \`${docPath}\` (already read below) as a Claude Artifact, then record the result as a stub file under this channel's \`docs/artifacts/\` folder (create the folder if it doesn't exist).
|
|
36055
36659
|
|
|
36056
|
-
Follow the exact stub convention already used elsewhere in this workspace: filename \`YYYY-MM-<topic-slug>.md\` (today is ${
|
|
36660
|
+
Follow the exact stub convention already used elsewhere in this workspace: filename \`YYYY-MM-<topic-slug>.md\` (today is ${today2}), containing the creation date, a short topic line, and the published artifact URL near the top, e.g.:
|
|
36057
36661
|
|
|
36058
36662
|
# ${title}
|
|
36059
36663
|
|
|
36060
|
-
\u5EFA\u7ACB\u65E5\u671F\uFF1A${
|
|
36664
|
+
\u5EFA\u7ACB\u65E5\u671F\uFF1A${today2}
|
|
36061
36665
|
\u4E3B\u984C\uFF1A<one-line topic in the doc's own language>
|
|
36062
36666
|
\u7DDA\u4E0A\u7248\uFF1A<the artifact URL>
|
|
36063
36667
|
|
|
@@ -36607,7 +37211,7 @@ function deleteDocEntry(root, path) {
|
|
|
36607
37211
|
};
|
|
36608
37212
|
}
|
|
36609
37213
|
function createDocsRouter({ gate = requireDocsAccess } = {}) {
|
|
36610
|
-
const app = new
|
|
37214
|
+
const app = new Hono37();
|
|
36611
37215
|
app.use("/:id/docs", gate);
|
|
36612
37216
|
app.use("/:id/docs/*", gate);
|
|
36613
37217
|
app.get("/:id/docs", (c) => {
|
|
@@ -36945,7 +37549,7 @@ function withDocLinkBridge(html) {
|
|
|
36945
37549
|
// src/dashboard/skills-routes-host.ts
|
|
36946
37550
|
import { existsSync as existsSync28, statSync as statSync7 } from "fs";
|
|
36947
37551
|
import { dirname as dirname9 } from "path";
|
|
36948
|
-
import { Hono as
|
|
37552
|
+
import { Hono as Hono38 } from "hono";
|
|
36949
37553
|
function workspaceScope() {
|
|
36950
37554
|
const claudeConfigDir = profileClaudeConfigDir();
|
|
36951
37555
|
const cwd = defaultClaudeCwd();
|
|
@@ -37051,12 +37655,12 @@ var diskBackend = {
|
|
|
37051
37655
|
write: writeSkillAndSync
|
|
37052
37656
|
};
|
|
37053
37657
|
function createWorkspaceSkillsRouter() {
|
|
37054
|
-
const app = new
|
|
37658
|
+
const app = new Hono38();
|
|
37055
37659
|
mountSkillRoutes(app, "/skills", workspaceRef, diskBackend);
|
|
37056
37660
|
return app;
|
|
37057
37661
|
}
|
|
37058
37662
|
function createChannelSkillsRouter() {
|
|
37059
|
-
const app = new
|
|
37663
|
+
const app = new Hono38();
|
|
37060
37664
|
mountSkillRoutes(app, "/:id/skill-files", channelRef, diskBackend);
|
|
37061
37665
|
return app;
|
|
37062
37666
|
}
|
|
@@ -37096,9 +37700,9 @@ var PROVIDER_LABELS = {
|
|
|
37096
37700
|
codex: "Codex"
|
|
37097
37701
|
};
|
|
37098
37702
|
var TTL_MS2 = 6e4;
|
|
37099
|
-
var
|
|
37703
|
+
var cache7 = /* @__PURE__ */ new Map();
|
|
37100
37704
|
function clearProviderStatusCache() {
|
|
37101
|
-
|
|
37705
|
+
cache7.clear();
|
|
37102
37706
|
}
|
|
37103
37707
|
function binaryOnPath(bin) {
|
|
37104
37708
|
try {
|
|
@@ -37176,11 +37780,11 @@ function withAuthFailure(status) {
|
|
|
37176
37780
|
}
|
|
37177
37781
|
function providerStatuses() {
|
|
37178
37782
|
const key = getProfile();
|
|
37179
|
-
const hit =
|
|
37783
|
+
const hit = cache7.get(key);
|
|
37180
37784
|
let statuses = hit && Date.now() - hit.at < TTL_MS2 ? hit.statuses : void 0;
|
|
37181
37785
|
if (!statuses) {
|
|
37182
37786
|
statuses = ["claude", "codex"].map(probe2);
|
|
37183
|
-
|
|
37787
|
+
cache7.set(key, { at: Date.now(), statuses });
|
|
37184
37788
|
}
|
|
37185
37789
|
return statuses.map((st) => st.runner === "claude" && st.connected ? withAuthFailure(st) : st);
|
|
37186
37790
|
}
|
|
@@ -37191,7 +37795,7 @@ import { randomUUID as randomUUID5 } from "crypto";
|
|
|
37191
37795
|
import { chmodSync, existsSync as existsSync30, mkdirSync as mkdirSync12, readFileSync as readFileSync24, writeFileSync as writeFileSync12 } from "fs";
|
|
37192
37796
|
import { createRequire } from "module";
|
|
37193
37797
|
import { dirname as dirname10, join as join25 } from "path";
|
|
37194
|
-
import { Hono as
|
|
37798
|
+
import { Hono as Hono39 } from "hono";
|
|
37195
37799
|
var SESSION_TTL_MS = 10 * 6e4;
|
|
37196
37800
|
var URL_WAIT_MS = 3e4;
|
|
37197
37801
|
var TOKEN_WAIT_MS = 6e4;
|
|
@@ -37348,7 +37952,7 @@ function failure2(c, err) {
|
|
|
37348
37952
|
return c.json({ error: err.message }, 500);
|
|
37349
37953
|
}
|
|
37350
37954
|
function createProviderLoginRouter() {
|
|
37351
|
-
const app = new
|
|
37955
|
+
const app = new Hono39();
|
|
37352
37956
|
app.use("*", async (c, next) => {
|
|
37353
37957
|
const denied = requireAdmin4(c.get("auth"));
|
|
37354
37958
|
if (denied) return c.json({ error: denied }, 403);
|
|
@@ -37392,7 +37996,7 @@ function createProviderLoginRouter() {
|
|
|
37392
37996
|
return app;
|
|
37393
37997
|
}
|
|
37394
37998
|
async function handleProviderLoginRequest(req) {
|
|
37395
|
-
const app = new
|
|
37999
|
+
const app = new Hono39();
|
|
37396
38000
|
app.use("*", async (c, next) => {
|
|
37397
38001
|
c.set("auth", { role: "admin" });
|
|
37398
38002
|
await next();
|
|
@@ -37784,13 +38388,13 @@ function handleSessionImportRequest(req) {
|
|
|
37784
38388
|
}
|
|
37785
38389
|
|
|
37786
38390
|
// src/dashboard/docs-relay-host.ts
|
|
37787
|
-
import { Hono as
|
|
38391
|
+
import { Hono as Hono40 } from "hono";
|
|
37788
38392
|
var RETURNED_HEADERS = ["content-type", "content-disposition", "content-security-policy", "cache-control"];
|
|
37789
38393
|
async function handleDocsRequest(req) {
|
|
37790
38394
|
return runRelayed(req, (app) => app.route("/channels", createDocsRouter({ gate: async (_c, next) => next() })));
|
|
37791
38395
|
}
|
|
37792
38396
|
async function runRelayed(req, register) {
|
|
37793
|
-
const app = new
|
|
38397
|
+
const app = new Hono40();
|
|
37794
38398
|
app.use("*", async (c, next) => {
|
|
37795
38399
|
c.set("auth", req.auth);
|
|
37796
38400
|
await next();
|
|
@@ -38063,9 +38667,9 @@ function startHostUpgrade() {
|
|
|
38063
38667
|
}
|
|
38064
38668
|
|
|
38065
38669
|
// src/dashboard/mcp-servers-host.ts
|
|
38066
|
-
import { execFile as
|
|
38670
|
+
import { execFile as execFile3 } from "child_process";
|
|
38067
38671
|
import { homedir as homedir11 } from "os";
|
|
38068
|
-
import { promisify as
|
|
38672
|
+
import { promisify as promisify3 } from "util";
|
|
38069
38673
|
|
|
38070
38674
|
// ../api/src/dashboard/mcp-servers.ts
|
|
38071
38675
|
var LINE = /^(.+?): (.+) - [✔✘!✓✗] ?(.*)$/u;
|
|
@@ -38112,7 +38716,7 @@ function parseMcpList(output) {
|
|
|
38112
38716
|
}
|
|
38113
38717
|
|
|
38114
38718
|
// src/dashboard/mcp-servers-host.ts
|
|
38115
|
-
var run4 =
|
|
38719
|
+
var run4 = promisify3(execFile3);
|
|
38116
38720
|
async function listMcpServers() {
|
|
38117
38721
|
const env = { ...process.env };
|
|
38118
38722
|
const pinned = pinnedClaudeConfigDir(profileClaudeConfigDir());
|
|
@@ -38156,9 +38760,11 @@ function localAgentCallbacks(chatAgent) {
|
|
|
38156
38760
|
onChatMessage: (msg) => chatAgent.handleMessage(msg),
|
|
38157
38761
|
isAgentThinking: (threadId) => chatAgent.isThinking(threadId),
|
|
38158
38762
|
getAgentActivities: (threadId) => chatAgent.getActivities(threadId),
|
|
38763
|
+
getBackgroundTasks: (threadId) => chatAgent.backgroundTasks(threadId),
|
|
38159
38764
|
cancelAgentRun: (threadId) => chatAgent.cancel(threadId),
|
|
38160
38765
|
regenerateAgentRun: (threadId, stoppedReplyId) => chatAgent.regenerate(threadId, stoppedReplyId),
|
|
38161
38766
|
listAgentRuns: () => chatAgent.runningThreadIds(),
|
|
38767
|
+
wakeAgentRun: (threadId, replyId, text) => chatAgent.wake(threadId, replyId, text),
|
|
38162
38768
|
completeMemoryExtraction: (req) => chatAgent.completeMemoryExtraction(req),
|
|
38163
38769
|
suggestChannelField: (req) => suggestChannelField(req),
|
|
38164
38770
|
listMissingCwds: () => auditChannelCwds().map((ch) => ch.id),
|
|
@@ -38465,8 +39071,8 @@ import { existsSync as existsSync34 } from "fs";
|
|
|
38465
39071
|
import { join as join28 } from "path";
|
|
38466
39072
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
38467
39073
|
|
|
38468
|
-
// src/dashboard/app-icon-routes.ts
|
|
38469
|
-
import { Hono as
|
|
39074
|
+
// ../api/src/dashboard/app-icon-routes.ts
|
|
39075
|
+
import { Hono as Hono41 } from "hono";
|
|
38470
39076
|
var NEUTRAL_MANIFEST = {
|
|
38471
39077
|
id: "/",
|
|
38472
39078
|
name: "Flyspace",
|
|
@@ -38504,7 +39110,7 @@ async function withResolvedProfile2(c, next) {
|
|
|
38504
39110
|
return profile ? runWithProfile(profile, () => next()) : next();
|
|
38505
39111
|
}
|
|
38506
39112
|
function createAppIconRouter() {
|
|
38507
|
-
const app = new
|
|
39113
|
+
const app = new Hono41();
|
|
38508
39114
|
app.get("/manifest.json", withResolvedProfile2, async (c) => {
|
|
38509
39115
|
if (!await resolvedProfileHost(c)) return c.json(NEUTRAL_MANIFEST);
|
|
38510
39116
|
const profile = getProfile();
|
|
@@ -39083,7 +39689,7 @@ async function main() {
|
|
|
39083
39689
|
break;
|
|
39084
39690
|
case "-v":
|
|
39085
39691
|
case "--version":
|
|
39086
|
-
printRaw("0.1.
|
|
39692
|
+
printRaw("0.1.50");
|
|
39087
39693
|
break;
|
|
39088
39694
|
case "-h":
|
|
39089
39695
|
case "--help":
|