flyspace-cli 0.1.52 → 0.1.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-67WA56OD.js +1243 -0
- package/dist/chunk-ONGRYEWS.js +178 -0
- package/dist/{chunk-ZBOOJCDU.js → chunk-ZSRDP5HJ.js} +2072 -2167
- package/dist/cli.js +916 -564
- package/dist/index.js +2 -2
- package/dist/{threads-QAVO2Z4L.js → threads-PTTZUNIJ.js} +43 -12
- package/package.json +1 -1
- package/system.capabilities.md +2 -0
- package/dist/chunk-HTFQL66T.js +0 -488
- package/dist/chunk-PIAF4FJX.js +0 -76
package/dist/cli.js
CHANGED
|
@@ -3,14 +3,14 @@ import { createRequire as __flyspaceCreateRequire } from 'node:module';
|
|
|
3
3
|
const require = __flyspaceCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
5
|
AutomationManager,
|
|
6
|
+
BOT_DM_KEY,
|
|
7
|
+
BOT_LABEL,
|
|
6
8
|
BOT_PROFILE_KEY,
|
|
7
9
|
BRANDING_DEFAULTS,
|
|
8
10
|
BUILT_IN_OUTPUT_STYLES,
|
|
9
11
|
CLI_VERSION,
|
|
10
|
-
ChannelCwdError,
|
|
11
12
|
ChatAgent,
|
|
12
13
|
DEFAULT_TIMEZONE,
|
|
13
|
-
DefaultChannelError,
|
|
14
14
|
DocShareSlugTakenError,
|
|
15
15
|
HANDLE_PATTERN,
|
|
16
16
|
HandleTakenError,
|
|
@@ -22,21 +22,18 @@ import {
|
|
|
22
22
|
PLATE,
|
|
23
23
|
SKIP_SUBTYPES,
|
|
24
24
|
SLACK_ENV,
|
|
25
|
-
|
|
26
|
-
SessionStore,
|
|
25
|
+
SUPPORT_AVATAR_URL,
|
|
27
26
|
TRANSLATION_LANGUAGES,
|
|
28
27
|
TRIAL_DAYS,
|
|
29
28
|
UsageStore,
|
|
30
29
|
acquireHostLock,
|
|
31
|
-
|
|
32
|
-
auditChannelCwds,
|
|
30
|
+
agentViewer,
|
|
33
31
|
authorFor,
|
|
34
32
|
blockToFallbackText,
|
|
35
33
|
bodyTextFor,
|
|
36
34
|
buildAuthorizeUrl,
|
|
37
35
|
buildAutoTitle,
|
|
38
36
|
cachedProfileConfig,
|
|
39
|
-
canSeeChannel,
|
|
40
37
|
canonicalLanguage,
|
|
41
38
|
channelSkillsDir,
|
|
42
39
|
claudeAuthFailed,
|
|
@@ -45,7 +42,6 @@ import {
|
|
|
45
42
|
codexAuthAvailable,
|
|
46
43
|
consumeOAuthState,
|
|
47
44
|
corsForShell,
|
|
48
|
-
createChannel,
|
|
49
45
|
createDocShare,
|
|
50
46
|
createDocsRouter,
|
|
51
47
|
createFeatureFlagsRouter,
|
|
@@ -56,6 +52,7 @@ import {
|
|
|
56
52
|
createPkcePair,
|
|
57
53
|
createPublicShareApiRouter,
|
|
58
54
|
createPublicShareAssetRouter,
|
|
55
|
+
createRequestSupabaseClient,
|
|
59
56
|
createSkillFile,
|
|
60
57
|
createStateToken,
|
|
61
58
|
createTtsRouter,
|
|
@@ -74,23 +71,18 @@ import {
|
|
|
74
71
|
deleteWorkspace,
|
|
75
72
|
deleteWorkspaceDomain,
|
|
76
73
|
deriveConnectionSlug,
|
|
74
|
+
detectSourceLanguage,
|
|
77
75
|
displayNameFor,
|
|
78
76
|
dropShareAudio,
|
|
79
77
|
dropShareLangAudioKeys,
|
|
80
78
|
effectiveModel,
|
|
81
|
-
ensureAgentDmChannel,
|
|
82
|
-
ensureGeneralChannel,
|
|
83
|
-
ensureMemberDmChannel,
|
|
84
79
|
ensureUsersCached,
|
|
85
80
|
escalateToHuman,
|
|
86
81
|
exchangeCode,
|
|
87
|
-
expandPath,
|
|
88
82
|
explainCost,
|
|
89
83
|
extractCategories,
|
|
90
84
|
extractTitle,
|
|
91
85
|
filterReadableDocsChannels,
|
|
92
|
-
findChannel,
|
|
93
|
-
findChannelById,
|
|
94
86
|
findDocShareBySource,
|
|
95
87
|
findOwningProfile,
|
|
96
88
|
findSkillDetail,
|
|
@@ -99,7 +91,6 @@ import {
|
|
|
99
91
|
getAllowGuestAccess,
|
|
100
92
|
getChannelDocsMemberAccess,
|
|
101
93
|
getChannelMemory,
|
|
102
|
-
getChannelRegistry,
|
|
103
94
|
getLocalCache,
|
|
104
95
|
getMcpConnection,
|
|
105
96
|
getMcpProvider,
|
|
@@ -107,7 +98,6 @@ import {
|
|
|
107
98
|
getMembershipByUserId,
|
|
108
99
|
getMemory,
|
|
109
100
|
getOutputStyleDefault,
|
|
110
|
-
getProfileChannelRegistry,
|
|
111
101
|
getWorkspaceAutoContinueLimit,
|
|
112
102
|
getWorkspaceBilling,
|
|
113
103
|
getWorkspaceBranding,
|
|
@@ -120,25 +110,22 @@ import {
|
|
|
120
110
|
getWorkspacePlanStatus,
|
|
121
111
|
handleAttachmentUrlResult,
|
|
122
112
|
handleHostDbResult,
|
|
113
|
+
handleShouldRespondResult,
|
|
123
114
|
handleSupportMention,
|
|
124
115
|
highlightLanguageOf,
|
|
125
116
|
insertMcpConnection,
|
|
126
117
|
insertWorkspaceDomain,
|
|
127
118
|
installUsageRecording,
|
|
119
|
+
invalidateAuthContextCache,
|
|
128
120
|
isAllowedModel,
|
|
129
|
-
isCwdUsable,
|
|
130
121
|
isDevHost,
|
|
131
122
|
isDocsAccess,
|
|
132
|
-
isEffort,
|
|
133
123
|
isFeatureEnabled,
|
|
134
124
|
isLockedPlan,
|
|
135
|
-
isLogicalCwd,
|
|
136
125
|
isMemoryType,
|
|
137
126
|
isOlderVersion,
|
|
138
|
-
isPermissionMode,
|
|
139
127
|
isSlugAvailable,
|
|
140
128
|
isTranslatableLanguage,
|
|
141
|
-
isUnderLogicalRoot,
|
|
142
129
|
isUnknownWorkspaceHost,
|
|
143
130
|
isUuid,
|
|
144
131
|
isValidSkillName,
|
|
@@ -173,13 +160,13 @@ import {
|
|
|
173
160
|
loadFullDashboardSettings,
|
|
174
161
|
loadWorkspaceBranding,
|
|
175
162
|
loadWorkspacePrompt,
|
|
176
|
-
markChannelGreeted,
|
|
177
163
|
markInviteResent,
|
|
178
164
|
markMemoryUsed,
|
|
179
165
|
markWorkspaceGreeted,
|
|
180
166
|
markWorkspaceProjectsSetup,
|
|
181
167
|
markdownToBlocks,
|
|
182
168
|
mentionedUserIds,
|
|
169
|
+
onboardingPending,
|
|
183
170
|
pinnedClaudeConfigDir,
|
|
184
171
|
profileClaudeConfigDir,
|
|
185
172
|
profileEnv,
|
|
@@ -194,7 +181,6 @@ import {
|
|
|
194
181
|
recentRunsForWorkspace,
|
|
195
182
|
refreshAutomationRegistry,
|
|
196
183
|
refreshCache,
|
|
197
|
-
refreshChannelRegistry,
|
|
198
184
|
refreshUserCache,
|
|
199
185
|
removeChannelMember,
|
|
200
186
|
renderAppIcon,
|
|
@@ -203,15 +189,16 @@ import {
|
|
|
203
189
|
requireSlackBotToken,
|
|
204
190
|
resetWorkspaceOnboarding,
|
|
205
191
|
resetWorkspacePrompt,
|
|
192
|
+
resolveAuthContext,
|
|
206
193
|
resolveChannelConfig,
|
|
207
194
|
resolveChannelId,
|
|
208
|
-
resolveCwd,
|
|
209
195
|
resolveDocPath,
|
|
210
196
|
resolveDocsAccess,
|
|
211
197
|
resolveRateCard,
|
|
212
198
|
resolveRawPath,
|
|
213
199
|
resolveUserId,
|
|
214
200
|
revokeDocShare,
|
|
201
|
+
rowToMemory,
|
|
215
202
|
runAutomation,
|
|
216
203
|
runScriptAutomation,
|
|
217
204
|
runnerForModel,
|
|
@@ -244,7 +231,6 @@ import {
|
|
|
244
231
|
slackConfigured,
|
|
245
232
|
slackMrkdwnToMarkdown,
|
|
246
233
|
startAutomationRegistryPolling,
|
|
247
|
-
startChannelRegistryPolling,
|
|
248
234
|
startServer,
|
|
249
235
|
suggestChannelField,
|
|
250
236
|
syncSlackAvatars,
|
|
@@ -253,9 +239,7 @@ import {
|
|
|
253
239
|
trustedHost,
|
|
254
240
|
tsToIso,
|
|
255
241
|
undoMemoryEvent,
|
|
256
|
-
updateChannelById,
|
|
257
242
|
updateChannelMemory,
|
|
258
|
-
updateChannelsMcpConnections,
|
|
259
243
|
updateDocShareFeatures,
|
|
260
244
|
updateDocShareSnapshot,
|
|
261
245
|
updateMcpConnectionSettings,
|
|
@@ -272,39 +256,66 @@ import {
|
|
|
272
256
|
useDirectSupabase,
|
|
273
257
|
useLocalCache,
|
|
274
258
|
validateMemoryInput,
|
|
275
|
-
warnOnBrokenChannelCwds,
|
|
276
259
|
workspaceHostname,
|
|
277
260
|
workspaceSkillsDir,
|
|
278
261
|
writeSkillFile
|
|
279
|
-
} from "./chunk-
|
|
262
|
+
} from "./chunk-ZSRDP5HJ.js";
|
|
280
263
|
import {
|
|
264
|
+
canReadThread,
|
|
281
265
|
firstReplyBody,
|
|
282
266
|
getThread,
|
|
283
267
|
listChannels,
|
|
284
268
|
listThreads,
|
|
285
|
-
|
|
286
|
-
resolveChannel
|
|
287
|
-
|
|
269
|
+
moveThreadFully,
|
|
270
|
+
resolveChannel,
|
|
271
|
+
resolveThreadOwner
|
|
272
|
+
} from "./chunk-ONGRYEWS.js";
|
|
288
273
|
import {
|
|
289
274
|
AGENT_AUTHOR,
|
|
275
|
+
ChannelCwdError,
|
|
290
276
|
DEFAULT_PROFILE,
|
|
277
|
+
DefaultChannelError,
|
|
291
278
|
SCRATCH_PREFIX,
|
|
279
|
+
SessionStore,
|
|
280
|
+
auditChannelCwds,
|
|
281
|
+
canSeeChannel,
|
|
282
|
+
createChannel,
|
|
292
283
|
databaseReachable,
|
|
284
|
+
ensureAgentDmChannel,
|
|
293
285
|
ensureDirs,
|
|
286
|
+
ensureGeneralChannel,
|
|
287
|
+
ensureMemberDmChannel,
|
|
288
|
+
expandPath,
|
|
289
|
+
findChannel,
|
|
290
|
+
findChannelById,
|
|
291
|
+
getChannelRegistry,
|
|
294
292
|
getProfile,
|
|
293
|
+
getProfileChannelRegistry,
|
|
295
294
|
getR2Bucket,
|
|
296
295
|
getR2Client,
|
|
297
296
|
getSupabaseClient,
|
|
298
297
|
hasSupabaseCredentials,
|
|
298
|
+
isCwdUsable,
|
|
299
|
+
isEffort,
|
|
299
300
|
isHumanAuthor,
|
|
301
|
+
isLogicalCwd,
|
|
302
|
+
isPermissionMode,
|
|
303
|
+
isUnderLogicalRoot,
|
|
304
|
+
markChannelGreeted,
|
|
300
305
|
paths,
|
|
301
306
|
postToDashboardChannel,
|
|
307
|
+
refreshChannelRegistry,
|
|
308
|
+
resolveCwd,
|
|
302
309
|
resolveDashboardChannelId,
|
|
303
310
|
runWithProfile,
|
|
304
311
|
setSupabaseClient,
|
|
312
|
+
startChannelRegistryPolling,
|
|
305
313
|
sumR2PrefixBytes,
|
|
306
|
-
syncPostToDashboard
|
|
307
|
-
|
|
314
|
+
syncPostToDashboard,
|
|
315
|
+
updateChannelById,
|
|
316
|
+
updateChannelsMcpConnections,
|
|
317
|
+
warnOnBrokenChannelCwds
|
|
318
|
+
} from "./chunk-67WA56OD.js";
|
|
308
319
|
|
|
309
320
|
// ../core/src/logger.ts
|
|
310
321
|
var ALREADY_STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
|
|
@@ -2153,8 +2164,8 @@ async function runUninstall(args = []) {
|
|
|
2153
2164
|
if (backup) {
|
|
2154
2165
|
const dir = join9(homedir4(), "Flyspace", ".uninstall-backups");
|
|
2155
2166
|
mkdirSync6(dir, { recursive: true });
|
|
2156
|
-
const
|
|
2157
|
-
backupFile = join9(dir, `flyspace-${
|
|
2167
|
+
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
2168
|
+
backupFile = join9(dir, `flyspace-${stamp2}.tar.gz`);
|
|
2158
2169
|
const rel = backupSources.map((s) => `"${s.replace(/^\//, "")}"`).join(" ");
|
|
2159
2170
|
try {
|
|
2160
2171
|
run2(`tar -czf "${backupFile}" -C / ${rel}`);
|
|
@@ -2346,7 +2357,7 @@ function npmEnv(target) {
|
|
|
2346
2357
|
return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
|
|
2347
2358
|
}
|
|
2348
2359
|
async function runUpgrade() {
|
|
2349
|
-
const current = "0.1.
|
|
2360
|
+
const current = "0.1.54";
|
|
2350
2361
|
console.log(`Current version: ${current}`);
|
|
2351
2362
|
console.log("Checking for updates...\n");
|
|
2352
2363
|
try {
|
|
@@ -2406,11 +2417,15 @@ function loadAutomationsFile() {
|
|
|
2406
2417
|
}
|
|
2407
2418
|
|
|
2408
2419
|
// src/commands/automation.ts
|
|
2420
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
2409
2421
|
var USAGE2 = `
|
|
2410
2422
|
Usage: flyspace automation <subcommand> [options]
|
|
2411
2423
|
|
|
2412
2424
|
Subcommands:
|
|
2413
2425
|
list List all automations (grouped by channel)
|
|
2426
|
+
show <name> Print one automation as JSON, prompt included
|
|
2427
|
+
edit <name> --prompt <text>|--prompt-file <path>
|
|
2428
|
+
Replace an automation's prompt
|
|
2414
2429
|
add --type schedule|trigger|mention-trigger Add an automation
|
|
2415
2430
|
remove <name> Remove an automation
|
|
2416
2431
|
enable <name> Enable an automation
|
|
@@ -2661,6 +2676,43 @@ async function handleRun(manager, name) {
|
|
|
2661
2676
|
});
|
|
2662
2677
|
console.log("Done.");
|
|
2663
2678
|
}
|
|
2679
|
+
function automationType(item) {
|
|
2680
|
+
if ("cron" in item) return "schedule";
|
|
2681
|
+
if ("patterns" in item) return "trigger";
|
|
2682
|
+
return "mention-trigger";
|
|
2683
|
+
}
|
|
2684
|
+
function handleShow(manager, name) {
|
|
2685
|
+
const located = manager.locate(name);
|
|
2686
|
+
if (!located) {
|
|
2687
|
+
console.error(`Automation "${name}" not found.`);
|
|
2688
|
+
process.exit(1);
|
|
2689
|
+
}
|
|
2690
|
+
console.log(JSON.stringify({ type: automationType(located.item), ...located.item }, null, 2));
|
|
2691
|
+
}
|
|
2692
|
+
async function handleEdit(manager, name, args) {
|
|
2693
|
+
const inline = getArg(args, "--prompt");
|
|
2694
|
+
const file = getArg(args, "--prompt-file");
|
|
2695
|
+
if (!inline === !file) {
|
|
2696
|
+
console.error("Specify exactly one of --prompt or --prompt-file");
|
|
2697
|
+
process.exit(1);
|
|
2698
|
+
}
|
|
2699
|
+
const located = manager.locate(name);
|
|
2700
|
+
if (!located) {
|
|
2701
|
+
console.error(`Automation "${name}" not found.`);
|
|
2702
|
+
process.exit(1);
|
|
2703
|
+
}
|
|
2704
|
+
if ("script" in located.item && located.item.script) {
|
|
2705
|
+
console.error(`"${name}" runs a script, not a prompt.`);
|
|
2706
|
+
process.exit(1);
|
|
2707
|
+
}
|
|
2708
|
+
const prompt = inline ?? readFileSync11(file, "utf8");
|
|
2709
|
+
if (!prompt.trim()) {
|
|
2710
|
+
console.error("Prompt must not be empty.");
|
|
2711
|
+
process.exit(1);
|
|
2712
|
+
}
|
|
2713
|
+
await manager.update(automationType(located.item), name, { ...located.item, prompt });
|
|
2714
|
+
console.log(`Prompt of "${name}" updated.`);
|
|
2715
|
+
}
|
|
2664
2716
|
async function handleImport(manager) {
|
|
2665
2717
|
const file = loadAutomationsFile();
|
|
2666
2718
|
const existing = new Set(loadAutomations().schedules.map((s) => s.name));
|
|
@@ -2707,6 +2759,20 @@ async function runAutomationCmd(args) {
|
|
|
2707
2759
|
case "list":
|
|
2708
2760
|
printList(manager);
|
|
2709
2761
|
break;
|
|
2762
|
+
case "show":
|
|
2763
|
+
if (!args[1]) {
|
|
2764
|
+
console.error("Usage: flyspace automation show <name>");
|
|
2765
|
+
process.exit(1);
|
|
2766
|
+
}
|
|
2767
|
+
handleShow(manager, args[1]);
|
|
2768
|
+
break;
|
|
2769
|
+
case "edit":
|
|
2770
|
+
if (!args[1]) {
|
|
2771
|
+
console.error("Usage: flyspace automation edit <name> --prompt <text>|--prompt-file <path>");
|
|
2772
|
+
process.exit(1);
|
|
2773
|
+
}
|
|
2774
|
+
await handleEdit(manager, args[1], args.slice(2));
|
|
2775
|
+
break;
|
|
2710
2776
|
case "add":
|
|
2711
2777
|
await handleAdd(manager, args.slice(1));
|
|
2712
2778
|
break;
|
|
@@ -3024,7 +3090,7 @@ async function runLogs(args) {
|
|
|
3024
3090
|
|
|
3025
3091
|
// src/commands/slack.ts
|
|
3026
3092
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
3027
|
-
import { existsSync as existsSync13, readFileSync as
|
|
3093
|
+
import { existsSync as existsSync13, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
|
|
3028
3094
|
import { resolve as resolve4 } from "path";
|
|
3029
3095
|
import { tmpdir as tmpdir2, homedir as homedir5 } from "os";
|
|
3030
3096
|
import { input, confirm as confirm4, select, checkbox } from "@inquirer/prompts";
|
|
@@ -3537,6 +3603,7 @@ async function issueSetupInvite(params) {
|
|
|
3537
3603
|
message: params.message,
|
|
3538
3604
|
invited_by: params.invitedBy,
|
|
3539
3605
|
token_hash: hashInviteToken(token),
|
|
3606
|
+
link_token: token,
|
|
3540
3607
|
expires_at: expiresAt.toISOString()
|
|
3541
3608
|
});
|
|
3542
3609
|
if (error2) throw new Error(`issueSetupInvite(${params.email}): ${error2.message}`);
|
|
@@ -3559,6 +3626,7 @@ async function reissueSetupInvite(id) {
|
|
|
3559
3626
|
const expiresAt = new Date(Date.now() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1e3);
|
|
3560
3627
|
const { error: updateError } = await db.from("workspace_setup_invites").update({
|
|
3561
3628
|
token_hash: hashInviteToken(token),
|
|
3629
|
+
link_token: token,
|
|
3562
3630
|
previous_token_hashes: [
|
|
3563
3631
|
...data.previous_token_hashes ?? [],
|
|
3564
3632
|
data.token_hash
|
|
@@ -3575,11 +3643,18 @@ async function reissueSetupInvite(id) {
|
|
|
3575
3643
|
}
|
|
3576
3644
|
};
|
|
3577
3645
|
}
|
|
3646
|
+
async function currentSetupInviteToken(id) {
|
|
3647
|
+
const { data, error: error2 } = await getSupabaseClient().from("workspace_setup_invites").select("link_token").eq("id", id).is("accepted_at", null).maybeSingle();
|
|
3648
|
+
if (error2) throw new Error(`currentSetupInviteToken(${id}): ${error2.message}`);
|
|
3649
|
+
if (!data) throw new Error("no pending invite with that id");
|
|
3650
|
+
return data.link_token ?? (await reissueSetupInvite(id)).token;
|
|
3651
|
+
}
|
|
3578
3652
|
async function lookupSetupInvite(token) {
|
|
3579
3653
|
const { data, error: error2 } = await getSupabaseClient().from("workspace_setup_invites").select("id, email, owner_name, plan, message, expires_at, accepted_at, workspace_id").or(tokenHashFilter(token)).maybeSingle();
|
|
3580
3654
|
if (error2) throw new Error(`lookupSetupInvite: ${error2.message}`);
|
|
3581
3655
|
if (!data) return { state: "unknown" };
|
|
3582
|
-
if (data.accepted_at)
|
|
3656
|
+
if (data.accepted_at)
|
|
3657
|
+
return { state: "used", workspaceId: data.workspace_id ?? null };
|
|
3583
3658
|
if (new Date(data.expires_at).getTime() <= Date.now()) return { state: "expired" };
|
|
3584
3659
|
return {
|
|
3585
3660
|
state: "valid",
|
|
@@ -3645,6 +3720,18 @@ var RESERVED = /* @__PURE__ */ new Set([
|
|
|
3645
3720
|
"portal",
|
|
3646
3721
|
"home",
|
|
3647
3722
|
"root",
|
|
3723
|
+
// Top-level Workspace routes: the slug is the first URL path segment
|
|
3724
|
+
// (`app.flyspace.ai/<slug>/...`), see packages/ui/src/lib/workspace-path.ts.
|
|
3725
|
+
"chat",
|
|
3726
|
+
"global",
|
|
3727
|
+
"device",
|
|
3728
|
+
"onboarding",
|
|
3729
|
+
"reset-password",
|
|
3730
|
+
"channels",
|
|
3731
|
+
"automations",
|
|
3732
|
+
"profiles",
|
|
3733
|
+
"sessions",
|
|
3734
|
+
"logs",
|
|
3648
3735
|
"share",
|
|
3649
3736
|
"shared",
|
|
3650
3737
|
"data",
|
|
@@ -4975,7 +5062,7 @@ async function threadReplies(client2, nameOrId, ts2) {
|
|
|
4975
5062
|
async function postMessage(client2, args) {
|
|
4976
5063
|
const channelArg = getArg2(args, "--channel");
|
|
4977
5064
|
const textFilePath = getArg2(args, "--text-file");
|
|
4978
|
-
const text = textFilePath ?
|
|
5065
|
+
const text = textFilePath ? readFileSync12(textFilePath, "utf8") : getArg2(args, "--text");
|
|
4979
5066
|
const threadTs = getArg2(args, "--thread");
|
|
4980
5067
|
const markdown = args.includes("--markdown");
|
|
4981
5068
|
const broadcast = args.includes("--broadcast") && Boolean(threadTs);
|
|
@@ -5130,7 +5217,7 @@ async function ensureClaudeCodeReady() {
|
|
|
5130
5217
|
}
|
|
5131
5218
|
function getManifestYaml(botName) {
|
|
5132
5219
|
const manifestPath = resolve4(paths.PACKAGE_ROOT, "slack-app-manifest.yml");
|
|
5133
|
-
const raw =
|
|
5220
|
+
const raw = readFileSync12(manifestPath, "utf-8");
|
|
5134
5221
|
return raw.replace(/name: Custie/g, `name: ${botName}`);
|
|
5135
5222
|
}
|
|
5136
5223
|
async function stepPersonalise() {
|
|
@@ -5562,7 +5649,7 @@ function copyDefaultPrompt(botName) {
|
|
|
5562
5649
|
if (!existsSync13(paths.PROMPT_FILE)) {
|
|
5563
5650
|
const defaultPrompt = resolve4(paths.PACKAGE_ROOT, "system.default.md");
|
|
5564
5651
|
if (existsSync13(defaultPrompt)) {
|
|
5565
|
-
const content =
|
|
5652
|
+
const content = readFileSync12(defaultPrompt, "utf-8").replace(/\{\{botName\}\}/g, botName);
|
|
5566
5653
|
writeFileSync6(paths.PROMPT_FILE, content);
|
|
5567
5654
|
success4(`Default prompt copied to ${paths.PROMPT_FILE}`);
|
|
5568
5655
|
}
|
|
@@ -5843,25 +5930,19 @@ async function runMove(args) {
|
|
|
5843
5930
|
console.log("\n--dry-run: nothing changed.");
|
|
5844
5931
|
return;
|
|
5845
5932
|
}
|
|
5846
|
-
await
|
|
5847
|
-
|
|
5848
|
-
const moved = store.moveThread(
|
|
5849
|
-
`chat:${thread.channelId}`,
|
|
5850
|
-
`chat:${destination.id}`,
|
|
5851
|
-
thread.id
|
|
5852
|
-
);
|
|
5853
|
-
store.close();
|
|
5933
|
+
const moved = await moveThreadFully(thread.id, destination.id);
|
|
5934
|
+
if (moved === "unchanged") return;
|
|
5854
5935
|
console.log(
|
|
5855
5936
|
`
|
|
5856
5937
|
Moved. Re-keyed ${moved.sessions} session(s), ${moved.modelOverrides} model override(s), ${moved.effortOverrides} effort override(s).`
|
|
5857
5938
|
);
|
|
5858
|
-
if (
|
|
5939
|
+
if (moved.cwdChanged && source) {
|
|
5859
5940
|
console.log(
|
|
5860
5941
|
`
|
|
5861
5942
|
Note: the channels have different working directories.
|
|
5862
5943
|
${source.cwd}
|
|
5863
5944
|
${destination.cwd}
|
|
5864
|
-
Files this thread created live in the old one
|
|
5945
|
+
Files this thread created live in the old one, move them yourself if the
|
|
5865
5946
|
thread still refers to them.`
|
|
5866
5947
|
);
|
|
5867
5948
|
}
|
|
@@ -5942,10 +6023,10 @@ async function runChatCmd(args) {
|
|
|
5942
6023
|
}
|
|
5943
6024
|
|
|
5944
6025
|
// src/commands/memory.ts
|
|
5945
|
-
import { readFileSync as
|
|
6026
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
5946
6027
|
|
|
5947
6028
|
// src/store/claude-memory-import.ts
|
|
5948
|
-
import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as
|
|
6029
|
+
import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as readFileSync13 } from "fs";
|
|
5949
6030
|
import { homedir as homedir6 } from "os";
|
|
5950
6031
|
import { basename as basename5, join as join12 } from "path";
|
|
5951
6032
|
import dotenv from "dotenv";
|
|
@@ -5955,7 +6036,7 @@ function claudeMemoryDir(cwd, configDir2) {
|
|
|
5955
6036
|
function profileClaudeConfigDirFor(profile) {
|
|
5956
6037
|
const dir = profile === "default" ? paths.BASE_CONFIG_DIR : join12(paths.PROFILES_DIR, profile);
|
|
5957
6038
|
const file = join12(dir, "config.env");
|
|
5958
|
-
const env = existsSync14(file) ? dotenv.parse(
|
|
6039
|
+
const env = existsSync14(file) ? dotenv.parse(readFileSync13(file)) : {};
|
|
5959
6040
|
return env["CLAUDE_CONFIG_DIR"]?.trim() || join12(homedir6(), ".claude");
|
|
5960
6041
|
}
|
|
5961
6042
|
var TYPE_MAP = {
|
|
@@ -6005,7 +6086,7 @@ async function importClaudeMemories(dir, channelId, opts = {}) {
|
|
|
6005
6086
|
const files = readdirSync3(dir).filter((f) => f.endsWith(".md") && f !== "MEMORY.md").sort();
|
|
6006
6087
|
const results = [];
|
|
6007
6088
|
for (const file of files) {
|
|
6008
|
-
const parsed = parseClaudeMemory(file,
|
|
6089
|
+
const parsed = parseClaudeMemory(file, readFileSync13(join12(dir, file), "utf-8"), channelId);
|
|
6009
6090
|
if ("skip" in parsed) {
|
|
6010
6091
|
results.push({ file, outcome: "skipped", reason: parsed.skip });
|
|
6011
6092
|
continue;
|
|
@@ -6117,7 +6198,7 @@ ${memory.body}`);
|
|
|
6117
6198
|
);
|
|
6118
6199
|
}
|
|
6119
6200
|
if (!isMemoryType(type)) throw new Error(`--type must be one of ${MEMORY_TYPES.join(", ")}`);
|
|
6120
|
-
const body = bodyArg === "-" ?
|
|
6201
|
+
const body = bodyArg === "-" ? readFileSync14(0, "utf-8") : bodyArg;
|
|
6121
6202
|
const thread = getArg4(rest, "--thread");
|
|
6122
6203
|
const { created, changed } = await saveMemory(
|
|
6123
6204
|
target,
|
|
@@ -6201,9 +6282,10 @@ async function runMcpCmd(args) {
|
|
|
6201
6282
|
}
|
|
6202
6283
|
restoreStdout();
|
|
6203
6284
|
loadEnvFiles();
|
|
6285
|
+
useHostDbWithoutCredentials();
|
|
6204
6286
|
switch (server) {
|
|
6205
6287
|
case "threads": {
|
|
6206
|
-
const { startThreadsServer } = await import("./threads-
|
|
6288
|
+
const { startThreadsServer } = await import("./threads-PTTZUNIJ.js");
|
|
6207
6289
|
await startThreadsServer();
|
|
6208
6290
|
return;
|
|
6209
6291
|
}
|
|
@@ -6218,7 +6300,7 @@ async function runMcpCmd(args) {
|
|
|
6218
6300
|
import { spawn as spawn6, spawnSync } from "child_process";
|
|
6219
6301
|
import { existsSync as existsSync28 } from "fs";
|
|
6220
6302
|
import { platform as platform7 } from "os";
|
|
6221
|
-
import { join as
|
|
6303
|
+
import { join as join20 } from "path";
|
|
6222
6304
|
|
|
6223
6305
|
// src/reconcile.ts
|
|
6224
6306
|
import { existsSync as existsSync15, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
@@ -6284,93 +6366,7 @@ async function ensureServices() {
|
|
|
6284
6366
|
}
|
|
6285
6367
|
|
|
6286
6368
|
// ../api/src/dashboard/api.ts
|
|
6287
|
-
import { Hono as
|
|
6288
|
-
|
|
6289
|
-
// ../api/src/dashboard/supabase-server-client.ts
|
|
6290
|
-
import { createServerClient, parseCookieHeader, serializeCookieHeader } from "@supabase/ssr";
|
|
6291
|
-
|
|
6292
|
-
// ../api/src/dashboard/scoped-auth-cookies.ts
|
|
6293
|
-
import { stringFromBase64URL } from "@supabase/ssr";
|
|
6294
|
-
var SESSION_NAME = /^(sb-.+-auth-token)(?:\.\d+)?$/;
|
|
6295
|
-
var SCOPE_MARK = "fsw_";
|
|
6296
|
-
var SCOPE_END = "__";
|
|
6297
|
-
function hostLabel(host) {
|
|
6298
|
-
return host.toLowerCase().replace(/:\d+$/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
6299
|
-
}
|
|
6300
|
-
var scopePrefix = (label2) => `${SCOPE_MARK}${label2}${SCOPE_END}`;
|
|
6301
|
-
function sessionUserId(cookies) {
|
|
6302
|
-
const base = cookies.map((c) => SESSION_NAME.exec(c.name)?.[1]).find(Boolean);
|
|
6303
|
-
if (!base) return null;
|
|
6304
|
-
const whole = cookies.find((c) => c.name === base)?.value;
|
|
6305
|
-
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("");
|
|
6306
|
-
if (!raw) return null;
|
|
6307
|
-
try {
|
|
6308
|
-
const json = raw.startsWith("base64-") ? stringFromBase64URL(raw.slice(7)) : raw;
|
|
6309
|
-
const id = JSON.parse(json).user?.id;
|
|
6310
|
-
return typeof id === "string" ? id : null;
|
|
6311
|
-
} catch {
|
|
6312
|
-
return null;
|
|
6313
|
-
}
|
|
6314
|
-
}
|
|
6315
|
-
var isScoped = (name) => name.startsWith(SCOPE_MARK);
|
|
6316
|
-
function readScopedCookies(all, label2) {
|
|
6317
|
-
const prefix = scopePrefix(label2);
|
|
6318
|
-
const own = all.filter((c) => c.name.startsWith(prefix)).map((c) => ({ name: c.name.slice(prefix.length), value: c.value }));
|
|
6319
|
-
return own.length ? own : all.filter((c) => !isScoped(c.name));
|
|
6320
|
-
}
|
|
6321
|
-
function routeCookieWrites(all, label2, writes) {
|
|
6322
|
-
const prefix = scopePrefix(label2);
|
|
6323
|
-
const hasOwn = all.some((c) => c.name.startsWith(prefix));
|
|
6324
|
-
const incoming = sessionUserId(writes.filter((c) => c.value !== ""));
|
|
6325
|
-
const shared = sessionUserId(all.filter((c) => !isScoped(c.name)));
|
|
6326
|
-
const toScoped = hasOwn || incoming !== null && shared !== null && incoming !== shared;
|
|
6327
|
-
return writes.map(
|
|
6328
|
-
(c) => toScoped ? { name: prefix + c.name, value: c.value, scoped: true } : { ...c, scoped: false }
|
|
6329
|
-
);
|
|
6330
|
-
}
|
|
6331
|
-
|
|
6332
|
-
// ../api/src/dashboard/supabase-server-client.ts
|
|
6333
|
-
var REQUEST_TIMEOUT_MS = 5e3;
|
|
6334
|
-
function fetchWithTimeout(input2, init2) {
|
|
6335
|
-
return fetch(input2, { ...init2, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
6336
|
-
}
|
|
6337
|
-
function createRequestSupabaseClient(c) {
|
|
6338
|
-
const url = process.env["SUPABASE_URL"];
|
|
6339
|
-
const key = process.env["VITE_SUPABASE_PUBLISHABLE_KEY"];
|
|
6340
|
-
if (!url || !key) {
|
|
6341
|
-
throw new Error("SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_KEY not set \u2014 check .env");
|
|
6342
|
-
}
|
|
6343
|
-
const origin = c.req.header("Origin");
|
|
6344
|
-
const label2 = hostLabel(
|
|
6345
|
-
(origin ? URL.parse(origin)?.host : void 0) ?? c.req.header("X-Forwarded-Host") ?? c.req.header("Host") ?? ""
|
|
6346
|
-
);
|
|
6347
|
-
const rawCookies = () => parseCookieHeader(c.req.header("Cookie") ?? "").map(({ name, value }) => ({
|
|
6348
|
-
name,
|
|
6349
|
-
value: value ?? ""
|
|
6350
|
-
}));
|
|
6351
|
-
return createServerClient(url, key, {
|
|
6352
|
-
global: { fetch: fetchWithTimeout },
|
|
6353
|
-
cookies: {
|
|
6354
|
-
// `parseCookieHeader` types `value` as optional; the client requires a
|
|
6355
|
-
// string, and a valueless cookie is the same as an empty one here.
|
|
6356
|
-
getAll: () => readScopedCookies(rawCookies(), label2),
|
|
6357
|
-
setAll: (cookies) => {
|
|
6358
|
-
const domain = process.env["AUTH_COOKIE_DOMAIN"]?.trim();
|
|
6359
|
-
const overrides = {
|
|
6360
|
-
...domain ? { domain } : {},
|
|
6361
|
-
...crossOriginShell(c) ? { sameSite: "none", secure: true } : {}
|
|
6362
|
-
};
|
|
6363
|
-
const routed = routeCookieWrites(rawCookies(), label2, cookies);
|
|
6364
|
-
cookies.forEach(({ options }, i) => {
|
|
6365
|
-
const { name, value } = routed[i];
|
|
6366
|
-
c.header("Set-Cookie", serializeCookieHeader(name, value, { ...options, ...overrides }), {
|
|
6367
|
-
append: true
|
|
6368
|
-
});
|
|
6369
|
-
});
|
|
6370
|
-
}
|
|
6371
|
-
}
|
|
6372
|
-
});
|
|
6373
|
-
}
|
|
6369
|
+
import { Hono as Hono35 } from "hono";
|
|
6374
6370
|
|
|
6375
6371
|
// ../api/src/dashboard/guest-routes.ts
|
|
6376
6372
|
import { Hono as Hono4 } from "hono";
|
|
@@ -6416,110 +6412,6 @@ function createGuestRouter() {
|
|
|
6416
6412
|
// ../api/src/dashboard/auth-routes.ts
|
|
6417
6413
|
import { Hono as Hono7 } from "hono";
|
|
6418
6414
|
|
|
6419
|
-
// ../api/src/dashboard/auth-context.ts
|
|
6420
|
-
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
6421
|
-
import { isAuthApiError, isAuthRetryableFetchError } from "@supabase/supabase-js";
|
|
6422
|
-
function onboardingPending(ctx) {
|
|
6423
|
-
const pending = [];
|
|
6424
|
-
if (!ctx.onboarded && !ctx.passwordSet) pending.push("account");
|
|
6425
|
-
if (!ctx.onboarded) pending.push("profile");
|
|
6426
|
-
if (ctx.role === "admin" && !ctx.agentConnectedAt) pending.push("agent");
|
|
6427
|
-
if (ctx.role === "admin" && !ctx.projectsSetupAt) pending.push("projects");
|
|
6428
|
-
return pending;
|
|
6429
|
-
}
|
|
6430
|
-
var inFlight = /* @__PURE__ */ new Map();
|
|
6431
|
-
var CACHE_TTL_MS = 3e4;
|
|
6432
|
-
var resolved = /* @__PURE__ */ new Map();
|
|
6433
|
-
function invalidateAuthContextCache() {
|
|
6434
|
-
resolved.clear();
|
|
6435
|
-
}
|
|
6436
|
-
function pruneExpired(now) {
|
|
6437
|
-
for (const [key, entry] of resolved) {
|
|
6438
|
-
if (entry.expires <= now) resolved.delete(key);
|
|
6439
|
-
}
|
|
6440
|
-
}
|
|
6441
|
-
var SUPPORT_NAME = "Flyspace Support";
|
|
6442
|
-
var SUPPORT_AVATAR_URL = "/logo/flyspace-support.svg";
|
|
6443
|
-
function workspaceArchivedError() {
|
|
6444
|
-
return new HTTPException2(403, {
|
|
6445
|
-
res: Response.json({ error: "workspace archived", archived: true }, { status: 403 })
|
|
6446
|
-
});
|
|
6447
|
-
}
|
|
6448
|
-
async function resolveAuthContext(c, opts = {}) {
|
|
6449
|
-
const ctx = await resolveAuthContextCached(c, opts);
|
|
6450
|
-
if (ctx?.archived && !ctx.isSupport) throw workspaceArchivedError();
|
|
6451
|
-
return ctx;
|
|
6452
|
-
}
|
|
6453
|
-
async function resolveAuthContextCached(c, opts) {
|
|
6454
|
-
const cookie = c.req?.header("Cookie") ?? "";
|
|
6455
|
-
if (!cookie) return resolveAuthContextUncached(c);
|
|
6456
|
-
const key = `${getProfile()}\0${cookie}`;
|
|
6457
|
-
const now = Date.now();
|
|
6458
|
-
pruneExpired(now);
|
|
6459
|
-
if (opts.fresh) resolved.delete(key);
|
|
6460
|
-
const cached = resolved.get(key);
|
|
6461
|
-
if (cached) return cached.value;
|
|
6462
|
-
const inflight = inFlight.get(key);
|
|
6463
|
-
if (inflight) return inflight;
|
|
6464
|
-
const promise = resolveAuthContextUncached(c).then((value) => {
|
|
6465
|
-
resolved.set(key, { value, expires: Date.now() + CACHE_TTL_MS });
|
|
6466
|
-
return value;
|
|
6467
|
-
}).finally(() => inFlight.delete(key));
|
|
6468
|
-
inFlight.set(key, promise);
|
|
6469
|
-
return promise;
|
|
6470
|
-
}
|
|
6471
|
-
async function getUserWithRetry(supabase) {
|
|
6472
|
-
let result = await supabase.auth.getUser();
|
|
6473
|
-
if (isAuthRetryableFetchError(result.error)) result = await supabase.auth.getUser();
|
|
6474
|
-
const { error: error2 } = result;
|
|
6475
|
-
if (isAuthRetryableFetchError(error2) || isAuthApiError(error2) && error2.status === 429) {
|
|
6476
|
-
throw error2;
|
|
6477
|
-
}
|
|
6478
|
-
return result;
|
|
6479
|
-
}
|
|
6480
|
-
async function resolveAuthContextUncached(c) {
|
|
6481
|
-
const supabase = createRequestSupabaseClient(c);
|
|
6482
|
-
let user;
|
|
6483
|
-
try {
|
|
6484
|
-
({
|
|
6485
|
-
data: { user }
|
|
6486
|
-
} = await getUserWithRetry(supabase));
|
|
6487
|
-
} catch (err) {
|
|
6488
|
-
if (isAuthRetryableFetchError(err)) {
|
|
6489
|
-
throw new HTTPException2(503, { message: "auth service unreachable" });
|
|
6490
|
-
}
|
|
6491
|
-
if (isAuthApiError(err) && err.status === 429) {
|
|
6492
|
-
throw new HTTPException2(503, { message: "auth service rate limited" });
|
|
6493
|
-
}
|
|
6494
|
-
return null;
|
|
6495
|
-
}
|
|
6496
|
-
if (!user?.email) return null;
|
|
6497
|
-
const workspace = await getWorkspaceBySlug(getProfile());
|
|
6498
|
-
if (!workspace) return null;
|
|
6499
|
-
const membership = await getMembershipByEmail(workspace.id, user.email);
|
|
6500
|
-
if (!membership) return null;
|
|
6501
|
-
if (membership.status === "invited") {
|
|
6502
|
-
await activateMembership(workspace.id, user.email);
|
|
6503
|
-
}
|
|
6504
|
-
const metadata = user.user_metadata ?? {};
|
|
6505
|
-
return {
|
|
6506
|
-
email: user.email,
|
|
6507
|
-
userId: user.id,
|
|
6508
|
-
handle: membership.handle,
|
|
6509
|
-
role: membership.role,
|
|
6510
|
-
workspaceId: workspace.id,
|
|
6511
|
-
// A support admin posts into a customer's workspace as Flyspace, not as
|
|
6512
|
-
// the staff member's personal profile.
|
|
6513
|
-
...membership.isSupport ? { name: SUPPORT_NAME, isSupport: true } : { name: metadata.name, avatarKey: metadata.avatarKey },
|
|
6514
|
-
onboarded: Boolean(metadata.onboardedAt),
|
|
6515
|
-
passwordSet: Boolean(metadata.passwordSetAt),
|
|
6516
|
-
agentConnectedAt: workspace.agentConnectedAt ?? null,
|
|
6517
|
-
projectsSetupAt: workspace.projectsSetupAt ?? null,
|
|
6518
|
-
plan: workspace.plan ?? null,
|
|
6519
|
-
...workspace.archivedAt ? { archived: true } : {}
|
|
6520
|
-
};
|
|
6521
|
-
}
|
|
6522
|
-
|
|
6523
6415
|
// ../api/src/dashboard/avatar-url.ts
|
|
6524
6416
|
import { GetObjectCommand } from "@aws-sdk/client-s3";
|
|
6525
6417
|
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
|
@@ -6542,13 +6434,13 @@ async function signAvatarUrl(key) {
|
|
|
6542
6434
|
|
|
6543
6435
|
// ../api/src/dashboard/turnstile.ts
|
|
6544
6436
|
var VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
6545
|
-
var
|
|
6437
|
+
var REQUEST_TIMEOUT_MS = 5e3;
|
|
6546
6438
|
function siteverify(secret, token) {
|
|
6547
6439
|
return fetch(VERIFY_URL, {
|
|
6548
6440
|
method: "POST",
|
|
6549
6441
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
6550
6442
|
body: new URLSearchParams({ secret, response: token }),
|
|
6551
|
-
signal: AbortSignal.timeout(
|
|
6443
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
6552
6444
|
});
|
|
6553
6445
|
}
|
|
6554
6446
|
async function verifyTurnstileToken(token) {
|
|
@@ -6815,7 +6707,7 @@ import { WebSocket, WebSocketServer } from "ws";
|
|
|
6815
6707
|
|
|
6816
6708
|
// ../api/src/dashboard/host-identity.ts
|
|
6817
6709
|
import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey3, generateKeyPairSync as generateKeyPairSync2 } from "crypto";
|
|
6818
|
-
import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as
|
|
6710
|
+
import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as readFileSync15, writeFileSync as writeFileSync8 } from "fs";
|
|
6819
6711
|
import { dirname as dirname6, join as join13 } from "path";
|
|
6820
6712
|
function hostPrivateKeyPath() {
|
|
6821
6713
|
return process.env["FLYSPACE_HOST_KEY_PATH"] || join13(paths.BASE_CONFIG_DIR, "host.key");
|
|
@@ -6826,7 +6718,7 @@ function loadHostPrivateKey(path = hostPrivateKeyPath()) {
|
|
|
6826
6718
|
`No Host identity at ${path}. Run \`pnpm run generate-host-key\` on this machine, then set FLYSPACE_HOST_PUBLIC_KEY on the Data process to the printed public key.`
|
|
6827
6719
|
);
|
|
6828
6720
|
}
|
|
6829
|
-
return createPrivateKey2(
|
|
6721
|
+
return createPrivateKey2(readFileSync15(path, "utf8"));
|
|
6830
6722
|
}
|
|
6831
6723
|
|
|
6832
6724
|
// ../api/src/dashboard/uploads-routes.ts
|
|
@@ -7541,6 +7433,17 @@ function createAdminRouter() {
|
|
|
7541
7433
|
await revokeSetupInvite(c.req.param("id"));
|
|
7542
7434
|
return c.json({ revoked: true });
|
|
7543
7435
|
});
|
|
7436
|
+
admin.get("/setup-invites/:id/link", async (c) => {
|
|
7437
|
+
let token;
|
|
7438
|
+
try {
|
|
7439
|
+
token = await currentSetupInviteToken(c.req.param("id"));
|
|
7440
|
+
} catch (err) {
|
|
7441
|
+
return c.json({ error: err instanceof Error ? err.message : "lookup failed" }, 404);
|
|
7442
|
+
}
|
|
7443
|
+
const inviteUrl = new URL(`${workspaceOrigin(c, "app")}/auth/new-workspace`);
|
|
7444
|
+
inviteUrl.searchParams.set("token", token);
|
|
7445
|
+
return c.json({ inviteLink: inviteUrl.toString() });
|
|
7446
|
+
});
|
|
7544
7447
|
admin.post("/setup-invites/:id/resend", async (c) => {
|
|
7545
7448
|
const operator = c.get("platformOperator");
|
|
7546
7449
|
let token;
|
|
@@ -7631,10 +7534,6 @@ function createAdminRouter() {
|
|
|
7631
7534
|
return admin;
|
|
7632
7535
|
}
|
|
7633
7536
|
|
|
7634
|
-
// ../api/src/dashboard/agent-identities.ts
|
|
7635
|
-
var BOT_LABEL = "Workspace Agent";
|
|
7636
|
-
var BOT_DM_KEY = "claude";
|
|
7637
|
-
|
|
7638
7537
|
// ../api/src/dashboard/data-api.ts
|
|
7639
7538
|
import { existsSync as existsSync18 } from "fs";
|
|
7640
7539
|
import sharp4 from "sharp";
|
|
@@ -7769,7 +7668,7 @@ function createCategoryWriteRouter() {
|
|
|
7769
7668
|
}
|
|
7770
7669
|
|
|
7771
7670
|
// ../api/src/dashboard/chat-routes.ts
|
|
7772
|
-
import { Hono as
|
|
7671
|
+
import { Hono as Hono13 } from "hono";
|
|
7773
7672
|
|
|
7774
7673
|
// ../api/src/dashboard/fork-summary.ts
|
|
7775
7674
|
var MAX_INPUT_CHARS = 6e4;
|
|
@@ -7813,6 +7712,188 @@ async function relevantThreadsPage(supabase, handle, channelIds, opts) {
|
|
|
7813
7712
|
return data ?? [];
|
|
7814
7713
|
}
|
|
7815
7714
|
|
|
7715
|
+
// ../api/src/dashboard/continuous-chat.ts
|
|
7716
|
+
import { Hono as Hono12 } from "hono";
|
|
7717
|
+
var GROQ_API_URL2 = "https://api.groq.com/openai/v1/chat/completions";
|
|
7718
|
+
var MODEL = "openai/gpt-oss-120b";
|
|
7719
|
+
var STREAM_DAYS = 30;
|
|
7720
|
+
var STREAM_LIMIT = 500;
|
|
7721
|
+
var ACTIVE_TOPIC_DAYS = 7;
|
|
7722
|
+
var BACKFILL_PER_REQUEST = 5;
|
|
7723
|
+
var UNSORTED = "unsorted";
|
|
7724
|
+
var isDmChannel = (ch) => !!(ch.dmKey || ch.agentName);
|
|
7725
|
+
var channelKeys = (ch) => ch.externalChannelId ? [ch.id, ch.externalChannelId] : [ch.id];
|
|
7726
|
+
function findChannel2(c, channelId) {
|
|
7727
|
+
return getProfileChannelRegistry().find(
|
|
7728
|
+
(ch) => (ch.id === channelId || ch.externalChannelId === channelId) && canSeeChannel(ch, c.get("auth"))
|
|
7729
|
+
);
|
|
7730
|
+
}
|
|
7731
|
+
function isShortAck(body) {
|
|
7732
|
+
const text = body.trim();
|
|
7733
|
+
return [...text].length <= 12 && !/[??]/.test(text);
|
|
7734
|
+
}
|
|
7735
|
+
var RULES = `You file one chat message from a personal assistant DM under a topic, so the user can later find everything about one subject together.
|
|
7736
|
+
You get the topics active in the last few days and the message (with a little preceding context).
|
|
7737
|
+
Pick the existing topic it belongs to, or name a NEW topic (2 to 5 words, in the language the user writes in, no punctuation) when it clearly starts a new subject.
|
|
7738
|
+
When you are not confident, answer unsorted.
|
|
7739
|
+
Output ONLY the topic name, or unsorted. No quotes, no explanation.`;
|
|
7740
|
+
async function askModel(apiKey, topics, examples, context, body) {
|
|
7741
|
+
const prompt = [
|
|
7742
|
+
`Active topics:
|
|
7743
|
+
${topics.length ? topics.map((t) => `- ${t}`).join("\n") : "(none yet)"}`,
|
|
7744
|
+
examples.length ? `Corrections the user made earlier (message -> topic):
|
|
7745
|
+
${examples.map((e) => `- ${e.body.slice(0, 160)} -> ${e.topic}`).join("\n")}` : "",
|
|
7746
|
+
context ? `Preceding messages:
|
|
7747
|
+
${context}` : "",
|
|
7748
|
+
`Message to file:
|
|
7749
|
+
${body.slice(0, 1500)}`
|
|
7750
|
+
].filter(Boolean).join("\n\n");
|
|
7751
|
+
const res = await fetch(GROQ_API_URL2, {
|
|
7752
|
+
method: "POST",
|
|
7753
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
7754
|
+
signal: AbortSignal.timeout(1e4),
|
|
7755
|
+
body: JSON.stringify({
|
|
7756
|
+
model: MODEL,
|
|
7757
|
+
max_completion_tokens: 300,
|
|
7758
|
+
reasoning_effort: "low",
|
|
7759
|
+
include_reasoning: false,
|
|
7760
|
+
temperature: 0,
|
|
7761
|
+
messages: [
|
|
7762
|
+
{ role: "system", content: RULES },
|
|
7763
|
+
{ role: "user", content: prompt }
|
|
7764
|
+
]
|
|
7765
|
+
})
|
|
7766
|
+
}).catch(() => null);
|
|
7767
|
+
if (!res?.ok) return null;
|
|
7768
|
+
const data = await res.json();
|
|
7769
|
+
const raw = (data.choices?.[0]?.message?.content ?? "").split("\n")[0].trim();
|
|
7770
|
+
const topic = raw.replace(/^["'「『]+|["'」』.。]+$/g, "").trim().slice(0, 60);
|
|
7771
|
+
if (!topic) return null;
|
|
7772
|
+
return topics.find((t) => t.toLowerCase() === topic.toLowerCase()) ?? topic;
|
|
7773
|
+
}
|
|
7774
|
+
async function tagReply(args) {
|
|
7775
|
+
const { channel, replyId, author, body, replyToId } = args;
|
|
7776
|
+
if (!isDmChannel(channel) || !isHumanAuthor(author)) return;
|
|
7777
|
+
const supabase = getSupabaseClient();
|
|
7778
|
+
const keys = channelKeys(channel);
|
|
7779
|
+
const channelKey = channel.id;
|
|
7780
|
+
const save = (topic2, source) => supabase.from("reply_topics").upsert({ reply_id: replyId, channel_id: channelKey, topic: topic2, source }).then(({ error: error2 }) => {
|
|
7781
|
+
if (error2) console.error("Reply topic save failed:", error2.message);
|
|
7782
|
+
});
|
|
7783
|
+
if (replyToId) {
|
|
7784
|
+
const { data } = await supabase.from("reply_topics").select("topic").eq("reply_id", replyToId).maybeSingle();
|
|
7785
|
+
if (data?.topic) return save(data.topic, "inherit");
|
|
7786
|
+
}
|
|
7787
|
+
const since2 = new Date(Date.now() - ACTIVE_TOPIC_DAYS * 864e5).toISOString();
|
|
7788
|
+
const { data: recentRows } = await supabase.from("reply_topics").select("reply_id, topic, source, created_at").in("channel_id", keys).gte("created_at", since2).order("created_at", { ascending: false }).limit(200);
|
|
7789
|
+
const recent = (recentRows ?? []).filter((r) => r.reply_id !== replyId);
|
|
7790
|
+
const previous = recent[0]?.topic;
|
|
7791
|
+
if (previous && isShortAck(body)) return save(previous, "inherit");
|
|
7792
|
+
const apiKey = process.env["GROQ_API_KEY"];
|
|
7793
|
+
if (!apiKey) return;
|
|
7794
|
+
const topics = [...new Set(recent.map((r) => r.topic).filter((t) => t !== UNSORTED))].slice(
|
|
7795
|
+
0,
|
|
7796
|
+
15
|
|
7797
|
+
);
|
|
7798
|
+
const manual = recent.filter((r) => r.source === "manual").slice(0, 5);
|
|
7799
|
+
const { data: manualBodies } = manual.length ? await supabase.from("thread_replies").select("id, body").in(
|
|
7800
|
+
"id",
|
|
7801
|
+
manual.map((m) => m.reply_id)
|
|
7802
|
+
) : { data: [] };
|
|
7803
|
+
const bodyOf = new Map(
|
|
7804
|
+
(manualBodies ?? []).map((r) => [r.id, r.body])
|
|
7805
|
+
);
|
|
7806
|
+
const examples = manual.flatMap(
|
|
7807
|
+
(m) => bodyOf.has(m.reply_id) ? [{ body: bodyOf.get(m.reply_id), topic: m.topic }] : []
|
|
7808
|
+
);
|
|
7809
|
+
const { data: ctxRows } = await supabase.from("thread_replies").select("author, body, created_at, threads!inner(channel_id)").in("threads.channel_id", keys).neq("id", replyId).is("archived_at", null).order("created_at", { ascending: false }).limit(3);
|
|
7810
|
+
const context = (ctxRows ?? []).reverse().map((r) => `${r.author}: ${r.body.slice(0, 300)}`).join("\n");
|
|
7811
|
+
const topic = await askModel(apiKey, topics, examples, context, body);
|
|
7812
|
+
if (topic) await save(topic, "model");
|
|
7813
|
+
}
|
|
7814
|
+
function tagStoredReply(c, args) {
|
|
7815
|
+
void (async () => {
|
|
7816
|
+
if (!await isFeatureEnabled(c, "continuous-chat")) return;
|
|
7817
|
+
const { data } = await getSupabaseClient().from("threads").select("channel_id").eq("id", args.threadId).maybeSingle();
|
|
7818
|
+
const channel = data?.channel_id ? findChannel2(c, data.channel_id) : void 0;
|
|
7819
|
+
if (channel) await tagReply({ channel, ...args });
|
|
7820
|
+
})().catch((err) => console.error("Reply topic tagging failed:", err));
|
|
7821
|
+
}
|
|
7822
|
+
var backfilling = /* @__PURE__ */ new Set();
|
|
7823
|
+
function createContinuousChatRouter() {
|
|
7824
|
+
const app = new Hono12();
|
|
7825
|
+
app.get("/channels/:channelId/continuous", async (c) => {
|
|
7826
|
+
if (!await isFeatureEnabled(c, "continuous-chat"))
|
|
7827
|
+
return c.json({ error: "feature not enabled" }, 403);
|
|
7828
|
+
const channel = findChannel2(c, c.req.param("channelId"));
|
|
7829
|
+
if (!channel || !isDmChannel(channel)) return c.json({ error: "not found" }, 404);
|
|
7830
|
+
const supabase = getSupabaseClient();
|
|
7831
|
+
const since2 = new Date(Date.now() - STREAM_DAYS * 864e5).toISOString();
|
|
7832
|
+
const { data: rows, error: error2 } = await supabase.from("thread_replies").select("id, thread_id, author, body, created_at, threads!inner(channel_id)").in("threads.channel_id", channelKeys(channel)).is("archived_at", null).gte("created_at", since2).order("created_at", { ascending: false }).limit(STREAM_LIMIT);
|
|
7833
|
+
if (error2) return c.json({ error: error2.message }, 500);
|
|
7834
|
+
const replies = (rows ?? []).reverse();
|
|
7835
|
+
const { data: tagRows } = replies.length ? await supabase.from("reply_topics").select("reply_id, topic, source, created_at").in(
|
|
7836
|
+
"reply_id",
|
|
7837
|
+
replies.map((r) => r.id)
|
|
7838
|
+
) : { data: [] };
|
|
7839
|
+
const tags = new Map((tagRows ?? []).map((t) => [t.reply_id, t]));
|
|
7840
|
+
const lastInThread = /* @__PURE__ */ new Map();
|
|
7841
|
+
const messages = replies.map((r) => {
|
|
7842
|
+
const tag = tags.get(r.id);
|
|
7843
|
+
const topic = tag?.topic ?? lastInThread.get(r.thread_id) ?? null;
|
|
7844
|
+
if (topic) lastInThread.set(r.thread_id, topic);
|
|
7845
|
+
return {
|
|
7846
|
+
id: r.id,
|
|
7847
|
+
thread_id: r.thread_id,
|
|
7848
|
+
author: r.author,
|
|
7849
|
+
body: slackMrkdwnToMarkdown(r.body),
|
|
7850
|
+
created_at: r.created_at,
|
|
7851
|
+
topic,
|
|
7852
|
+
tagged: !!tag
|
|
7853
|
+
};
|
|
7854
|
+
});
|
|
7855
|
+
const activeSince = Date.now() - ACTIVE_TOPIC_DAYS * 864e5;
|
|
7856
|
+
const pending = replies.filter(
|
|
7857
|
+
(r) => !tags.has(r.id) && isHumanAuthor(r.author) && Date.parse(r.created_at) >= activeSince && !backfilling.has(r.id)
|
|
7858
|
+
).slice(0, BACKFILL_PER_REQUEST);
|
|
7859
|
+
if (pending.length) {
|
|
7860
|
+
for (const r of pending) backfilling.add(r.id);
|
|
7861
|
+
void (async () => {
|
|
7862
|
+
for (const r of pending) {
|
|
7863
|
+
await tagReply({ channel, replyId: r.id, author: r.author, body: r.body }).catch(
|
|
7864
|
+
() => {
|
|
7865
|
+
}
|
|
7866
|
+
);
|
|
7867
|
+
backfilling.delete(r.id);
|
|
7868
|
+
}
|
|
7869
|
+
})();
|
|
7870
|
+
}
|
|
7871
|
+
const activeTopics = [
|
|
7872
|
+
...new Set(
|
|
7873
|
+
messages.filter((m) => m.topic && Date.parse(m.created_at) >= activeSince).map((m) => m.topic)
|
|
7874
|
+
)
|
|
7875
|
+
];
|
|
7876
|
+
return c.json({ messages, topics: activeTopics, pendingTags: pending.length });
|
|
7877
|
+
});
|
|
7878
|
+
app.patch("/replies/:replyId/topic", async (c) => {
|
|
7879
|
+
if (!await isFeatureEnabled(c, "continuous-chat"))
|
|
7880
|
+
return c.json({ error: "feature not enabled" }, 403);
|
|
7881
|
+
const replyId = c.req.param("replyId");
|
|
7882
|
+
const input2 = await c.req.json().catch(() => null);
|
|
7883
|
+
const topic = typeof input2?.topic === "string" ? input2.topic.trim().slice(0, 60) : "";
|
|
7884
|
+
if (!topic) return c.json({ error: "topic is required" }, 400);
|
|
7885
|
+
const supabase = getSupabaseClient();
|
|
7886
|
+
const { data } = await supabase.from("thread_replies").select("id, threads!inner(channel_id)").eq("id", replyId).maybeSingle();
|
|
7887
|
+
const channelId = data?.threads?.channel_id;
|
|
7888
|
+
const channel = channelId ? findChannel2(c, channelId) : void 0;
|
|
7889
|
+
if (!channel || !isDmChannel(channel)) return c.json({ error: "not found" }, 404);
|
|
7890
|
+
const { error: error2 } = await supabase.from("reply_topics").upsert({ reply_id: replyId, channel_id: channel.id, topic, source: "manual" });
|
|
7891
|
+
if (error2) return c.json({ error: error2.message }, 500);
|
|
7892
|
+
return c.json({ ok: true, topic });
|
|
7893
|
+
});
|
|
7894
|
+
return app;
|
|
7895
|
+
}
|
|
7896
|
+
|
|
7816
7897
|
// ../api/src/dashboard/thread-translate.ts
|
|
7817
7898
|
import { createHash as createHash3 } from "crypto";
|
|
7818
7899
|
|
|
@@ -7822,11 +7903,11 @@ var TABLES = {
|
|
|
7822
7903
|
title: { table: "thread_title_translations", idColumn: "thread_id" }
|
|
7823
7904
|
};
|
|
7824
7905
|
async function getThreadTranslations(lang, keys, kind = "reply") {
|
|
7825
|
-
const { table, idColumn } = TABLES[kind];
|
|
7906
|
+
const { table: table2, idColumn } = TABLES[kind];
|
|
7826
7907
|
const found = /* @__PURE__ */ new Map();
|
|
7827
7908
|
if (keys.length === 0) return found;
|
|
7828
7909
|
const clauses = keys.map((k) => `and(${idColumn}.eq.${k.replyId},body_hash.eq.${k.bodyHash})`).join(",");
|
|
7829
|
-
const { data, error: error2 } = await getSupabaseClient().from(
|
|
7910
|
+
const { data, error: error2 } = await getSupabaseClient().from(table2).select(`${idColumn}, body, passthrough`).eq("lang", lang).or(clauses);
|
|
7830
7911
|
if (error2) throw new Error(`getThreadTranslations(${lang}): ${error2.message}`);
|
|
7831
7912
|
for (const row of data ?? []) {
|
|
7832
7913
|
const replyId = row[idColumn];
|
|
@@ -7840,8 +7921,8 @@ async function getThreadTranslations(lang, keys, kind = "reply") {
|
|
|
7840
7921
|
}
|
|
7841
7922
|
async function putThreadTranslations(lang, rows, kind = "reply") {
|
|
7842
7923
|
if (rows.length === 0) return;
|
|
7843
|
-
const { table, idColumn } = TABLES[kind];
|
|
7844
|
-
const { error: error2 } = await getSupabaseClient().from(
|
|
7924
|
+
const { table: table2, idColumn } = TABLES[kind];
|
|
7925
|
+
const { error: error2 } = await getSupabaseClient().from(table2).upsert(
|
|
7845
7926
|
rows.map((r) => ({
|
|
7846
7927
|
[idColumn]: r.replyId,
|
|
7847
7928
|
lang,
|
|
@@ -7874,7 +7955,7 @@ async function addTranslationTokens(workspaceId, tokens2) {
|
|
|
7874
7955
|
}
|
|
7875
7956
|
|
|
7876
7957
|
// ../api/src/dashboard/thread-translate.ts
|
|
7877
|
-
var
|
|
7958
|
+
var GROQ_API_URL3 = "https://api.groq.com/openai/v1/chat/completions";
|
|
7878
7959
|
var TRANSLATION_MODEL = "openai/gpt-oss-120b";
|
|
7879
7960
|
var RECIPE_VERSION = 1;
|
|
7880
7961
|
var BATCH_CHAR_BUDGET = 16e3;
|
|
@@ -7957,7 +8038,7 @@ async function translateBatch(batch, context, lang, scope) {
|
|
|
7957
8038
|
batch.map((m) => m.body)
|
|
7958
8039
|
)
|
|
7959
8040
|
};
|
|
7960
|
-
const res = await fetch(
|
|
8041
|
+
const res = await fetch(GROQ_API_URL3, {
|
|
7961
8042
|
method: "POST",
|
|
7962
8043
|
headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
|
|
7963
8044
|
body: JSON.stringify({
|
|
@@ -8003,14 +8084,14 @@ async function translateBatch(batch, context, lang, scope) {
|
|
|
8003
8084
|
};
|
|
8004
8085
|
});
|
|
8005
8086
|
}
|
|
8006
|
-
var
|
|
8087
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
8007
8088
|
async function translateCached(lang, scope, messages, contextFor) {
|
|
8008
8089
|
if (!BY_CODE.has(lang)) throw new Error(`unsupported translation language: ${lang}`);
|
|
8009
8090
|
if (messages.length === 0) return [];
|
|
8010
8091
|
const keyed = messages.map((m) => ({ ...m, hash: translationHash(m.author, m.body) }));
|
|
8011
8092
|
const shape = createHash3("sha256").update(keyed.map((m) => `${m.kind}:${m.id}:${m.hash}`).join("\n")).digest("hex");
|
|
8012
8093
|
const key = `${lang}:${shape}`;
|
|
8013
|
-
const running2 =
|
|
8094
|
+
const running2 = inFlight.get(key);
|
|
8014
8095
|
if (running2) return running2;
|
|
8015
8096
|
const job = (async () => {
|
|
8016
8097
|
const kinds = ["reply", "title"];
|
|
@@ -8066,8 +8147,8 @@ async function translateCached(lang, scope, messages, contextFor) {
|
|
|
8066
8147
|
if (hit) return { id: m.id, body: hit.body, passthrough: hit.passthrough };
|
|
8067
8148
|
return fresh.get(freshKey(m)) ?? { id: m.id, body: m.body, passthrough: true };
|
|
8068
8149
|
});
|
|
8069
|
-
})().finally(() =>
|
|
8070
|
-
|
|
8150
|
+
})().finally(() => inFlight.delete(key));
|
|
8151
|
+
inFlight.set(key, job);
|
|
8071
8152
|
return job;
|
|
8072
8153
|
}
|
|
8073
8154
|
async function translateThread(lang, scope, messages) {
|
|
@@ -8120,6 +8201,75 @@ async function getChannelGlossaries(channelIds) {
|
|
|
8120
8201
|
return found;
|
|
8121
8202
|
}
|
|
8122
8203
|
|
|
8204
|
+
// ../api/src/store/notification-store.ts
|
|
8205
|
+
function rowToNotification(row) {
|
|
8206
|
+
const reply = row["thread_replies"];
|
|
8207
|
+
return {
|
|
8208
|
+
id: row["id"],
|
|
8209
|
+
threadId: row["thread_id"],
|
|
8210
|
+
channelId: row["channel_id"],
|
|
8211
|
+
replyId: row["reply_id"] ?? null,
|
|
8212
|
+
kind: row["kind"],
|
|
8213
|
+
createdAt: row["created_at"],
|
|
8214
|
+
author: reply?.author ?? null,
|
|
8215
|
+
body: reply?.body ?? null
|
|
8216
|
+
};
|
|
8217
|
+
}
|
|
8218
|
+
async function listUnreadNotifications(channelIds, userId, limit = 100) {
|
|
8219
|
+
if (channelIds.length === 0) return [];
|
|
8220
|
+
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("id, thread_id, channel_id, reply_id, kind, created_at, thread_replies (author, body)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).order("created_at", { ascending: false }).limit(limit);
|
|
8221
|
+
if (error2) throw new Error(`listUnreadNotifications(${userId}): ${error2.message}`);
|
|
8222
|
+
return (data ?? []).map(rowToNotification);
|
|
8223
|
+
}
|
|
8224
|
+
async function countUnreadNotifications(channelIds, userId) {
|
|
8225
|
+
if (channelIds.length === 0) return 0;
|
|
8226
|
+
const { count, error: error2 } = await getSupabaseClient().from("notifications").select("id, threads!inner(archived_at)", { count: "exact", head: true }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
8227
|
+
if (error2) throw new Error(`countUnreadNotifications(${userId}): ${error2.message}`);
|
|
8228
|
+
return count ?? 0;
|
|
8229
|
+
}
|
|
8230
|
+
async function countUnreadByChannel(channelIds, userId) {
|
|
8231
|
+
if (channelIds.length === 0) return {};
|
|
8232
|
+
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("channel_id, thread_id, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
8233
|
+
if (error2) throw new Error(`countUnreadByChannel(${userId}): ${error2.message}`);
|
|
8234
|
+
const threads = /* @__PURE__ */ new Map();
|
|
8235
|
+
for (const row of data ?? []) {
|
|
8236
|
+
const channelId = row["channel_id"];
|
|
8237
|
+
const set = threads.get(channelId) ?? /* @__PURE__ */ new Set();
|
|
8238
|
+
set.add(row["thread_id"]);
|
|
8239
|
+
threads.set(channelId, set);
|
|
8240
|
+
}
|
|
8241
|
+
return Object.fromEntries([...threads].map(([id, set]) => [id, set.size]));
|
|
8242
|
+
}
|
|
8243
|
+
async function countUnreadByThread(channelIds, userId) {
|
|
8244
|
+
if (channelIds.length === 0) return {};
|
|
8245
|
+
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("thread_id, kind, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
8246
|
+
if (error2) throw new Error(`countUnreadByThread(${userId}): ${error2.message}`);
|
|
8247
|
+
const byThread = {};
|
|
8248
|
+
for (const row of data ?? []) {
|
|
8249
|
+
const threadId = row["thread_id"];
|
|
8250
|
+
const entry = byThread[threadId] ?? { count: 0, mention: false };
|
|
8251
|
+
entry.count += 1;
|
|
8252
|
+
if (row["kind"] === "mention") entry.mention = true;
|
|
8253
|
+
byThread[threadId] = entry;
|
|
8254
|
+
}
|
|
8255
|
+
return byThread;
|
|
8256
|
+
}
|
|
8257
|
+
async function markThreadRead(userId, threadId) {
|
|
8258
|
+
const supabase = getSupabaseClient();
|
|
8259
|
+
const { error: readError } = await supabase.from("thread_reads").upsert(
|
|
8260
|
+
{ user_id: userId, thread_id: threadId, seen_at: (/* @__PURE__ */ new Date()).toISOString() },
|
|
8261
|
+
{ onConflict: "user_id,thread_id" }
|
|
8262
|
+
);
|
|
8263
|
+
if (readError) throw new Error(`markThreadRead(${threadId}): ${readError.message}`);
|
|
8264
|
+
const { error: notifError } = await supabase.from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).eq("thread_id", threadId).is("read_at", null);
|
|
8265
|
+
if (notifError) throw new Error(`markThreadRead(${threadId}): ${notifError.message}`);
|
|
8266
|
+
}
|
|
8267
|
+
async function markAllRead(channelIds, userId) {
|
|
8268
|
+
if (channelIds.length === 0) return;
|
|
8269
|
+
const { error: error2 } = await getSupabaseClient().from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null);
|
|
8270
|
+
if (error2) throw new Error(`markAllRead(${userId}): ${error2.message}`);
|
|
8271
|
+
}
|
|
8272
|
+
|
|
8123
8273
|
// ../api/src/dashboard/chat-routes.ts
|
|
8124
8274
|
function isNonEmptyString(v) {
|
|
8125
8275
|
return typeof v === "string" && v.trim().length > 0;
|
|
@@ -8282,7 +8432,7 @@ var MARKDOWN_IMAGE_RE = /!\[[^\]]*\]\(\s*<?([^\s)>]+)>?(?:\s+"[^"]*")?\s*\)/g;
|
|
|
8282
8432
|
function markdownImageUrls(markdown) {
|
|
8283
8433
|
return [...markdown.matchAll(MARKDOWN_IMAGE_RE)].map((m) => m[1]);
|
|
8284
8434
|
}
|
|
8285
|
-
async function labelThread(channelId, body, scope) {
|
|
8435
|
+
async function labelThread(channelId, body, scope, language) {
|
|
8286
8436
|
const channel = getProfileChannelRegistry().find(
|
|
8287
8437
|
(ch) => ch.id === channelId || ch.externalChannelId === channelId
|
|
8288
8438
|
);
|
|
@@ -8303,7 +8453,8 @@ async function labelThread(channelId, body, scope) {
|
|
|
8303
8453
|
titlePrompt: (await loadWorkspaceBranding()).autoTitlePrompt,
|
|
8304
8454
|
existingCategories,
|
|
8305
8455
|
body,
|
|
8306
|
-
scope
|
|
8456
|
+
scope,
|
|
8457
|
+
language
|
|
8307
8458
|
});
|
|
8308
8459
|
}
|
|
8309
8460
|
function deriveForkTitle(body) {
|
|
@@ -8318,7 +8469,7 @@ async function generateAutoTitle(threadId, channelId, body) {
|
|
|
8318
8469
|
await supabase.from("threads").update({ auto_title: autoTitle }).eq("id", threadId).is("title", null);
|
|
8319
8470
|
}
|
|
8320
8471
|
function createChatRouter(agent = {}) {
|
|
8321
|
-
const app = new
|
|
8472
|
+
const app = new Hono13();
|
|
8322
8473
|
const {
|
|
8323
8474
|
onChatMessage: onMessage,
|
|
8324
8475
|
isAgentThinking,
|
|
@@ -8368,6 +8519,12 @@ function createChatRouter(agent = {}) {
|
|
|
8368
8519
|
const supabase = getSupabaseClient();
|
|
8369
8520
|
let query = supabase.from("threads").select("*").eq("channel_id", channelId).is("archived_at", null).order(sortColumn, { ascending: false }).limit(limit);
|
|
8370
8521
|
if (before) query = query.lt(sortColumn, before);
|
|
8522
|
+
if (c.req.query("unread") === "1") {
|
|
8523
|
+
const userId = c.get("auth")?.userId;
|
|
8524
|
+
const ids = userId ? Object.keys(await countUnreadByThread([channelId], userId)) : [];
|
|
8525
|
+
if (ids.length === 0) return c.json({ threads: [], nextCursor: null });
|
|
8526
|
+
query = query.in("id", ids);
|
|
8527
|
+
}
|
|
8371
8528
|
if (statusFilter.length) {
|
|
8372
8529
|
const withoutNone = statusFilter.filter((s) => s !== NO_STATUS_COLUMN);
|
|
8373
8530
|
const includeNone = statusFilter.includes(NO_STATUS_COLUMN);
|
|
@@ -8700,12 +8857,14 @@ function createChatRouter(agent = {}) {
|
|
|
8700
8857
|
app.post("/threads/:id/suggest-title", async (c) => {
|
|
8701
8858
|
const id = c.req.param("id");
|
|
8702
8859
|
if (!await threadIsKnown(id, c)) return c.json({ error: "not found" }, 404);
|
|
8860
|
+
const input2 = await c.req.json().catch(() => null);
|
|
8861
|
+
const language = typeof input2?.language === "string" && /^[A-Za-z-]{2,16}$/.test(input2.language) ? input2.language : void 0;
|
|
8703
8862
|
const { data: thread } = await getSupabaseClient().from("threads").select("channel_id").eq("id", id).single();
|
|
8704
8863
|
if (!thread) return c.json({ error: "not found" }, 404);
|
|
8705
8864
|
const { data: rows, error: error2 } = await getSupabaseClient().from("thread_replies").select("author, body").eq("thread_id", id).is("archived_at", null).order("created_at", { ascending: true });
|
|
8706
8865
|
if (error2) return c.json({ error: error2.message }, 500);
|
|
8707
8866
|
const transcript = (rows ?? []).map((r) => `${r.author}: ${slackMrkdwnToMarkdown(r.body)}`).join("\n\n");
|
|
8708
|
-
const title = await labelThread(thread.channel_id, transcript, "thread");
|
|
8867
|
+
const title = await labelThread(thread.channel_id, transcript, "thread", language);
|
|
8709
8868
|
if (!title) return c.json({ error: "could not generate a topic" }, 502);
|
|
8710
8869
|
return c.json({ title });
|
|
8711
8870
|
});
|
|
@@ -8844,6 +9003,12 @@ function createChatRouter(agent = {}) {
|
|
|
8844
9003
|
effort: effortFromRow(reply["effort"])
|
|
8845
9004
|
});
|
|
8846
9005
|
askSupport(c, thread.id, input2.author, input2.body);
|
|
9006
|
+
tagStoredReply(c, {
|
|
9007
|
+
threadId: thread.id,
|
|
9008
|
+
replyId: reply.id,
|
|
9009
|
+
author: input2.author,
|
|
9010
|
+
body: input2.body
|
|
9011
|
+
});
|
|
8847
9012
|
}
|
|
8848
9013
|
if (!replayed && pickedStatus !== void 0) {
|
|
8849
9014
|
void rememberComposerStatus(c, channelId, pickedStatus).catch(
|
|
@@ -8962,6 +9127,13 @@ function createChatRouter(agent = {}) {
|
|
|
8962
9127
|
effort: effortFromRow(data.effort)
|
|
8963
9128
|
});
|
|
8964
9129
|
askSupport(c, threadId, input2.author, input2.body);
|
|
9130
|
+
tagStoredReply(c, {
|
|
9131
|
+
threadId,
|
|
9132
|
+
replyId: data.id,
|
|
9133
|
+
author: input2.author,
|
|
9134
|
+
body: input2.body,
|
|
9135
|
+
replyToId: isNonEmptyString(input2.replyToId) ? input2.replyToId : void 0
|
|
9136
|
+
});
|
|
8965
9137
|
void syncSupportReply({ threadId, author: input2.author, body: input2.body });
|
|
8966
9138
|
return c.json(data, 201);
|
|
8967
9139
|
});
|
|
@@ -8992,7 +9164,7 @@ function createChatRouter(agent = {}) {
|
|
|
8992
9164
|
}
|
|
8993
9165
|
|
|
8994
9166
|
// ../api/src/dashboard/doc-shares-routes.ts
|
|
8995
|
-
import { Hono as
|
|
9167
|
+
import { Hono as Hono14 } from "hono";
|
|
8996
9168
|
|
|
8997
9169
|
// ../api/src/dashboard/doc-share-features.ts
|
|
8998
9170
|
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
@@ -9057,72 +9229,6 @@ import { CopyObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-s
|
|
|
9057
9229
|
// ../api/src/dashboard/bridge-types.ts
|
|
9058
9230
|
var SHARE_ASSET_PLACEHOLDER = "/share/{{flyspace-share-id}}/assets/";
|
|
9059
9231
|
|
|
9060
|
-
// ../api/src/dashboard/share-language.ts
|
|
9061
|
-
var GROQ_API_URL3 = "https://api.groq.com/openai/v1/chat/completions";
|
|
9062
|
-
var CLASSIFIER_MODEL = "openai/gpt-oss-20b";
|
|
9063
|
-
var SAMPLE_CHARS = 4e3;
|
|
9064
|
-
var NOISE = [
|
|
9065
|
-
/```[\s\S]*?```/g,
|
|
9066
|
-
/`[^`\n]*`/g,
|
|
9067
|
-
/!?\[[^\]]*\]\([^)]*\)/g,
|
|
9068
|
-
/https?:\/\/\S+/g
|
|
9069
|
-
];
|
|
9070
|
-
function languageSample(title, content) {
|
|
9071
|
-
let text = content;
|
|
9072
|
-
for (const pattern of NOISE) text = text.replace(pattern, " ");
|
|
9073
|
-
return `${title}
|
|
9074
|
-
|
|
9075
|
-
${text}`.replace(/\s+/g, " ").trim().slice(0, SAMPLE_CHARS);
|
|
9076
|
-
}
|
|
9077
|
-
var MIN_SAMPLE_CHARS = 40;
|
|
9078
|
-
var CODES = SOURCE_LANGUAGES.map((l) => l.code);
|
|
9079
|
-
function systemPrompt2() {
|
|
9080
|
-
const list = SOURCE_LANGUAGES.map((l) => `${l.code} (${l.name})`).join("\n");
|
|
9081
|
-
return `You identify the language an article is written in.
|
|
9082
|
-
|
|
9083
|
-
Reply with exactly one code from this list, and nothing else:
|
|
9084
|
-
${list}
|
|
9085
|
-
|
|
9086
|
-
If the article is written in a language that is not on the list, or you cannot tell, reply with exactly: unknown
|
|
9087
|
-
|
|
9088
|
-
Rules:
|
|
9089
|
-
- Judge by the PROSE the author wrote, not by code, product names, technical terms, or quoted fragments. An article written in one language routinely keeps technical vocabulary in English; that does not make it English.
|
|
9090
|
-
- Mixed-language articles take the language the body is mostly written in.
|
|
9091
|
-
- Traditional Chinese is zh-TW and Simplified Chinese is zh-CN. Decide by the characters used, not by the topic.
|
|
9092
|
-
- Output the code alone. No explanation, no punctuation, no quotes.`;
|
|
9093
|
-
}
|
|
9094
|
-
async function detectSourceLanguage(title, content) {
|
|
9095
|
-
const apiKey = process.env["GROQ_API_KEY"];
|
|
9096
|
-
if (!apiKey) return null;
|
|
9097
|
-
const sample = languageSample(title, content);
|
|
9098
|
-
if (sample.length < MIN_SAMPLE_CHARS) return null;
|
|
9099
|
-
try {
|
|
9100
|
-
const res = await fetch(GROQ_API_URL3, {
|
|
9101
|
-
method: "POST",
|
|
9102
|
-
headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
|
|
9103
|
-
body: JSON.stringify({
|
|
9104
|
-
model: CLASSIFIER_MODEL,
|
|
9105
|
-
temperature: 0,
|
|
9106
|
-
reasoning_effort: "low",
|
|
9107
|
-
// gpt-oss reasons before it answers, and those tokens count against
|
|
9108
|
-
// this cap — 8 was right for the old non-reasoning model but leaves
|
|
9109
|
-
// no room for the answer itself here.
|
|
9110
|
-
max_tokens: 150,
|
|
9111
|
-
messages: [
|
|
9112
|
-
{ role: "system", content: systemPrompt2() },
|
|
9113
|
-
{ role: "user", content: sample }
|
|
9114
|
-
]
|
|
9115
|
-
})
|
|
9116
|
-
});
|
|
9117
|
-
if (!res.ok) return null;
|
|
9118
|
-
const data = await res.json();
|
|
9119
|
-
const answer = data.choices?.[0]?.message?.content?.trim() ?? "";
|
|
9120
|
-
return CODES.find((code) => code.toLowerCase() === answer.toLowerCase()) ?? null;
|
|
9121
|
-
} catch {
|
|
9122
|
-
return null;
|
|
9123
|
-
}
|
|
9124
|
-
}
|
|
9125
|
-
|
|
9126
9232
|
// ../api/src/dashboard/doc-share-publish.ts
|
|
9127
9233
|
var SHARE_KEY_PREFIX = "share";
|
|
9128
9234
|
function generateShareId() {
|
|
@@ -9327,7 +9433,7 @@ function resolveChannel2(c) {
|
|
|
9327
9433
|
}
|
|
9328
9434
|
var LIST_LIMIT = 500;
|
|
9329
9435
|
function createDocShareListRouter() {
|
|
9330
|
-
const app = new
|
|
9436
|
+
const app = new Hono14();
|
|
9331
9437
|
app.get("/shares", async (c) => {
|
|
9332
9438
|
const viewer = c.get("auth");
|
|
9333
9439
|
const readable = await filterReadableDocsChannels(
|
|
@@ -9371,22 +9477,22 @@ function createDocShareListRouter() {
|
|
|
9371
9477
|
return app;
|
|
9372
9478
|
}
|
|
9373
9479
|
function createDocShareWriteRouter(agent = {}) {
|
|
9374
|
-
const app = new
|
|
9480
|
+
const app = new Hono14();
|
|
9375
9481
|
app.use("/:id/docs/share", requireDocsAccess);
|
|
9376
9482
|
app.use("/:id/docs/share/*", requireDocsAccess);
|
|
9377
9483
|
app.use("/:id/docs/shares", requireDocsAccess);
|
|
9378
9484
|
app.get("/:id/docs/share", async (c) => {
|
|
9379
|
-
const
|
|
9380
|
-
if ("error" in
|
|
9485
|
+
const resolved = resolveChannel2(c);
|
|
9486
|
+
if ("error" in resolved) return resolved.error;
|
|
9381
9487
|
const path = c.req.query("path") ?? "";
|
|
9382
9488
|
if (!path) return c.json({ error: "path is required" }, 400);
|
|
9383
|
-
const share = await findDocShareBySource(
|
|
9489
|
+
const share = await findDocShareBySource(resolved.auth.workspaceId, resolved.channel.id, path);
|
|
9384
9490
|
return c.json({ share: share ? shareJson(c, share) : null });
|
|
9385
9491
|
});
|
|
9386
9492
|
app.get("/:id/docs/shares", async (c) => {
|
|
9387
|
-
const
|
|
9388
|
-
if ("error" in
|
|
9389
|
-
const shares = await listLiveDocShares([
|
|
9493
|
+
const resolved = resolveChannel2(c);
|
|
9494
|
+
if ("error" in resolved) return resolved.error;
|
|
9495
|
+
const shares = await listLiveDocShares([resolved.channel.id], LIST_LIMIT + 1);
|
|
9390
9496
|
return c.json({
|
|
9391
9497
|
truncated: shares.length > LIST_LIMIT,
|
|
9392
9498
|
shares: shares.slice(0, LIST_LIMIT).map((s) => ({
|
|
@@ -9399,14 +9505,14 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9399
9505
|
});
|
|
9400
9506
|
});
|
|
9401
9507
|
app.get("/:id/docs/share/slug", async (c) => {
|
|
9402
|
-
const
|
|
9403
|
-
if ("error" in
|
|
9508
|
+
const resolved = resolveChannel2(c);
|
|
9509
|
+
if ("error" in resolved) return resolved.error;
|
|
9404
9510
|
const normalized = normalizeSlug(c.req.query("slug") ?? "");
|
|
9405
9511
|
if ("error" in normalized) {
|
|
9406
9512
|
return c.json({ available: false, reason: slugErrorMessage(normalized.error) });
|
|
9407
9513
|
}
|
|
9408
9514
|
const path = c.req.query("path");
|
|
9409
|
-
const own = path ? await findDocShareBySource(
|
|
9515
|
+
const own = path ? await findDocShareBySource(resolved.auth.workspaceId, resolved.channel.id, path) : null;
|
|
9410
9516
|
const available = await isSlugAvailable(normalized.slug, own?.id);
|
|
9411
9517
|
return c.json({
|
|
9412
9518
|
slug: normalized.slug,
|
|
@@ -9415,8 +9521,8 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9415
9521
|
});
|
|
9416
9522
|
});
|
|
9417
9523
|
app.post("/:id/docs/share", async (c) => {
|
|
9418
|
-
const
|
|
9419
|
-
if ("error" in
|
|
9524
|
+
const resolved = resolveChannel2(c);
|
|
9525
|
+
if ("error" in resolved) return resolved.error;
|
|
9420
9526
|
const body = await c.req.json().catch(() => null);
|
|
9421
9527
|
if (!body || typeof body["path"] !== "string" || !body["path"]) {
|
|
9422
9528
|
return c.json({ error: "path is required" }, 400);
|
|
@@ -9424,18 +9530,18 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9424
9530
|
const slug = readSlug(body);
|
|
9425
9531
|
if ("invalid" in slug)
|
|
9426
9532
|
return c.json({ error: slugErrorMessage(slug.invalid), field: "slug" }, 400);
|
|
9427
|
-
const { cwd } = resolveChannelConfig(
|
|
9533
|
+
const { cwd } = resolveChannelConfig(resolved.channel.id);
|
|
9428
9534
|
let result;
|
|
9429
9535
|
try {
|
|
9430
9536
|
const readBundle = agent.readDocShareBundle;
|
|
9431
9537
|
result = readBundle ? await publishDocShare(
|
|
9432
9538
|
{
|
|
9433
9539
|
cwd,
|
|
9434
|
-
workspaceId:
|
|
9435
|
-
profile:
|
|
9436
|
-
channelId:
|
|
9540
|
+
workspaceId: resolved.auth.workspaceId,
|
|
9541
|
+
profile: resolved.channel.profile,
|
|
9542
|
+
channelId: resolved.channel.id,
|
|
9437
9543
|
sourcePath: body["path"],
|
|
9438
|
-
createdBy:
|
|
9544
|
+
createdBy: resolved.auth.email,
|
|
9439
9545
|
..."slug" in slug ? { slug: slug.slug } : {},
|
|
9440
9546
|
features: readFeatures(body)
|
|
9441
9547
|
},
|
|
@@ -9474,8 +9580,8 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9474
9580
|
}
|
|
9475
9581
|
});
|
|
9476
9582
|
app.patch("/:id/docs/share", async (c) => {
|
|
9477
|
-
const
|
|
9478
|
-
if ("error" in
|
|
9583
|
+
const resolved = resolveChannel2(c);
|
|
9584
|
+
if ("error" in resolved) return resolved.error;
|
|
9479
9585
|
const body = await c.req.json().catch(() => null);
|
|
9480
9586
|
if (!body || typeof body["path"] !== "string" || !body["path"]) {
|
|
9481
9587
|
return c.json({ error: "path is required" }, 400);
|
|
@@ -9494,8 +9600,8 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9494
9600
|
);
|
|
9495
9601
|
}
|
|
9496
9602
|
const existing = await findDocShareBySource(
|
|
9497
|
-
|
|
9498
|
-
|
|
9603
|
+
resolved.auth.workspaceId,
|
|
9604
|
+
resolved.channel.id,
|
|
9499
9605
|
body["path"]
|
|
9500
9606
|
);
|
|
9501
9607
|
if (!existing) return c.json({ error: "not shared" }, 404);
|
|
@@ -9521,13 +9627,13 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9521
9627
|
return c.json(shareJson(c, updated));
|
|
9522
9628
|
});
|
|
9523
9629
|
app.delete("/:id/docs/share", async (c) => {
|
|
9524
|
-
const
|
|
9525
|
-
if ("error" in
|
|
9630
|
+
const resolved = resolveChannel2(c);
|
|
9631
|
+
if ("error" in resolved) return resolved.error;
|
|
9526
9632
|
const path = c.req.query("path") ?? "";
|
|
9527
9633
|
if (!path) return c.json({ error: "path is required" }, 400);
|
|
9528
9634
|
const existing = await findDocShareBySource(
|
|
9529
|
-
|
|
9530
|
-
|
|
9635
|
+
resolved.auth.workspaceId,
|
|
9636
|
+
resolved.channel.id,
|
|
9531
9637
|
path
|
|
9532
9638
|
);
|
|
9533
9639
|
if (!existing) return c.json({ error: "not shared" }, 404);
|
|
@@ -9544,7 +9650,7 @@ function createDocShareWriteRouter(agent = {}) {
|
|
|
9544
9650
|
}
|
|
9545
9651
|
|
|
9546
9652
|
// ../api/src/dashboard/search-routes.ts
|
|
9547
|
-
import { Hono as
|
|
9653
|
+
import { Hono as Hono15 } from "hono";
|
|
9548
9654
|
function matchScore(q, fields) {
|
|
9549
9655
|
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
|
|
9550
9656
|
if (terms.length === 0) return 0;
|
|
@@ -9692,7 +9798,7 @@ function searchAutomations(q) {
|
|
|
9692
9798
|
}
|
|
9693
9799
|
var RESULT_LIMIT = 30;
|
|
9694
9800
|
function createSearchRouter() {
|
|
9695
|
-
const app = new
|
|
9801
|
+
const app = new Hono15();
|
|
9696
9802
|
app.get("/", async (c) => {
|
|
9697
9803
|
const q = c.req.query("q")?.trim();
|
|
9698
9804
|
if (!q) return c.json({ results: [] });
|
|
@@ -9708,7 +9814,7 @@ function createSearchRouter() {
|
|
|
9708
9814
|
}
|
|
9709
9815
|
|
|
9710
9816
|
// ../api/src/dashboard/domain-routes.ts
|
|
9711
|
-
import { Hono as
|
|
9817
|
+
import { Hono as Hono16 } from "hono";
|
|
9712
9818
|
var FALLBACK_ORIGIN = "custom.flyspace.ai";
|
|
9713
9819
|
function isValidCustomHostname(hostname2) {
|
|
9714
9820
|
if (hostname2.length > 253 || hostname2.endsWith(".flyspace.ai") || hostname2 === "flyspace.ai") {
|
|
@@ -9778,7 +9884,7 @@ function view(row, dcv) {
|
|
|
9778
9884
|
};
|
|
9779
9885
|
}
|
|
9780
9886
|
function createDomainRouter() {
|
|
9781
|
-
const app = new
|
|
9887
|
+
const app = new Hono16();
|
|
9782
9888
|
app.use("*", async (c, next) => {
|
|
9783
9889
|
const auth = c.get("auth");
|
|
9784
9890
|
if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
@@ -9842,17 +9948,15 @@ function createDomainRouter() {
|
|
|
9842
9948
|
}
|
|
9843
9949
|
|
|
9844
9950
|
// ../api/src/dashboard/transcribe-routes.ts
|
|
9845
|
-
import { Hono as
|
|
9951
|
+
import { Hono as Hono17 } from "hono";
|
|
9846
9952
|
var GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
|
|
9847
|
-
var
|
|
9953
|
+
var MODEL2 = "whisper-large-v3-turbo";
|
|
9848
9954
|
var MAX_AUDIO_BYTES = 5 * 1024 * 1024;
|
|
9849
9955
|
var MAX_PROMPT_CHARS = 400;
|
|
9850
9956
|
var NO_SPEECH_THRESHOLD = 0.6;
|
|
9851
9957
|
function createTranscribeRouter() {
|
|
9852
|
-
const app = new
|
|
9958
|
+
const app = new Hono17();
|
|
9853
9959
|
app.post("/transcribe", async (c) => {
|
|
9854
|
-
if (!await isFeatureEnabled(c, "dictation"))
|
|
9855
|
-
return c.json({ error: "feature not enabled" }, 403);
|
|
9856
9960
|
const apiKey = process.env["GROQ_API_KEY"];
|
|
9857
9961
|
if (!apiKey) return c.json({ error: "transcription is not configured" }, 503);
|
|
9858
9962
|
const body = await c.req.parseBody().catch(() => null);
|
|
@@ -9861,7 +9965,7 @@ function createTranscribeRouter() {
|
|
|
9861
9965
|
if (file.size > MAX_AUDIO_BYTES) return c.json({ error: "audio segment too large" }, 400);
|
|
9862
9966
|
const form = new FormData();
|
|
9863
9967
|
form.append("file", file, file.name || "segment.wav");
|
|
9864
|
-
form.append("model",
|
|
9968
|
+
form.append("model", MODEL2);
|
|
9865
9969
|
form.append("temperature", "0");
|
|
9866
9970
|
form.append("response_format", "verbose_json");
|
|
9867
9971
|
const prompt = body?.["prompt"];
|
|
@@ -9888,21 +9992,19 @@ function createTranscribeRouter() {
|
|
|
9888
9992
|
}
|
|
9889
9993
|
|
|
9890
9994
|
// ../api/src/dashboard/autocomplete-routes.ts
|
|
9891
|
-
import { Hono as
|
|
9995
|
+
import { Hono as Hono18 } from "hono";
|
|
9892
9996
|
var GROQ_API_URL4 = "https://api.groq.com/openai/v1/chat/completions";
|
|
9893
|
-
var
|
|
9997
|
+
var MODEL3 = "openai/gpt-oss-120b";
|
|
9894
9998
|
var MAX_REPLY_CHARS = 4e3;
|
|
9895
9999
|
var MAX_EARLIER_CHARS = 1500;
|
|
9896
10000
|
var THREAD_TAIL_REPLIES = 5;
|
|
9897
|
-
var
|
|
10001
|
+
var RULES2 = `You predict the next message a user will send in a chat thread, right after the AI agent's last reply, like Claude Code's prompt suggestions. The composer is empty; you suggest the whole message.
|
|
9898
10002
|
Base it on the agent's last reply: answer a question it asked, approve or pick an option it offered, or ask for the obvious next step (commit, deploy, run the tests, check a specific file or feature it named). Use specific nouns from the reply.
|
|
9899
10003
|
Keep it short (under 15 words), in the language the user writes in. No greetings, thanks or filler.
|
|
9900
10004
|
Output ONLY the message text, no quotes or explanation. If there is no clear next step, output nothing.`;
|
|
9901
10005
|
function createAutocompleteRouter() {
|
|
9902
|
-
const app = new
|
|
10006
|
+
const app = new Hono18();
|
|
9903
10007
|
app.post("/autocomplete", async (c) => {
|
|
9904
|
-
if (!await isFeatureEnabled(c, "autocomplete"))
|
|
9905
|
-
return c.json({ error: "feature not enabled" }, 403);
|
|
9906
10008
|
const apiKey = process.env["GROQ_API_KEY"];
|
|
9907
10009
|
if (!apiKey) return c.json({ error: "autocomplete is not configured" }, 503);
|
|
9908
10010
|
const body = await c.req.json().catch(() => null);
|
|
@@ -9919,7 +10021,7 @@ ${thread}`;
|
|
|
9919
10021
|
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
9920
10022
|
signal: AbortSignal.timeout(5e3),
|
|
9921
10023
|
body: JSON.stringify({
|
|
9922
|
-
model:
|
|
10024
|
+
model: MODEL3,
|
|
9923
10025
|
// gpt-oss reasons first; a newline stop would cut it off before any content.
|
|
9924
10026
|
max_completion_tokens: 200,
|
|
9925
10027
|
reasoning_effort: "low",
|
|
@@ -9928,8 +10030,8 @@ ${thread}`;
|
|
|
9928
10030
|
messages: [
|
|
9929
10031
|
{
|
|
9930
10032
|
role: "system",
|
|
9931
|
-
content: typeof body.language === "string" && /^[A-Za-z-]{2,16}$/.test(body.language) ? `${
|
|
9932
|
-
The user reads this thread in ${body.language}: write the suggestion in that language (BCP 47 tag).` :
|
|
10033
|
+
content: typeof body.language === "string" && /^[A-Za-z-]{2,16}$/.test(body.language) ? `${RULES2}
|
|
10034
|
+
The user reads this thread in ${body.language}: write the suggestion in that language (BCP 47 tag).` : RULES2
|
|
9933
10035
|
},
|
|
9934
10036
|
{ role: "user", content: context }
|
|
9935
10037
|
]
|
|
@@ -9966,9 +10068,220 @@ Agent's last reply:
|
|
|
9966
10068
|
${last.body.slice(-MAX_REPLY_CHARS)}`;
|
|
9967
10069
|
}
|
|
9968
10070
|
|
|
10071
|
+
// ../api/src/dashboard/daily-line-routes.ts
|
|
10072
|
+
import { Hono as Hono19 } from "hono";
|
|
10073
|
+
var GROQ_API_URL5 = "https://api.groq.com/openai/v1/chat/completions";
|
|
10074
|
+
var MODEL4 = "openai/gpt-oss-120b";
|
|
10075
|
+
var DAY_MS = 864e5;
|
|
10076
|
+
var RULES3 = `You write one short line of encouragement shown in the corner of an empty screen, for a founder building a product with a small team.
|
|
10077
|
+
You are given what the team recently built and decided. Draw on its real substance to remind them how far they have come or why the work matters, so they feel like pushing on.
|
|
10078
|
+
Never a task, reminder, instruction or rule (no "remember to", "do X first", "never Y"). Not a summary of the item either.
|
|
10079
|
+
Under 30 Chinese characters or 18 English words. Warm but plain, like a note from a friend: no hype, no exclamation marks, no emoji, no quotes, no cliches.
|
|
10080
|
+
Output ONLY the line.`;
|
|
10081
|
+
var CONTEXT_COUNT = 5;
|
|
10082
|
+
var cache3 = /* @__PURE__ */ new Map();
|
|
10083
|
+
function dayIndex(now = /* @__PURE__ */ new Date()) {
|
|
10084
|
+
const local = new Date(now.toLocaleString("en-US", { timeZone: "Australia/Sydney" }));
|
|
10085
|
+
return Math.floor(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate()) / DAY_MS);
|
|
10086
|
+
}
|
|
10087
|
+
var RECENT_MS = 60 * DAY_MS;
|
|
10088
|
+
function pickMemories(memories, day, now = Date.now()) {
|
|
10089
|
+
const recent = memories.filter((m) => now - Date.parse(m.updatedAt) < RECENT_MS);
|
|
10090
|
+
const pool = (recent.length ? recent : memories).sort(
|
|
10091
|
+
(a, b) => b.updatedAt.localeCompare(a.updatedAt)
|
|
10092
|
+
);
|
|
10093
|
+
if (!pool.length) return [];
|
|
10094
|
+
const start = day % pool.length;
|
|
10095
|
+
return [...pool, ...pool].slice(start, start + Math.min(CONTEXT_COUNT, pool.length));
|
|
10096
|
+
}
|
|
10097
|
+
function createDailyLineRouter() {
|
|
10098
|
+
const app = new Hono19();
|
|
10099
|
+
app.get("/daily-line", async (c) => {
|
|
10100
|
+
if (!await isFeatureEnabled(c, "daily-line"))
|
|
10101
|
+
return c.json({ error: "feature not enabled" }, 403);
|
|
10102
|
+
const apiKey = process.env["GROQ_API_KEY"];
|
|
10103
|
+
if (!apiKey) return c.json({ text: "" });
|
|
10104
|
+
const auth = c.get("auth");
|
|
10105
|
+
const language = c.req.query("language") ?? "en";
|
|
10106
|
+
if (!/^[A-Za-z-]{2,16}$/.test(language)) return c.json({ text: "" });
|
|
10107
|
+
const { data } = await getSupabaseClient().from("memories").select("*").eq("workspace_id", auth.workspaceId).in("scope", ["channel", "workspace"]).in("type", ["decision", "fact"]);
|
|
10108
|
+
const visible = new Set(
|
|
10109
|
+
getChannelRegistry().filter((ch) => canSeeChannel(ch, auth)).map((ch) => ch.id)
|
|
10110
|
+
);
|
|
10111
|
+
const memories = (data ?? []).map(rowToMemory).filter((m) => !m.channelId || visible.has(m.channelId));
|
|
10112
|
+
const day = dayIndex();
|
|
10113
|
+
const picked = pickMemories(memories, day);
|
|
10114
|
+
const memory = picked[0];
|
|
10115
|
+
if (!memory) return c.json({ text: "" });
|
|
10116
|
+
const key = `${day}:${memory.id}:${language}`;
|
|
10117
|
+
let text = cache3.get(key);
|
|
10118
|
+
if (text === void 0) {
|
|
10119
|
+
const res = await fetch(GROQ_API_URL5, {
|
|
10120
|
+
method: "POST",
|
|
10121
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
10122
|
+
signal: AbortSignal.timeout(8e3),
|
|
10123
|
+
body: JSON.stringify({
|
|
10124
|
+
model: MODEL4,
|
|
10125
|
+
max_completion_tokens: 300,
|
|
10126
|
+
reasoning_effort: "low",
|
|
10127
|
+
include_reasoning: false,
|
|
10128
|
+
temperature: 0.7,
|
|
10129
|
+
messages: [
|
|
10130
|
+
{
|
|
10131
|
+
role: "system",
|
|
10132
|
+
content: `${RULES3}
|
|
10133
|
+
Write it in ${language} (BCP 47 tag). For Chinese use Traditional Chinese (Taiwan) with full-width punctuation.`
|
|
10134
|
+
},
|
|
10135
|
+
{
|
|
10136
|
+
role: "user",
|
|
10137
|
+
content: picked.map((m) => `- ${m.description}
|
|
10138
|
+
${m.body.slice(0, 400)}`).join("\n")
|
|
10139
|
+
}
|
|
10140
|
+
]
|
|
10141
|
+
})
|
|
10142
|
+
}).catch(() => null);
|
|
10143
|
+
if (!res?.ok) return c.json({ text: "" });
|
|
10144
|
+
const out = await res.json();
|
|
10145
|
+
text = (out.choices?.[0]?.message?.content ?? "").trim().split("\n")[0];
|
|
10146
|
+
if (text) cache3.set(key, text);
|
|
10147
|
+
}
|
|
10148
|
+
return c.json({ text, date: memory.updatedAt, threadId: memory.sourceThreadId });
|
|
10149
|
+
});
|
|
10150
|
+
return app;
|
|
10151
|
+
}
|
|
10152
|
+
|
|
10153
|
+
// ../api/src/dashboard/channel-route.ts
|
|
10154
|
+
import { Hono as Hono20 } from "hono";
|
|
10155
|
+
var GROQ_API_URL6 = "https://api.groq.com/openai/v1/chat/completions";
|
|
10156
|
+
var MODEL5 = "openai/gpt-oss-120b";
|
|
10157
|
+
var MAX_MESSAGE_CHARS2 = 3e3;
|
|
10158
|
+
var MAX_PROMPT_CHARS2 = 300;
|
|
10159
|
+
var TITLES_PER_CHANNEL = 8;
|
|
10160
|
+
var RECENT_THREADS = 600;
|
|
10161
|
+
var TABLE_TTL_MS = 30 * 6e4;
|
|
10162
|
+
var VISION_MODEL = "qwen/qwen3.8-27b";
|
|
10163
|
+
var MAX_IMAGES = 3;
|
|
10164
|
+
var ATTACHMENT_KEY = /\/api\/attachments\/([^)?\s]+)/g;
|
|
10165
|
+
var DESCRIBE = `Describe these screenshots in 2 to 4 short lines so someone can tell which project they belong to: the app or website shown, its visible product, brand, workspace and channel names, and the screen or feature. Quote names exactly as written. No guesses beyond what is visible.`;
|
|
10166
|
+
async function describeImages(text, workspace, apiKey) {
|
|
10167
|
+
if (!workspace) return "";
|
|
10168
|
+
const keys = [...text.matchAll(ATTACHMENT_KEY)].map((m) => decodeURIComponent(m[1])).filter((key) => key.split("/")[1] === workspace).slice(0, MAX_IMAGES);
|
|
10169
|
+
const urls = (await Promise.all(keys.map((k) => presignAttachmentRead(k).catch(() => null)))).filter(
|
|
10170
|
+
(u) => !!u
|
|
10171
|
+
);
|
|
10172
|
+
if (urls.length === 0) return "";
|
|
10173
|
+
const res = await fetch(GROQ_API_URL6, {
|
|
10174
|
+
method: "POST",
|
|
10175
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
10176
|
+
signal: AbortSignal.timeout(1e4),
|
|
10177
|
+
body: JSON.stringify({
|
|
10178
|
+
model: VISION_MODEL,
|
|
10179
|
+
max_completion_tokens: 200,
|
|
10180
|
+
reasoning_effort: "none",
|
|
10181
|
+
temperature: 0,
|
|
10182
|
+
messages: [
|
|
10183
|
+
{
|
|
10184
|
+
role: "user",
|
|
10185
|
+
content: [
|
|
10186
|
+
{ type: "text", text: DESCRIBE },
|
|
10187
|
+
...urls.map((url) => ({ type: "image_url", image_url: { url } }))
|
|
10188
|
+
]
|
|
10189
|
+
}
|
|
10190
|
+
]
|
|
10191
|
+
})
|
|
10192
|
+
}).catch(() => null);
|
|
10193
|
+
if (!res?.ok) return "";
|
|
10194
|
+
const data = await res.json();
|
|
10195
|
+
return (data.choices?.[0]?.message?.content ?? "").trim();
|
|
10196
|
+
}
|
|
10197
|
+
var table = null;
|
|
10198
|
+
async function recentTitles(channels) {
|
|
10199
|
+
const key = channels.map((ch) => ch.id).sort().join(",");
|
|
10200
|
+
if (table?.key === key && Date.now() - table.builtAt < TABLE_TTL_MS) return table.titles;
|
|
10201
|
+
const keyOf = /* @__PURE__ */ new Map();
|
|
10202
|
+
for (const ch of channels) {
|
|
10203
|
+
keyOf.set(ch.id, ch.id);
|
|
10204
|
+
if (ch.externalChannelId) keyOf.set(ch.externalChannelId, ch.id);
|
|
10205
|
+
}
|
|
10206
|
+
const { data: threads } = await getSupabaseClient().from("threads").select("channel_id, title, auto_title").in("channel_id", [...keyOf.keys()]).order("created_at", { ascending: false }).limit(RECENT_THREADS);
|
|
10207
|
+
const titles = /* @__PURE__ */ new Map();
|
|
10208
|
+
for (const t of threads ?? []) {
|
|
10209
|
+
const id = keyOf.get(t.channel_id);
|
|
10210
|
+
const title = t.title ?? t.auto_title;
|
|
10211
|
+
if (!id || !title) continue;
|
|
10212
|
+
const list = titles.get(id) ?? [];
|
|
10213
|
+
if (list.length < TITLES_PER_CHANNEL) titles.set(id, [...list, title]);
|
|
10214
|
+
}
|
|
10215
|
+
table = { key, builtAt: Date.now(), titles };
|
|
10216
|
+
return titles;
|
|
10217
|
+
}
|
|
10218
|
+
var RULES4 = `You route a new chat topic to the channel it belongs in. Each channel is a project or area of work; you get its name, instructions and recent topic titles.
|
|
10219
|
+
Pick the single channel whose project the message is about. Prefer a specific project channel over a general one. Match on concrete nouns (product, client, repo, feature names) rather than tone.
|
|
10220
|
+
A topic word that could fit many projects (notification, scrollbar, login, bug) is not evidence: unless the message clearly names another project, pick the channel the user is currently in.
|
|
10221
|
+
When a screenshot description is given, the app and names visible in it are strong evidence of the project.
|
|
10222
|
+
Output ONLY the channel's number and your confidence, e.g. "3 high" or "3 low". Say low when the message could reasonably belong to more than one channel.`;
|
|
10223
|
+
function createChannelRouteRouter() {
|
|
10224
|
+
const app = new Hono20();
|
|
10225
|
+
app.post("/route-channel", async (c) => {
|
|
10226
|
+
if (!await isFeatureEnabled(c, "auto-channel"))
|
|
10227
|
+
return c.json({ error: "feature not enabled" }, 403);
|
|
10228
|
+
const apiKey = process.env["GROQ_API_KEY"];
|
|
10229
|
+
if (!apiKey) return c.json({ error: "channel routing is not configured" }, 503);
|
|
10230
|
+
const body = await c.req.json().catch(() => null);
|
|
10231
|
+
const text = typeof body?.text === "string" ? body.text.trim().slice(0, MAX_MESSAGE_CHARS2) : "";
|
|
10232
|
+
if (!text) return c.json({ channelId: null, confident: false });
|
|
10233
|
+
const auth = c.get("auth");
|
|
10234
|
+
const channels = getChannelRegistry().filter((ch) => !ch.archivedAt && canSeeChannel(ch, auth));
|
|
10235
|
+
if (channels.length <= 1) return c.json({ channelId: channels[0]?.id ?? null, confident: true });
|
|
10236
|
+
const [titles, screenshots] = await Promise.all([
|
|
10237
|
+
recentTitles(getChannelRegistry().filter((ch) => !ch.archivedAt)),
|
|
10238
|
+
describeImages(text, c.req.query("workspace"), apiKey)
|
|
10239
|
+
]);
|
|
10240
|
+
const current = channels.findIndex((ch) => ch.id === body?.currentChannelId);
|
|
10241
|
+
const listing = channels.map(
|
|
10242
|
+
(ch, i) => [
|
|
10243
|
+
`${i + 1}. ${ch.agentName ? "@" : "#"}${ch.name}`,
|
|
10244
|
+
ch.prompt ? ` Instructions: ${ch.prompt.replace(/\s+/g, " ").slice(0, MAX_PROMPT_CHARS2)}` : "",
|
|
10245
|
+
titles.get(ch.id)?.length ? ` Recent topics: ${titles.get(ch.id).join(" | ")}` : ""
|
|
10246
|
+
].filter(Boolean).join("\n")
|
|
10247
|
+
).join("\n");
|
|
10248
|
+
const res = await fetch(GROQ_API_URL6, {
|
|
10249
|
+
method: "POST",
|
|
10250
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
10251
|
+
signal: AbortSignal.timeout(8e3),
|
|
10252
|
+
body: JSON.stringify({
|
|
10253
|
+
model: MODEL5,
|
|
10254
|
+
max_completion_tokens: 400,
|
|
10255
|
+
reasoning_effort: "low",
|
|
10256
|
+
include_reasoning: false,
|
|
10257
|
+
temperature: 0,
|
|
10258
|
+
messages: [
|
|
10259
|
+
{ role: "system", content: RULES4 },
|
|
10260
|
+
{ role: "user", content: `Channels:
|
|
10261
|
+
${listing}${current >= 0 ? `
|
|
10262
|
+
|
|
10263
|
+
The user is currently in channel ${current + 1}.` : ""}
|
|
10264
|
+
|
|
10265
|
+
New topic:
|
|
10266
|
+
${text}${screenshots ? `
|
|
10267
|
+
|
|
10268
|
+
Attached screenshots show:
|
|
10269
|
+
${screenshots}` : ""}` }
|
|
10270
|
+
]
|
|
10271
|
+
})
|
|
10272
|
+
}).catch(() => null);
|
|
10273
|
+
if (!res?.ok) return c.json({ channelId: null, confident: false });
|
|
10274
|
+
const data = await res.json();
|
|
10275
|
+
const reply = data.choices?.[0]?.message?.content ?? "";
|
|
10276
|
+
const channelId = channels[Number(reply.match(/\d+/)?.[0]) - 1]?.id ?? null;
|
|
10277
|
+
return c.json({ channelId, confident: !!channelId && /\bhigh\b/i.test(reply) });
|
|
10278
|
+
});
|
|
10279
|
+
return app;
|
|
10280
|
+
}
|
|
10281
|
+
|
|
9969
10282
|
// ../api/src/dashboard/avatars-routes.ts
|
|
9970
10283
|
import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
|
|
9971
|
-
import { Hono as
|
|
10284
|
+
import { Hono as Hono21 } from "hono";
|
|
9972
10285
|
import sharp3 from "sharp";
|
|
9973
10286
|
import { PutObjectCommand as PutObjectCommand3, DeleteObjectCommand as DeleteObjectCommand2 } from "@aws-sdk/client-s3";
|
|
9974
10287
|
var AVATAR_SIZE = 192;
|
|
@@ -10021,7 +10334,7 @@ function avatarKeyPrefix() {
|
|
|
10021
10334
|
return `${KEY_PREFIX2}/${getProfile()}/`;
|
|
10022
10335
|
}
|
|
10023
10336
|
function createAvatarsRouter() {
|
|
10024
|
-
const app = new
|
|
10337
|
+
const app = new Hono21();
|
|
10025
10338
|
app.get("/avatars/slack", async (c) => {
|
|
10026
10339
|
const ctx = await resolveAuthContext(c);
|
|
10027
10340
|
if (!ctx) return c.json({ error: "not signed in" }, 401);
|
|
@@ -10070,7 +10383,7 @@ function createAvatarsRouter() {
|
|
|
10070
10383
|
}
|
|
10071
10384
|
|
|
10072
10385
|
// ../api/src/dashboard/members-routes.ts
|
|
10073
|
-
import { Hono as
|
|
10386
|
+
import { Hono as Hono22 } from "hono";
|
|
10074
10387
|
function inviteLinkFor(c, token) {
|
|
10075
10388
|
const url = new URL("/auth/invite", callbackUrl(c));
|
|
10076
10389
|
url.searchParams.set("token", token);
|
|
@@ -10078,7 +10391,7 @@ function inviteLinkFor(c, token) {
|
|
|
10078
10391
|
}
|
|
10079
10392
|
var EMAIL_RE2 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
10080
10393
|
function createMembersRouter() {
|
|
10081
|
-
const members = new
|
|
10394
|
+
const members = new Hono22();
|
|
10082
10395
|
members.get("/", async (c) => {
|
|
10083
10396
|
const ctx = await resolveAuthContext(c);
|
|
10084
10397
|
if (ctx?.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
@@ -10301,74 +10614,7 @@ function createMembersRouter() {
|
|
|
10301
10614
|
}
|
|
10302
10615
|
|
|
10303
10616
|
// ../api/src/dashboard/notifications-routes.ts
|
|
10304
|
-
import { Hono as
|
|
10305
|
-
|
|
10306
|
-
// ../api/src/store/notification-store.ts
|
|
10307
|
-
function rowToNotification(row) {
|
|
10308
|
-
const reply = row["thread_replies"];
|
|
10309
|
-
return {
|
|
10310
|
-
id: row["id"],
|
|
10311
|
-
threadId: row["thread_id"],
|
|
10312
|
-
channelId: row["channel_id"],
|
|
10313
|
-
replyId: row["reply_id"] ?? null,
|
|
10314
|
-
kind: row["kind"],
|
|
10315
|
-
createdAt: row["created_at"],
|
|
10316
|
-
author: reply?.author ?? null,
|
|
10317
|
-
body: reply?.body ?? null
|
|
10318
|
-
};
|
|
10319
|
-
}
|
|
10320
|
-
async function listUnreadNotifications(channelIds, userId, limit = 100) {
|
|
10321
|
-
if (channelIds.length === 0) return [];
|
|
10322
|
-
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("id, thread_id, channel_id, reply_id, kind, created_at, thread_replies (author, body)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).order("created_at", { ascending: false }).limit(limit);
|
|
10323
|
-
if (error2) throw new Error(`listUnreadNotifications(${userId}): ${error2.message}`);
|
|
10324
|
-
return (data ?? []).map(rowToNotification);
|
|
10325
|
-
}
|
|
10326
|
-
async function countUnreadNotifications(channelIds, userId) {
|
|
10327
|
-
if (channelIds.length === 0) return 0;
|
|
10328
|
-
const { count, error: error2 } = await getSupabaseClient().from("notifications").select("id, threads!inner(archived_at)", { count: "exact", head: true }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
10329
|
-
if (error2) throw new Error(`countUnreadNotifications(${userId}): ${error2.message}`);
|
|
10330
|
-
return count ?? 0;
|
|
10331
|
-
}
|
|
10332
|
-
async function countUnreadByChannel(channelIds, userId) {
|
|
10333
|
-
if (channelIds.length === 0) return {};
|
|
10334
|
-
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("channel_id, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
10335
|
-
if (error2) throw new Error(`countUnreadByChannel(${userId}): ${error2.message}`);
|
|
10336
|
-
const byChannel = {};
|
|
10337
|
-
for (const row of data ?? []) {
|
|
10338
|
-
const channelId = row["channel_id"];
|
|
10339
|
-
byChannel[channelId] = (byChannel[channelId] ?? 0) + 1;
|
|
10340
|
-
}
|
|
10341
|
-
return byChannel;
|
|
10342
|
-
}
|
|
10343
|
-
async function countUnreadByThread(channelIds, userId) {
|
|
10344
|
-
if (channelIds.length === 0) return {};
|
|
10345
|
-
const { data, error: error2 } = await getSupabaseClient().from("notifications").select("thread_id, kind, threads!inner(archived_at)").eq("user_id", userId).in("channel_id", channelIds).is("read_at", null).is("threads.archived_at", null);
|
|
10346
|
-
if (error2) throw new Error(`countUnreadByThread(${userId}): ${error2.message}`);
|
|
10347
|
-
const byThread = {};
|
|
10348
|
-
for (const row of data ?? []) {
|
|
10349
|
-
const threadId = row["thread_id"];
|
|
10350
|
-
const entry = byThread[threadId] ?? { count: 0, mention: false };
|
|
10351
|
-
entry.count += 1;
|
|
10352
|
-
if (row["kind"] === "mention") entry.mention = true;
|
|
10353
|
-
byThread[threadId] = entry;
|
|
10354
|
-
}
|
|
10355
|
-
return byThread;
|
|
10356
|
-
}
|
|
10357
|
-
async function markThreadRead(userId, threadId) {
|
|
10358
|
-
const supabase = getSupabaseClient();
|
|
10359
|
-
const { error: readError } = await supabase.from("thread_reads").upsert(
|
|
10360
|
-
{ user_id: userId, thread_id: threadId, seen_at: (/* @__PURE__ */ new Date()).toISOString() },
|
|
10361
|
-
{ onConflict: "user_id,thread_id" }
|
|
10362
|
-
);
|
|
10363
|
-
if (readError) throw new Error(`markThreadRead(${threadId}): ${readError.message}`);
|
|
10364
|
-
const { error: notifError } = await supabase.from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).eq("thread_id", threadId).is("read_at", null);
|
|
10365
|
-
if (notifError) throw new Error(`markThreadRead(${threadId}): ${notifError.message}`);
|
|
10366
|
-
}
|
|
10367
|
-
async function markAllRead(channelIds, userId) {
|
|
10368
|
-
if (channelIds.length === 0) return;
|
|
10369
|
-
const { error: error2 } = await getSupabaseClient().from("notifications").update({ read_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId).in("channel_id", channelIds).is("read_at", null);
|
|
10370
|
-
if (error2) throw new Error(`markAllRead(${userId}): ${error2.message}`);
|
|
10371
|
-
}
|
|
10617
|
+
import { Hono as Hono23 } from "hono";
|
|
10372
10618
|
|
|
10373
10619
|
// ../api/src/store/push-store.ts
|
|
10374
10620
|
function rowToSubscription(row) {
|
|
@@ -10553,7 +10799,7 @@ function startPushWatcher() {
|
|
|
10553
10799
|
|
|
10554
10800
|
// ../api/src/dashboard/notifications-routes.ts
|
|
10555
10801
|
function createNotificationsRouter() {
|
|
10556
|
-
const notifications = new
|
|
10802
|
+
const notifications = new Hono23();
|
|
10557
10803
|
notifications.get("/", async (c) => {
|
|
10558
10804
|
const auth = c.get("auth");
|
|
10559
10805
|
const channelIds = getProfileChannelRegistry().filter((ch) => canSeeChannel(ch, auth)).map((ch) => ch.id);
|
|
@@ -10580,7 +10826,7 @@ function createNotificationsRouter() {
|
|
|
10580
10826
|
return notifications;
|
|
10581
10827
|
}
|
|
10582
10828
|
function createThreadReadRouter() {
|
|
10583
|
-
const threads = new
|
|
10829
|
+
const threads = new Hono23();
|
|
10584
10830
|
threads.post("/threads/:threadId/read", async (c) => {
|
|
10585
10831
|
const { userId } = c.get("auth");
|
|
10586
10832
|
const threadId = c.req.param("threadId");
|
|
@@ -10588,13 +10834,25 @@ function createThreadReadRouter() {
|
|
|
10588
10834
|
await markThreadRead(userId, threadId);
|
|
10589
10835
|
return c.json({ ok: true });
|
|
10590
10836
|
});
|
|
10837
|
+
threads.get("/threads/:threadId/workspace", async (c) => {
|
|
10838
|
+
const { userId } = c.get("auth");
|
|
10839
|
+
const owner = await resolveThreadOwner(c.req.param("threadId"));
|
|
10840
|
+
if (!owner || !await canReadThread(owner, userId)) {
|
|
10841
|
+
return c.json({ error: "not found" }, 404);
|
|
10842
|
+
}
|
|
10843
|
+
return c.json({
|
|
10844
|
+
workspace: owner.workspace,
|
|
10845
|
+
channelId: owner.channelId,
|
|
10846
|
+
threadId: owner.threadId
|
|
10847
|
+
});
|
|
10848
|
+
});
|
|
10591
10849
|
return threads;
|
|
10592
10850
|
}
|
|
10593
10851
|
|
|
10594
10852
|
// ../api/src/dashboard/push-routes.ts
|
|
10595
|
-
import { Hono as
|
|
10853
|
+
import { Hono as Hono24 } from "hono";
|
|
10596
10854
|
function createPushRouter() {
|
|
10597
|
-
const push = new
|
|
10855
|
+
const push = new Hono24();
|
|
10598
10856
|
push.get("/key", (c) => c.json({ publicKey: getVapidPublicKey() }));
|
|
10599
10857
|
push.post("/subscribe", async (c) => {
|
|
10600
10858
|
const { userId } = c.get("auth");
|
|
@@ -10625,7 +10883,7 @@ function createPushRouter() {
|
|
|
10625
10883
|
}
|
|
10626
10884
|
|
|
10627
10885
|
// ../api/src/dashboard/mcp-oauth-routes.ts
|
|
10628
|
-
import { Hono as
|
|
10886
|
+
import { Hono as Hono25 } from "hono";
|
|
10629
10887
|
var CONNECTIONS_PAGE = "/settings/connections";
|
|
10630
10888
|
function callbackUri(c) {
|
|
10631
10889
|
const proto = c.req.header("x-forwarded-proto") ?? "http";
|
|
@@ -10640,7 +10898,7 @@ function backToDashboard(c, to, params) {
|
|
|
10640
10898
|
return c.redirect(`${target.pathname}${target.search}`);
|
|
10641
10899
|
}
|
|
10642
10900
|
function createMcpOAuthRouter() {
|
|
10643
|
-
const app = new
|
|
10901
|
+
const app = new Hono25();
|
|
10644
10902
|
app.get("/oauth/:provider/start", async (c) => {
|
|
10645
10903
|
const auth = c.get("auth");
|
|
10646
10904
|
if (auth.role !== "admin") return c.json({ error: "admin access required" }, 403);
|
|
@@ -10767,7 +11025,7 @@ function createMcpOAuthRouter() {
|
|
|
10767
11025
|
}
|
|
10768
11026
|
|
|
10769
11027
|
// ../api/src/dashboard/mcp-routes.ts
|
|
10770
|
-
import { Hono as
|
|
11028
|
+
import { Hono as Hono26 } from "hono";
|
|
10771
11029
|
|
|
10772
11030
|
// ../api/src/mcp/transport.ts
|
|
10773
11031
|
var KINDS = ["inherit", "npx", "local", "http", "sse"];
|
|
@@ -10897,7 +11155,7 @@ function bindingsByConnection() {
|
|
|
10897
11155
|
return map;
|
|
10898
11156
|
}
|
|
10899
11157
|
function createMcpRouter() {
|
|
10900
|
-
const app = new
|
|
11158
|
+
const app = new Hono26();
|
|
10901
11159
|
app.get("/providers", async (c) => {
|
|
10902
11160
|
const denied = requireAdmin(c.get("auth"));
|
|
10903
11161
|
if (denied) return c.json({ error: denied }, 403);
|
|
@@ -11293,7 +11551,7 @@ async function buildChannelUsageReport(channelId, days, labelChannel) {
|
|
|
11293
11551
|
}
|
|
11294
11552
|
}
|
|
11295
11553
|
}
|
|
11296
|
-
var COMPACT_THRESHOLD_TOKENS = Number(process.env["SESSION_COMPACT_THRESHOLD_TOKENS"]) ||
|
|
11554
|
+
var COMPACT_THRESHOLD_TOKENS = Number(process.env["SESSION_COMPACT_THRESHOLD_TOKENS"]) || 8e4;
|
|
11297
11555
|
function contextOf(run4) {
|
|
11298
11556
|
if (!run4) return void 0;
|
|
11299
11557
|
const total = run4.inputTokens + run4.cacheReadTokens + run4.cacheCreationTokens;
|
|
@@ -11341,7 +11599,7 @@ var SYSTEM_PROMPT2 = `You review how an AI coding agent spent money in one chat
|
|
|
11341
11599
|
- Only habits the user controls. Never mention billing, pricing, cost accounting or the app's own bugs, even if the transcript discusses them: the thread's topic is not a cost driver. Never suggest switching models; the user does not pick the model per turn.
|
|
11342
11600
|
- cache_read and context_total are summed over every API call inside one run (turns=N), so a large figure means many steps, not a huge context. Do not call it context size.
|
|
11343
11601
|
- Be brief: problem at most 6 words, detail one short clause with a number from the data (at most 15 words), fix one short imperative clause (at most 12 words).
|
|
11344
|
-
- Write in the language the user
|
|
11602
|
+
- Write headline, problem, detail and fix entirely in the output language given in the user message, whatever language the transcript is in. For Traditional Chinese (zh-TW), use Taiwan wording, full-width punctuation, Arabic numerals, and keep technical terms in English.
|
|
11345
11603
|
- Never use em dashes or en dashes. No Markdown.`;
|
|
11346
11604
|
function runLine(r, i) {
|
|
11347
11605
|
const ctx = r.inputTokens + r.cacheReadTokens + r.cacheCreationTokens;
|
|
@@ -11379,7 +11637,7 @@ function parseJson(raw) {
|
|
|
11379
11637
|
return null;
|
|
11380
11638
|
}
|
|
11381
11639
|
}
|
|
11382
|
-
async function buildSessionRetro(threadId, complete) {
|
|
11640
|
+
async function buildSessionRetro(threadId, complete, locale = "en") {
|
|
11383
11641
|
const runs2 = await threadRuns(getProfile(), threadId);
|
|
11384
11642
|
if (runs2.length === 0) return null;
|
|
11385
11643
|
const { data, error: error2 } = await getSupabaseClient().from("thread_replies").select("author, body, activities").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: true });
|
|
@@ -11399,7 +11657,9 @@ async function buildSessionRetro(threadId, complete) {
|
|
|
11399
11657
|
channelId: thread.channel_id,
|
|
11400
11658
|
tier: "cheap",
|
|
11401
11659
|
system: SYSTEM_PROMPT2,
|
|
11402
|
-
user: `
|
|
11660
|
+
user: `Output language: ${locale}
|
|
11661
|
+
|
|
11662
|
+
Total: $${costUsd.toFixed(2)} over ${runs2.length} runs.
|
|
11403
11663
|
|
|
11404
11664
|
Runs (oldest first):
|
|
11405
11665
|
${runs2.map(runLine).join("\n")}
|
|
@@ -11425,9 +11685,9 @@ ${transcriptOf(data ?? [])}`
|
|
|
11425
11685
|
}
|
|
11426
11686
|
|
|
11427
11687
|
// ../api/src/dashboard/permission-routes.ts
|
|
11428
|
-
import { Hono as
|
|
11688
|
+
import { Hono as Hono27 } from "hono";
|
|
11429
11689
|
function createPermissionRequestsRouter() {
|
|
11430
|
-
const app = new
|
|
11690
|
+
const app = new Hono27();
|
|
11431
11691
|
app.post("/:id", async (c) => {
|
|
11432
11692
|
const auth = c.get("auth");
|
|
11433
11693
|
if (auth.role !== "admin") return c.json({ error: "only an admin can answer this" }, 403);
|
|
@@ -11457,7 +11717,7 @@ function createPermissionRequestsRouter() {
|
|
|
11457
11717
|
}
|
|
11458
11718
|
|
|
11459
11719
|
// ../api/src/dashboard/channel-greeting.ts
|
|
11460
|
-
import { Hono as
|
|
11720
|
+
import { Hono as Hono28 } from "hono";
|
|
11461
11721
|
function eligible(ch) {
|
|
11462
11722
|
return !!ch && !ch.isDefault && !ch.dmKey && !ch.agentName && !ch.archivedAt;
|
|
11463
11723
|
}
|
|
@@ -11486,7 +11746,7 @@ function introOpening(channelName) {
|
|
|
11486
11746
|
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.`;
|
|
11487
11747
|
}
|
|
11488
11748
|
function createChannelGreetingRouter(agent) {
|
|
11489
|
-
const app = new
|
|
11749
|
+
const app = new Hono28();
|
|
11490
11750
|
app.get("/:id/greeting", async (c) => {
|
|
11491
11751
|
const ctx = await resolveAuthContext(c);
|
|
11492
11752
|
const ch = findChannelById(c.req.param("id"));
|
|
@@ -11544,7 +11804,7 @@ async function ensureIntroThread(ch) {
|
|
|
11544
11804
|
}
|
|
11545
11805
|
|
|
11546
11806
|
// ../api/src/dashboard/channel-suggest.ts
|
|
11547
|
-
import { Hono as
|
|
11807
|
+
import { Hono as Hono29 } from "hono";
|
|
11548
11808
|
var CATEGORY_MAX_CHARS = 16;
|
|
11549
11809
|
var CATEGORY_MAX_ITEMS = 30;
|
|
11550
11810
|
var PROMPT_MAX_CHARS = 4e3;
|
|
@@ -11592,7 +11852,7 @@ function parseSuggestion(field, raw) {
|
|
|
11592
11852
|
return items2.length ? items2.slice(0, CATEGORY_MAX_ITEMS).join("\n") : null;
|
|
11593
11853
|
}
|
|
11594
11854
|
function createChannelSuggestRouter(agent) {
|
|
11595
|
-
const router = new
|
|
11855
|
+
const router = new Hono29();
|
|
11596
11856
|
router.post("/:id/suggest", async (c) => {
|
|
11597
11857
|
const channel = findChannel(c.req.param("id"));
|
|
11598
11858
|
if (!channel || !canSeeChannel(channel, c.get("auth"))) {
|
|
@@ -11630,7 +11890,7 @@ function createChannelSuggestRouter(agent) {
|
|
|
11630
11890
|
}
|
|
11631
11891
|
|
|
11632
11892
|
// ../api/src/dashboard/channel-members-routes.ts
|
|
11633
|
-
import { Hono as
|
|
11893
|
+
import { Hono as Hono30 } from "hono";
|
|
11634
11894
|
async function isChannelAdmin(ctx, channelId) {
|
|
11635
11895
|
if (ctx.role === "admin") return true;
|
|
11636
11896
|
const membership = await getMembershipByUserId(ctx.workspaceId, ctx.userId);
|
|
@@ -11639,7 +11899,7 @@ async function isChannelAdmin(ctx, channelId) {
|
|
|
11639
11899
|
return members.some((m) => m.membershipId === membership.id && m.role === "channel_admin");
|
|
11640
11900
|
}
|
|
11641
11901
|
function createChannelMembersRouter() {
|
|
11642
|
-
const router = new
|
|
11902
|
+
const router = new Hono30();
|
|
11643
11903
|
router.get("/:id/members", async (c) => {
|
|
11644
11904
|
const ctx = await resolveAuthContext(c);
|
|
11645
11905
|
if (!ctx) return c.json({ error: "workspace access required" }, 403);
|
|
@@ -11709,7 +11969,7 @@ function createChannelMembersRouter() {
|
|
|
11709
11969
|
}
|
|
11710
11970
|
|
|
11711
11971
|
// ../api/src/dashboard/memories-routes.ts
|
|
11712
|
-
import { Hono as
|
|
11972
|
+
import { Hono as Hono31 } from "hono";
|
|
11713
11973
|
async function readPatch(c) {
|
|
11714
11974
|
const body = await c.req.json().catch(() => ({}));
|
|
11715
11975
|
const patch = {};
|
|
@@ -11737,7 +11997,7 @@ var requireAgentMemory = async (c, next) => {
|
|
|
11737
11997
|
await next();
|
|
11738
11998
|
};
|
|
11739
11999
|
function createMemoriesRouter() {
|
|
11740
|
-
const router = new
|
|
12000
|
+
const router = new Hono31();
|
|
11741
12001
|
for (const path of [
|
|
11742
12002
|
"/:id/memories",
|
|
11743
12003
|
"/:id/memories/*",
|
|
@@ -11810,7 +12070,7 @@ function createMemoriesRouter() {
|
|
|
11810
12070
|
return router;
|
|
11811
12071
|
}
|
|
11812
12072
|
function createScopedMemoriesRouter() {
|
|
11813
|
-
const router = new
|
|
12073
|
+
const router = new Hono31();
|
|
11814
12074
|
router.use("*", requireAgentMemory);
|
|
11815
12075
|
const workspace = (c) => ({
|
|
11816
12076
|
scope: "workspace",
|
|
@@ -11870,9 +12130,9 @@ function createScopedMemoriesRouter() {
|
|
|
11870
12130
|
}
|
|
11871
12131
|
|
|
11872
12132
|
// ../api/src/dashboard/session-import-routes.ts
|
|
11873
|
-
import { Hono as
|
|
12133
|
+
import { Hono as Hono32 } from "hono";
|
|
11874
12134
|
var MAX_FOLDERS2 = 20;
|
|
11875
|
-
var
|
|
12135
|
+
var DAY_MS2 = 24 * 60 * 60 * 1e3;
|
|
11876
12136
|
var IMPORT_RANGES = ["all", "7d", "latest5"];
|
|
11877
12137
|
async function ask(agent, req) {
|
|
11878
12138
|
const res = await agent.sessionImportRequest?.(req);
|
|
@@ -11889,7 +12149,7 @@ function hostUnavailable2(c, agent) {
|
|
|
11889
12149
|
}
|
|
11890
12150
|
function pickSessions(sessions2, range, now = Date.now()) {
|
|
11891
12151
|
if (range === "latest5") return sessions2.slice(0, 5);
|
|
11892
|
-
if (range === "7d") return sessions2.filter((s) => s.lastUsed >= now - 7 *
|
|
12152
|
+
if (range === "7d") return sessions2.filter((s) => s.lastUsed >= now - 7 * DAY_MS2);
|
|
11893
12153
|
return sessions2;
|
|
11894
12154
|
}
|
|
11895
12155
|
function channelForFolder(folder, channels) {
|
|
@@ -11917,8 +12177,9 @@ var rowKey = (channelId, agent, sessionId) => `${channelId}:${agent}:${sessionId
|
|
|
11917
12177
|
function replyRows(threadId, messages, author, fallbackAt) {
|
|
11918
12178
|
return messages.map((m, i) => ({
|
|
11919
12179
|
thread_id: threadId,
|
|
11920
|
-
author: m.role === "user" ? author : AGENT_AUTHOR,
|
|
12180
|
+
author: m.role === "user" && !m.compactSummary ? author : AGENT_AUTHOR,
|
|
11921
12181
|
body: m.text,
|
|
12182
|
+
...m.compactSummary ? { author_kind: "compact_summary" } : {},
|
|
11922
12183
|
created_at: m.at ?? new Date(fallbackAt + i).toISOString()
|
|
11923
12184
|
}));
|
|
11924
12185
|
}
|
|
@@ -11976,7 +12237,7 @@ async function syncSession(agent, channelId, session, author, existing) {
|
|
|
11976
12237
|
return messages.length;
|
|
11977
12238
|
}
|
|
11978
12239
|
function createSessionImportRouter(agent) {
|
|
11979
|
-
const app = new
|
|
12240
|
+
const app = new Hono32();
|
|
11980
12241
|
const scanFolders = async () => {
|
|
11981
12242
|
const scan = await ask(agent, { op: "scan", slug: getProfile() });
|
|
11982
12243
|
return scan && importableFolders(scan.folders, getProfileChannelRegistry());
|
|
@@ -12244,7 +12505,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12244
12505
|
categoryId: ch.categoryId,
|
|
12245
12506
|
position: ch.position,
|
|
12246
12507
|
// A DM is stored as "<a>, <b>"; each side sees the other's handle.
|
|
12247
|
-
name: ch.dmKey ? ch.name.split(", ").filter((h) => h !== auth.handle).join(", ") || ch.name : ch.name,
|
|
12508
|
+
name: ch.dmKey && !ch.agentName ? ch.name.split(", ").filter((h) => h !== auth.handle).join(", ") || ch.name : ch.name,
|
|
12248
12509
|
configured: true,
|
|
12249
12510
|
cwd: ch.cwd,
|
|
12250
12511
|
// Surfaces a rotted working directory in the sidebar instead of
|
|
@@ -12388,13 +12649,16 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12388
12649
|
if (!await isFeatureEnabled(c, "session-retro")) return c.json({ error: "feature not enabled" }, 403);
|
|
12389
12650
|
const complete = agent.completeMemoryExtraction;
|
|
12390
12651
|
if (!complete) return c.json({ error: "host offline" }, 503);
|
|
12391
|
-
const
|
|
12652
|
+
const body = await c.req.json().catch(() => ({}));
|
|
12653
|
+
const locale = typeof body.locale === "string" && /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(body.locale) ? body.locale : "en";
|
|
12654
|
+
const retro = await buildSessionRetro(c.req.param("threadTs"), complete, locale);
|
|
12392
12655
|
if (retro === "host-offline") return c.json({ error: "host offline" }, 503);
|
|
12393
12656
|
if (!retro) return c.json({ error: "could not generate a retro" }, 502);
|
|
12394
12657
|
return c.json(retro);
|
|
12395
12658
|
});
|
|
12396
12659
|
api.route("/automations", createAutomationWriteRouter());
|
|
12397
12660
|
api.route("/billing", createBillingRouter());
|
|
12661
|
+
api.route("/chat", createContinuousChatRouter());
|
|
12398
12662
|
api.route("/chat", createChatRouter(agent));
|
|
12399
12663
|
api.route("/search", createSearchRouter());
|
|
12400
12664
|
api.use("/tts/*", async (c, next) => {
|
|
@@ -12482,6 +12746,8 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12482
12746
|
api.route("/", createUploadsRouter());
|
|
12483
12747
|
api.route("/", createTranscribeRouter());
|
|
12484
12748
|
api.route("/", createAutocompleteRouter());
|
|
12749
|
+
api.route("/", createDailyLineRouter());
|
|
12750
|
+
api.route("/", createChannelRouteRouter());
|
|
12485
12751
|
api.route("/", createAvatarsRouter());
|
|
12486
12752
|
api.get("/profiles", async (c) => {
|
|
12487
12753
|
const active = getProfile();
|
|
@@ -12491,18 +12757,23 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12491
12757
|
const running2 = new Set(await agent.listRunningProfiles?.() ?? []);
|
|
12492
12758
|
const auth = c.get("auth");
|
|
12493
12759
|
const [{ data: memberships }, workspaces] = await Promise.all([
|
|
12494
|
-
getSupabaseClient().from("memberships").select("workspace_id").eq("user_id", auth.userId),
|
|
12760
|
+
getSupabaseClient().from("memberships").select("workspace_id").eq("user_id", auth.userId).eq("status", "active").eq("is_support", false),
|
|
12495
12761
|
listWorkspaces()
|
|
12496
12762
|
]);
|
|
12497
12763
|
const memberOf = new Set(
|
|
12498
12764
|
(memberships ?? []).map((m) => m.workspace_id)
|
|
12499
12765
|
);
|
|
12500
|
-
const
|
|
12501
|
-
allowed.
|
|
12766
|
+
const live = workspaces.filter((w) => !w.archivedAt);
|
|
12767
|
+
const allowed = new Set(live.filter((w) => memberOf.has(w.id)).map((w) => w.slug));
|
|
12768
|
+
if (live.some((w) => w.slug === active)) allowed.add(active);
|
|
12769
|
+
const bySlug = new Map(live.map((w) => [w.slug, w]));
|
|
12502
12770
|
const list = await Promise.all(
|
|
12503
12771
|
known.filter((name) => allowed.has(name)).map(async (name) => {
|
|
12504
12772
|
const branding = await loadWorkspaceBranding(name);
|
|
12773
|
+
const w = bySlug.get(name);
|
|
12774
|
+
const billing = w?.planStatus === "canceled" ? "expired" : w?.planStatus === "paused" || w?.trialEndsAt && Date.parse(w.trialEndsAt) < Date.now() ? "trial_ended" : void 0;
|
|
12505
12775
|
return {
|
|
12776
|
+
billing,
|
|
12506
12777
|
name,
|
|
12507
12778
|
active: name === active,
|
|
12508
12779
|
running: running2.has(name),
|
|
@@ -12579,7 +12850,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12579
12850
|
// ../api/src/dashboard/device-auth-routes.ts
|
|
12580
12851
|
import { verify } from "crypto";
|
|
12581
12852
|
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
12582
|
-
import { Hono as
|
|
12853
|
+
import { Hono as Hono33 } from "hono";
|
|
12583
12854
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12584
12855
|
function cleanText(value, max) {
|
|
12585
12856
|
if (typeof value !== "string") return null;
|
|
@@ -12609,7 +12880,7 @@ async function readBody(c) {
|
|
|
12609
12880
|
return {};
|
|
12610
12881
|
}
|
|
12611
12882
|
}
|
|
12612
|
-
async function
|
|
12883
|
+
async function sessionUserId(c) {
|
|
12613
12884
|
try {
|
|
12614
12885
|
const { data } = await createRequestSupabaseClient(c).auth.getUser();
|
|
12615
12886
|
return data.user?.id ?? null;
|
|
@@ -12627,7 +12898,7 @@ async function boundWorkspaceIds(publicKey, userId) {
|
|
|
12627
12898
|
return new Set(existing ? (await listDeviceWorkspaces(existing)).map((w) => w.id) : []);
|
|
12628
12899
|
}
|
|
12629
12900
|
function createDeviceAuthRouter() {
|
|
12630
|
-
const app = new
|
|
12901
|
+
const app = new Hono33();
|
|
12631
12902
|
app.post("/code", async (c) => {
|
|
12632
12903
|
const body = await readBody(c);
|
|
12633
12904
|
const publicKey = typeof body["public_key"] === "string" ? body["public_key"] : "";
|
|
@@ -12712,7 +12983,7 @@ function createDeviceAuthRouter() {
|
|
|
12712
12983
|
return c.json({ ok: true });
|
|
12713
12984
|
});
|
|
12714
12985
|
app.get("/lookup", async (c) => {
|
|
12715
|
-
const userId = await
|
|
12986
|
+
const userId = await sessionUserId(c);
|
|
12716
12987
|
if (!userId) return c.json({ error: "not signed in" }, 401);
|
|
12717
12988
|
const userCode = normalizeUserCode(c.req.query("user_code") ?? "");
|
|
12718
12989
|
const pending = userCode ? await getDeviceCodeByUserCode(userCode) : null;
|
|
@@ -12737,7 +13008,7 @@ function createDeviceAuthRouter() {
|
|
|
12737
13008
|
});
|
|
12738
13009
|
});
|
|
12739
13010
|
app.get("/workspace", async (c) => {
|
|
12740
|
-
const userId = await
|
|
13011
|
+
const userId = await sessionUserId(c);
|
|
12741
13012
|
if (!userId) return c.json({ error: "not signed in" }, 401);
|
|
12742
13013
|
const slug = getProfile();
|
|
12743
13014
|
const workspace = (await listAdminWorkspaces(userId)).find((w) => w.slug === slug);
|
|
@@ -12750,7 +13021,7 @@ function createDeviceAuthRouter() {
|
|
|
12750
13021
|
});
|
|
12751
13022
|
});
|
|
12752
13023
|
app.post("/approve", async (c) => {
|
|
12753
|
-
const userId = await
|
|
13024
|
+
const userId = await sessionUserId(c);
|
|
12754
13025
|
if (!userId) return c.json({ error: "not signed in" }, 401);
|
|
12755
13026
|
const body = await readBody(c);
|
|
12756
13027
|
const userCode = normalizeUserCode(typeof body["user_code"] === "string" ? body["user_code"] : "");
|
|
@@ -12946,7 +13217,7 @@ var workspaceRef = () => ({ kind: "workspace" });
|
|
|
12946
13217
|
var channelRef = (c) => ({ kind: "channel", channelId: c.req.param("id") });
|
|
12947
13218
|
|
|
12948
13219
|
// ../api/src/dashboard/output-styles-routes.ts
|
|
12949
|
-
import { Hono as
|
|
13220
|
+
import { Hono as Hono34 } from "hono";
|
|
12950
13221
|
function requireAdmin3(auth) {
|
|
12951
13222
|
return auth?.role === "admin" ? null : "admin access required";
|
|
12952
13223
|
}
|
|
@@ -12966,7 +13237,7 @@ function failure(c, err) {
|
|
|
12966
13237
|
return c.json({ error: message }, err instanceof OutputStyleConflictError ? 409 : 500);
|
|
12967
13238
|
}
|
|
12968
13239
|
function createOutputStylesRouter() {
|
|
12969
|
-
const app = new
|
|
13240
|
+
const app = new Hono34();
|
|
12970
13241
|
app.get("/", (c) => {
|
|
12971
13242
|
const auth = c.get("auth");
|
|
12972
13243
|
const denied = requireAdmin3(auth);
|
|
@@ -13058,7 +13329,7 @@ function createOutputStylesRouter() {
|
|
|
13058
13329
|
return app;
|
|
13059
13330
|
}
|
|
13060
13331
|
async function handleOutputStylesRequest(req) {
|
|
13061
|
-
const app = new
|
|
13332
|
+
const app = new Hono34();
|
|
13062
13333
|
app.use("*", async (c, next) => {
|
|
13063
13334
|
c.set("auth", { role: "admin" });
|
|
13064
13335
|
await next();
|
|
@@ -13088,15 +13359,16 @@ async function viewerProfile(c, known) {
|
|
|
13088
13359
|
listMembershipsByEmail(user.email),
|
|
13089
13360
|
listWorkspaces()
|
|
13090
13361
|
]);
|
|
13091
|
-
const
|
|
13092
|
-
|
|
13093
|
-
|
|
13094
|
-
|
|
13095
|
-
}
|
|
13096
|
-
|
|
13362
|
+
const byId = new Map(workspaces.filter((w) => !w.archivedAt).map((w) => [w.id, w]));
|
|
13363
|
+
const candidates = memberships.map((m) => ({ m, w: byId.get(m.workspaceId) })).filter(
|
|
13364
|
+
(x) => !!x.w && known.includes(x.w.slug)
|
|
13365
|
+
);
|
|
13366
|
+
const rank = ({ m, w }) => (m.isSupport ? 2 : 0) + (isLockedPlan(w.planStatus ?? null) ? 1 : 0);
|
|
13367
|
+
candidates.sort((a, b) => rank(a) - rank(b));
|
|
13368
|
+
return candidates[0]?.w.slug ?? null;
|
|
13097
13369
|
}
|
|
13098
13370
|
function createGatedRouter(agent, register) {
|
|
13099
|
-
const api = new
|
|
13371
|
+
const api = new Hono35();
|
|
13100
13372
|
api.use("*", async (c, next) => {
|
|
13101
13373
|
const known = await listKnownWorkspaces();
|
|
13102
13374
|
const fromHost = profileFromHost(trustedHost(c), known);
|
|
@@ -13116,8 +13388,8 @@ function createGatedRouter(agent, register) {
|
|
|
13116
13388
|
api.get("/public-branding", async (c) => {
|
|
13117
13389
|
const requested = c.req.query("workspace");
|
|
13118
13390
|
const known = await listKnownWorkspaces();
|
|
13119
|
-
const
|
|
13120
|
-
if (!
|
|
13391
|
+
const resolved = requested && known.includes(requested) ? requested : profileFromHost(trustedHost(c), known);
|
|
13392
|
+
if (!resolved) {
|
|
13121
13393
|
return c.json({
|
|
13122
13394
|
unknownWorkspace: isUnknownWorkspaceHost(trustedHost(c), known),
|
|
13123
13395
|
theme: BRANDING_DEFAULTS.theme,
|
|
@@ -13128,7 +13400,7 @@ function createGatedRouter(agent, register) {
|
|
|
13128
13400
|
logo: "/icons/favicon-64.png"
|
|
13129
13401
|
});
|
|
13130
13402
|
}
|
|
13131
|
-
const branding = await loadWorkspaceBranding(
|
|
13403
|
+
const branding = await loadWorkspaceBranding(resolved);
|
|
13132
13404
|
return c.json({
|
|
13133
13405
|
theme: branding.theme,
|
|
13134
13406
|
font: branding.font,
|
|
@@ -13143,12 +13415,12 @@ function createGatedRouter(agent, register) {
|
|
|
13143
13415
|
}
|
|
13144
13416
|
|
|
13145
13417
|
// src/dashboard/host-api.ts
|
|
13146
|
-
import { existsSync as existsSync24, readFileSync as
|
|
13418
|
+
import { existsSync as existsSync24, readFileSync as readFileSync18, statSync as statSync5 } from "fs";
|
|
13147
13419
|
import sharp5 from "sharp";
|
|
13148
13420
|
|
|
13149
13421
|
// src/dashboard/channels-routes.ts
|
|
13150
13422
|
import { existsSync as existsSync20, mkdirSync as mkdirSync9 } from "fs";
|
|
13151
|
-
import { Hono as
|
|
13423
|
+
import { Hono as Hono36 } from "hono";
|
|
13152
13424
|
function coerceAccess(raw) {
|
|
13153
13425
|
if (raw === "open" || raw === "*" || raw === "all") return raw;
|
|
13154
13426
|
if (Array.isArray(raw) && raw.every((v) => typeof v === "string")) return raw;
|
|
@@ -13220,7 +13492,7 @@ function toResponse3(channel) {
|
|
|
13220
13492
|
};
|
|
13221
13493
|
}
|
|
13222
13494
|
function createChannelWriteRouter() {
|
|
13223
|
-
const app = new
|
|
13495
|
+
const app = new Hono36();
|
|
13224
13496
|
app.post("/", async (c) => {
|
|
13225
13497
|
const body = await c.req.json().catch(() => ({}));
|
|
13226
13498
|
const name = typeof body["name"] === "string" ? body["name"].trim() : "";
|
|
@@ -13349,7 +13621,7 @@ function createChannelWriteRouter() {
|
|
|
13349
13621
|
// src/dashboard/skills-routes-host.ts
|
|
13350
13622
|
import { existsSync as existsSync21, statSync as statSync4 } from "fs";
|
|
13351
13623
|
import { dirname as dirname8 } from "path";
|
|
13352
|
-
import { Hono as
|
|
13624
|
+
import { Hono as Hono37 } from "hono";
|
|
13353
13625
|
function workspaceScope() {
|
|
13354
13626
|
const claudeConfigDir = profileClaudeConfigDir();
|
|
13355
13627
|
const cwd = defaultClaudeCwd();
|
|
@@ -13455,35 +13727,32 @@ var diskBackend = {
|
|
|
13455
13727
|
write: writeSkillAndSync
|
|
13456
13728
|
};
|
|
13457
13729
|
function createWorkspaceSkillsRouter() {
|
|
13458
|
-
const app = new
|
|
13730
|
+
const app = new Hono37();
|
|
13459
13731
|
mountSkillRoutes(app, "/skills", workspaceRef, diskBackend);
|
|
13460
13732
|
return app;
|
|
13461
13733
|
}
|
|
13462
13734
|
function createChannelSkillsRouter() {
|
|
13463
|
-
const app = new
|
|
13735
|
+
const app = new Hono37();
|
|
13464
13736
|
mountSkillRoutes(app, "/:id/skill-files", channelRef, diskBackend);
|
|
13465
13737
|
return app;
|
|
13466
13738
|
}
|
|
13467
13739
|
|
|
13468
13740
|
// src/dashboard/agent-identities-host.ts
|
|
13469
|
-
async function resolveAgentIdentities() {
|
|
13741
|
+
async function resolveAgentIdentities(viewer) {
|
|
13470
13742
|
const settings = loadDashboardSettings();
|
|
13471
|
-
const { cwd: defaultCwd } = resolveChannelConfig("");
|
|
13472
13743
|
const main2 = [
|
|
13473
13744
|
{
|
|
13474
13745
|
name: BOT_DM_KEY,
|
|
13475
13746
|
label: BOT_LABEL,
|
|
13476
13747
|
kind: "main",
|
|
13477
|
-
cwd: defaultCwd,
|
|
13478
13748
|
model: settings.agentProfiles?.[BOT_DM_KEY]?.model,
|
|
13479
13749
|
...await loadBotIdentity()
|
|
13480
13750
|
}
|
|
13481
13751
|
];
|
|
13482
13752
|
return Promise.all(
|
|
13483
|
-
main2.map(async (
|
|
13484
|
-
const dm = await ensureAgentDmChannel(agent.name, {
|
|
13485
|
-
name: agent.displayName ?? agent.label
|
|
13486
|
-
cwd
|
|
13753
|
+
main2.map(async (agent) => {
|
|
13754
|
+
const dm = await ensureAgentDmChannel(agent.name, viewer, {
|
|
13755
|
+
name: agent.displayName ?? agent.label
|
|
13487
13756
|
});
|
|
13488
13757
|
return { ...agent, channelId: dm.id };
|
|
13489
13758
|
})
|
|
@@ -13492,7 +13761,7 @@ async function resolveAgentIdentities() {
|
|
|
13492
13761
|
|
|
13493
13762
|
// ../api/src/dashboard/providers.ts
|
|
13494
13763
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
13495
|
-
import { existsSync as existsSync22, readFileSync as
|
|
13764
|
+
import { existsSync as existsSync22, readFileSync as readFileSync16 } from "fs";
|
|
13496
13765
|
import { homedir as homedir7 } from "os";
|
|
13497
13766
|
import { join as join14, resolve as resolve5 } from "path";
|
|
13498
13767
|
var PROVIDER_LABELS = {
|
|
@@ -13500,9 +13769,9 @@ var PROVIDER_LABELS = {
|
|
|
13500
13769
|
codex: "Codex"
|
|
13501
13770
|
};
|
|
13502
13771
|
var TTL_MS2 = 6e4;
|
|
13503
|
-
var
|
|
13772
|
+
var cache4 = /* @__PURE__ */ new Map();
|
|
13504
13773
|
function clearProviderStatusCache() {
|
|
13505
|
-
|
|
13774
|
+
cache4.clear();
|
|
13506
13775
|
}
|
|
13507
13776
|
function binaryOnPath(bin) {
|
|
13508
13777
|
try {
|
|
@@ -13561,7 +13830,7 @@ function claudeAccount() {
|
|
|
13561
13830
|
function codexAccount() {
|
|
13562
13831
|
const home2 = process.env["CODEX_HOME"]?.trim() || join14(homedir7(), ".codex");
|
|
13563
13832
|
try {
|
|
13564
|
-
const auth = JSON.parse(
|
|
13833
|
+
const auth = JSON.parse(readFileSync16(join14(home2, "auth.json"), "utf8"));
|
|
13565
13834
|
const payload = auth.tokens?.id_token?.split(".")[1];
|
|
13566
13835
|
if (!payload) return void 0;
|
|
13567
13836
|
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
@@ -13580,11 +13849,11 @@ function withAuthFailure(status) {
|
|
|
13580
13849
|
}
|
|
13581
13850
|
function providerStatuses() {
|
|
13582
13851
|
const key = getProfile();
|
|
13583
|
-
const hit =
|
|
13852
|
+
const hit = cache4.get(key);
|
|
13584
13853
|
let statuses = hit && Date.now() - hit.at < TTL_MS2 ? hit.statuses : void 0;
|
|
13585
13854
|
if (!statuses) {
|
|
13586
13855
|
statuses = ["claude", "codex"].map(probe2);
|
|
13587
|
-
|
|
13856
|
+
cache4.set(key, { at: Date.now(), statuses });
|
|
13588
13857
|
}
|
|
13589
13858
|
return statuses.map((st) => st.runner === "claude" && st.connected ? withAuthFailure(st) : st);
|
|
13590
13859
|
}
|
|
@@ -13592,10 +13861,10 @@ function providerStatuses() {
|
|
|
13592
13861
|
// src/dashboard/provider-login-host.ts
|
|
13593
13862
|
import { spawn as spawn4 } from "child_process";
|
|
13594
13863
|
import { randomUUID as randomUUID4 } from "crypto";
|
|
13595
|
-
import { chmodSync, existsSync as existsSync23, mkdirSync as mkdirSync10, readFileSync as
|
|
13864
|
+
import { chmodSync, existsSync as existsSync23, mkdirSync as mkdirSync10, readFileSync as readFileSync17, writeFileSync as writeFileSync9 } from "fs";
|
|
13596
13865
|
import { createRequire } from "module";
|
|
13597
13866
|
import { dirname as dirname9, join as join15 } from "path";
|
|
13598
|
-
import { Hono as
|
|
13867
|
+
import { Hono as Hono38 } from "hono";
|
|
13599
13868
|
var SESSION_TTL_MS = 10 * 6e4;
|
|
13600
13869
|
var URL_WAIT_MS = 3e4;
|
|
13601
13870
|
var TOKEN_WAIT_MS = 6e4;
|
|
@@ -13701,7 +13970,7 @@ async function startClaude() {
|
|
|
13701
13970
|
}
|
|
13702
13971
|
function saveClaudeToken(configFile, token) {
|
|
13703
13972
|
mkdirSync10(dirname9(configFile), { recursive: true });
|
|
13704
|
-
const current = existsSync23(configFile) ?
|
|
13973
|
+
const current = existsSync23(configFile) ? readFileSync17(configFile, "utf-8") : "";
|
|
13705
13974
|
writeFileSync9(configFile, upsertEnvLine(current, "CLAUDE_CODE_OAUTH_TOKEN", token), { mode: 384 });
|
|
13706
13975
|
const cached = cachedProfileConfig();
|
|
13707
13976
|
if (cached) cached.env["CLAUDE_CODE_OAUTH_TOKEN"] = token;
|
|
@@ -13754,7 +14023,7 @@ function failure2(c, err) {
|
|
|
13754
14023
|
return c.json({ error: err.message }, 500);
|
|
13755
14024
|
}
|
|
13756
14025
|
function createProviderLoginRouter() {
|
|
13757
|
-
const app = new
|
|
14026
|
+
const app = new Hono38();
|
|
13758
14027
|
app.use("*", async (c, next) => {
|
|
13759
14028
|
const denied = requireAdmin4(c.get("auth"));
|
|
13760
14029
|
if (denied) return c.json({ error: denied }, 403);
|
|
@@ -13798,7 +14067,7 @@ function createProviderLoginRouter() {
|
|
|
13798
14067
|
return app;
|
|
13799
14068
|
}
|
|
13800
14069
|
async function handleProviderLoginRequest(req) {
|
|
13801
|
-
const app = new
|
|
14070
|
+
const app = new Hono38();
|
|
13802
14071
|
app.use("*", async (c, next) => {
|
|
13803
14072
|
c.set("auth", { role: "admin" });
|
|
13804
14073
|
await next();
|
|
@@ -13883,7 +14152,11 @@ function registerHostRoutes(api) {
|
|
|
13883
14152
|
"/settings/bot",
|
|
13884
14153
|
async (c) => c.json({ name: BOT_PROFILE_KEY, label: "Workspace Agent", ...await loadBotIdentity() })
|
|
13885
14154
|
);
|
|
13886
|
-
api.get("/settings/agents", async (c) =>
|
|
14155
|
+
api.get("/settings/agents", async (c) => {
|
|
14156
|
+
const viewer = await agentViewer(c);
|
|
14157
|
+
if (!viewer) return c.json({ error: "not signed in" }, 401);
|
|
14158
|
+
return c.json({ agents: await resolveAgentIdentities(viewer) });
|
|
14159
|
+
});
|
|
13887
14160
|
api.put("/settings/agents/:name", async (c) => {
|
|
13888
14161
|
const body = await c.req.json().catch(() => ({}));
|
|
13889
14162
|
const displayName = body["displayName"] === null || typeof body["displayName"] === "string" ? body["displayName"] : void 0;
|
|
@@ -13932,7 +14205,7 @@ function registerHostRoutes(api) {
|
|
|
13932
14205
|
}
|
|
13933
14206
|
function tailFile(file, limit) {
|
|
13934
14207
|
if (!existsSync24(file)) return [];
|
|
13935
|
-
const lines =
|
|
14208
|
+
const lines = readFileSync18(file, "utf-8").split("\n");
|
|
13936
14209
|
if (lines.at(-1) === "") lines.pop();
|
|
13937
14210
|
return lines.slice(-limit);
|
|
13938
14211
|
}
|
|
@@ -13950,7 +14223,7 @@ function createHostApiRouter(agent = {}) {
|
|
|
13950
14223
|
|
|
13951
14224
|
// src/dashboard/agent-bridge-host.ts
|
|
13952
14225
|
import { sign as signRaw, timingSafeEqual } from "crypto";
|
|
13953
|
-
import { existsSync as existsSync26, readFileSync as
|
|
14226
|
+
import { existsSync as existsSync26, readFileSync as readFileSync21 } from "fs";
|
|
13954
14227
|
import dotenv2 from "dotenv";
|
|
13955
14228
|
import { WebSocket as WebSocket2 } from "ws";
|
|
13956
14229
|
|
|
@@ -13960,7 +14233,7 @@ import {
|
|
|
13960
14233
|
existsSync as existsSync25,
|
|
13961
14234
|
openSync as openSync2,
|
|
13962
14235
|
readdirSync as readdirSync4,
|
|
13963
|
-
readFileSync as
|
|
14236
|
+
readFileSync as readFileSync19,
|
|
13964
14237
|
readSync as readSync2,
|
|
13965
14238
|
realpathSync as realpathSync4
|
|
13966
14239
|
} from "fs";
|
|
@@ -14020,11 +14293,18 @@ function claudeMessages(lines) {
|
|
|
14020
14293
|
continue;
|
|
14021
14294
|
if (o["entrypoint"] === "sdk-cli") continue;
|
|
14022
14295
|
const role = o["type"];
|
|
14023
|
-
const
|
|
14296
|
+
const message = o["message"];
|
|
14297
|
+
if (message?.model === "<synthetic>") continue;
|
|
14298
|
+
const text = blocksText(message?.content, ["text"]);
|
|
14024
14299
|
if (!text || typeof o["uuid"] !== "string") continue;
|
|
14300
|
+
if (role === "user" && text.startsWith("[Request interrupted by user")) continue;
|
|
14025
14301
|
const at = typeof o["timestamp"] === "string" ? o["timestamp"] : null;
|
|
14302
|
+
if (o["isCompactSummary"]) {
|
|
14303
|
+
out.push({ uuid: o["uuid"], role: "assistant", text, at, compactSummary: true });
|
|
14304
|
+
continue;
|
|
14305
|
+
}
|
|
14026
14306
|
const last = out[out.length - 1];
|
|
14027
|
-
if (role === "assistant" && last?.role === "assistant") {
|
|
14307
|
+
if (role === "assistant" && last?.role === "assistant" && !last.compactSummary) {
|
|
14028
14308
|
last.text += `
|
|
14029
14309
|
|
|
14030
14310
|
${text}`;
|
|
@@ -14162,7 +14442,7 @@ function findTranscript(agent, sessionId) {
|
|
|
14162
14442
|
function readSessionMessages(agent, sessionId, afterUuid) {
|
|
14163
14443
|
const file = findTranscript(agent, sessionId);
|
|
14164
14444
|
if (!file) return null;
|
|
14165
|
-
const lines = parseLines(
|
|
14445
|
+
const lines = parseLines(readFileSync19(file, "utf-8"));
|
|
14166
14446
|
const messages = agent === "claude" ? claudeMessages(lines) : codexMessages(lines);
|
|
14167
14447
|
if (!afterUuid) return messages;
|
|
14168
14448
|
const idx = messages.findIndex((m) => m.uuid === afterUuid);
|
|
@@ -14190,13 +14470,13 @@ function handleSessionImportRequest(req) {
|
|
|
14190
14470
|
}
|
|
14191
14471
|
|
|
14192
14472
|
// src/dashboard/docs-relay-host.ts
|
|
14193
|
-
import { Hono as
|
|
14473
|
+
import { Hono as Hono39 } from "hono";
|
|
14194
14474
|
var RETURNED_HEADERS = ["content-type", "content-disposition", "content-security-policy", "cache-control"];
|
|
14195
14475
|
async function handleDocsRequest(req) {
|
|
14196
14476
|
return runRelayed(req, (app) => app.route("/channels", createDocsRouter({ gate: async (_c, next) => next() })));
|
|
14197
14477
|
}
|
|
14198
14478
|
async function runRelayed(req, register) {
|
|
14199
|
-
const app = new
|
|
14479
|
+
const app = new Hono39();
|
|
14200
14480
|
app.use("*", async (c, next) => {
|
|
14201
14481
|
c.set("auth", req.auth);
|
|
14202
14482
|
await next();
|
|
@@ -14219,7 +14499,7 @@ async function handleHostRequest(req) {
|
|
|
14219
14499
|
}
|
|
14220
14500
|
|
|
14221
14501
|
// src/dashboard/doc-share-publisher.ts
|
|
14222
|
-
import { readFileSync as
|
|
14502
|
+
import { readFileSync as readFileSync20, statSync as statSync6 } from "fs";
|
|
14223
14503
|
import { extname, posix } from "path";
|
|
14224
14504
|
var MAX_ASSET_BYTES = 20 * 1024 * 1024;
|
|
14225
14505
|
var MAX_CONTENT_BYTES = 2 * 1024 * 1024;
|
|
@@ -14334,7 +14614,7 @@ function readDocShareBundle({ cwd, sourcePath }) {
|
|
|
14334
14614
|
}
|
|
14335
14615
|
if (!stat.isFile()) return { status: "not-found" };
|
|
14336
14616
|
if (stat.size > MAX_CONTENT_BYTES) return { status: "too-large" };
|
|
14337
|
-
const source =
|
|
14617
|
+
const source = readFileSync20(abs, "utf8");
|
|
14338
14618
|
const title = extractTitle(abs, kind === "markdown" ? "md" : kind);
|
|
14339
14619
|
if (kind === "excalidraw") {
|
|
14340
14620
|
try {
|
|
@@ -14405,7 +14685,7 @@ function readDocShareBundle({ cwd, sourcePath }) {
|
|
|
14405
14685
|
let text = null;
|
|
14406
14686
|
try {
|
|
14407
14687
|
const size = statSync6(docAbs).size;
|
|
14408
|
-
if (size <= budget) text =
|
|
14688
|
+
if (size <= budget) text = readFileSync20(docAbs, "utf8");
|
|
14409
14689
|
} catch {
|
|
14410
14690
|
continue;
|
|
14411
14691
|
}
|
|
@@ -14417,19 +14697,19 @@ function readDocShareBundle({ cwd, sourcePath }) {
|
|
|
14417
14697
|
continue;
|
|
14418
14698
|
}
|
|
14419
14699
|
}
|
|
14420
|
-
const
|
|
14421
|
-
if (!
|
|
14700
|
+
const resolved = resolveRawPath(cwd, ref.rel) ?? (docAbs ? { abs: docAbs, contentType: "text/plain; charset=utf-8" } : null);
|
|
14701
|
+
if (!resolved) continue;
|
|
14422
14702
|
let body;
|
|
14423
14703
|
try {
|
|
14424
|
-
if (statSync6(
|
|
14425
|
-
body =
|
|
14704
|
+
if (statSync6(resolved.abs).size > MAX_ASSET_BYTES) continue;
|
|
14705
|
+
body = readFileSync20(resolved.abs);
|
|
14426
14706
|
} catch {
|
|
14427
14707
|
continue;
|
|
14428
14708
|
}
|
|
14429
14709
|
assetBytes += body.length;
|
|
14430
14710
|
if (assetBytes > MAX_BUNDLE_ASSET_BYTES) return { status: "too-large" };
|
|
14431
14711
|
const name = claimName(ref.rel.split("/").pop() ?? "file");
|
|
14432
|
-
assets.push({ name, contentType:
|
|
14712
|
+
assets.push({ name, contentType: resolved.contentType, data: body.toString("base64") });
|
|
14433
14713
|
rewritten.set(href, `${SHARE_ASSET_PLACEHOLDER}${name}`);
|
|
14434
14714
|
}
|
|
14435
14715
|
if (kind === "html") {
|
|
@@ -14571,7 +14851,7 @@ function localAgentCallbacks(chatAgent) {
|
|
|
14571
14851
|
suggestChannelField: (req) => suggestChannelField(req),
|
|
14572
14852
|
listMissingCwds: () => auditChannelCwds().map((ch) => ch.id),
|
|
14573
14853
|
listRunningProfiles: () => listProfiles().filter(isServiceRunning2),
|
|
14574
|
-
getAgentIdentities: () => resolveAgentIdentities(),
|
|
14854
|
+
getAgentIdentities: (viewer) => resolveAgentIdentities(viewer),
|
|
14575
14855
|
readDocShareBundle: (req) => readDocShareBundle(req.channelId ? { ...req, cwd: resolveChannelConfig(req.channelId).cwd } : req),
|
|
14576
14856
|
listChannelSkills: (args) => {
|
|
14577
14857
|
const { cwd, claudeConfigDir } = args.channelId ? resolveChannelConfig(args.channelId) : args;
|
|
@@ -14601,7 +14881,7 @@ function buildHostConfigSnapshot() {
|
|
|
14601
14881
|
const snapshot2 = {};
|
|
14602
14882
|
for (const profile of listProfiles()) {
|
|
14603
14883
|
snapshot2[profile] = runWithProfile(profile, () => ({
|
|
14604
|
-
env: existsSync26(paths.CONFIG_FILE) ? dotenv2.parse(
|
|
14884
|
+
env: existsSync26(paths.CONFIG_FILE) ? dotenv2.parse(readFileSync21(paths.CONFIG_FILE, "utf-8")) : {},
|
|
14605
14885
|
// Only a model someone actually saved: before that it is just the Claude
|
|
14606
14886
|
// default, which would show the wrong agent in admin for a Codex user.
|
|
14607
14887
|
agentModel: existsSync26(paths.DASHBOARD_SETTINGS_FILE) ? loadDashboardSettings().agent : void 0
|
|
@@ -14691,6 +14971,10 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14691
14971
|
handleAttachmentUrlResult(msg.id, msg.url);
|
|
14692
14972
|
return;
|
|
14693
14973
|
}
|
|
14974
|
+
if (msg.type === "should-respond-result") {
|
|
14975
|
+
handleShouldRespondResult(msg.id, msg.respond);
|
|
14976
|
+
return;
|
|
14977
|
+
}
|
|
14694
14978
|
if (msg.type === "call") {
|
|
14695
14979
|
void handleCall(msg, callbacks, ws);
|
|
14696
14980
|
}
|
|
@@ -14790,7 +15074,7 @@ import { join as join18 } from "path";
|
|
|
14790
15074
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
14791
15075
|
|
|
14792
15076
|
// ../api/src/dashboard/app-icon-routes.ts
|
|
14793
|
-
import { Hono as
|
|
15077
|
+
import { Hono as Hono40 } from "hono";
|
|
14794
15078
|
var MANIFEST = {
|
|
14795
15079
|
id: "/",
|
|
14796
15080
|
name: "Flyspace",
|
|
@@ -14824,7 +15108,7 @@ async function resolvedProfileHost(c) {
|
|
|
14824
15108
|
return profileFromHost(trustedHost(c), known);
|
|
14825
15109
|
}
|
|
14826
15110
|
function createAppIconRouter() {
|
|
14827
|
-
const app = new
|
|
15111
|
+
const app = new Hono40();
|
|
14828
15112
|
app.get("/manifest.json", (c) => c.json(MANIFEST));
|
|
14829
15113
|
app.get("/icons/app/:profile/:file", async (c) => {
|
|
14830
15114
|
const profile = c.req.param("profile");
|
|
@@ -14902,9 +15186,49 @@ The JSON API is live under /api.` : "This install has no bundled Workspace UI.\n
|
|
|
14902
15186
|
});
|
|
14903
15187
|
}
|
|
14904
15188
|
|
|
15189
|
+
// src/dashboard/host-log-file.ts
|
|
15190
|
+
import { createWriteStream, fstatSync, mkdirSync as mkdirSync12, statSync as statSync7 } from "fs";
|
|
15191
|
+
import { join as join19 } from "path";
|
|
15192
|
+
var STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
|
|
15193
|
+
function stamp(text) {
|
|
15194
|
+
const ts2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
15195
|
+
return text.split("\n").map((line, i, all) => i === all.length - 1 && line === "" || STAMPED.test(line) ? line : `[${ts2}] ${line}`).join("\n");
|
|
15196
|
+
}
|
|
15197
|
+
function alreadyRedirected(fd, file) {
|
|
15198
|
+
try {
|
|
15199
|
+
const a = fstatSync(fd);
|
|
15200
|
+
const b = statSync7(file);
|
|
15201
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
15202
|
+
} catch {
|
|
15203
|
+
return false;
|
|
15204
|
+
}
|
|
15205
|
+
}
|
|
15206
|
+
function tee(stream, fd, file) {
|
|
15207
|
+
if (alreadyRedirected(fd, file)) return;
|
|
15208
|
+
const out = createWriteStream(file, { flags: "a" });
|
|
15209
|
+
out.on("error", () => {
|
|
15210
|
+
});
|
|
15211
|
+
const write = stream.write.bind(stream);
|
|
15212
|
+
stream.write = ((chunk3, ...rest) => {
|
|
15213
|
+
const text = typeof chunk3 === "string" ? chunk3 : Buffer.from(chunk3).toString("utf8");
|
|
15214
|
+
out.write(stamp(text));
|
|
15215
|
+
return write(chunk3, ...rest);
|
|
15216
|
+
});
|
|
15217
|
+
}
|
|
15218
|
+
function ensureHostLogFiles() {
|
|
15219
|
+
try {
|
|
15220
|
+
mkdirSync12(paths.LOG_DIR, { recursive: true });
|
|
15221
|
+
} catch {
|
|
15222
|
+
return;
|
|
15223
|
+
}
|
|
15224
|
+
tee(process.stdout, 1, join19(paths.LOG_DIR, "host.log"));
|
|
15225
|
+
tee(process.stderr, 2, join19(paths.LOG_DIR, "host-error.log"));
|
|
15226
|
+
}
|
|
15227
|
+
|
|
14905
15228
|
// src/dashboard/host-dashboard.ts
|
|
14906
15229
|
async function startHostDashboard(preferredPort, host) {
|
|
14907
15230
|
loadEnvFiles();
|
|
15231
|
+
ensureHostLogFiles();
|
|
14908
15232
|
let lateCallbacks;
|
|
14909
15233
|
let onHostConnected;
|
|
14910
15234
|
const bootCallbacks = new Proxy({}, {
|
|
@@ -15024,8 +15348,8 @@ function openBrowser2(url) {
|
|
|
15024
15348
|
}
|
|
15025
15349
|
}
|
|
15026
15350
|
function ensureWebBuild() {
|
|
15027
|
-
if (existsSync28(
|
|
15028
|
-
if (!existsSync28(
|
|
15351
|
+
if (existsSync28(join20(paths.WEB_ROOT, "dist", "index.html"))) return;
|
|
15352
|
+
if (!existsSync28(join20(paths.WEB_ROOT, "package.json"))) return;
|
|
15029
15353
|
console.log(" packages/ui/dist missing, building the dashboard UI...");
|
|
15030
15354
|
const result = spawnSync("pnpm", ["build"], {
|
|
15031
15355
|
cwd: paths.WEB_ROOT,
|
|
@@ -15075,7 +15399,7 @@ async function runDashboard(args) {
|
|
|
15075
15399
|
}
|
|
15076
15400
|
|
|
15077
15401
|
// src/commands/workspace.ts
|
|
15078
|
-
import { existsSync as existsSync29, mkdirSync as
|
|
15402
|
+
import { existsSync as existsSync29, mkdirSync as mkdirSync13, writeFileSync as writeFileSync10 } from "fs";
|
|
15079
15403
|
var USAGE7 = `
|
|
15080
15404
|
Usage: flyspace workspace <subcommand> [options]
|
|
15081
15405
|
|
|
@@ -15184,7 +15508,7 @@ async function provisionChannels(specs) {
|
|
|
15184
15508
|
}
|
|
15185
15509
|
const cwd = expandPath(spec.cwd);
|
|
15186
15510
|
if (!existsSync29(cwd)) {
|
|
15187
|
-
|
|
15511
|
+
mkdirSync13(cwd, { recursive: true });
|
|
15188
15512
|
console.log(` created cwd ${cwd}`);
|
|
15189
15513
|
}
|
|
15190
15514
|
await createChannel({ name: spec.name, cwd, position: index });
|
|
@@ -15260,16 +15584,40 @@ async function runReconcileCmd(args) {
|
|
|
15260
15584
|
printLog(target, log5);
|
|
15261
15585
|
}
|
|
15262
15586
|
|
|
15587
|
+
// src/commands/desktop.ts
|
|
15588
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
15589
|
+
var SCRIPT_SH = "https://flyspace.ai/install-desktop.sh";
|
|
15590
|
+
var SCRIPT_PS1 = "https://flyspace.ai/install-desktop.ps1";
|
|
15591
|
+
var USAGE9 = "Usage: flyspace desktop install [--dev]";
|
|
15592
|
+
async function runDesktopCmd(args) {
|
|
15593
|
+
const [sub, ...rest] = args;
|
|
15594
|
+
if (sub !== "install" || rest.some((a) => a !== "--dev")) {
|
|
15595
|
+
printRaw(USAGE9);
|
|
15596
|
+
process.exit(1);
|
|
15597
|
+
}
|
|
15598
|
+
const dev = rest.includes("--dev");
|
|
15599
|
+
const result = process.platform === "win32" ? spawnSync2(
|
|
15600
|
+
"powershell",
|
|
15601
|
+
["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `& ([scriptblock]::Create((irm ${SCRIPT_PS1})))${dev ? " -Dev" : ""}`],
|
|
15602
|
+
{ stdio: "inherit" }
|
|
15603
|
+
) : spawnSync2("bash", ["-c", `curl -fsSL ${SCRIPT_SH} | bash -s --${dev ? " --dev" : ""}`], { stdio: "inherit" });
|
|
15604
|
+
if (result.error) {
|
|
15605
|
+
printRaw(`Could not run the desktop installer: ${result.error.message}`);
|
|
15606
|
+
process.exit(1);
|
|
15607
|
+
}
|
|
15608
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
15609
|
+
}
|
|
15610
|
+
|
|
15263
15611
|
// src/cli.ts
|
|
15264
|
-
import { join as
|
|
15612
|
+
import { join as join21 } from "path";
|
|
15265
15613
|
var home = flyspaceHome();
|
|
15266
15614
|
if (home) {
|
|
15267
|
-
const bin =
|
|
15615
|
+
const bin = join21(home, "bin");
|
|
15268
15616
|
const path = process.env.PATH ?? "";
|
|
15269
15617
|
if (!path.split(":").includes(bin)) process.env.PATH = path ? `${bin}:${path}` : bin;
|
|
15270
15618
|
}
|
|
15271
15619
|
var XERO_USAGE = false ? " xero Connect to Xero and expose it as an MCP server\n" : "";
|
|
15272
|
-
var
|
|
15620
|
+
var USAGE10 = `
|
|
15273
15621
|
Usage: flyspace <command> [options]
|
|
15274
15622
|
|
|
15275
15623
|
Commands:
|
|
@@ -15282,6 +15630,7 @@ var USAGE9 = `
|
|
|
15282
15630
|
restart Restart the service
|
|
15283
15631
|
logs Tail the service log (-e for error log)
|
|
15284
15632
|
upgrade Upgrade Flyspace to the latest version
|
|
15633
|
+
desktop Install or update the desktop app (desktop install [--dev])
|
|
15285
15634
|
uninstall Remove Flyspace from this machine (CLI, services, config)
|
|
15286
15635
|
config Show resolved config (--edit to edit, --path for file path)
|
|
15287
15636
|
automation Manage scheduled tasks and triggers
|
|
@@ -15397,17 +15746,20 @@ async function main() {
|
|
|
15397
15746
|
case "dashboard":
|
|
15398
15747
|
await runDashboard(args.slice(1));
|
|
15399
15748
|
break;
|
|
15749
|
+
case "desktop":
|
|
15750
|
+
await runDesktopCmd(args.slice(1));
|
|
15751
|
+
break;
|
|
15400
15752
|
case "mcp":
|
|
15401
15753
|
await runMcpCmd(args.slice(1));
|
|
15402
15754
|
break;
|
|
15403
15755
|
case "-v":
|
|
15404
15756
|
case "--version":
|
|
15405
|
-
printRaw("0.1.
|
|
15757
|
+
printRaw("0.1.54");
|
|
15406
15758
|
break;
|
|
15407
15759
|
case "-h":
|
|
15408
15760
|
case "--help":
|
|
15409
15761
|
case void 0:
|
|
15410
|
-
printRaw(
|
|
15762
|
+
printRaw(USAGE10);
|
|
15411
15763
|
break;
|
|
15412
15764
|
case "xero":
|
|
15413
15765
|
if (false) {
|
|
@@ -15418,7 +15770,7 @@ async function main() {
|
|
|
15418
15770
|
// falls through
|
|
15419
15771
|
default:
|
|
15420
15772
|
printRaw(`Unknown command: ${command}`);
|
|
15421
|
-
printRaw(
|
|
15773
|
+
printRaw(USAGE10);
|
|
15422
15774
|
process.exit(1);
|
|
15423
15775
|
}
|
|
15424
15776
|
}
|