flyspace-cli 0.1.59 → 0.1.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-7W5FEG63.js → chunk-METRJ6PG.js} +1091 -972
- package/dist/chunk-PLLJ7M62.js +14799 -0
- package/dist/chunk-UZMHXV4D.js +1136 -0
- package/dist/cli.js +844 -314
- package/dist/index.js +2 -2
- package/dist/threads-BFRTS4EB.js +245 -0
- package/package.json +1 -1
- package/system.capabilities.md +2 -0
- package/dist/chunk-44WHW7NK.js +0 -178
- package/dist/chunk-XACRG7BO.js +0 -1257
- package/dist/threads-I52LSA5X.js +0 -361
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createRequire as __flyspaceCreateRequire } from 'node:module';
|
|
3
3
|
const require = __flyspaceCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
-
|
|
5
|
+
AGENT_AUTHOR,
|
|
6
6
|
AutomationManager,
|
|
7
7
|
BOT_DM_KEY,
|
|
8
8
|
BOT_LABEL,
|
|
@@ -10,47 +10,45 @@ import {
|
|
|
10
10
|
BRANDING_DEFAULTS,
|
|
11
11
|
BUILT_IN_OUTPUT_STYLES,
|
|
12
12
|
CLI_VERSION,
|
|
13
|
+
ChannelCwdError,
|
|
13
14
|
ChatAgent,
|
|
14
|
-
DEFAULT_API_URL,
|
|
15
15
|
DEFAULT_TIMEZONE,
|
|
16
|
+
DefaultChannelError,
|
|
16
17
|
DocShareSlugTakenError,
|
|
17
18
|
HANDLE_PATTERN,
|
|
18
19
|
HandleTakenError,
|
|
19
20
|
InvalidTransferError,
|
|
20
|
-
LOCAL_DB_PATH,
|
|
21
21
|
LastAdminError,
|
|
22
22
|
MEMORY_TYPES,
|
|
23
23
|
OutputStyleConflictError,
|
|
24
24
|
PLATE,
|
|
25
25
|
SKIP_SUBTYPES,
|
|
26
|
-
SLACK_ENV,
|
|
27
26
|
SUPPORT_AVATAR_URL,
|
|
28
27
|
TRANSLATION_LANGUAGES,
|
|
29
28
|
TRIAL_DAYS,
|
|
30
29
|
UsageStore,
|
|
31
|
-
acquireHostLock,
|
|
32
30
|
agentViewer,
|
|
33
|
-
|
|
31
|
+
allowedOrigins,
|
|
32
|
+
auditChannelCwds,
|
|
34
33
|
authorFor,
|
|
35
34
|
blockToFallbackText,
|
|
36
35
|
bodyTextFor,
|
|
37
|
-
boundWorkspaces,
|
|
38
36
|
buildAuthorizeUrl,
|
|
39
37
|
buildAutoTitle,
|
|
40
38
|
cachedProfileConfig,
|
|
39
|
+
canSeeChannel,
|
|
41
40
|
canonicalLanguage,
|
|
42
41
|
channelSkillsDir,
|
|
43
42
|
claudeAuthFailed,
|
|
44
43
|
clearClaudeAuthFailed,
|
|
45
|
-
clearLocalAuth,
|
|
46
44
|
clientKey,
|
|
47
45
|
codexAuthAvailable,
|
|
48
46
|
consumeOAuthState,
|
|
49
47
|
corsForShell,
|
|
48
|
+
createChannel,
|
|
50
49
|
createDocShare,
|
|
51
50
|
createDocsRouter,
|
|
52
51
|
createFeatureFlagsRouter,
|
|
53
|
-
createHostDbClient,
|
|
54
52
|
createMembership,
|
|
55
53
|
createOAuthState,
|
|
56
54
|
createOutputStyle,
|
|
@@ -62,7 +60,6 @@ import {
|
|
|
62
60
|
createStateToken,
|
|
63
61
|
createTtsRouter,
|
|
64
62
|
createWorkspace,
|
|
65
|
-
credentialsPath,
|
|
66
63
|
crossOriginShell,
|
|
67
64
|
defaultClaudeCwd,
|
|
68
65
|
defaultEffort,
|
|
@@ -77,30 +74,34 @@ import {
|
|
|
77
74
|
deleteWorkspace,
|
|
78
75
|
deleteWorkspaceDomain,
|
|
79
76
|
deriveConnectionSlug,
|
|
77
|
+
deriveThreadTitle,
|
|
80
78
|
detectSourceLanguage,
|
|
81
|
-
deviceKeyPath,
|
|
82
79
|
displayNameFor,
|
|
83
80
|
dropShareAudio,
|
|
84
81
|
dropShareLangAudioKeys,
|
|
85
82
|
effectiveModel,
|
|
86
|
-
|
|
83
|
+
ensureAgentDmChannel,
|
|
84
|
+
ensureGeneralChannel,
|
|
85
|
+
ensureMemberDmChannel,
|
|
87
86
|
ensureUsersCached,
|
|
88
87
|
escalateToHuman,
|
|
89
88
|
exchangeCode,
|
|
89
|
+
expandPath,
|
|
90
90
|
explainCost,
|
|
91
91
|
extractCategories,
|
|
92
92
|
extractTitle,
|
|
93
|
-
fetchWhoAmI,
|
|
94
93
|
filterReadableDocsChannels,
|
|
94
|
+
findChannel,
|
|
95
|
+
findChannelById,
|
|
95
96
|
findDocShareBySource,
|
|
96
97
|
findOwningProfile,
|
|
97
98
|
findSkillDetail,
|
|
98
99
|
flatDocs,
|
|
99
|
-
getAccessToken,
|
|
100
100
|
getAgentPaused,
|
|
101
101
|
getAllowGuestAccess,
|
|
102
102
|
getChannelDocsMemberAccess,
|
|
103
103
|
getChannelMemory,
|
|
104
|
+
getChannelRegistry,
|
|
104
105
|
getLocalCache,
|
|
105
106
|
getMcpConnection,
|
|
106
107
|
getMcpProvider,
|
|
@@ -108,6 +109,7 @@ import {
|
|
|
108
109
|
getMembershipByUserId,
|
|
109
110
|
getMemory,
|
|
110
111
|
getOutputStyleDefault,
|
|
112
|
+
getProfileChannelRegistry,
|
|
111
113
|
getWorkspaceAutoContinueLimit,
|
|
112
114
|
getWorkspaceBilling,
|
|
113
115
|
getWorkspaceBranding,
|
|
@@ -119,10 +121,6 @@ import {
|
|
|
119
121
|
getWorkspaceOwnPersona,
|
|
120
122
|
getWorkspacePermissionMode,
|
|
121
123
|
getWorkspacePlanStatus,
|
|
122
|
-
handleAttachmentUrlResult,
|
|
123
|
-
handleHostDbResult,
|
|
124
|
-
handlePluginSvgResult,
|
|
125
|
-
handleShouldRespondResult,
|
|
126
124
|
handleSupportMention,
|
|
127
125
|
highlightLanguageOf,
|
|
128
126
|
insertMcpConnection,
|
|
@@ -130,14 +128,19 @@ import {
|
|
|
130
128
|
installUsageRecording,
|
|
131
129
|
invalidateAuthContextCache,
|
|
132
130
|
isAllowedModel,
|
|
131
|
+
isCwdUsable,
|
|
133
132
|
isDevHost,
|
|
134
133
|
isDocsAccess,
|
|
135
134
|
isFeatureEnabled,
|
|
135
|
+
isHumanAuthor,
|
|
136
136
|
isLockedPlan,
|
|
137
|
+
isLogicalCwd,
|
|
137
138
|
isMemoryType,
|
|
138
139
|
isOlderVersion,
|
|
140
|
+
isPermissionMode,
|
|
139
141
|
isSlugAvailable,
|
|
140
142
|
isTranslatableLanguage,
|
|
143
|
+
isUnderLogicalRoot,
|
|
141
144
|
isUnknownWorkspaceHost,
|
|
142
145
|
isUuid,
|
|
143
146
|
isValidSkillName,
|
|
@@ -166,14 +169,13 @@ import {
|
|
|
166
169
|
loadAutomations,
|
|
167
170
|
loadBotIdentity,
|
|
168
171
|
loadChatAgentConfig,
|
|
169
|
-
loadConfig,
|
|
170
|
-
loadCredentials,
|
|
171
172
|
loadDashboardSettings,
|
|
172
173
|
loadEffectiveAutomations,
|
|
173
|
-
loadEnvFiles,
|
|
174
174
|
loadFullDashboardSettings,
|
|
175
175
|
loadWorkspaceBranding,
|
|
176
176
|
loadWorkspacePrompt,
|
|
177
|
+
localDefaults,
|
|
178
|
+
markChannelGreeted,
|
|
177
179
|
markInviteResent,
|
|
178
180
|
markMemoryUsed,
|
|
179
181
|
markWorkspaceGreeted,
|
|
@@ -182,38 +184,35 @@ import {
|
|
|
182
184
|
mentionedUserIds,
|
|
183
185
|
onboardingPending,
|
|
184
186
|
pinnedClaudeConfigDir,
|
|
185
|
-
|
|
187
|
+
postToDashboardChannel,
|
|
186
188
|
profileClaudeConfigDir,
|
|
187
189
|
profileEnv,
|
|
188
190
|
profileFromHost,
|
|
189
191
|
profileOauthToken,
|
|
190
192
|
promoteChannelMemory,
|
|
191
|
-
publishHostEndpoint,
|
|
192
193
|
queueShareAudio,
|
|
193
|
-
readHostEndpoint,
|
|
194
194
|
readOAuthClient,
|
|
195
195
|
readSkillFile,
|
|
196
196
|
recentRunsForWorkspace,
|
|
197
197
|
refreshAutomationRegistry,
|
|
198
198
|
refreshCache,
|
|
199
|
+
refreshChannelRegistry,
|
|
199
200
|
refreshUserCache,
|
|
200
201
|
removeChannelMember,
|
|
201
202
|
renderAppIcon,
|
|
202
|
-
requestDeviceCode,
|
|
203
|
-
requestHostDb,
|
|
204
203
|
requireDocsAccess,
|
|
205
|
-
requireSlackBotToken,
|
|
206
204
|
resetWorkspaceOnboarding,
|
|
207
205
|
resetWorkspacePrompt,
|
|
208
206
|
resolveAuthContext,
|
|
209
207
|
resolveChannelConfig,
|
|
210
208
|
resolveChannelId,
|
|
209
|
+
resolveCwd,
|
|
210
|
+
resolveDashboardChannelId,
|
|
211
211
|
resolveDocPath,
|
|
212
212
|
resolveDocsAccess,
|
|
213
213
|
resolveRateCard,
|
|
214
214
|
resolveRawPath,
|
|
215
215
|
resolveUserId,
|
|
216
|
-
revokeDevice,
|
|
217
216
|
revokeDocShare,
|
|
218
217
|
rowToMemory,
|
|
219
218
|
runAutomation,
|
|
@@ -224,7 +223,6 @@ import {
|
|
|
224
223
|
saveAgentProfile,
|
|
225
224
|
saveBotIdentity,
|
|
226
225
|
saveChannelMemory,
|
|
227
|
-
saveCredentials,
|
|
228
226
|
saveDashboardSettings,
|
|
229
227
|
saveMemory,
|
|
230
228
|
saveWorkspaceBranding,
|
|
@@ -237,7 +235,6 @@ import {
|
|
|
237
235
|
setChannelDocsMemberAccess,
|
|
238
236
|
setDocShareSlug,
|
|
239
237
|
setDocShareTags,
|
|
240
|
-
setHostDbSender,
|
|
241
238
|
setMcpConnectionApiKey,
|
|
242
239
|
setMembershipHandle,
|
|
243
240
|
setMemoryAutoPaused,
|
|
@@ -248,18 +245,21 @@ import {
|
|
|
248
245
|
setWorkspaceOwnPersona,
|
|
249
246
|
setWorkspacePermissionMode,
|
|
250
247
|
setWorkspaceStripeSubscription,
|
|
251
|
-
slackConfigured,
|
|
252
248
|
slackMrkdwnToMarkdown,
|
|
253
249
|
startAutomationRegistryPolling,
|
|
250
|
+
startChannelRegistryPolling,
|
|
254
251
|
startServer,
|
|
255
252
|
suggestChannelField,
|
|
253
|
+
syncPostToDashboard,
|
|
256
254
|
syncSlackAvatars,
|
|
257
255
|
syncSupportReply,
|
|
258
256
|
transferWorkspaceAdmin,
|
|
259
257
|
trustedHost,
|
|
260
258
|
tsToIso,
|
|
261
259
|
undoMemoryEvent,
|
|
260
|
+
updateChannelById,
|
|
262
261
|
updateChannelMemory,
|
|
262
|
+
updateChannelsMcpConnections,
|
|
263
263
|
updateDocShareFeatures,
|
|
264
264
|
updateDocShareSnapshot,
|
|
265
265
|
updateMcpConnectionSettings,
|
|
@@ -274,68 +274,82 @@ import {
|
|
|
274
274
|
usageLimitedModels,
|
|
275
275
|
usageLimitedUntil,
|
|
276
276
|
useDirectSupabase,
|
|
277
|
-
useHostDbWithoutCredentials,
|
|
278
277
|
useLocalCache,
|
|
279
278
|
validateMemoryInput,
|
|
279
|
+
warnOnBrokenChannelCwds,
|
|
280
280
|
workspaceHostname,
|
|
281
281
|
workspaceSkillsDir,
|
|
282
282
|
writeSkillFile
|
|
283
|
-
} from "./chunk-
|
|
283
|
+
} from "./chunk-METRJ6PG.js";
|
|
284
284
|
import {
|
|
285
|
-
|
|
285
|
+
checkPermissionAction,
|
|
286
|
+
createThreadAction,
|
|
286
287
|
firstReplyBody,
|
|
287
288
|
getThread,
|
|
288
289
|
listChannels,
|
|
290
|
+
listChannelsAction,
|
|
289
291
|
listThreads,
|
|
290
|
-
|
|
292
|
+
moveThread,
|
|
293
|
+
moveThreadAction,
|
|
294
|
+
postReplyAction,
|
|
295
|
+
readThreadAction,
|
|
296
|
+
requestPermissionAction,
|
|
291
297
|
resolveChannel,
|
|
292
|
-
|
|
293
|
-
|
|
298
|
+
runDocsCmd,
|
|
299
|
+
searchThreadsAction,
|
|
300
|
+
shareDocAction
|
|
301
|
+
} from "./chunk-PLLJ7M62.js";
|
|
294
302
|
import {
|
|
295
|
-
|
|
296
|
-
|
|
303
|
+
AuthApiError,
|
|
304
|
+
DEFAULT_API_URL,
|
|
297
305
|
DEFAULT_PROFILE,
|
|
298
|
-
|
|
306
|
+
LOCAL_ACTION_PATH,
|
|
307
|
+
LOCAL_DB_PATH,
|
|
299
308
|
SCRATCH_PREFIX,
|
|
309
|
+
SLACK_ENV,
|
|
300
310
|
SessionStore,
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
311
|
+
acquireHostLock,
|
|
312
|
+
apiUrl,
|
|
313
|
+
boundWorkspaces,
|
|
314
|
+
clearLocalAuth,
|
|
315
|
+
createHostDbClient,
|
|
316
|
+
credentialsPath,
|
|
304
317
|
databaseReachable,
|
|
305
|
-
|
|
318
|
+
deviceKeyPath,
|
|
319
|
+
ensureDeviceKey,
|
|
306
320
|
ensureDirs,
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
expandPath,
|
|
310
|
-
findChannel,
|
|
311
|
-
findChannelById,
|
|
312
|
-
getChannelRegistry,
|
|
321
|
+
fetchWhoAmI,
|
|
322
|
+
getAccessToken,
|
|
313
323
|
getProfile,
|
|
314
|
-
getProfileChannelRegistry,
|
|
315
324
|
getR2Bucket,
|
|
316
325
|
getR2Client,
|
|
317
326
|
getSupabaseClient,
|
|
318
|
-
|
|
327
|
+
handleActionResult,
|
|
328
|
+
handleAttachmentUrlResult,
|
|
329
|
+
handleHostDbResult,
|
|
330
|
+
handlePluginSvgResult,
|
|
331
|
+
handleShouldRespondResult,
|
|
319
332
|
isEffort,
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
isUnderLogicalRoot,
|
|
324
|
-
markChannelGreeted,
|
|
333
|
+
loadConfig,
|
|
334
|
+
loadCredentials,
|
|
335
|
+
loadEnvFiles,
|
|
325
336
|
paths,
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
337
|
+
pollDeviceToken,
|
|
338
|
+
publishHostEndpoint,
|
|
339
|
+
readHostEndpoint,
|
|
340
|
+
requestAction,
|
|
341
|
+
requestDeviceCode,
|
|
342
|
+
requestHostDb,
|
|
343
|
+
requireSlackBotToken,
|
|
344
|
+
revokeDevice,
|
|
330
345
|
runWithProfile,
|
|
346
|
+
saveCredentials,
|
|
347
|
+
setHostDbSender,
|
|
331
348
|
setSupabaseClient,
|
|
332
|
-
|
|
349
|
+
slackConfigured,
|
|
333
350
|
sumR2PrefixBytes,
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
updateChannelsMcpConnections,
|
|
337
|
-
warnOnBrokenChannelCwds
|
|
338
|
-
} from "./chunk-XACRG7BO.js";
|
|
351
|
+
useHostDbWithoutCredentials
|
|
352
|
+
} from "./chunk-UZMHXV4D.js";
|
|
339
353
|
|
|
340
354
|
// ../core/src/logger.ts
|
|
341
355
|
var ALREADY_STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
|
|
@@ -2192,7 +2206,7 @@ function npmEnv(target) {
|
|
|
2192
2206
|
return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
|
|
2193
2207
|
}
|
|
2194
2208
|
async function runUpgrade() {
|
|
2195
|
-
const current = "0.1.
|
|
2209
|
+
const current = "0.1.61";
|
|
2196
2210
|
console.log(`Current version: ${current}`);
|
|
2197
2211
|
console.log("Checking for updates...\n");
|
|
2198
2212
|
try {
|
|
@@ -3053,17 +3067,17 @@ async function issueInvite(membershipId, message) {
|
|
|
3053
3067
|
const db = getSupabaseClient();
|
|
3054
3068
|
const token = randomBytes(32).toString("hex");
|
|
3055
3069
|
const expiresAt = new Date(Date.now() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1e3).toISOString();
|
|
3056
|
-
const { data:
|
|
3070
|
+
const { data: pending2, error: pendingError } = await db.from("workspace_invites").select("id, token_hash, previous_token_hashes").eq("membership_id", membershipId).is("accepted_at", null).order("created_at", { ascending: false }).limit(1).maybeSingle();
|
|
3057
3071
|
if (pendingError) throw new Error(`issueInvite(${membershipId}): ${pendingError.message}`);
|
|
3058
|
-
const { error: error2 } =
|
|
3072
|
+
const { error: error2 } = pending2 ? await db.from("workspace_invites").update({
|
|
3059
3073
|
token_hash: hashInviteToken(token),
|
|
3060
3074
|
previous_token_hashes: [
|
|
3061
|
-
...
|
|
3062
|
-
|
|
3075
|
+
...pending2.previous_token_hashes ?? [],
|
|
3076
|
+
pending2.token_hash
|
|
3063
3077
|
],
|
|
3064
3078
|
message,
|
|
3065
3079
|
expires_at: expiresAt
|
|
3066
|
-
}).eq("id",
|
|
3080
|
+
}).eq("id", pending2.id) : await db.from("workspace_invites").insert({
|
|
3067
3081
|
membership_id: membershipId,
|
|
3068
3082
|
token_hash: hashInviteToken(token),
|
|
3069
3083
|
message,
|
|
@@ -5650,10 +5664,31 @@ async function runSlackCmd(args) {
|
|
|
5650
5664
|
}
|
|
5651
5665
|
}
|
|
5652
5666
|
|
|
5667
|
+
// src/store/thread-move.ts
|
|
5668
|
+
async function moveThreadFully(threadId, toChannelId) {
|
|
5669
|
+
const thread = await getThread(threadId);
|
|
5670
|
+
if (!thread) throw new Error(`No thread with id ${threadId}.`);
|
|
5671
|
+
if (thread.channelId === toChannelId) return "unchanged";
|
|
5672
|
+
const channels = await listChannels();
|
|
5673
|
+
const to = channels.find((c) => c.id === toChannelId);
|
|
5674
|
+
if (!to) throw new Error(`No channel with id ${toChannelId}.`);
|
|
5675
|
+
const from = channels.find((c) => c.id === thread.channelId);
|
|
5676
|
+
const store = new SessionStore(paths.DB_FILE);
|
|
5677
|
+
try {
|
|
5678
|
+
await moveThread(thread.id, to.id);
|
|
5679
|
+
const counts = store.moveThread(`chat:${thread.channelId}`, `chat:${to.id}`, thread.id);
|
|
5680
|
+
return { from, to, ...counts, cwdChanged: !!from && from.cwd !== to.cwd };
|
|
5681
|
+
} finally {
|
|
5682
|
+
store.close();
|
|
5683
|
+
}
|
|
5684
|
+
}
|
|
5685
|
+
|
|
5653
5686
|
// ../core/src/bridge-protocol.ts
|
|
5654
5687
|
var HOST_SOCKET_PATH = "/internal/host-socket";
|
|
5655
5688
|
var DEFAULT_DATA_API_PORT = 4757;
|
|
5656
5689
|
var CALL_TIMEOUT_MS = 15e3;
|
|
5690
|
+
var DOCS_CALL_TIMEOUT_MS = 12e4;
|
|
5691
|
+
var MEMORY_EXTRACTION_TIMEOUT_MS = 165e3;
|
|
5657
5692
|
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
5658
5693
|
var HEARTBEAT_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 2.5;
|
|
5659
5694
|
var LOCAL_RELAY_PATH = "/internal/agent-call";
|
|
@@ -6104,7 +6139,7 @@ Usage: flyspace mcp <server>
|
|
|
6104
6139
|
Servers:
|
|
6105
6140
|
threads Search, read, and write this workspace's chat threads
|
|
6106
6141
|
(search_threads, read_thread, list_channels, create_thread,
|
|
6107
|
-
post_reply, move_thread)
|
|
6142
|
+
post_reply, move_thread, share_doc)
|
|
6108
6143
|
|
|
6109
6144
|
Try it by hand (type a JSON-RPC line, or pipe one in):
|
|
6110
6145
|
flyspace mcp threads
|
|
@@ -6120,7 +6155,7 @@ async function runMcpCmd(args) {
|
|
|
6120
6155
|
useHostDbWithoutCredentials();
|
|
6121
6156
|
switch (server) {
|
|
6122
6157
|
case "threads": {
|
|
6123
|
-
const { startThreadsServer } = await import("./threads-
|
|
6158
|
+
const { startThreadsServer } = await import("./threads-BFRTS4EB.js");
|
|
6124
6159
|
await startThreadsServer();
|
|
6125
6160
|
return;
|
|
6126
6161
|
}
|
|
@@ -6408,26 +6443,26 @@ async function decideDeviceCode(id, userId, decision) {
|
|
|
6408
6443
|
if (error2) fail("decideDeviceCode", error2);
|
|
6409
6444
|
return (data ?? []).length > 0;
|
|
6410
6445
|
}
|
|
6411
|
-
async function redeemDeviceCode(
|
|
6446
|
+
async function redeemDeviceCode(pending2) {
|
|
6412
6447
|
const db = getSupabaseClient();
|
|
6413
|
-
const { data: claimed, error: claimError } = await db.from("device_codes").delete().eq("id",
|
|
6448
|
+
const { data: claimed, error: claimError } = await db.from("device_codes").delete().eq("id", pending2.id).select("id");
|
|
6414
6449
|
if (claimError) fail("redeemDeviceCode", claimError);
|
|
6415
6450
|
if (!claimed?.length) return null;
|
|
6416
|
-
const existing =
|
|
6417
|
-
const { data, error: error2 } = existing ? await db.from("devices").update({ name:
|
|
6418
|
-
user_id:
|
|
6419
|
-
name:
|
|
6420
|
-
platform:
|
|
6421
|
-
public_key:
|
|
6451
|
+
const existing = pending2.approvedBy ? await findDeviceByKey(pending2.publicKey, pending2.approvedBy) : null;
|
|
6452
|
+
const { data, error: error2 } = existing ? await db.from("devices").update({ name: pending2.name, platform: pending2.platform }).eq("id", existing.id).select("*").single() : await db.from("devices").insert({
|
|
6453
|
+
user_id: pending2.approvedBy,
|
|
6454
|
+
name: pending2.name,
|
|
6455
|
+
platform: pending2.platform,
|
|
6456
|
+
public_key: pending2.publicKey
|
|
6422
6457
|
}).select("*").single();
|
|
6423
6458
|
if (error2) fail("redeemDeviceCode", error2);
|
|
6424
6459
|
const device = toDevice(data);
|
|
6425
|
-
if (
|
|
6460
|
+
if (pending2.workspaceIds.length) {
|
|
6426
6461
|
const { error: bindError } = await db.from("device_workspaces").upsert(
|
|
6427
|
-
|
|
6462
|
+
pending2.workspaceIds.map((workspaceId) => ({
|
|
6428
6463
|
device_id: device.id,
|
|
6429
6464
|
workspace_id: workspaceId,
|
|
6430
|
-
bound_by:
|
|
6465
|
+
bound_by: pending2.approvedBy
|
|
6431
6466
|
})),
|
|
6432
6467
|
{ onConflict: "device_id,workspace_id", ignoreDuplicates: true }
|
|
6433
6468
|
);
|
|
@@ -6537,7 +6572,7 @@ async function userEmail(userId) {
|
|
|
6537
6572
|
}
|
|
6538
6573
|
|
|
6539
6574
|
// ../api/src/dashboard/agent-bridge-data.ts
|
|
6540
|
-
import { randomBytes as
|
|
6575
|
+
import { randomBytes as randomBytes5, randomUUID as randomUUID2, verify as verifyRaw } from "crypto";
|
|
6541
6576
|
import { WebSocket, WebSocketServer } from "ws";
|
|
6542
6577
|
|
|
6543
6578
|
// ../api/src/dashboard/host-identity.ts
|
|
@@ -6634,12 +6669,546 @@ function createUploadsRouter() {
|
|
|
6634
6669
|
c.header("Cache-Control", `private, max-age=${PRESIGN_TTL_SECONDS - 60}`);
|
|
6635
6670
|
return c.redirect(url, 302);
|
|
6636
6671
|
});
|
|
6637
|
-
return app;
|
|
6672
|
+
return app;
|
|
6673
|
+
}
|
|
6674
|
+
|
|
6675
|
+
// ../api/src/dashboard/thread-access.ts
|
|
6676
|
+
var ON_BEHALF_HEADER = "x-flyspace-on-behalf-of";
|
|
6677
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6678
|
+
function parseThreadRef(input2) {
|
|
6679
|
+
const raw = input2.trim();
|
|
6680
|
+
if (UUID.test(raw)) return raw.toLowerCase();
|
|
6681
|
+
let url;
|
|
6682
|
+
try {
|
|
6683
|
+
url = new URL(raw, "http://ref.invalid");
|
|
6684
|
+
} catch {
|
|
6685
|
+
return null;
|
|
6686
|
+
}
|
|
6687
|
+
const fromPath = /(?:^|\/)chat\/[^/]+\/([^/]+)\/?$/.exec(url.pathname)?.[1];
|
|
6688
|
+
if (fromPath && UUID.test(fromPath)) return fromPath.toLowerCase();
|
|
6689
|
+
const fromQuery = url.searchParams.get("t");
|
|
6690
|
+
return fromQuery && UUID.test(fromQuery) ? fromQuery.toLowerCase() : null;
|
|
6691
|
+
}
|
|
6692
|
+
function readingFor(query, userId) {
|
|
6693
|
+
return userId ? query.setHeader(ON_BEHALF_HEADER, userId) : query;
|
|
6694
|
+
}
|
|
6695
|
+
async function resolveThreadOwner(threadId, onBehalfOf) {
|
|
6696
|
+
if (!UUID.test(threadId)) return null;
|
|
6697
|
+
const db = getSupabaseClient();
|
|
6698
|
+
const { data: thread, error: error2 } = await readingFor(
|
|
6699
|
+
db.from("threads").select("id, channel_id").eq("id", threadId),
|
|
6700
|
+
onBehalfOf
|
|
6701
|
+
).maybeSingle();
|
|
6702
|
+
if (error2) throw new Error(`resolveThreadOwner: ${error2.message}`);
|
|
6703
|
+
const channelId = thread?.channel_id;
|
|
6704
|
+
if (!channelId) return null;
|
|
6705
|
+
const { data: channel, error: channelError } = await readingFor(
|
|
6706
|
+
db.from("channels").select("profile, visibility, dm_key, member_emails").eq(UUID.test(channelId) ? "id" : "external_channel_id", channelId),
|
|
6707
|
+
onBehalfOf
|
|
6708
|
+
).maybeSingle();
|
|
6709
|
+
if (channelError) throw new Error(`resolveThreadOwner: ${channelError.message}`);
|
|
6710
|
+
const row = channel;
|
|
6711
|
+
if (!row?.profile) return null;
|
|
6712
|
+
const { data: workspace, error: workspaceError } = await readingFor(
|
|
6713
|
+
db.from("workspaces").select("id").eq("slug", row.profile),
|
|
6714
|
+
onBehalfOf
|
|
6715
|
+
).maybeSingle();
|
|
6716
|
+
if (workspaceError) throw new Error(`resolveThreadOwner: ${workspaceError.message}`);
|
|
6717
|
+
const workspaceId = workspace?.id;
|
|
6718
|
+
if (!workspaceId) return null;
|
|
6719
|
+
return {
|
|
6720
|
+
threadId,
|
|
6721
|
+
channelId,
|
|
6722
|
+
workspace: row.profile,
|
|
6723
|
+
workspaceId,
|
|
6724
|
+
channel: {
|
|
6725
|
+
// Same default as rowToChannel: anything not explicitly public is private.
|
|
6726
|
+
visibility: row.visibility === "public" ? "public" : "private",
|
|
6727
|
+
dmKey: row.dm_key,
|
|
6728
|
+
memberEmails: Array.isArray(row.member_emails) ? row.member_emails.filter((e) => typeof e === "string").map((e) => e.trim().toLowerCase()) : []
|
|
6729
|
+
}
|
|
6730
|
+
};
|
|
6731
|
+
}
|
|
6732
|
+
async function canReadThread(owner, userId) {
|
|
6733
|
+
if (!UUID.test(userId)) return false;
|
|
6734
|
+
const { data, error: error2 } = await readingFor(
|
|
6735
|
+
getSupabaseClient().from("memberships").select("email, role").eq("workspace_id", owner.workspaceId).eq("user_id", userId),
|
|
6736
|
+
userId
|
|
6737
|
+
).maybeSingle();
|
|
6738
|
+
if (error2) throw new Error(`canReadThread: ${error2.message}`);
|
|
6739
|
+
const membership = data;
|
|
6740
|
+
if (!membership) return false;
|
|
6741
|
+
return canSeeChannel(owner.channel, {
|
|
6742
|
+
email: membership.email ?? void 0,
|
|
6743
|
+
role: membership.role
|
|
6744
|
+
});
|
|
6745
|
+
}
|
|
6746
|
+
function threadPath(workspace, channelId, threadId) {
|
|
6747
|
+
return `/${encodeURIComponent(workspace)}/chat/${encodeURIComponent(channelId)}/${threadId}`;
|
|
6748
|
+
}
|
|
6749
|
+
|
|
6750
|
+
// ../api/src/dashboard/doc-share-publish.ts
|
|
6751
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
6752
|
+
import { CopyObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-sdk/client-s3";
|
|
6753
|
+
|
|
6754
|
+
// ../api/src/dashboard/bridge-types.ts
|
|
6755
|
+
var SHARE_ASSET_PLACEHOLDER = "/share/{{flyspace-share-id}}/assets/";
|
|
6756
|
+
|
|
6757
|
+
// ../api/src/dashboard/doc-share-features.ts
|
|
6758
|
+
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
6759
|
+
var DEFAULT_FEATURES = {
|
|
6760
|
+
audioEnabled: false,
|
|
6761
|
+
askEnabled: true,
|
|
6762
|
+
socialEnabled: false,
|
|
6763
|
+
brandingEnabled: true,
|
|
6764
|
+
translationEnabled: false,
|
|
6765
|
+
translationLangs: []
|
|
6766
|
+
};
|
|
6767
|
+
var HTML_FEATURES = {
|
|
6768
|
+
audioEnabled: false,
|
|
6769
|
+
askEnabled: false,
|
|
6770
|
+
socialEnabled: false,
|
|
6771
|
+
brandingEnabled: false,
|
|
6772
|
+
translationEnabled: false,
|
|
6773
|
+
translationLangs: []
|
|
6774
|
+
};
|
|
6775
|
+
function resolveFeatures(requested, existing) {
|
|
6776
|
+
const base = existing ?? DEFAULT_FEATURES;
|
|
6777
|
+
return {
|
|
6778
|
+
audioEnabled: requested?.audio ?? base.audioEnabled,
|
|
6779
|
+
askEnabled: requested?.ask ?? base.askEnabled,
|
|
6780
|
+
socialEnabled: requested?.social ?? base.socialEnabled,
|
|
6781
|
+
brandingEnabled: requested?.branding ?? base.brandingEnabled,
|
|
6782
|
+
translationEnabled: requested?.translation ?? base.translationEnabled,
|
|
6783
|
+
// Replaced wholesale, not merged: the allowlist IS the answer to "which
|
|
6784
|
+
// languages does this link offer", and a merge would make removing one
|
|
6785
|
+
// impossible.
|
|
6786
|
+
translationLangs: requested?.translationLangs ?? base.translationLangs
|
|
6787
|
+
};
|
|
6788
|
+
}
|
|
6789
|
+
async function deleteShareAssets(keys) {
|
|
6790
|
+
const client2 = getR2Client();
|
|
6791
|
+
const bucket = getR2Bucket();
|
|
6792
|
+
for (const key of keys) {
|
|
6793
|
+
try {
|
|
6794
|
+
await client2.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
|
|
6795
|
+
} catch {
|
|
6796
|
+
}
|
|
6797
|
+
}
|
|
6798
|
+
}
|
|
6799
|
+
async function updateShareFeatures(share, requested) {
|
|
6800
|
+
if (share.kind === "html") return share;
|
|
6801
|
+
if (share.kind === "excalidraw") {
|
|
6802
|
+
if (requested.branding === void 0) return share;
|
|
6803
|
+
return updateDocShareFeatures(share.id, { ...share, brandingEnabled: requested.branding });
|
|
6804
|
+
}
|
|
6805
|
+
const features = resolveFeatures(requested, share);
|
|
6806
|
+
const updated = await updateDocShareFeatures(share.id, features);
|
|
6807
|
+
if (!updated) return null;
|
|
6808
|
+
if (features.audioEnabled) void queueShareAudio(updated);
|
|
6809
|
+
else if (share.audioEnabled) await dropShareAudio(share);
|
|
6810
|
+
return updated;
|
|
6811
|
+
}
|
|
6812
|
+
|
|
6813
|
+
// ../api/src/dashboard/doc-share-publish.ts
|
|
6814
|
+
var SHARE_KEY_PREFIX = "share";
|
|
6815
|
+
function generateShareId() {
|
|
6816
|
+
return randomBytes4(9).toString("base64url");
|
|
6817
|
+
}
|
|
6818
|
+
async function publishDocShare(input2, readBundle) {
|
|
6819
|
+
const bundle = await readBundle({ channelId: input2.channelId, cwd: input2.cwd, sourcePath: input2.sourcePath });
|
|
6820
|
+
if (bundle.status !== "ok") return bundle;
|
|
6821
|
+
const existing = await findDocShareBySource(input2.workspaceId, input2.channelId, input2.sourcePath);
|
|
6822
|
+
const shareId = existing?.id ?? generateShareId();
|
|
6823
|
+
const client2 = getR2Client();
|
|
6824
|
+
const bucket = getR2Bucket();
|
|
6825
|
+
const assetKeys = [];
|
|
6826
|
+
for (const asset of bundle.assets) {
|
|
6827
|
+
const key = `${SHARE_KEY_PREFIX}/${shareId}/${asset.name}`;
|
|
6828
|
+
if ("copyFrom" in asset) {
|
|
6829
|
+
await client2.send(
|
|
6830
|
+
new CopyObjectCommand({
|
|
6831
|
+
Bucket: bucket,
|
|
6832
|
+
Key: key,
|
|
6833
|
+
CopySource: `${bucket}/${asset.copyFrom}`.split("/").map(encodeURIComponent).join("/")
|
|
6834
|
+
})
|
|
6835
|
+
);
|
|
6836
|
+
} else {
|
|
6837
|
+
await client2.send(
|
|
6838
|
+
new PutObjectCommand2({
|
|
6839
|
+
Bucket: bucket,
|
|
6840
|
+
Key: key,
|
|
6841
|
+
Body: Buffer.from(asset.data, "base64"),
|
|
6842
|
+
ContentType: asset.contentType
|
|
6843
|
+
})
|
|
6844
|
+
);
|
|
6845
|
+
}
|
|
6846
|
+
assetKeys.push(key);
|
|
6847
|
+
}
|
|
6848
|
+
const built = {
|
|
6849
|
+
kind: bundle.kind,
|
|
6850
|
+
title: bundle.title,
|
|
6851
|
+
content: bundle.content.split(SHARE_ASSET_PLACEHOLDER).join(`/share/${shareId}/assets/`),
|
|
6852
|
+
assetKeys
|
|
6853
|
+
};
|
|
6854
|
+
const html = built.kind !== "markdown";
|
|
6855
|
+
const features = built.kind === "excalidraw" ? {
|
|
6856
|
+
...HTML_FEATURES,
|
|
6857
|
+
brandingEnabled: resolveFeatures(input2.features, existing).brandingEnabled
|
|
6858
|
+
} : html ? HTML_FEATURES : resolveFeatures(input2.features, existing);
|
|
6859
|
+
const snapshot2 = {
|
|
6860
|
+
...built,
|
|
6861
|
+
sourceLang: html ? null : await detectSourceLanguage(built.title, built.content)
|
|
6862
|
+
};
|
|
6863
|
+
const slug = input2.slug === void 0 ? existing?.slug ?? null : input2.slug;
|
|
6864
|
+
if (existing) {
|
|
6865
|
+
if (slug !== (existing.slug ?? null)) {
|
|
6866
|
+
const renamed = await setDocShareSlug(existing.id, slug);
|
|
6867
|
+
if (!renamed) return { status: "not-found" };
|
|
6868
|
+
}
|
|
6869
|
+
const share2 = await updateDocShareSnapshot(existing.id, snapshot2, features);
|
|
6870
|
+
const stale = existing.assetKeys.filter((key) => !snapshot2.assetKeys.includes(key));
|
|
6871
|
+
await deleteShareAssets(stale);
|
|
6872
|
+
if (!features.audioEnabled && existing.audioEnabled) await dropShareAudio(existing);
|
|
6873
|
+
void queueShareAudio(share2);
|
|
6874
|
+
return { status: "ok", share: share2 };
|
|
6875
|
+
}
|
|
6876
|
+
const share = await createDocShare({
|
|
6877
|
+
id: shareId,
|
|
6878
|
+
slug,
|
|
6879
|
+
workspaceId: input2.workspaceId,
|
|
6880
|
+
profile: input2.profile,
|
|
6881
|
+
channelId: input2.channelId,
|
|
6882
|
+
sourcePath: input2.sourcePath,
|
|
6883
|
+
createdBy: input2.createdBy,
|
|
6884
|
+
...snapshot2,
|
|
6885
|
+
...features
|
|
6886
|
+
});
|
|
6887
|
+
void queueShareAudio(share);
|
|
6888
|
+
return { status: "ok", share };
|
|
6889
|
+
}
|
|
6890
|
+
|
|
6891
|
+
// ../api/src/dashboard/share-slug.ts
|
|
6892
|
+
var MIN_SLUG = 2;
|
|
6893
|
+
var MAX_SLUG = 64;
|
|
6894
|
+
var SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
6895
|
+
var RESERVED2 = /* @__PURE__ */ new Set([
|
|
6896
|
+
"admin",
|
|
6897
|
+
"api",
|
|
6898
|
+
"assets",
|
|
6899
|
+
"audio",
|
|
6900
|
+
"auth",
|
|
6901
|
+
"favicon",
|
|
6902
|
+
"login",
|
|
6903
|
+
"new",
|
|
6904
|
+
"og",
|
|
6905
|
+
"robots",
|
|
6906
|
+
"share",
|
|
6907
|
+
"sitemap",
|
|
6908
|
+
"static"
|
|
6909
|
+
]);
|
|
6910
|
+
function normalizeSlug(raw) {
|
|
6911
|
+
const slug = raw.trim().toLowerCase();
|
|
6912
|
+
if (slug.length < MIN_SLUG) return { error: "too-short" };
|
|
6913
|
+
if (slug.length > MAX_SLUG) return { error: "too-long" };
|
|
6914
|
+
if (!SLUG_SHAPE.test(slug)) return { error: "shape" };
|
|
6915
|
+
if (RESERVED2.has(slug)) return { error: "reserved" };
|
|
6916
|
+
return { slug };
|
|
6917
|
+
}
|
|
6918
|
+
function slugErrorMessage(err) {
|
|
6919
|
+
switch (err) {
|
|
6920
|
+
case "too-short":
|
|
6921
|
+
return `Use at least ${MIN_SLUG} characters.`;
|
|
6922
|
+
case "too-long":
|
|
6923
|
+
return `Keep it under ${MAX_SLUG} characters.`;
|
|
6924
|
+
case "reserved":
|
|
6925
|
+
return "That word is reserved. Try something more specific.";
|
|
6926
|
+
default:
|
|
6927
|
+
return "Use lowercase letters, numbers and hyphens.";
|
|
6928
|
+
}
|
|
6929
|
+
}
|
|
6930
|
+
|
|
6931
|
+
// ../api/src/dashboard/doc-share-host-request.ts
|
|
6932
|
+
function workspaceShareOrigin(slug) {
|
|
6933
|
+
const wildcard = allowedOrigins().find((o) => o.includes("://*."));
|
|
6934
|
+
return wildcard ? wildcard.replace("://*.", `://${slug}.`) : `https://${slug}.flyspace.ai`;
|
|
6935
|
+
}
|
|
6936
|
+
async function publishDocShareForHost(scopeWorkspaces, req) {
|
|
6937
|
+
if (typeof req.channelId !== "string" || typeof req.path !== "string" || !req.path) {
|
|
6938
|
+
return { error: "channel and path are required" };
|
|
6939
|
+
}
|
|
6940
|
+
const channel = findChannelById(req.channelId);
|
|
6941
|
+
if (!channel || scopeWorkspaces !== null && !scopeWorkspaces.includes(channel.profile)) {
|
|
6942
|
+
return { error: "channel not found" };
|
|
6943
|
+
}
|
|
6944
|
+
let slug;
|
|
6945
|
+
if (typeof req.slug === "string") {
|
|
6946
|
+
const normalized = normalizeSlug(req.slug);
|
|
6947
|
+
if ("error" in normalized) return { error: slugErrorMessage(normalized.error) };
|
|
6948
|
+
slug = normalized.slug;
|
|
6949
|
+
}
|
|
6950
|
+
const workspace = await getWorkspaceBySlug(channel.profile);
|
|
6951
|
+
if (!workspace) return { error: "workspace not found" };
|
|
6952
|
+
return runWithProfile(channel.profile, async () => {
|
|
6953
|
+
let result;
|
|
6954
|
+
try {
|
|
6955
|
+
result = await publishDocShare(
|
|
6956
|
+
{
|
|
6957
|
+
cwd: resolveChannelConfig(channel.id).cwd,
|
|
6958
|
+
workspaceId: workspace.id,
|
|
6959
|
+
profile: channel.profile,
|
|
6960
|
+
channelId: channel.id,
|
|
6961
|
+
sourcePath: req.path,
|
|
6962
|
+
createdBy: "agent",
|
|
6963
|
+
...slug ? { slug } : {},
|
|
6964
|
+
features: {}
|
|
6965
|
+
},
|
|
6966
|
+
remoteAgentCallbacks().readDocShareBundle
|
|
6967
|
+
);
|
|
6968
|
+
} catch (err) {
|
|
6969
|
+
if (err instanceof DocShareSlugTakenError) return { error: `/share/${err.slug} is already taken.` };
|
|
6970
|
+
throw err;
|
|
6971
|
+
}
|
|
6972
|
+
switch (result.status) {
|
|
6973
|
+
case "not-found":
|
|
6974
|
+
return { error: "doc not found" };
|
|
6975
|
+
case "unsupported":
|
|
6976
|
+
return { error: "only Markdown and HTML docs can be shared" };
|
|
6977
|
+
case "too-large":
|
|
6978
|
+
return { error: "doc or its assets too large to share" };
|
|
6979
|
+
case "host-unavailable":
|
|
6980
|
+
case "host-outdated":
|
|
6981
|
+
return { error: "the Host could not read the doc" };
|
|
6982
|
+
default:
|
|
6983
|
+
return { url: `${workspaceShareOrigin(channel.profile)}/share/${result.share.slug ?? result.share.id}` };
|
|
6984
|
+
}
|
|
6985
|
+
});
|
|
6986
|
+
}
|
|
6987
|
+
|
|
6988
|
+
// ../api/src/actions/run-action.ts
|
|
6989
|
+
var ActionError = class extends Error {
|
|
6990
|
+
};
|
|
6991
|
+
var DEFAULT_PERMISSION_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
6992
|
+
var MAX_REPLIES = 100;
|
|
6993
|
+
var inScope = (ctx, workspace) => ctx.scope === null || ctx.scope.includes(workspace);
|
|
6994
|
+
async function channelInScope(ctx, channelId) {
|
|
6995
|
+
const { data, error: error2 } = await getSupabaseClient().from("channels").select("id, name, profile, cwd").eq("id", channelId).maybeSingle();
|
|
6996
|
+
if (error2) throw new Error(error2.message);
|
|
6997
|
+
if (!data || !inScope(ctx, data["profile"]))
|
|
6998
|
+
throw new ActionError(`No channel with id ${channelId}.`);
|
|
6999
|
+
return data;
|
|
6638
7000
|
}
|
|
7001
|
+
async function threadInScope(ctx, threadId) {
|
|
7002
|
+
const owner = await resolveThreadOwner(threadId);
|
|
7003
|
+
if (!owner || !inScope(ctx, owner.workspace))
|
|
7004
|
+
throw new ActionError(`No thread with id ${threadId}.`);
|
|
7005
|
+
return owner;
|
|
7006
|
+
}
|
|
7007
|
+
async function requesterUserId(ctx) {
|
|
7008
|
+
const { handle, workspace } = ctx.requester;
|
|
7009
|
+
if (!handle || !workspace || !inScope(ctx, workspace)) return null;
|
|
7010
|
+
const supabase = getSupabaseClient();
|
|
7011
|
+
const { data: ws } = await supabase.from("workspaces").select("id").eq("slug", workspace).maybeSingle();
|
|
7012
|
+
if (!ws) return null;
|
|
7013
|
+
const { data } = await supabase.from("memberships").select("user_id").eq("workspace_id", ws["id"]).ilike("handle", handle).maybeSingle();
|
|
7014
|
+
return data?.["user_id"] ?? null;
|
|
7015
|
+
}
|
|
7016
|
+
async function insertAgentReply(threadId, body) {
|
|
7017
|
+
const { data, error: error2 } = await getSupabaseClient().from("thread_replies").insert({ thread_id: threadId, author: AGENT_AUTHOR, body }).select("id").single();
|
|
7018
|
+
if (error2 || !data)
|
|
7019
|
+
throw new Error(`failed to write reply: ${error2?.message ?? "no row returned"}`);
|
|
7020
|
+
return data["id"];
|
|
7021
|
+
}
|
|
7022
|
+
var searchThreads = async (input2, ctx) => {
|
|
7023
|
+
const limit = Math.min(Math.max(Math.trunc(input2.limit ?? 10), 1), 30);
|
|
7024
|
+
const { data, error: error2 } = await getSupabaseClient().rpc("search_threads", {
|
|
7025
|
+
q: input2.query,
|
|
7026
|
+
match_limit: Math.min(limit * 5, 100)
|
|
7027
|
+
});
|
|
7028
|
+
if (error2) throw new Error(`search failed: ${error2.message}`);
|
|
7029
|
+
let rows = data ?? [];
|
|
7030
|
+
if (input2.channel_id) rows = rows.filter((r) => r.channel_id === input2.channel_id);
|
|
7031
|
+
if (ctx.scope !== null && rows.length) {
|
|
7032
|
+
const { data: channels } = await getSupabaseClient().from("channels").select("id").in("profile", ctx.scope).in("id", [...new Set(rows.map((r) => r.channel_id))]);
|
|
7033
|
+
const own = new Set((channels ?? []).map((c) => c["id"]));
|
|
7034
|
+
rows = rows.filter((r) => own.has(r.channel_id));
|
|
7035
|
+
}
|
|
7036
|
+
return rows.slice(0, limit);
|
|
7037
|
+
};
|
|
7038
|
+
var readThread = async (input2, ctx) => {
|
|
7039
|
+
const threadId = parseThreadRef(input2.thread_id);
|
|
7040
|
+
if (!threadId) throw new ActionError(`Not a thread id or thread link: ${input2.thread_id}`);
|
|
7041
|
+
const userId = await requesterUserId(ctx);
|
|
7042
|
+
const owner = await resolveThreadOwner(threadId);
|
|
7043
|
+
const allowed = !!owner && (userId ? await canReadThread(owner, userId) : inScope(ctx, owner.workspace));
|
|
7044
|
+
if (!owner || !allowed) return null;
|
|
7045
|
+
const supabase = getSupabaseClient();
|
|
7046
|
+
const { data: thread, error: error2 } = await supabase.from("threads").select("title, auto_title, author, created_at").eq("id", threadId).maybeSingle();
|
|
7047
|
+
if (error2) throw new Error(`read failed: ${error2.message}`);
|
|
7048
|
+
if (!thread) return null;
|
|
7049
|
+
const { data: replies, error: repliesError } = await supabase.from("thread_replies").select("author, body, created_at").eq("thread_id", threadId).is("archived_at", null).order("created_at", { ascending: true }).limit(MAX_REPLIES);
|
|
7050
|
+
if (repliesError) throw new Error(`read failed: ${repliesError.message}`);
|
|
7051
|
+
return {
|
|
7052
|
+
link: threadPath(owner.workspace, owner.channelId, threadId),
|
|
7053
|
+
title: thread["title"] ?? thread["auto_title"] ?? null,
|
|
7054
|
+
author: thread["author"],
|
|
7055
|
+
created_at: thread["created_at"],
|
|
7056
|
+
replies: replies ?? []
|
|
7057
|
+
};
|
|
7058
|
+
};
|
|
7059
|
+
var listChannels3 = async (_input, ctx) => {
|
|
7060
|
+
let query = getSupabaseClient().from("channels").select("id, name, profile, cwd");
|
|
7061
|
+
if (ctx.scope !== null) query = query.in("profile", ctx.scope);
|
|
7062
|
+
const { data, error: error2 } = await query.order("name");
|
|
7063
|
+
if (error2) throw new Error(`list channels failed: ${error2.message}`);
|
|
7064
|
+
return data ?? [];
|
|
7065
|
+
};
|
|
7066
|
+
var createThread = async (input2, ctx) => {
|
|
7067
|
+
const channel = await channelInScope(ctx, input2.channel_id);
|
|
7068
|
+
const { data, error: error2 } = await getSupabaseClient().from("threads").insert({
|
|
7069
|
+
channel_id: channel.id,
|
|
7070
|
+
// An untitled thread is effectively invisible in the sidebar, so derive
|
|
7071
|
+
// one from the first line unless the caller named the thread itself.
|
|
7072
|
+
title: input2.title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(input2.text),
|
|
7073
|
+
author: AGENT_AUTHOR
|
|
7074
|
+
}).select("id").single();
|
|
7075
|
+
if (error2 || !data)
|
|
7076
|
+
throw new Error(`failed to create thread: ${error2?.message ?? "no row returned"}`);
|
|
7077
|
+
const threadId = data["id"];
|
|
7078
|
+
return { threadId, replyId: await insertAgentReply(threadId, input2.text) };
|
|
7079
|
+
};
|
|
7080
|
+
var postReply = async (input2, ctx) => {
|
|
7081
|
+
const owner = await threadInScope(ctx, input2.thread_id);
|
|
7082
|
+
return { threadId: owner.threadId, replyId: await insertAgentReply(owner.threadId, input2.text) };
|
|
7083
|
+
};
|
|
7084
|
+
var moveThread2 = async (input2, ctx) => {
|
|
7085
|
+
const owner = await threadInScope(ctx, input2.thread_id);
|
|
7086
|
+
if (owner.channelId === input2.to_channel_id) return "unchanged";
|
|
7087
|
+
const to = await channelInScope(ctx, input2.to_channel_id);
|
|
7088
|
+
const supabase = getSupabaseClient();
|
|
7089
|
+
const { data: fromRow } = await supabase.from("channels").select("id, name, cwd").eq("id", owner.channelId).maybeSingle();
|
|
7090
|
+
const { error: error2 } = await supabase.from("threads").update({ channel_id: to.id }).eq("id", owner.threadId);
|
|
7091
|
+
if (error2) throw new Error(`move failed: ${error2.message}`);
|
|
7092
|
+
const { error: notifyError } = await supabase.from("notifications").update({ channel_id: to.id }).eq("thread_id", owner.threadId);
|
|
7093
|
+
if (notifyError) throw new Error(`move failed (notifications): ${notifyError.message}`);
|
|
7094
|
+
return {
|
|
7095
|
+
from: fromRow ?? null,
|
|
7096
|
+
to: { id: to.id, name: to.name, cwd: to.cwd }
|
|
7097
|
+
};
|
|
7098
|
+
};
|
|
7099
|
+
var shareDoc = async (input2, ctx) => {
|
|
7100
|
+
const res = await publishDocShareForHost(ctx.scope, {
|
|
7101
|
+
channelId: input2.channel_id,
|
|
7102
|
+
path: input2.path,
|
|
7103
|
+
...input2.slug?.trim() ? { slug: input2.slug.trim() } : {}
|
|
7104
|
+
});
|
|
7105
|
+
if (!res.url) throw new ActionError(`Share failed: ${res.error ?? "unknown error"}`);
|
|
7106
|
+
return { url: res.url };
|
|
7107
|
+
};
|
|
7108
|
+
function describeToolInput(input2) {
|
|
7109
|
+
const pick = input2["command"] ?? input2["file_path"] ?? input2["path"] ?? input2["url"];
|
|
7110
|
+
const text = typeof pick === "string" ? pick : JSON.stringify(input2, null, 2);
|
|
7111
|
+
return text.length > 1500 ? `${text.slice(0, 1500)}\u2026` : text;
|
|
7112
|
+
}
|
|
7113
|
+
var permissionMarker = (id) => `[PERMISSION: ${id}]`;
|
|
7114
|
+
var requestPermission = async (input2, ctx) => {
|
|
7115
|
+
const { threadId, channelId, permissionTimeoutMs } = ctx.requester;
|
|
7116
|
+
if (!threadId || !channelId) throw new ActionError("No thread to ask in.");
|
|
7117
|
+
const owner = await threadInScope(ctx, threadId);
|
|
7118
|
+
if (owner.channelId !== channelId) throw new ActionError(`No thread with id ${threadId}.`);
|
|
7119
|
+
const supabase = getSupabaseClient();
|
|
7120
|
+
const timeoutMs = permissionTimeoutMs && permissionTimeoutMs > 0 ? permissionTimeoutMs : DEFAULT_PERMISSION_TIMEOUT_MS;
|
|
7121
|
+
const { data: request, error: error2 } = await supabase.from("permission_requests").insert({
|
|
7122
|
+
channel_id: channelId,
|
|
7123
|
+
thread_id: threadId,
|
|
7124
|
+
tool_name: input2.tool_name,
|
|
7125
|
+
input: input2.input,
|
|
7126
|
+
expires_at: new Date(Date.now() + timeoutMs).toISOString()
|
|
7127
|
+
}).select("id").single();
|
|
7128
|
+
if (error2 || !request) throw new Error(`failed to create permission request: ${error2?.message}`);
|
|
7129
|
+
const requestId = request["id"];
|
|
7130
|
+
const prompt = `The agent wants to use **${input2.tool_name}**:
|
|
7131
|
+
|
|
7132
|
+
\`\`\`
|
|
7133
|
+
${describeToolInput(input2.input)}
|
|
7134
|
+
\`\`\`
|
|
7135
|
+
|
|
7136
|
+
` + permissionMarker(requestId);
|
|
7137
|
+
const replyId = await insertAgentReply(threadId, prompt).catch(() => null);
|
|
7138
|
+
if (replyId)
|
|
7139
|
+
await supabase.from("permission_requests").update({ reply_id: replyId }).eq("id", requestId);
|
|
7140
|
+
return { requestId };
|
|
7141
|
+
};
|
|
7142
|
+
var checkPermission = async (input2, ctx) => {
|
|
7143
|
+
const supabase = getSupabaseClient();
|
|
7144
|
+
const read = async () => {
|
|
7145
|
+
const { data } = await supabase.from("permission_requests").select("channel_id, thread_id, reply_id, status, decided_by, expires_at").eq("id", input2.request_id).maybeSingle();
|
|
7146
|
+
return data;
|
|
7147
|
+
};
|
|
7148
|
+
let row = await read();
|
|
7149
|
+
if (!row) throw new ActionError(`No permission request ${input2.request_id}.`);
|
|
7150
|
+
const channel = await channelInScope(ctx, row["channel_id"]).catch(() => null);
|
|
7151
|
+
if (!channel) throw new ActionError(`No permission request ${input2.request_id}.`);
|
|
7152
|
+
if (row["status"] === "pending" && Date.parse(row["expires_at"]) <= Date.now()) {
|
|
7153
|
+
await supabase.from("permission_requests").update({ status: "expired" }).eq("id", input2.request_id).eq("status", "pending");
|
|
7154
|
+
row = await read() ?? row;
|
|
7155
|
+
}
|
|
7156
|
+
const status = row["status"];
|
|
7157
|
+
const decidedBy = row["decided_by"] ?? null;
|
|
7158
|
+
const replyId = row["reply_id"];
|
|
7159
|
+
if (status !== "pending" && replyId) {
|
|
7160
|
+
const outcome = status === "allow" ? `\u2705 Allowed by @${decidedBy}` : status === "deny" ? `\u{1F6AB} Denied by @${decidedBy}` : "\u23F0 No answer in time, denied automatically";
|
|
7161
|
+
const { data: reply } = await supabase.from("thread_replies").select("body").eq("id", replyId).maybeSingle();
|
|
7162
|
+
const body = reply?.["body"];
|
|
7163
|
+
if (body?.includes(permissionMarker(input2.request_id))) {
|
|
7164
|
+
await supabase.from("thread_replies").update({ body: body.replace(permissionMarker(input2.request_id), outcome) }).eq("id", replyId).eq("thread_id", row["thread_id"]);
|
|
7165
|
+
}
|
|
7166
|
+
}
|
|
7167
|
+
return { status, decidedBy };
|
|
7168
|
+
};
|
|
7169
|
+
var HANDLERS = {
|
|
7170
|
+
[searchThreadsAction.name]: searchThreads,
|
|
7171
|
+
[readThreadAction.name]: readThread,
|
|
7172
|
+
[listChannelsAction.name]: listChannels3,
|
|
7173
|
+
[createThreadAction.name]: createThread,
|
|
7174
|
+
[postReplyAction.name]: postReply,
|
|
7175
|
+
[moveThreadAction.name]: moveThread2,
|
|
7176
|
+
[shareDocAction.name]: shareDoc,
|
|
7177
|
+
[requestPermissionAction.name]: requestPermission,
|
|
7178
|
+
[checkPermissionAction.name]: checkPermission
|
|
7179
|
+
};
|
|
6639
7180
|
|
|
6640
7181
|
// ../api/src/dashboard/agent-bridge-data.ts
|
|
6641
7182
|
var hosts = /* @__PURE__ */ new Map();
|
|
7183
|
+
var pending = /* @__PURE__ */ new Map();
|
|
6642
7184
|
var hostStatusListeners = /* @__PURE__ */ new Set();
|
|
7185
|
+
var lastAuthFailure = null;
|
|
7186
|
+
function hostFor(profile) {
|
|
7187
|
+
let legacy = null;
|
|
7188
|
+
let scoped = null;
|
|
7189
|
+
for (const [ws, scope] of hosts) {
|
|
7190
|
+
if (ws.readyState !== WebSocket.OPEN) continue;
|
|
7191
|
+
if (scope.workspaces === null) legacy = ws;
|
|
7192
|
+
else if (scope.workspaces.includes(profile)) scoped = ws;
|
|
7193
|
+
}
|
|
7194
|
+
return scoped ?? legacy;
|
|
7195
|
+
}
|
|
7196
|
+
function isHostConnected(profile) {
|
|
7197
|
+
if (profile) return hostFor(profile) !== null;
|
|
7198
|
+
for (const ws of hosts.keys()) if (ws.readyState === WebSocket.OPEN) return true;
|
|
7199
|
+
return false;
|
|
7200
|
+
}
|
|
7201
|
+
function getHostCliVersion(profile) {
|
|
7202
|
+
const ws = hostFor(profile);
|
|
7203
|
+
return ws && hosts.get(ws)?.cliVersion || null;
|
|
7204
|
+
}
|
|
7205
|
+
function getHostPinnedModel(profile) {
|
|
7206
|
+
const ws = hostFor(profile);
|
|
7207
|
+
return ws && hosts.get(ws)?.pinnedModel || null;
|
|
7208
|
+
}
|
|
7209
|
+
function getHostOfflineReason() {
|
|
7210
|
+
return lastAuthFailure;
|
|
7211
|
+
}
|
|
6643
7212
|
function notifyHostStatus() {
|
|
6644
7213
|
const online = hosts.size > 0;
|
|
6645
7214
|
for (const l of hostStatusListeners) l(online);
|
|
@@ -6656,10 +7225,134 @@ function disconnectHostDevice(deviceId) {
|
|
|
6656
7225
|
}
|
|
6657
7226
|
}
|
|
6658
7227
|
var LAST_SEEN_RESOLUTION_MS = 60 * 6e4;
|
|
7228
|
+
var lastCallFailure = /* @__PURE__ */ new Map();
|
|
6659
7229
|
var lastCallError = /* @__PURE__ */ new Map();
|
|
6660
7230
|
function getHostCallError(method, profile = getProfile()) {
|
|
6661
7231
|
return lastCallError.get(`${profile}:${method}`) ?? null;
|
|
6662
7232
|
}
|
|
7233
|
+
function getHostCallFailure(method, profile = getProfile()) {
|
|
7234
|
+
return lastCallFailure.get(`${profile}:${method}`) ?? null;
|
|
7235
|
+
}
|
|
7236
|
+
function callHost(method, args, timeoutMs = CALL_TIMEOUT_MS) {
|
|
7237
|
+
const profile = getProfile();
|
|
7238
|
+
const ws = hostFor(profile);
|
|
7239
|
+
const key = `${profile}:${method}`;
|
|
7240
|
+
lastCallFailure.delete(key);
|
|
7241
|
+
lastCallError.delete(key);
|
|
7242
|
+
if (!ws) {
|
|
7243
|
+
lastCallFailure.set(key, isHostConnected() ? "unscoped" : "offline");
|
|
7244
|
+
console.error(
|
|
7245
|
+
isHostConnected() ? `[host-socket] ${method} -> not scoped to workspace "${profile}"` : `[host-socket] ${method} -> no Host connected`
|
|
7246
|
+
);
|
|
7247
|
+
return Promise.resolve(null);
|
|
7248
|
+
}
|
|
7249
|
+
if (method === "docsRequest") console.log(`[host-socket] docsRequest for "${profile}" -> device ${hosts.get(ws)?.deviceId ?? "legacy"}`);
|
|
7250
|
+
const id = randomUUID2();
|
|
7251
|
+
return new Promise((resolve7) => {
|
|
7252
|
+
const timer2 = setTimeout(() => {
|
|
7253
|
+
pending.delete(id);
|
|
7254
|
+
lastCallFailure.set(key, "timeout");
|
|
7255
|
+
console.error(`[host-socket] ${method} -> timed out after ${timeoutMs}ms`);
|
|
7256
|
+
resolve7(null);
|
|
7257
|
+
}, timeoutMs);
|
|
7258
|
+
pending.set(id, {
|
|
7259
|
+
key,
|
|
7260
|
+
resolve: (value) => {
|
|
7261
|
+
clearTimeout(timer2);
|
|
7262
|
+
resolve7(value);
|
|
7263
|
+
}
|
|
7264
|
+
});
|
|
7265
|
+
const sent = [...args];
|
|
7266
|
+
while (sent.length > 0 && sent[sent.length - 1] === void 0) sent.pop();
|
|
7267
|
+
send(ws, { type: "call", id, method, profile, args: sent });
|
|
7268
|
+
});
|
|
7269
|
+
}
|
|
7270
|
+
function remoteAgentCallbacks() {
|
|
7271
|
+
return {
|
|
7272
|
+
// Fire-and-forget on the Data side exactly as the in-process call was:
|
|
7273
|
+
// the reply lands in Supabase later, via Realtime, not in this response.
|
|
7274
|
+
onChatMessage: (msg) => {
|
|
7275
|
+
void callHost("onChatMessage", [msg]);
|
|
7276
|
+
},
|
|
7277
|
+
isAgentThinking: async (threadId) => await callHost("isAgentThinking", [threadId]) ?? false,
|
|
7278
|
+
getAgentActivities: async (threadId) => await callHost("getAgentActivities", [threadId]) ?? [],
|
|
7279
|
+
getBackgroundTasks: async (threadId) => await callHost("getBackgroundTasks", [threadId]) ?? [],
|
|
7280
|
+
cancelAgentRun: async (threadId) => await callHost("cancelAgentRun", [threadId]) ?? false,
|
|
7281
|
+
regenerateAgentRun: async (threadId, stoppedReplyId) => await callHost("regenerateAgentRun", [threadId, stoppedReplyId]) ?? false,
|
|
7282
|
+
listAgentRuns: async () => await callHost("listAgentRuns", []) ?? [],
|
|
7283
|
+
// `null` (no Host, or no answer in time) passes through: the extractor
|
|
7284
|
+
// reads it as a failed call and retries the thread next sweep.
|
|
7285
|
+
completeMemoryExtraction: (req) => callHost("completeMemoryExtraction", [req], MEMORY_EXTRACTION_TIMEOUT_MS),
|
|
7286
|
+
// `null` passes through: channel-suggest.ts tells "no Host" from "old Host".
|
|
7287
|
+
suggestChannelField: (req) => callHost("suggestChannelField", [req], MEMORY_EXTRACTION_TIMEOUT_MS),
|
|
7288
|
+
// Deliberately passes `null` through rather than defaulting to `[]`: with
|
|
7289
|
+
// no Host connected, claiming every folder is fine would be a guess.
|
|
7290
|
+
listMissingCwds: () => callHost("listMissingCwds", []),
|
|
7291
|
+
// Unlike listMissingCwds, `[]` is a fine fallback here: this only feeds
|
|
7292
|
+
// the "running" badge next to a profile name in the switcher, so with no
|
|
7293
|
+
// Host connected, showing nobody as running is a reasonable default
|
|
7294
|
+
// rather than a false claim of certainty either way.
|
|
7295
|
+
listRunningProfiles: async () => await callHost("listRunningProfiles", []) ?? [],
|
|
7296
|
+
// `null` (no Host) falls back to `offlineAgentIdentities` in api.ts.
|
|
7297
|
+
getAgentIdentities: (viewer) => callHost("getAgentIdentities", [viewer]),
|
|
7298
|
+
// Reading the doc and its assets can only happen where the channel's
|
|
7299
|
+
// real folder is, so this goes to the Host; the DB and R2 work stays here
|
|
7300
|
+
// (doc-share-publish.ts). `null` with no recorded failure means the Host
|
|
7301
|
+
// answered but has no such method: an install from before the split.
|
|
7302
|
+
// Longer timeout because the reply carries the assets' bytes.
|
|
7303
|
+
readDocShareBundle: async (req) => {
|
|
7304
|
+
const bundle = await callHost("readDocShareBundle", [req], DOCS_CALL_TIMEOUT_MS);
|
|
7305
|
+
if (bundle) return bundle;
|
|
7306
|
+
return getHostCallFailure("readDocShareBundle") ? { status: "host-unavailable" } : { status: "host-outdated" };
|
|
7307
|
+
},
|
|
7308
|
+
// Empty is a fine fallback for a discovery list: no Host connected means
|
|
7309
|
+
// no skills to offer, not a fabricated claim about what's available.
|
|
7310
|
+
listChannelSkills: async (args) => await callHost("listChannelSkills", [args]) ?? [],
|
|
7311
|
+
// Same reasoning as listChannelSkills — this only feeds the Docs pane's
|
|
7312
|
+
// List view/search, so an empty result reads as "nothing found yet".
|
|
7313
|
+
listFlatDocs: async (args) => await callHost("listFlatDocs", [args]) ?? [],
|
|
7314
|
+
// `localDefaults()` mirrors what `loadDashboardSettings()` itself returns
|
|
7315
|
+
// for a missing/corrupt file, so "no Host connected" reads the same as a
|
|
7316
|
+
// freshly provisioned workspace rather than as broken settings.
|
|
7317
|
+
getLocalDashboardSettings: async () => await callHost("getLocalDashboardSettings", []) ?? localDefaults(),
|
|
7318
|
+
// A write: no honest empty-ish fallback, so `null` (callHost's own
|
|
7319
|
+
// no-Host/timeout result) surfaces as a 503 on the Data side rather than
|
|
7320
|
+
// a fabricated success (see readDocShareBundle).
|
|
7321
|
+
saveLocalDashboardSettings: (patch) => callHost("saveLocalDashboardSettings", [patch]),
|
|
7322
|
+
// Same posture as saveLocalDashboardSettings: `null` becomes a 503.
|
|
7323
|
+
writeSkill: (ref, write) => callHost("writeSkill", [ref, write]),
|
|
7324
|
+
// Same posture as writeSkill: `null` becomes a 503.
|
|
7325
|
+
outputStylesRequest: (req) => callHost("outputStylesRequest", [req]),
|
|
7326
|
+
// Submitting a Claude code waits on the CLI to mint the token.
|
|
7327
|
+
providerLoginRequest: (req) => callHost("providerLoginRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7328
|
+
// Same posture again. Longer timeout: a first translation of a doc runs a
|
|
7329
|
+
// model call on the Host before it answers.
|
|
7330
|
+
docsRequest: (req) => callHost("docsRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7331
|
+
hostRequest: (req) => callHost("hostRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7332
|
+
// `null` (no Host connected) is passed through rather than defaulting to
|
|
7333
|
+
// `[]` — see listSessions's doc comment on AgentCallbacks.
|
|
7334
|
+
listSessions: () => callHost("listSessions", []),
|
|
7335
|
+
// `claude mcp list` health-checks every server, which takes seconds.
|
|
7336
|
+
listMcpServers: () => callHost("listMcpServers", [], DOCS_CALL_TIMEOUT_MS),
|
|
7337
|
+
upgradeHost: () => callHost("upgradeHost", []),
|
|
7338
|
+
// Both need this machine's disk and CLI history, so `null` (no Host)
|
|
7339
|
+
// surfaces as a 503 rather than an empty scan or a fake success.
|
|
7340
|
+
// A first scan walks every CLI transcript on a cold disk, so it gets the
|
|
7341
|
+
// long timeout; linking can create and seed several folders.
|
|
7342
|
+
scanOnboarding: (slug) => callHost("scanOnboarding", [slug], DOCS_CALL_TIMEOUT_MS),
|
|
7343
|
+
linkProjectFolders: (slug, items2) => callHost("linkProjectFolders", [slug, items2], DOCS_CALL_TIMEOUT_MS),
|
|
7344
|
+
// A first scan or a long transcript walks a lot of disk: the long timeout.
|
|
7345
|
+
sessionImportRequest: (req) => callHost("sessionImportRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7346
|
+
getHostCallFailure: (method) => getHostCallFailure(method),
|
|
7347
|
+
isHostOnline: (profile) => isHostConnected(profile),
|
|
7348
|
+
getHostOfflineReason,
|
|
7349
|
+
getHostCliVersion,
|
|
7350
|
+
getHostPinnedModel
|
|
7351
|
+
};
|
|
7352
|
+
}
|
|
7353
|
+
function send(ws, msg) {
|
|
7354
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(encodeWireMessage(msg));
|
|
7355
|
+
}
|
|
6663
7356
|
|
|
6664
7357
|
// ../api/src/dashboard/unique-channel-name.ts
|
|
6665
7358
|
function uniqueChannelName(raw, taken) {
|
|
@@ -6853,11 +7546,11 @@ function createOnboardingRouter(agent) {
|
|
|
6853
7546
|
const ctx = await resolveAuthContext(c);
|
|
6854
7547
|
if (ctx?.role !== "admin") return c.json({ pending: false });
|
|
6855
7548
|
const greetedAt = await getWorkspaceGreetedAt(ctx.workspaceId);
|
|
6856
|
-
const
|
|
6857
|
-
if (!
|
|
7549
|
+
const pending2 = !!ctx.projectsSetupAt && !greetedAt;
|
|
7550
|
+
if (!pending2) return c.json({ pending: pending2, channelId: null, threadId: null });
|
|
6858
7551
|
const general = await ensureGeneralChannel();
|
|
6859
7552
|
const threadId = await ensureGreetingThread(ctx.workspaceId, general.id, ctx.name?.trim() || ctx.handle);
|
|
6860
|
-
return c.json({ pending, channelId: general.id, threadId });
|
|
7553
|
+
return c.json({ pending: pending2, channelId: general.id, threadId });
|
|
6861
7554
|
});
|
|
6862
7555
|
app.post("/greeting", async (c) => {
|
|
6863
7556
|
const ctx = await resolveAuthContext(c);
|
|
@@ -7690,13 +8383,13 @@ function createContinuousChatRouter() {
|
|
|
7690
8383
|
};
|
|
7691
8384
|
});
|
|
7692
8385
|
const activeSince = Date.now() - ACTIVE_TOPIC_DAYS * 864e5;
|
|
7693
|
-
const
|
|
8386
|
+
const pending2 = replies.filter(
|
|
7694
8387
|
(r) => !tags.has(r.id) && isHumanAuthor(r.author) && Date.parse(r.created_at) >= activeSince && !backfilling.has(r.id)
|
|
7695
8388
|
).slice(0, BACKFILL_PER_REQUEST);
|
|
7696
|
-
if (
|
|
7697
|
-
for (const r of
|
|
8389
|
+
if (pending2.length) {
|
|
8390
|
+
for (const r of pending2) backfilling.add(r.id);
|
|
7698
8391
|
void (async () => {
|
|
7699
|
-
for (const r of
|
|
8392
|
+
for (const r of pending2) {
|
|
7700
8393
|
await tagReply({ channel, replyId: r.id, author: r.author, body: r.body }).catch(
|
|
7701
8394
|
() => {
|
|
7702
8395
|
}
|
|
@@ -7710,7 +8403,7 @@ function createContinuousChatRouter() {
|
|
|
7710
8403
|
messages.filter((m) => m.topic && Date.parse(m.created_at) >= activeSince).map((m) => m.topic)
|
|
7711
8404
|
)
|
|
7712
8405
|
];
|
|
7713
|
-
return c.json({ messages, topics: activeTopics, pendingTags:
|
|
8406
|
+
return c.json({ messages, topics: activeTopics, pendingTags: pending2.length });
|
|
7714
8407
|
});
|
|
7715
8408
|
app.patch("/replies/:replyId/topic", async (c) => {
|
|
7716
8409
|
if (!await isFeatureEnabled(c, "continuous-chat"))
|
|
@@ -9032,147 +9725,6 @@ function createChatRouter(agent = {}) {
|
|
|
9032
9725
|
// ../api/src/dashboard/doc-shares-routes.ts
|
|
9033
9726
|
import { Hono as Hono14 } from "hono";
|
|
9034
9727
|
|
|
9035
|
-
// ../api/src/dashboard/doc-share-features.ts
|
|
9036
|
-
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
9037
|
-
var DEFAULT_FEATURES = {
|
|
9038
|
-
audioEnabled: false,
|
|
9039
|
-
askEnabled: true,
|
|
9040
|
-
socialEnabled: false,
|
|
9041
|
-
brandingEnabled: true,
|
|
9042
|
-
translationEnabled: false,
|
|
9043
|
-
translationLangs: []
|
|
9044
|
-
};
|
|
9045
|
-
var HTML_FEATURES = {
|
|
9046
|
-
audioEnabled: false,
|
|
9047
|
-
askEnabled: false,
|
|
9048
|
-
socialEnabled: false,
|
|
9049
|
-
brandingEnabled: false,
|
|
9050
|
-
translationEnabled: false,
|
|
9051
|
-
translationLangs: []
|
|
9052
|
-
};
|
|
9053
|
-
function resolveFeatures(requested, existing) {
|
|
9054
|
-
const base = existing ?? DEFAULT_FEATURES;
|
|
9055
|
-
return {
|
|
9056
|
-
audioEnabled: requested?.audio ?? base.audioEnabled,
|
|
9057
|
-
askEnabled: requested?.ask ?? base.askEnabled,
|
|
9058
|
-
socialEnabled: requested?.social ?? base.socialEnabled,
|
|
9059
|
-
brandingEnabled: requested?.branding ?? base.brandingEnabled,
|
|
9060
|
-
translationEnabled: requested?.translation ?? base.translationEnabled,
|
|
9061
|
-
// Replaced wholesale, not merged: the allowlist IS the answer to "which
|
|
9062
|
-
// languages does this link offer", and a merge would make removing one
|
|
9063
|
-
// impossible.
|
|
9064
|
-
translationLangs: requested?.translationLangs ?? base.translationLangs
|
|
9065
|
-
};
|
|
9066
|
-
}
|
|
9067
|
-
async function deleteShareAssets(keys) {
|
|
9068
|
-
const client2 = getR2Client();
|
|
9069
|
-
const bucket = getR2Bucket();
|
|
9070
|
-
for (const key of keys) {
|
|
9071
|
-
try {
|
|
9072
|
-
await client2.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
|
|
9073
|
-
} catch {
|
|
9074
|
-
}
|
|
9075
|
-
}
|
|
9076
|
-
}
|
|
9077
|
-
async function updateShareFeatures(share, requested) {
|
|
9078
|
-
if (share.kind === "html") return share;
|
|
9079
|
-
if (share.kind === "excalidraw") {
|
|
9080
|
-
if (requested.branding === void 0) return share;
|
|
9081
|
-
return updateDocShareFeatures(share.id, { ...share, brandingEnabled: requested.branding });
|
|
9082
|
-
}
|
|
9083
|
-
const features = resolveFeatures(requested, share);
|
|
9084
|
-
const updated = await updateDocShareFeatures(share.id, features);
|
|
9085
|
-
if (!updated) return null;
|
|
9086
|
-
if (features.audioEnabled) void queueShareAudio(updated);
|
|
9087
|
-
else if (share.audioEnabled) await dropShareAudio(share);
|
|
9088
|
-
return updated;
|
|
9089
|
-
}
|
|
9090
|
-
|
|
9091
|
-
// ../api/src/dashboard/doc-share-publish.ts
|
|
9092
|
-
import { randomBytes as randomBytes5 } from "crypto";
|
|
9093
|
-
import { CopyObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-sdk/client-s3";
|
|
9094
|
-
|
|
9095
|
-
// ../api/src/dashboard/bridge-types.ts
|
|
9096
|
-
var SHARE_ASSET_PLACEHOLDER = "/share/{{flyspace-share-id}}/assets/";
|
|
9097
|
-
|
|
9098
|
-
// ../api/src/dashboard/doc-share-publish.ts
|
|
9099
|
-
var SHARE_KEY_PREFIX = "share";
|
|
9100
|
-
function generateShareId() {
|
|
9101
|
-
return randomBytes5(9).toString("base64url");
|
|
9102
|
-
}
|
|
9103
|
-
async function publishDocShare(input2, readBundle) {
|
|
9104
|
-
const bundle = await readBundle({ channelId: input2.channelId, cwd: input2.cwd, sourcePath: input2.sourcePath });
|
|
9105
|
-
if (bundle.status !== "ok") return bundle;
|
|
9106
|
-
const existing = await findDocShareBySource(input2.workspaceId, input2.channelId, input2.sourcePath);
|
|
9107
|
-
const shareId = existing?.id ?? generateShareId();
|
|
9108
|
-
const client2 = getR2Client();
|
|
9109
|
-
const bucket = getR2Bucket();
|
|
9110
|
-
const assetKeys = [];
|
|
9111
|
-
for (const asset of bundle.assets) {
|
|
9112
|
-
const key = `${SHARE_KEY_PREFIX}/${shareId}/${asset.name}`;
|
|
9113
|
-
if ("copyFrom" in asset) {
|
|
9114
|
-
await client2.send(
|
|
9115
|
-
new CopyObjectCommand({
|
|
9116
|
-
Bucket: bucket,
|
|
9117
|
-
Key: key,
|
|
9118
|
-
CopySource: `${bucket}/${asset.copyFrom}`.split("/").map(encodeURIComponent).join("/")
|
|
9119
|
-
})
|
|
9120
|
-
);
|
|
9121
|
-
} else {
|
|
9122
|
-
await client2.send(
|
|
9123
|
-
new PutObjectCommand2({
|
|
9124
|
-
Bucket: bucket,
|
|
9125
|
-
Key: key,
|
|
9126
|
-
Body: Buffer.from(asset.data, "base64"),
|
|
9127
|
-
ContentType: asset.contentType
|
|
9128
|
-
})
|
|
9129
|
-
);
|
|
9130
|
-
}
|
|
9131
|
-
assetKeys.push(key);
|
|
9132
|
-
}
|
|
9133
|
-
const built = {
|
|
9134
|
-
kind: bundle.kind,
|
|
9135
|
-
title: bundle.title,
|
|
9136
|
-
content: bundle.content.split(SHARE_ASSET_PLACEHOLDER).join(`/share/${shareId}/assets/`),
|
|
9137
|
-
assetKeys
|
|
9138
|
-
};
|
|
9139
|
-
const html = built.kind !== "markdown";
|
|
9140
|
-
const features = built.kind === "excalidraw" ? {
|
|
9141
|
-
...HTML_FEATURES,
|
|
9142
|
-
brandingEnabled: resolveFeatures(input2.features, existing).brandingEnabled
|
|
9143
|
-
} : html ? HTML_FEATURES : resolveFeatures(input2.features, existing);
|
|
9144
|
-
const snapshot2 = {
|
|
9145
|
-
...built,
|
|
9146
|
-
sourceLang: html ? null : await detectSourceLanguage(built.title, built.content)
|
|
9147
|
-
};
|
|
9148
|
-
const slug = input2.slug === void 0 ? existing?.slug ?? null : input2.slug;
|
|
9149
|
-
if (existing) {
|
|
9150
|
-
if (slug !== (existing.slug ?? null)) {
|
|
9151
|
-
const renamed = await setDocShareSlug(existing.id, slug);
|
|
9152
|
-
if (!renamed) return { status: "not-found" };
|
|
9153
|
-
}
|
|
9154
|
-
const share2 = await updateDocShareSnapshot(existing.id, snapshot2, features);
|
|
9155
|
-
const stale = existing.assetKeys.filter((key) => !snapshot2.assetKeys.includes(key));
|
|
9156
|
-
await deleteShareAssets(stale);
|
|
9157
|
-
if (!features.audioEnabled && existing.audioEnabled) await dropShareAudio(existing);
|
|
9158
|
-
void queueShareAudio(share2);
|
|
9159
|
-
return { status: "ok", share: share2 };
|
|
9160
|
-
}
|
|
9161
|
-
const share = await createDocShare({
|
|
9162
|
-
id: shareId,
|
|
9163
|
-
slug,
|
|
9164
|
-
workspaceId: input2.workspaceId,
|
|
9165
|
-
profile: input2.profile,
|
|
9166
|
-
channelId: input2.channelId,
|
|
9167
|
-
sourcePath: input2.sourcePath,
|
|
9168
|
-
createdBy: input2.createdBy,
|
|
9169
|
-
...snapshot2,
|
|
9170
|
-
...features
|
|
9171
|
-
});
|
|
9172
|
-
void queueShareAudio(share);
|
|
9173
|
-
return { status: "ok", share };
|
|
9174
|
-
}
|
|
9175
|
-
|
|
9176
9728
|
// ../api/src/dashboard/share-tags.ts
|
|
9177
9729
|
var MAX_TAGS = 10;
|
|
9178
9730
|
var MAX_TAG_LENGTH = 30;
|
|
@@ -9192,46 +9744,6 @@ function normalizeTags(raw) {
|
|
|
9192
9744
|
return [...tags];
|
|
9193
9745
|
}
|
|
9194
9746
|
|
|
9195
|
-
// ../api/src/dashboard/share-slug.ts
|
|
9196
|
-
var MIN_SLUG = 2;
|
|
9197
|
-
var MAX_SLUG = 64;
|
|
9198
|
-
var SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
9199
|
-
var RESERVED2 = /* @__PURE__ */ new Set([
|
|
9200
|
-
"admin",
|
|
9201
|
-
"api",
|
|
9202
|
-
"assets",
|
|
9203
|
-
"audio",
|
|
9204
|
-
"auth",
|
|
9205
|
-
"favicon",
|
|
9206
|
-
"login",
|
|
9207
|
-
"new",
|
|
9208
|
-
"og",
|
|
9209
|
-
"robots",
|
|
9210
|
-
"share",
|
|
9211
|
-
"sitemap",
|
|
9212
|
-
"static"
|
|
9213
|
-
]);
|
|
9214
|
-
function normalizeSlug(raw) {
|
|
9215
|
-
const slug = raw.trim().toLowerCase();
|
|
9216
|
-
if (slug.length < MIN_SLUG) return { error: "too-short" };
|
|
9217
|
-
if (slug.length > MAX_SLUG) return { error: "too-long" };
|
|
9218
|
-
if (!SLUG_SHAPE.test(slug)) return { error: "shape" };
|
|
9219
|
-
if (RESERVED2.has(slug)) return { error: "reserved" };
|
|
9220
|
-
return { slug };
|
|
9221
|
-
}
|
|
9222
|
-
function slugErrorMessage(err) {
|
|
9223
|
-
switch (err) {
|
|
9224
|
-
case "too-short":
|
|
9225
|
-
return `Use at least ${MIN_SLUG} characters.`;
|
|
9226
|
-
case "too-long":
|
|
9227
|
-
return `Keep it under ${MAX_SLUG} characters.`;
|
|
9228
|
-
case "reserved":
|
|
9229
|
-
return "That word is reserved. Try something more specific.";
|
|
9230
|
-
default:
|
|
9231
|
-
return "Use lowercase letters, numbers and hyphens.";
|
|
9232
|
-
}
|
|
9233
|
-
}
|
|
9234
|
-
|
|
9235
9747
|
// ../api/src/dashboard/doc-shares-routes.ts
|
|
9236
9748
|
function shareUrl(c, ref) {
|
|
9237
9749
|
const proto = c.req.header("x-forwarded-proto") ?? "http";
|
|
@@ -9543,7 +10055,7 @@ function snippetAround(text, q) {
|
|
|
9543
10055
|
const end = Math.min(text.length, start + SNIPPET_LENGTH);
|
|
9544
10056
|
return `${start > 0 ? "\u2026" : ""}${text.slice(start, end).trim()}${end < text.length ? "\u2026" : ""}`;
|
|
9545
10057
|
}
|
|
9546
|
-
async function
|
|
10058
|
+
async function searchThreads2(q) {
|
|
9547
10059
|
const supabase = getSupabaseClient();
|
|
9548
10060
|
const { data, error: error2 } = await supabase.rpc("search_threads", { q, match_limit: 20 });
|
|
9549
10061
|
if (error2) {
|
|
@@ -9669,7 +10181,7 @@ function createSearchRouter() {
|
|
|
9669
10181
|
const q = c.req.query("q")?.trim();
|
|
9670
10182
|
if (!q) return c.json({ results: [] });
|
|
9671
10183
|
const [threadResults, channelResults, automationResults] = await Promise.all([
|
|
9672
|
-
|
|
10184
|
+
searchThreads2(q),
|
|
9673
10185
|
Promise.resolve(searchChannels(q)),
|
|
9674
10186
|
Promise.resolve(searchAutomations(q))
|
|
9675
10187
|
]);
|
|
@@ -11616,8 +12128,8 @@ function createChannelGreetingRouter(agent) {
|
|
|
11616
12128
|
app.get("/:id/greeting", async (c) => {
|
|
11617
12129
|
const ctx = await resolveAuthContext(c);
|
|
11618
12130
|
const ch = findChannelById(c.req.param("id"));
|
|
11619
|
-
const
|
|
11620
|
-
if (!
|
|
12131
|
+
const pending2 = isWorkspaceOwner(ctx) && eligible(ch) && !ch.greetedAt && (agent.isHostOnline?.(ch.profile) ?? false);
|
|
12132
|
+
if (!pending2) return c.json({ pending: false, threadId: null });
|
|
11621
12133
|
const threadId = await ensureIntroThread(ch);
|
|
11622
12134
|
return c.json({ pending: !!threadId, threadId });
|
|
11623
12135
|
});
|
|
@@ -12729,7 +13241,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12729
13241
|
import { verify } from "crypto";
|
|
12730
13242
|
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
12731
13243
|
import { Hono as Hono33 } from "hono";
|
|
12732
|
-
var
|
|
13244
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12733
13245
|
function cleanText(value, max) {
|
|
12734
13246
|
if (typeof value !== "string") return null;
|
|
12735
13247
|
const trimmed = value.trim();
|
|
@@ -12800,18 +13312,18 @@ function createDeviceAuthRouter() {
|
|
|
12800
13312
|
app.post("/token", async (c) => {
|
|
12801
13313
|
const body = await readBody(c);
|
|
12802
13314
|
const code = typeof body["device_code"] === "string" ? body["device_code"] : "";
|
|
12803
|
-
const
|
|
12804
|
-
if (!
|
|
13315
|
+
const pending2 = code ? await getDeviceCodeBySecret(code) : null;
|
|
13316
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now()) {
|
|
12805
13317
|
return c.json({ error: "expired_token" }, 400);
|
|
12806
13318
|
}
|
|
12807
|
-
if (
|
|
12808
|
-
if (!
|
|
12809
|
-
const last =
|
|
12810
|
-
await markPolled(
|
|
13319
|
+
if (pending2.deniedAt) return c.json({ error: "access_denied" }, 400);
|
|
13320
|
+
if (!pending2.approvedBy) {
|
|
13321
|
+
const last = pending2.lastPolledAt ? Date.parse(pending2.lastPolledAt) : 0;
|
|
13322
|
+
await markPolled(pending2.id);
|
|
12811
13323
|
const tooSoon = Date.now() - last < (POLL_INTERVAL_S - 1) * 1e3;
|
|
12812
13324
|
return c.json({ error: tooSoon ? "slow_down" : "authorization_pending" }, 400);
|
|
12813
13325
|
}
|
|
12814
|
-
const device = await redeemDeviceCode(
|
|
13326
|
+
const device = await redeemDeviceCode(pending2);
|
|
12815
13327
|
if (!device) return c.json({ error: "expired_token" }, 400);
|
|
12816
13328
|
const { token, expiresInS } = await issueAccessToken(device.id);
|
|
12817
13329
|
return c.json({
|
|
@@ -12825,14 +13337,14 @@ function createDeviceAuthRouter() {
|
|
|
12825
13337
|
});
|
|
12826
13338
|
app.post("/challenge", async (c) => {
|
|
12827
13339
|
const body = await readBody(c);
|
|
12828
|
-
const deviceId = typeof body["device_id"] === "string" &&
|
|
13340
|
+
const deviceId = typeof body["device_id"] === "string" && UUID2.test(body["device_id"]) ? body["device_id"] : "";
|
|
12829
13341
|
const device = deviceId ? await getDevice(deviceId) : null;
|
|
12830
13342
|
if (!device || device.revokedAt) return c.json({ error: "unknown_device" }, 401);
|
|
12831
13343
|
return c.json({ nonce: await createChallenge(device.id) });
|
|
12832
13344
|
});
|
|
12833
13345
|
app.post("/refresh", async (c) => {
|
|
12834
13346
|
const body = await readBody(c);
|
|
12835
|
-
const deviceId = typeof body["device_id"] === "string" &&
|
|
13347
|
+
const deviceId = typeof body["device_id"] === "string" && UUID2.test(body["device_id"]) ? body["device_id"] : "";
|
|
12836
13348
|
const nonce = typeof body["nonce"] === "string" ? body["nonce"] : "";
|
|
12837
13349
|
const signature = typeof body["signature"] === "string" ? body["signature"] : "";
|
|
12838
13350
|
const device = deviceId ? await getDevice(deviceId) : null;
|
|
@@ -12864,22 +13376,22 @@ function createDeviceAuthRouter() {
|
|
|
12864
13376
|
const userId = await sessionUserId(c);
|
|
12865
13377
|
if (!userId) return c.json({ error: "not signed in" }, 401);
|
|
12866
13378
|
const userCode = normalizeUserCode(c.req.query("user_code") ?? "");
|
|
12867
|
-
const
|
|
12868
|
-
if (!
|
|
13379
|
+
const pending2 = userCode ? await getDeviceCodeByUserCode(userCode) : null;
|
|
13380
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now() || pending2.approvedBy || pending2.deniedAt) {
|
|
12869
13381
|
return c.json({ error: "That code is invalid, expired, or already used." }, 404);
|
|
12870
13382
|
}
|
|
12871
13383
|
const workspaces = await listAdminWorkspaces(userId);
|
|
12872
13384
|
const hosts2 = await listWorkspaceHosts(
|
|
12873
13385
|
workspaces.map((w) => w.id),
|
|
12874
|
-
|
|
13386
|
+
pending2.publicKey
|
|
12875
13387
|
);
|
|
12876
|
-
const bound = await boundWorkspaceIds(
|
|
13388
|
+
const bound = await boundWorkspaceIds(pending2.publicKey, userId);
|
|
12877
13389
|
return c.json({
|
|
12878
|
-
user_code:
|
|
12879
|
-
name:
|
|
12880
|
-
platform:
|
|
12881
|
-
ip:
|
|
12882
|
-
created_at:
|
|
13390
|
+
user_code: pending2.userCode,
|
|
13391
|
+
name: pending2.name,
|
|
13392
|
+
platform: pending2.platform,
|
|
13393
|
+
ip: pending2.requesterIp,
|
|
13394
|
+
created_at: pending2.createdAt,
|
|
12883
13395
|
// `host`: another machine this workspace already runs on, so it can't be
|
|
12884
13396
|
// picked. `bound`: this machine already serves it, so there's nothing to pick.
|
|
12885
13397
|
workspaces: workspaces.map((w) => ({ ...w, host: hosts2.get(w.id) ?? null, bound: bound.has(w.id) }))
|
|
@@ -12905,8 +13417,8 @@ function createDeviceAuthRouter() {
|
|
|
12905
13417
|
const userCode = normalizeUserCode(typeof body["user_code"] === "string" ? body["user_code"] : "");
|
|
12906
13418
|
const decision = body["decision"];
|
|
12907
13419
|
if (!userCode || decision !== "approve" && decision !== "deny") return c.json({ error: "invalid request" }, 400);
|
|
12908
|
-
const
|
|
12909
|
-
if (!
|
|
13420
|
+
const pending2 = await getDeviceCodeByUserCode(userCode);
|
|
13421
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now()) {
|
|
12910
13422
|
return c.json({ error: "That code is invalid or expired." }, 404);
|
|
12911
13423
|
}
|
|
12912
13424
|
let workspaceIds = [];
|
|
@@ -12917,22 +13429,22 @@ function createDeviceAuthRouter() {
|
|
|
12917
13429
|
if (workspaceIds.some((id) => !allowed.has(id))) {
|
|
12918
13430
|
return c.json({ error: "You can only add a device to workspaces you are an admin of." }, 403);
|
|
12919
13431
|
}
|
|
12920
|
-
if (!workspaceIds.length && !(await boundWorkspaceIds(
|
|
13432
|
+
if (!workspaceIds.length && !(await boundWorkspaceIds(pending2.publicKey, userId)).size) {
|
|
12921
13433
|
return c.json({ error: "Pick at least one workspace." }, 400);
|
|
12922
13434
|
}
|
|
12923
13435
|
}
|
|
12924
|
-
if ((await listWorkspaceHosts(workspaceIds,
|
|
13436
|
+
if ((await listWorkspaceHosts(workspaceIds, pending2.publicKey)).size) {
|
|
12925
13437
|
return c.json({ error: "That workspace already has a Host. Its Host cannot be replaced." }, 409);
|
|
12926
13438
|
}
|
|
12927
13439
|
const decided = await decideDeviceCode(
|
|
12928
|
-
|
|
13440
|
+
pending2.id,
|
|
12929
13441
|
userId,
|
|
12930
13442
|
decision === "approve" ? { approve: true, workspaceIds } : { approve: false }
|
|
12931
13443
|
);
|
|
12932
13444
|
if (!decided) {
|
|
12933
13445
|
return c.json({ error: "That code was already used." }, 409);
|
|
12934
13446
|
}
|
|
12935
|
-
await releaseStaleHosts(workspaceIds,
|
|
13447
|
+
await releaseStaleHosts(workspaceIds, pending2.publicKey);
|
|
12936
13448
|
return c.json({ ok: true });
|
|
12937
13449
|
});
|
|
12938
13450
|
return app;
|
|
@@ -14811,7 +15323,7 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14811
15323
|
...CLI_VERSION ? { cliVersion: CLI_VERSION } : {},
|
|
14812
15324
|
...pinnedModel ? { pinnedModel } : {}
|
|
14813
15325
|
};
|
|
14814
|
-
|
|
15326
|
+
send2(ws, deviceId ? { type: "auth", signature, deviceId, ...version } : { type: "auth", signature, ...version });
|
|
14815
15327
|
return;
|
|
14816
15328
|
}
|
|
14817
15329
|
if (msg.type === "auth-failed") {
|
|
@@ -14831,11 +15343,11 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14831
15343
|
}
|
|
14832
15344
|
if (msg.type === "auth-ok") {
|
|
14833
15345
|
console.log("[host-socket] authenticated");
|
|
14834
|
-
setHostDbSender((out) =>
|
|
14835
|
-
|
|
15346
|
+
setHostDbSender((out) => send2(ws, out));
|
|
15347
|
+
send2(ws, { type: "host-config", configs: buildHostConfigSnapshot() });
|
|
14836
15348
|
if (configPushTimer) clearInterval(configPushTimer);
|
|
14837
15349
|
configPushTimer = setInterval(() => {
|
|
14838
|
-
|
|
15350
|
+
send2(ws, { type: "host-config", configs: buildHostConfigSnapshot() });
|
|
14839
15351
|
}, HOST_CONFIG_PUSH_INTERVAL_MS);
|
|
14840
15352
|
onAuthenticated?.();
|
|
14841
15353
|
if (msg.workspaces) onWorkspaces?.(msg.workspaces);
|
|
@@ -14849,6 +15361,10 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14849
15361
|
handlePluginSvgResult(msg.id, msg.url);
|
|
14850
15362
|
return;
|
|
14851
15363
|
}
|
|
15364
|
+
if (msg.type === "action-result") {
|
|
15365
|
+
handleActionResult(msg.id, { value: msg.value, error: msg.error });
|
|
15366
|
+
return;
|
|
15367
|
+
}
|
|
14852
15368
|
if (msg.type === "attachment-url-result") {
|
|
14853
15369
|
handleAttachmentUrlResult(msg.id, msg.url);
|
|
14854
15370
|
return;
|
|
@@ -14898,9 +15414,9 @@ async function handleCall(msg, callbacks, ws) {
|
|
|
14898
15414
|
try {
|
|
14899
15415
|
const handler = callbacks[msg.method];
|
|
14900
15416
|
const value = await handler?.(...msg.args);
|
|
14901
|
-
|
|
15417
|
+
send2(ws, { type: "result", id: msg.id, value: value ?? null });
|
|
14902
15418
|
} catch (err) {
|
|
14903
|
-
|
|
15419
|
+
send2(ws, { type: "call-error", id: msg.id, message: err.message });
|
|
14904
15420
|
}
|
|
14905
15421
|
});
|
|
14906
15422
|
}
|
|
@@ -14946,7 +15462,7 @@ async function handleLocalRelay(req, callbacks, token) {
|
|
|
14946
15462
|
);
|
|
14947
15463
|
return Response.json({ value: value ?? null });
|
|
14948
15464
|
}
|
|
14949
|
-
function
|
|
15465
|
+
function send2(ws, msg) {
|
|
14950
15466
|
if (ws.readyState === WebSocket2.OPEN) ws.send(encodeWireMessage(msg));
|
|
14951
15467
|
}
|
|
14952
15468
|
|
|
@@ -15149,6 +15665,16 @@ async function startHostDashboard(preferredPort, host) {
|
|
|
15149
15665
|
}
|
|
15150
15666
|
});
|
|
15151
15667
|
}
|
|
15668
|
+
app.post(LOCAL_ACTION_PATH, async (c) => {
|
|
15669
|
+
if (!relayAuthorized(c.req.raw, relayToken)) return c.json({ error: "unauthorized" }, 401);
|
|
15670
|
+
const body = await c.req.json().catch(() => null);
|
|
15671
|
+
if (!body || typeof body.name !== "string") return c.json({ error: "bad request" }, 400);
|
|
15672
|
+
try {
|
|
15673
|
+
return c.json(await requestAction(body.name, body.input, body.requester));
|
|
15674
|
+
} catch (err) {
|
|
15675
|
+
return c.json({ error: err.message }, 503);
|
|
15676
|
+
}
|
|
15677
|
+
});
|
|
15152
15678
|
mountSpa(app);
|
|
15153
15679
|
const { server, port, url } = await listen(app, preferredPort, host);
|
|
15154
15680
|
relayToken = publishHostEndpoint(port);
|
|
@@ -15519,6 +16045,7 @@ var USAGE10 = `
|
|
|
15519
16045
|
usage Show agent token usage and cost for this workspace
|
|
15520
16046
|
chat Inspect dashboard chat channels and move threads between them
|
|
15521
16047
|
memory Read and write a channel's persistent agent memory
|
|
16048
|
+
docs Publish a channel doc as a public link (docs share)
|
|
15522
16049
|
persona Use a claudecafe character's faces as the bot's avatars
|
|
15523
16050
|
profiles List local profiles (bound here? scheduler?) or remove one
|
|
15524
16051
|
workspace Provision a workspace (Supabase rows + local profile dirs)
|
|
@@ -15622,6 +16149,9 @@ async function main() {
|
|
|
15622
16149
|
case "memory":
|
|
15623
16150
|
await runMemoryCmd(args.slice(1));
|
|
15624
16151
|
break;
|
|
16152
|
+
case "docs":
|
|
16153
|
+
await runDocsCmd(args.slice(1));
|
|
16154
|
+
break;
|
|
15625
16155
|
case "persona":
|
|
15626
16156
|
await runPersonaCmd(args.slice(1));
|
|
15627
16157
|
break;
|
|
@@ -15640,7 +16170,7 @@ async function main() {
|
|
|
15640
16170
|
break;
|
|
15641
16171
|
case "-v":
|
|
15642
16172
|
case "--version":
|
|
15643
|
-
printRaw("0.1.
|
|
16173
|
+
printRaw("0.1.61");
|
|
15644
16174
|
break;
|
|
15645
16175
|
case "-h":
|
|
15646
16176
|
case "--help":
|