flyspace-cli 0.1.60 → 0.1.62
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-SIR6PTDT.js → chunk-BDUA5N6B.js} +1088 -384
- package/dist/chunk-PLLJ7M62.js +14799 -0
- package/dist/{chunk-XYS7SVWC.js → chunk-UZMHXV4D.js} +40 -742
- package/dist/cli.js +675 -120
- package/dist/index.js +2 -2
- package/dist/threads-BFRTS4EB.js +245 -0
- package/package.json +1 -1
- package/dist/chunk-PXZUNZ4S.js +0 -230
- package/dist/threads-QQRWT3OM.js +0 -382
package/dist/cli.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { createRequire as __flyspaceCreateRequire } from 'node:module';
|
|
3
3
|
const require = __flyspaceCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
+
AGENT_AUTHOR,
|
|
5
6
|
AutomationManager,
|
|
6
7
|
BOT_DM_KEY,
|
|
7
8
|
BOT_LABEL,
|
|
@@ -9,8 +10,10 @@ import {
|
|
|
9
10
|
BRANDING_DEFAULTS,
|
|
10
11
|
BUILT_IN_OUTPUT_STYLES,
|
|
11
12
|
CLI_VERSION,
|
|
13
|
+
ChannelCwdError,
|
|
12
14
|
ChatAgent,
|
|
13
15
|
DEFAULT_TIMEZONE,
|
|
16
|
+
DefaultChannelError,
|
|
14
17
|
DocShareSlugTakenError,
|
|
15
18
|
HANDLE_PATTERN,
|
|
16
19
|
HandleTakenError,
|
|
@@ -25,12 +28,15 @@ import {
|
|
|
25
28
|
TRIAL_DAYS,
|
|
26
29
|
UsageStore,
|
|
27
30
|
agentViewer,
|
|
31
|
+
allowedOrigins,
|
|
32
|
+
auditChannelCwds,
|
|
28
33
|
authorFor,
|
|
29
34
|
blockToFallbackText,
|
|
30
35
|
bodyTextFor,
|
|
31
36
|
buildAuthorizeUrl,
|
|
32
37
|
buildAutoTitle,
|
|
33
38
|
cachedProfileConfig,
|
|
39
|
+
canSeeChannel,
|
|
34
40
|
canonicalLanguage,
|
|
35
41
|
channelSkillsDir,
|
|
36
42
|
claudeAuthFailed,
|
|
@@ -39,6 +45,7 @@ import {
|
|
|
39
45
|
codexAuthAvailable,
|
|
40
46
|
consumeOAuthState,
|
|
41
47
|
corsForShell,
|
|
48
|
+
createChannel,
|
|
42
49
|
createDocShare,
|
|
43
50
|
createDocsRouter,
|
|
44
51
|
createFeatureFlagsRouter,
|
|
@@ -67,18 +74,25 @@ import {
|
|
|
67
74
|
deleteWorkspace,
|
|
68
75
|
deleteWorkspaceDomain,
|
|
69
76
|
deriveConnectionSlug,
|
|
77
|
+
deriveThreadTitle,
|
|
70
78
|
detectSourceLanguage,
|
|
71
79
|
displayNameFor,
|
|
72
80
|
dropShareAudio,
|
|
73
81
|
dropShareLangAudioKeys,
|
|
74
82
|
effectiveModel,
|
|
83
|
+
ensureAgentDmChannel,
|
|
84
|
+
ensureGeneralChannel,
|
|
85
|
+
ensureMemberDmChannel,
|
|
75
86
|
ensureUsersCached,
|
|
76
87
|
escalateToHuman,
|
|
77
88
|
exchangeCode,
|
|
89
|
+
expandPath,
|
|
78
90
|
explainCost,
|
|
79
91
|
extractCategories,
|
|
80
92
|
extractTitle,
|
|
81
93
|
filterReadableDocsChannels,
|
|
94
|
+
findChannel,
|
|
95
|
+
findChannelById,
|
|
82
96
|
findDocShareBySource,
|
|
83
97
|
findOwningProfile,
|
|
84
98
|
findSkillDetail,
|
|
@@ -87,6 +101,7 @@ import {
|
|
|
87
101
|
getAllowGuestAccess,
|
|
88
102
|
getChannelDocsMemberAccess,
|
|
89
103
|
getChannelMemory,
|
|
104
|
+
getChannelRegistry,
|
|
90
105
|
getLocalCache,
|
|
91
106
|
getMcpConnection,
|
|
92
107
|
getMcpProvider,
|
|
@@ -94,6 +109,7 @@ import {
|
|
|
94
109
|
getMembershipByUserId,
|
|
95
110
|
getMemory,
|
|
96
111
|
getOutputStyleDefault,
|
|
112
|
+
getProfileChannelRegistry,
|
|
97
113
|
getWorkspaceAutoContinueLimit,
|
|
98
114
|
getWorkspaceBilling,
|
|
99
115
|
getWorkspaceBranding,
|
|
@@ -112,14 +128,20 @@ import {
|
|
|
112
128
|
installUsageRecording,
|
|
113
129
|
invalidateAuthContextCache,
|
|
114
130
|
isAllowedModel,
|
|
131
|
+
isCwdUsable,
|
|
115
132
|
isDevHost,
|
|
116
133
|
isDocsAccess,
|
|
117
134
|
isFeatureEnabled,
|
|
135
|
+
isHumanAuthor,
|
|
118
136
|
isLockedPlan,
|
|
137
|
+
isLogicalCwd,
|
|
119
138
|
isMemoryType,
|
|
120
139
|
isOlderVersion,
|
|
140
|
+
isPermissionMode,
|
|
121
141
|
isSlugAvailable,
|
|
142
|
+
isSourceLanguage,
|
|
122
143
|
isTranslatableLanguage,
|
|
144
|
+
isUnderLogicalRoot,
|
|
123
145
|
isUnknownWorkspaceHost,
|
|
124
146
|
isUuid,
|
|
125
147
|
isValidSkillName,
|
|
@@ -153,6 +175,8 @@ import {
|
|
|
153
175
|
loadFullDashboardSettings,
|
|
154
176
|
loadWorkspaceBranding,
|
|
155
177
|
loadWorkspacePrompt,
|
|
178
|
+
localDefaults,
|
|
179
|
+
markChannelGreeted,
|
|
156
180
|
markInviteResent,
|
|
157
181
|
markMemoryUsed,
|
|
158
182
|
markWorkspaceGreeted,
|
|
@@ -161,6 +185,7 @@ import {
|
|
|
161
185
|
mentionedUserIds,
|
|
162
186
|
onboardingPending,
|
|
163
187
|
pinnedClaudeConfigDir,
|
|
188
|
+
postToDashboardChannel,
|
|
164
189
|
profileClaudeConfigDir,
|
|
165
190
|
profileEnv,
|
|
166
191
|
profileFromHost,
|
|
@@ -172,6 +197,7 @@ import {
|
|
|
172
197
|
recentRunsForWorkspace,
|
|
173
198
|
refreshAutomationRegistry,
|
|
174
199
|
refreshCache,
|
|
200
|
+
refreshChannelRegistry,
|
|
175
201
|
refreshUserCache,
|
|
176
202
|
removeChannelMember,
|
|
177
203
|
renderAppIcon,
|
|
@@ -181,6 +207,8 @@ import {
|
|
|
181
207
|
resolveAuthContext,
|
|
182
208
|
resolveChannelConfig,
|
|
183
209
|
resolveChannelId,
|
|
210
|
+
resolveCwd,
|
|
211
|
+
resolveDashboardChannelId,
|
|
184
212
|
resolveDocPath,
|
|
185
213
|
resolveDocsAccess,
|
|
186
214
|
resolveRateCard,
|
|
@@ -220,15 +248,19 @@ import {
|
|
|
220
248
|
setWorkspaceStripeSubscription,
|
|
221
249
|
slackMrkdwnToMarkdown,
|
|
222
250
|
startAutomationRegistryPolling,
|
|
251
|
+
startChannelRegistryPolling,
|
|
223
252
|
startServer,
|
|
224
253
|
suggestChannelField,
|
|
254
|
+
syncPostToDashboard,
|
|
225
255
|
syncSlackAvatars,
|
|
226
256
|
syncSupportReply,
|
|
227
257
|
transferWorkspaceAdmin,
|
|
228
258
|
trustedHost,
|
|
229
259
|
tsToIso,
|
|
230
260
|
undoMemoryEvent,
|
|
261
|
+
updateChannelById,
|
|
231
262
|
updateChannelMemory,
|
|
263
|
+
updateChannelsMcpConnections,
|
|
232
264
|
updateDocShareFeatures,
|
|
233
265
|
updateDocShareSnapshot,
|
|
234
266
|
updateMcpConnectionSettings,
|
|
@@ -245,101 +277,80 @@ import {
|
|
|
245
277
|
useDirectSupabase,
|
|
246
278
|
useLocalCache,
|
|
247
279
|
validateMemoryInput,
|
|
280
|
+
warnOnBrokenChannelCwds,
|
|
248
281
|
workspaceHostname,
|
|
249
282
|
workspaceSkillsDir,
|
|
250
283
|
writeSkillFile
|
|
251
|
-
} from "./chunk-
|
|
284
|
+
} from "./chunk-BDUA5N6B.js";
|
|
252
285
|
import {
|
|
253
|
-
|
|
286
|
+
checkPermissionAction,
|
|
287
|
+
createThreadAction,
|
|
254
288
|
firstReplyBody,
|
|
255
289
|
getThread,
|
|
256
290
|
listChannels,
|
|
291
|
+
listChannelsAction,
|
|
257
292
|
listThreads,
|
|
258
|
-
|
|
293
|
+
moveThread,
|
|
294
|
+
moveThreadAction,
|
|
295
|
+
postReplyAction,
|
|
296
|
+
readThreadAction,
|
|
297
|
+
requestPermissionAction,
|
|
259
298
|
resolveChannel,
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
299
|
+
runDocsCmd,
|
|
300
|
+
searchThreadsAction,
|
|
301
|
+
shareDocAction
|
|
302
|
+
} from "./chunk-PLLJ7M62.js";
|
|
263
303
|
import {
|
|
264
|
-
AGENT_AUTHOR,
|
|
265
304
|
AuthApiError,
|
|
266
|
-
ChannelCwdError,
|
|
267
305
|
DEFAULT_API_URL,
|
|
268
306
|
DEFAULT_PROFILE,
|
|
269
|
-
|
|
307
|
+
LOCAL_ACTION_PATH,
|
|
270
308
|
LOCAL_DB_PATH,
|
|
271
|
-
LOCAL_DOC_SHARE_PATH,
|
|
272
309
|
SCRATCH_PREFIX,
|
|
273
310
|
SLACK_ENV,
|
|
274
311
|
SessionStore,
|
|
275
312
|
acquireHostLock,
|
|
276
313
|
apiUrl,
|
|
277
|
-
auditChannelCwds,
|
|
278
314
|
boundWorkspaces,
|
|
279
|
-
canSeeChannel,
|
|
280
315
|
clearLocalAuth,
|
|
281
|
-
createChannel,
|
|
282
316
|
createHostDbClient,
|
|
283
317
|
credentialsPath,
|
|
284
318
|
databaseReachable,
|
|
285
319
|
deviceKeyPath,
|
|
286
|
-
ensureAgentDmChannel,
|
|
287
320
|
ensureDeviceKey,
|
|
288
321
|
ensureDirs,
|
|
289
|
-
ensureGeneralChannel,
|
|
290
|
-
ensureMemberDmChannel,
|
|
291
|
-
expandPath,
|
|
292
322
|
fetchWhoAmI,
|
|
293
|
-
findChannel,
|
|
294
|
-
findChannelById,
|
|
295
323
|
getAccessToken,
|
|
296
|
-
getChannelRegistry,
|
|
297
324
|
getProfile,
|
|
298
|
-
getProfileChannelRegistry,
|
|
299
325
|
getR2Bucket,
|
|
300
326
|
getR2Client,
|
|
301
327
|
getSupabaseClient,
|
|
328
|
+
handleActionResult,
|
|
302
329
|
handleAttachmentUrlResult,
|
|
303
|
-
handleDocShareResult,
|
|
304
330
|
handleHostDbResult,
|
|
305
331
|
handlePluginSvgResult,
|
|
306
332
|
handleShouldRespondResult,
|
|
307
|
-
isCwdUsable,
|
|
308
333
|
isEffort,
|
|
309
|
-
isHumanAuthor,
|
|
310
|
-
isLogicalCwd,
|
|
311
|
-
isPermissionMode,
|
|
312
|
-
isUnderLogicalRoot,
|
|
313
334
|
loadConfig,
|
|
314
335
|
loadCredentials,
|
|
315
336
|
loadEnvFiles,
|
|
316
|
-
markChannelGreeted,
|
|
317
337
|
paths,
|
|
318
338
|
pollDeviceToken,
|
|
319
|
-
postToDashboardChannel,
|
|
320
339
|
publishHostEndpoint,
|
|
321
340
|
readHostEndpoint,
|
|
322
|
-
|
|
341
|
+
requestAction,
|
|
323
342
|
requestDeviceCode,
|
|
324
|
-
requestDocShare,
|
|
325
343
|
requestHostDb,
|
|
326
344
|
requireSlackBotToken,
|
|
327
|
-
resolveCwd,
|
|
328
|
-
resolveDashboardChannelId,
|
|
329
345
|
revokeDevice,
|
|
330
346
|
runWithProfile,
|
|
331
347
|
saveCredentials,
|
|
332
348
|
setHostDbSender,
|
|
333
349
|
setSupabaseClient,
|
|
334
350
|
slackConfigured,
|
|
335
|
-
startChannelRegistryPolling,
|
|
336
351
|
sumR2PrefixBytes,
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
updateChannelsMcpConnections,
|
|
340
|
-
useHostDbWithoutCredentials,
|
|
341
|
-
warnOnBrokenChannelCwds
|
|
342
|
-
} from "./chunk-XYS7SVWC.js";
|
|
352
|
+
useHostDbWithoutCredentials
|
|
353
|
+
} from "./chunk-UZMHXV4D.js";
|
|
343
354
|
|
|
344
355
|
// ../core/src/logger.ts
|
|
345
356
|
var ALREADY_STAMPED = /^\[\d{4}-\d{2}-\d{2}T/;
|
|
@@ -2196,7 +2207,7 @@ function npmEnv(target) {
|
|
|
2196
2207
|
return nodeBin ? { ...process.env, PATH: `${nodeBin}:${process.env.PATH ?? ""}` } : process.env;
|
|
2197
2208
|
}
|
|
2198
2209
|
async function runUpgrade() {
|
|
2199
|
-
const current = "0.1.
|
|
2210
|
+
const current = "0.1.62";
|
|
2200
2211
|
console.log(`Current version: ${current}`);
|
|
2201
2212
|
console.log("Checking for updates...\n");
|
|
2202
2213
|
try {
|
|
@@ -3057,17 +3068,17 @@ async function issueInvite(membershipId, message) {
|
|
|
3057
3068
|
const db = getSupabaseClient();
|
|
3058
3069
|
const token = randomBytes(32).toString("hex");
|
|
3059
3070
|
const expiresAt = new Date(Date.now() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1e3).toISOString();
|
|
3060
|
-
const { data:
|
|
3071
|
+
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();
|
|
3061
3072
|
if (pendingError) throw new Error(`issueInvite(${membershipId}): ${pendingError.message}`);
|
|
3062
|
-
const { error: error2 } =
|
|
3073
|
+
const { error: error2 } = pending2 ? await db.from("workspace_invites").update({
|
|
3063
3074
|
token_hash: hashInviteToken(token),
|
|
3064
3075
|
previous_token_hashes: [
|
|
3065
|
-
...
|
|
3066
|
-
|
|
3076
|
+
...pending2.previous_token_hashes ?? [],
|
|
3077
|
+
pending2.token_hash
|
|
3067
3078
|
],
|
|
3068
3079
|
message,
|
|
3069
3080
|
expires_at: expiresAt
|
|
3070
|
-
}).eq("id",
|
|
3081
|
+
}).eq("id", pending2.id) : await db.from("workspace_invites").insert({
|
|
3071
3082
|
membership_id: membershipId,
|
|
3072
3083
|
token_hash: hashInviteToken(token),
|
|
3073
3084
|
message,
|
|
@@ -4110,7 +4121,10 @@ function createAuthConfirmRouter() {
|
|
|
4110
4121
|
const back = `/auth/invite?token=${encodeURIComponent(token)}`;
|
|
4111
4122
|
const lookup = await findInvite(token);
|
|
4112
4123
|
if (lookup.state !== "valid") return c.redirect(back, 303);
|
|
4113
|
-
const
|
|
4124
|
+
const workspace = await getWorkspaceById(lookup.invite.workspaceId);
|
|
4125
|
+
const callback = new URL(callbackUrl(c));
|
|
4126
|
+
if (workspace) callback.searchParams.set("next", `/${encodeURIComponent(workspace.slug)}`);
|
|
4127
|
+
const link = await generateSignInLink(lookup.invite.email, callback.toString());
|
|
4114
4128
|
const src = new URL(link.actionLink);
|
|
4115
4129
|
const params = readParams({
|
|
4116
4130
|
token: src.searchParams.get("token") ?? void 0,
|
|
@@ -5654,10 +5668,31 @@ async function runSlackCmd(args) {
|
|
|
5654
5668
|
}
|
|
5655
5669
|
}
|
|
5656
5670
|
|
|
5671
|
+
// src/store/thread-move.ts
|
|
5672
|
+
async function moveThreadFully(threadId, toChannelId) {
|
|
5673
|
+
const thread = await getThread(threadId);
|
|
5674
|
+
if (!thread) throw new Error(`No thread with id ${threadId}.`);
|
|
5675
|
+
if (thread.channelId === toChannelId) return "unchanged";
|
|
5676
|
+
const channels = await listChannels();
|
|
5677
|
+
const to = channels.find((c) => c.id === toChannelId);
|
|
5678
|
+
if (!to) throw new Error(`No channel with id ${toChannelId}.`);
|
|
5679
|
+
const from = channels.find((c) => c.id === thread.channelId);
|
|
5680
|
+
const store = new SessionStore(paths.DB_FILE);
|
|
5681
|
+
try {
|
|
5682
|
+
await moveThread(thread.id, to.id);
|
|
5683
|
+
const counts = store.moveThread(`chat:${thread.channelId}`, `chat:${to.id}`, thread.id);
|
|
5684
|
+
return { from, to, ...counts, cwdChanged: !!from && from.cwd !== to.cwd };
|
|
5685
|
+
} finally {
|
|
5686
|
+
store.close();
|
|
5687
|
+
}
|
|
5688
|
+
}
|
|
5689
|
+
|
|
5657
5690
|
// ../core/src/bridge-protocol.ts
|
|
5658
5691
|
var HOST_SOCKET_PATH = "/internal/host-socket";
|
|
5659
5692
|
var DEFAULT_DATA_API_PORT = 4757;
|
|
5660
5693
|
var CALL_TIMEOUT_MS = 15e3;
|
|
5694
|
+
var DOCS_CALL_TIMEOUT_MS = 12e4;
|
|
5695
|
+
var MEMORY_EXTRACTION_TIMEOUT_MS = 165e3;
|
|
5661
5696
|
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
5662
5697
|
var HEARTBEAT_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 2.5;
|
|
5663
5698
|
var LOCAL_RELAY_PATH = "/internal/agent-call";
|
|
@@ -6124,7 +6159,7 @@ async function runMcpCmd(args) {
|
|
|
6124
6159
|
useHostDbWithoutCredentials();
|
|
6125
6160
|
switch (server) {
|
|
6126
6161
|
case "threads": {
|
|
6127
|
-
const { startThreadsServer } = await import("./threads-
|
|
6162
|
+
const { startThreadsServer } = await import("./threads-BFRTS4EB.js");
|
|
6128
6163
|
await startThreadsServer();
|
|
6129
6164
|
return;
|
|
6130
6165
|
}
|
|
@@ -6412,26 +6447,26 @@ async function decideDeviceCode(id, userId, decision) {
|
|
|
6412
6447
|
if (error2) fail("decideDeviceCode", error2);
|
|
6413
6448
|
return (data ?? []).length > 0;
|
|
6414
6449
|
}
|
|
6415
|
-
async function redeemDeviceCode(
|
|
6450
|
+
async function redeemDeviceCode(pending2) {
|
|
6416
6451
|
const db = getSupabaseClient();
|
|
6417
|
-
const { data: claimed, error: claimError } = await db.from("device_codes").delete().eq("id",
|
|
6452
|
+
const { data: claimed, error: claimError } = await db.from("device_codes").delete().eq("id", pending2.id).select("id");
|
|
6418
6453
|
if (claimError) fail("redeemDeviceCode", claimError);
|
|
6419
6454
|
if (!claimed?.length) return null;
|
|
6420
|
-
const existing =
|
|
6421
|
-
const { data, error: error2 } = existing ? await db.from("devices").update({ name:
|
|
6422
|
-
user_id:
|
|
6423
|
-
name:
|
|
6424
|
-
platform:
|
|
6425
|
-
public_key:
|
|
6455
|
+
const existing = pending2.approvedBy ? await findDeviceByKey(pending2.publicKey, pending2.approvedBy) : null;
|
|
6456
|
+
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({
|
|
6457
|
+
user_id: pending2.approvedBy,
|
|
6458
|
+
name: pending2.name,
|
|
6459
|
+
platform: pending2.platform,
|
|
6460
|
+
public_key: pending2.publicKey
|
|
6426
6461
|
}).select("*").single();
|
|
6427
6462
|
if (error2) fail("redeemDeviceCode", error2);
|
|
6428
6463
|
const device = toDevice(data);
|
|
6429
|
-
if (
|
|
6464
|
+
if (pending2.workspaceIds.length) {
|
|
6430
6465
|
const { error: bindError } = await db.from("device_workspaces").upsert(
|
|
6431
|
-
|
|
6466
|
+
pending2.workspaceIds.map((workspaceId) => ({
|
|
6432
6467
|
device_id: device.id,
|
|
6433
6468
|
workspace_id: workspaceId,
|
|
6434
|
-
bound_by:
|
|
6469
|
+
bound_by: pending2.approvedBy
|
|
6435
6470
|
})),
|
|
6436
6471
|
{ onConflict: "device_id,workspace_id", ignoreDuplicates: true }
|
|
6437
6472
|
);
|
|
@@ -6641,6 +6676,81 @@ function createUploadsRouter() {
|
|
|
6641
6676
|
return app;
|
|
6642
6677
|
}
|
|
6643
6678
|
|
|
6679
|
+
// ../api/src/dashboard/thread-access.ts
|
|
6680
|
+
var ON_BEHALF_HEADER = "x-flyspace-on-behalf-of";
|
|
6681
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6682
|
+
function parseThreadRef(input2) {
|
|
6683
|
+
const raw = input2.trim();
|
|
6684
|
+
if (UUID.test(raw)) return raw.toLowerCase();
|
|
6685
|
+
let url;
|
|
6686
|
+
try {
|
|
6687
|
+
url = new URL(raw, "http://ref.invalid");
|
|
6688
|
+
} catch {
|
|
6689
|
+
return null;
|
|
6690
|
+
}
|
|
6691
|
+
const fromPath = /(?:^|\/)chat\/[^/]+\/([^/]+)\/?$/.exec(url.pathname)?.[1];
|
|
6692
|
+
if (fromPath && UUID.test(fromPath)) return fromPath.toLowerCase();
|
|
6693
|
+
const fromQuery = url.searchParams.get("t");
|
|
6694
|
+
return fromQuery && UUID.test(fromQuery) ? fromQuery.toLowerCase() : null;
|
|
6695
|
+
}
|
|
6696
|
+
function readingFor(query, userId) {
|
|
6697
|
+
return userId ? query.setHeader(ON_BEHALF_HEADER, userId) : query;
|
|
6698
|
+
}
|
|
6699
|
+
async function resolveThreadOwner(threadId, onBehalfOf) {
|
|
6700
|
+
if (!UUID.test(threadId)) return null;
|
|
6701
|
+
const db = getSupabaseClient();
|
|
6702
|
+
const { data: thread, error: error2 } = await readingFor(
|
|
6703
|
+
db.from("threads").select("id, channel_id").eq("id", threadId),
|
|
6704
|
+
onBehalfOf
|
|
6705
|
+
).maybeSingle();
|
|
6706
|
+
if (error2) throw new Error(`resolveThreadOwner: ${error2.message}`);
|
|
6707
|
+
const channelId = thread?.channel_id;
|
|
6708
|
+
if (!channelId) return null;
|
|
6709
|
+
const { data: channel, error: channelError } = await readingFor(
|
|
6710
|
+
db.from("channels").select("profile, visibility, dm_key, member_emails").eq(UUID.test(channelId) ? "id" : "external_channel_id", channelId),
|
|
6711
|
+
onBehalfOf
|
|
6712
|
+
).maybeSingle();
|
|
6713
|
+
if (channelError) throw new Error(`resolveThreadOwner: ${channelError.message}`);
|
|
6714
|
+
const row = channel;
|
|
6715
|
+
if (!row?.profile) return null;
|
|
6716
|
+
const { data: workspace, error: workspaceError } = await readingFor(
|
|
6717
|
+
db.from("workspaces").select("id").eq("slug", row.profile),
|
|
6718
|
+
onBehalfOf
|
|
6719
|
+
).maybeSingle();
|
|
6720
|
+
if (workspaceError) throw new Error(`resolveThreadOwner: ${workspaceError.message}`);
|
|
6721
|
+
const workspaceId = workspace?.id;
|
|
6722
|
+
if (!workspaceId) return null;
|
|
6723
|
+
return {
|
|
6724
|
+
threadId,
|
|
6725
|
+
channelId,
|
|
6726
|
+
workspace: row.profile,
|
|
6727
|
+
workspaceId,
|
|
6728
|
+
channel: {
|
|
6729
|
+
// Same default as rowToChannel: anything not explicitly public is private.
|
|
6730
|
+
visibility: row.visibility === "public" ? "public" : "private",
|
|
6731
|
+
dmKey: row.dm_key,
|
|
6732
|
+
memberEmails: Array.isArray(row.member_emails) ? row.member_emails.filter((e) => typeof e === "string").map((e) => e.trim().toLowerCase()) : []
|
|
6733
|
+
}
|
|
6734
|
+
};
|
|
6735
|
+
}
|
|
6736
|
+
async function canReadThread(owner, userId) {
|
|
6737
|
+
if (!UUID.test(userId)) return false;
|
|
6738
|
+
const { data, error: error2 } = await readingFor(
|
|
6739
|
+
getSupabaseClient().from("memberships").select("email, role").eq("workspace_id", owner.workspaceId).eq("user_id", userId),
|
|
6740
|
+
userId
|
|
6741
|
+
).maybeSingle();
|
|
6742
|
+
if (error2) throw new Error(`canReadThread: ${error2.message}`);
|
|
6743
|
+
const membership = data;
|
|
6744
|
+
if (!membership) return false;
|
|
6745
|
+
return canSeeChannel(owner.channel, {
|
|
6746
|
+
email: membership.email ?? void 0,
|
|
6747
|
+
role: membership.role
|
|
6748
|
+
});
|
|
6749
|
+
}
|
|
6750
|
+
function threadPath(workspace, channelId, threadId) {
|
|
6751
|
+
return `/${encodeURIComponent(workspace)}/chat/${encodeURIComponent(channelId)}/${threadId}`;
|
|
6752
|
+
}
|
|
6753
|
+
|
|
6644
6754
|
// ../api/src/dashboard/doc-share-publish.ts
|
|
6645
6755
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
6646
6756
|
import { CopyObjectCommand, PutObjectCommand as PutObjectCommand2 } from "@aws-sdk/client-s3";
|
|
@@ -6822,9 +6932,287 @@ function slugErrorMessage(err) {
|
|
|
6822
6932
|
}
|
|
6823
6933
|
}
|
|
6824
6934
|
|
|
6935
|
+
// ../api/src/dashboard/doc-share-host-request.ts
|
|
6936
|
+
function workspaceShareOrigin(slug) {
|
|
6937
|
+
const wildcard = allowedOrigins().find((o) => o.includes("://*."));
|
|
6938
|
+
return wildcard ? wildcard.replace("://*.", `://${slug}.`) : `https://${slug}.flyspace.ai`;
|
|
6939
|
+
}
|
|
6940
|
+
async function publishDocShareForHost(scopeWorkspaces, req) {
|
|
6941
|
+
if (typeof req.channelId !== "string" || typeof req.path !== "string" || !req.path) {
|
|
6942
|
+
return { error: "channel and path are required" };
|
|
6943
|
+
}
|
|
6944
|
+
const channel = findChannelById(req.channelId);
|
|
6945
|
+
if (!channel || scopeWorkspaces !== null && !scopeWorkspaces.includes(channel.profile)) {
|
|
6946
|
+
return { error: "channel not found" };
|
|
6947
|
+
}
|
|
6948
|
+
let slug;
|
|
6949
|
+
if (typeof req.slug === "string") {
|
|
6950
|
+
const normalized = normalizeSlug(req.slug);
|
|
6951
|
+
if ("error" in normalized) return { error: slugErrorMessage(normalized.error) };
|
|
6952
|
+
slug = normalized.slug;
|
|
6953
|
+
}
|
|
6954
|
+
const workspace = await getWorkspaceBySlug(channel.profile);
|
|
6955
|
+
if (!workspace) return { error: "workspace not found" };
|
|
6956
|
+
return runWithProfile(channel.profile, async () => {
|
|
6957
|
+
let result;
|
|
6958
|
+
try {
|
|
6959
|
+
result = await publishDocShare(
|
|
6960
|
+
{
|
|
6961
|
+
cwd: resolveChannelConfig(channel.id).cwd,
|
|
6962
|
+
workspaceId: workspace.id,
|
|
6963
|
+
profile: channel.profile,
|
|
6964
|
+
channelId: channel.id,
|
|
6965
|
+
sourcePath: req.path,
|
|
6966
|
+
createdBy: "agent",
|
|
6967
|
+
...slug ? { slug } : {},
|
|
6968
|
+
features: {}
|
|
6969
|
+
},
|
|
6970
|
+
remoteAgentCallbacks().readDocShareBundle
|
|
6971
|
+
);
|
|
6972
|
+
} catch (err) {
|
|
6973
|
+
if (err instanceof DocShareSlugTakenError) return { error: `/share/${err.slug} is already taken.` };
|
|
6974
|
+
throw err;
|
|
6975
|
+
}
|
|
6976
|
+
switch (result.status) {
|
|
6977
|
+
case "not-found":
|
|
6978
|
+
return { error: "doc not found" };
|
|
6979
|
+
case "unsupported":
|
|
6980
|
+
return { error: "only Markdown and HTML docs can be shared" };
|
|
6981
|
+
case "too-large":
|
|
6982
|
+
return { error: "doc or its assets too large to share" };
|
|
6983
|
+
case "host-unavailable":
|
|
6984
|
+
case "host-outdated":
|
|
6985
|
+
return { error: "the Host could not read the doc" };
|
|
6986
|
+
default:
|
|
6987
|
+
return { url: `${workspaceShareOrigin(channel.profile)}/share/${result.share.slug ?? result.share.id}` };
|
|
6988
|
+
}
|
|
6989
|
+
});
|
|
6990
|
+
}
|
|
6991
|
+
|
|
6992
|
+
// ../api/src/actions/run-action.ts
|
|
6993
|
+
var ActionError = class extends Error {
|
|
6994
|
+
};
|
|
6995
|
+
var DEFAULT_PERMISSION_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
6996
|
+
var MAX_REPLIES = 100;
|
|
6997
|
+
var inScope = (ctx, workspace) => ctx.scope === null || ctx.scope.includes(workspace);
|
|
6998
|
+
async function channelInScope(ctx, channelId) {
|
|
6999
|
+
const { data, error: error2 } = await getSupabaseClient().from("channels").select("id, name, profile, cwd").eq("id", channelId).maybeSingle();
|
|
7000
|
+
if (error2) throw new Error(error2.message);
|
|
7001
|
+
if (!data || !inScope(ctx, data["profile"]))
|
|
7002
|
+
throw new ActionError(`No channel with id ${channelId}.`);
|
|
7003
|
+
return data;
|
|
7004
|
+
}
|
|
7005
|
+
async function threadInScope(ctx, threadId) {
|
|
7006
|
+
const owner = await resolveThreadOwner(threadId);
|
|
7007
|
+
if (!owner || !inScope(ctx, owner.workspace))
|
|
7008
|
+
throw new ActionError(`No thread with id ${threadId}.`);
|
|
7009
|
+
return owner;
|
|
7010
|
+
}
|
|
7011
|
+
async function requesterUserId(ctx) {
|
|
7012
|
+
const { handle, workspace } = ctx.requester;
|
|
7013
|
+
if (!handle || !workspace || !inScope(ctx, workspace)) return null;
|
|
7014
|
+
const supabase = getSupabaseClient();
|
|
7015
|
+
const { data: ws } = await supabase.from("workspaces").select("id").eq("slug", workspace).maybeSingle();
|
|
7016
|
+
if (!ws) return null;
|
|
7017
|
+
const { data } = await supabase.from("memberships").select("user_id").eq("workspace_id", ws["id"]).ilike("handle", handle).maybeSingle();
|
|
7018
|
+
return data?.["user_id"] ?? null;
|
|
7019
|
+
}
|
|
7020
|
+
async function insertAgentReply(threadId, body) {
|
|
7021
|
+
const { data, error: error2 } = await getSupabaseClient().from("thread_replies").insert({ thread_id: threadId, author: AGENT_AUTHOR, body }).select("id").single();
|
|
7022
|
+
if (error2 || !data)
|
|
7023
|
+
throw new Error(`failed to write reply: ${error2?.message ?? "no row returned"}`);
|
|
7024
|
+
return data["id"];
|
|
7025
|
+
}
|
|
7026
|
+
var searchThreads = async (input2, ctx) => {
|
|
7027
|
+
const limit = Math.min(Math.max(Math.trunc(input2.limit ?? 10), 1), 30);
|
|
7028
|
+
const { data, error: error2 } = await getSupabaseClient().rpc("search_threads", {
|
|
7029
|
+
q: input2.query,
|
|
7030
|
+
match_limit: Math.min(limit * 5, 100)
|
|
7031
|
+
});
|
|
7032
|
+
if (error2) throw new Error(`search failed: ${error2.message}`);
|
|
7033
|
+
let rows = data ?? [];
|
|
7034
|
+
if (input2.channel_id) rows = rows.filter((r) => r.channel_id === input2.channel_id);
|
|
7035
|
+
if (ctx.scope !== null && rows.length) {
|
|
7036
|
+
const { data: channels } = await getSupabaseClient().from("channels").select("id").in("profile", ctx.scope).in("id", [...new Set(rows.map((r) => r.channel_id))]);
|
|
7037
|
+
const own = new Set((channels ?? []).map((c) => c["id"]));
|
|
7038
|
+
rows = rows.filter((r) => own.has(r.channel_id));
|
|
7039
|
+
}
|
|
7040
|
+
return rows.slice(0, limit);
|
|
7041
|
+
};
|
|
7042
|
+
var readThread = async (input2, ctx) => {
|
|
7043
|
+
const threadId = parseThreadRef(input2.thread_id);
|
|
7044
|
+
if (!threadId) throw new ActionError(`Not a thread id or thread link: ${input2.thread_id}`);
|
|
7045
|
+
const userId = await requesterUserId(ctx);
|
|
7046
|
+
const owner = await resolveThreadOwner(threadId);
|
|
7047
|
+
const allowed = !!owner && (userId ? await canReadThread(owner, userId) : inScope(ctx, owner.workspace));
|
|
7048
|
+
if (!owner || !allowed) return null;
|
|
7049
|
+
const supabase = getSupabaseClient();
|
|
7050
|
+
const { data: thread, error: error2 } = await supabase.from("threads").select("title, auto_title, author, created_at").eq("id", threadId).maybeSingle();
|
|
7051
|
+
if (error2) throw new Error(`read failed: ${error2.message}`);
|
|
7052
|
+
if (!thread) return null;
|
|
7053
|
+
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);
|
|
7054
|
+
if (repliesError) throw new Error(`read failed: ${repliesError.message}`);
|
|
7055
|
+
return {
|
|
7056
|
+
link: threadPath(owner.workspace, owner.channelId, threadId),
|
|
7057
|
+
title: thread["title"] ?? thread["auto_title"] ?? null,
|
|
7058
|
+
author: thread["author"],
|
|
7059
|
+
created_at: thread["created_at"],
|
|
7060
|
+
replies: replies ?? []
|
|
7061
|
+
};
|
|
7062
|
+
};
|
|
7063
|
+
var listChannels3 = async (_input, ctx) => {
|
|
7064
|
+
let query = getSupabaseClient().from("channels").select("id, name, profile, cwd");
|
|
7065
|
+
if (ctx.scope !== null) query = query.in("profile", ctx.scope);
|
|
7066
|
+
const { data, error: error2 } = await query.order("name");
|
|
7067
|
+
if (error2) throw new Error(`list channels failed: ${error2.message}`);
|
|
7068
|
+
return data ?? [];
|
|
7069
|
+
};
|
|
7070
|
+
var createThread = async (input2, ctx) => {
|
|
7071
|
+
const channel = await channelInScope(ctx, input2.channel_id);
|
|
7072
|
+
const { data, error: error2 } = await getSupabaseClient().from("threads").insert({
|
|
7073
|
+
channel_id: channel.id,
|
|
7074
|
+
// An untitled thread is effectively invisible in the sidebar, so derive
|
|
7075
|
+
// one from the first line unless the caller named the thread itself.
|
|
7076
|
+
title: input2.title?.trim().replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, "$1") || deriveThreadTitle(input2.text),
|
|
7077
|
+
author: AGENT_AUTHOR
|
|
7078
|
+
}).select("id").single();
|
|
7079
|
+
if (error2 || !data)
|
|
7080
|
+
throw new Error(`failed to create thread: ${error2?.message ?? "no row returned"}`);
|
|
7081
|
+
const threadId = data["id"];
|
|
7082
|
+
return { threadId, replyId: await insertAgentReply(threadId, input2.text) };
|
|
7083
|
+
};
|
|
7084
|
+
var postReply = async (input2, ctx) => {
|
|
7085
|
+
const owner = await threadInScope(ctx, input2.thread_id);
|
|
7086
|
+
return { threadId: owner.threadId, replyId: await insertAgentReply(owner.threadId, input2.text) };
|
|
7087
|
+
};
|
|
7088
|
+
var moveThread2 = async (input2, ctx) => {
|
|
7089
|
+
const owner = await threadInScope(ctx, input2.thread_id);
|
|
7090
|
+
if (owner.channelId === input2.to_channel_id) return "unchanged";
|
|
7091
|
+
const to = await channelInScope(ctx, input2.to_channel_id);
|
|
7092
|
+
const supabase = getSupabaseClient();
|
|
7093
|
+
const { data: fromRow } = await supabase.from("channels").select("id, name, cwd").eq("id", owner.channelId).maybeSingle();
|
|
7094
|
+
const { error: error2 } = await supabase.from("threads").update({ channel_id: to.id }).eq("id", owner.threadId);
|
|
7095
|
+
if (error2) throw new Error(`move failed: ${error2.message}`);
|
|
7096
|
+
const { error: notifyError } = await supabase.from("notifications").update({ channel_id: to.id }).eq("thread_id", owner.threadId);
|
|
7097
|
+
if (notifyError) throw new Error(`move failed (notifications): ${notifyError.message}`);
|
|
7098
|
+
return {
|
|
7099
|
+
from: fromRow ?? null,
|
|
7100
|
+
to: { id: to.id, name: to.name, cwd: to.cwd }
|
|
7101
|
+
};
|
|
7102
|
+
};
|
|
7103
|
+
var shareDoc = async (input2, ctx) => {
|
|
7104
|
+
const res = await publishDocShareForHost(ctx.scope, {
|
|
7105
|
+
channelId: input2.channel_id,
|
|
7106
|
+
path: input2.path,
|
|
7107
|
+
...input2.slug?.trim() ? { slug: input2.slug.trim() } : {}
|
|
7108
|
+
});
|
|
7109
|
+
if (!res.url) throw new ActionError(`Share failed: ${res.error ?? "unknown error"}`);
|
|
7110
|
+
return { url: res.url };
|
|
7111
|
+
};
|
|
7112
|
+
function describeToolInput(input2) {
|
|
7113
|
+
const pick = input2["command"] ?? input2["file_path"] ?? input2["path"] ?? input2["url"];
|
|
7114
|
+
const text = typeof pick === "string" ? pick : JSON.stringify(input2, null, 2);
|
|
7115
|
+
return text.length > 1500 ? `${text.slice(0, 1500)}\u2026` : text;
|
|
7116
|
+
}
|
|
7117
|
+
var permissionMarker = (id) => `[PERMISSION: ${id}]`;
|
|
7118
|
+
var requestPermission = async (input2, ctx) => {
|
|
7119
|
+
const { threadId, channelId, permissionTimeoutMs } = ctx.requester;
|
|
7120
|
+
if (!threadId || !channelId) throw new ActionError("No thread to ask in.");
|
|
7121
|
+
const owner = await threadInScope(ctx, threadId);
|
|
7122
|
+
if (owner.channelId !== channelId) throw new ActionError(`No thread with id ${threadId}.`);
|
|
7123
|
+
const supabase = getSupabaseClient();
|
|
7124
|
+
const timeoutMs = permissionTimeoutMs && permissionTimeoutMs > 0 ? permissionTimeoutMs : DEFAULT_PERMISSION_TIMEOUT_MS;
|
|
7125
|
+
const { data: request, error: error2 } = await supabase.from("permission_requests").insert({
|
|
7126
|
+
channel_id: channelId,
|
|
7127
|
+
thread_id: threadId,
|
|
7128
|
+
tool_name: input2.tool_name,
|
|
7129
|
+
input: input2.input,
|
|
7130
|
+
expires_at: new Date(Date.now() + timeoutMs).toISOString()
|
|
7131
|
+
}).select("id").single();
|
|
7132
|
+
if (error2 || !request) throw new Error(`failed to create permission request: ${error2?.message}`);
|
|
7133
|
+
const requestId = request["id"];
|
|
7134
|
+
const prompt = `The agent wants to use **${input2.tool_name}**:
|
|
7135
|
+
|
|
7136
|
+
\`\`\`
|
|
7137
|
+
${describeToolInput(input2.input)}
|
|
7138
|
+
\`\`\`
|
|
7139
|
+
|
|
7140
|
+
` + permissionMarker(requestId);
|
|
7141
|
+
const replyId = await insertAgentReply(threadId, prompt).catch(() => null);
|
|
7142
|
+
if (replyId)
|
|
7143
|
+
await supabase.from("permission_requests").update({ reply_id: replyId }).eq("id", requestId);
|
|
7144
|
+
return { requestId };
|
|
7145
|
+
};
|
|
7146
|
+
var checkPermission = async (input2, ctx) => {
|
|
7147
|
+
const supabase = getSupabaseClient();
|
|
7148
|
+
const read = async () => {
|
|
7149
|
+
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();
|
|
7150
|
+
return data;
|
|
7151
|
+
};
|
|
7152
|
+
let row = await read();
|
|
7153
|
+
if (!row) throw new ActionError(`No permission request ${input2.request_id}.`);
|
|
7154
|
+
const channel = await channelInScope(ctx, row["channel_id"]).catch(() => null);
|
|
7155
|
+
if (!channel) throw new ActionError(`No permission request ${input2.request_id}.`);
|
|
7156
|
+
if (row["status"] === "pending" && Date.parse(row["expires_at"]) <= Date.now()) {
|
|
7157
|
+
await supabase.from("permission_requests").update({ status: "expired" }).eq("id", input2.request_id).eq("status", "pending");
|
|
7158
|
+
row = await read() ?? row;
|
|
7159
|
+
}
|
|
7160
|
+
const status = row["status"];
|
|
7161
|
+
const decidedBy = row["decided_by"] ?? null;
|
|
7162
|
+
const replyId = row["reply_id"];
|
|
7163
|
+
if (status !== "pending" && replyId) {
|
|
7164
|
+
const outcome = status === "allow" ? `\u2705 Allowed by @${decidedBy}` : status === "deny" ? `\u{1F6AB} Denied by @${decidedBy}` : "\u23F0 No answer in time, denied automatically";
|
|
7165
|
+
const { data: reply } = await supabase.from("thread_replies").select("body").eq("id", replyId).maybeSingle();
|
|
7166
|
+
const body = reply?.["body"];
|
|
7167
|
+
if (body?.includes(permissionMarker(input2.request_id))) {
|
|
7168
|
+
await supabase.from("thread_replies").update({ body: body.replace(permissionMarker(input2.request_id), outcome) }).eq("id", replyId).eq("thread_id", row["thread_id"]);
|
|
7169
|
+
}
|
|
7170
|
+
}
|
|
7171
|
+
return { status, decidedBy };
|
|
7172
|
+
};
|
|
7173
|
+
var HANDLERS = {
|
|
7174
|
+
[searchThreadsAction.name]: searchThreads,
|
|
7175
|
+
[readThreadAction.name]: readThread,
|
|
7176
|
+
[listChannelsAction.name]: listChannels3,
|
|
7177
|
+
[createThreadAction.name]: createThread,
|
|
7178
|
+
[postReplyAction.name]: postReply,
|
|
7179
|
+
[moveThreadAction.name]: moveThread2,
|
|
7180
|
+
[shareDocAction.name]: shareDoc,
|
|
7181
|
+
[requestPermissionAction.name]: requestPermission,
|
|
7182
|
+
[checkPermissionAction.name]: checkPermission
|
|
7183
|
+
};
|
|
7184
|
+
|
|
6825
7185
|
// ../api/src/dashboard/agent-bridge-data.ts
|
|
6826
7186
|
var hosts = /* @__PURE__ */ new Map();
|
|
7187
|
+
var pending = /* @__PURE__ */ new Map();
|
|
6827
7188
|
var hostStatusListeners = /* @__PURE__ */ new Set();
|
|
7189
|
+
var lastAuthFailure = null;
|
|
7190
|
+
function hostFor(profile) {
|
|
7191
|
+
let legacy = null;
|
|
7192
|
+
let scoped = null;
|
|
7193
|
+
for (const [ws, scope] of hosts) {
|
|
7194
|
+
if (ws.readyState !== WebSocket.OPEN) continue;
|
|
7195
|
+
if (scope.workspaces === null) legacy = ws;
|
|
7196
|
+
else if (scope.workspaces.includes(profile)) scoped = ws;
|
|
7197
|
+
}
|
|
7198
|
+
return scoped ?? legacy;
|
|
7199
|
+
}
|
|
7200
|
+
function isHostConnected(profile) {
|
|
7201
|
+
if (profile) return hostFor(profile) !== null;
|
|
7202
|
+
for (const ws of hosts.keys()) if (ws.readyState === WebSocket.OPEN) return true;
|
|
7203
|
+
return false;
|
|
7204
|
+
}
|
|
7205
|
+
function getHostCliVersion(profile) {
|
|
7206
|
+
const ws = hostFor(profile);
|
|
7207
|
+
return ws && hosts.get(ws)?.cliVersion || null;
|
|
7208
|
+
}
|
|
7209
|
+
function getHostPinnedModel(profile) {
|
|
7210
|
+
const ws = hostFor(profile);
|
|
7211
|
+
return ws && hosts.get(ws)?.pinnedModel || null;
|
|
7212
|
+
}
|
|
7213
|
+
function getHostOfflineReason() {
|
|
7214
|
+
return lastAuthFailure;
|
|
7215
|
+
}
|
|
6828
7216
|
function notifyHostStatus() {
|
|
6829
7217
|
const online = hosts.size > 0;
|
|
6830
7218
|
for (const l of hostStatusListeners) l(online);
|
|
@@ -6841,10 +7229,134 @@ function disconnectHostDevice(deviceId) {
|
|
|
6841
7229
|
}
|
|
6842
7230
|
}
|
|
6843
7231
|
var LAST_SEEN_RESOLUTION_MS = 60 * 6e4;
|
|
7232
|
+
var lastCallFailure = /* @__PURE__ */ new Map();
|
|
6844
7233
|
var lastCallError = /* @__PURE__ */ new Map();
|
|
6845
7234
|
function getHostCallError(method, profile = getProfile()) {
|
|
6846
7235
|
return lastCallError.get(`${profile}:${method}`) ?? null;
|
|
6847
7236
|
}
|
|
7237
|
+
function getHostCallFailure(method, profile = getProfile()) {
|
|
7238
|
+
return lastCallFailure.get(`${profile}:${method}`) ?? null;
|
|
7239
|
+
}
|
|
7240
|
+
function callHost(method, args, timeoutMs = CALL_TIMEOUT_MS) {
|
|
7241
|
+
const profile = getProfile();
|
|
7242
|
+
const ws = hostFor(profile);
|
|
7243
|
+
const key = `${profile}:${method}`;
|
|
7244
|
+
lastCallFailure.delete(key);
|
|
7245
|
+
lastCallError.delete(key);
|
|
7246
|
+
if (!ws) {
|
|
7247
|
+
lastCallFailure.set(key, isHostConnected() ? "unscoped" : "offline");
|
|
7248
|
+
console.error(
|
|
7249
|
+
isHostConnected() ? `[host-socket] ${method} -> not scoped to workspace "${profile}"` : `[host-socket] ${method} -> no Host connected`
|
|
7250
|
+
);
|
|
7251
|
+
return Promise.resolve(null);
|
|
7252
|
+
}
|
|
7253
|
+
if (method === "docsRequest") console.log(`[host-socket] docsRequest for "${profile}" -> device ${hosts.get(ws)?.deviceId ?? "legacy"}`);
|
|
7254
|
+
const id = randomUUID2();
|
|
7255
|
+
return new Promise((resolve7) => {
|
|
7256
|
+
const timer2 = setTimeout(() => {
|
|
7257
|
+
pending.delete(id);
|
|
7258
|
+
lastCallFailure.set(key, "timeout");
|
|
7259
|
+
console.error(`[host-socket] ${method} -> timed out after ${timeoutMs}ms`);
|
|
7260
|
+
resolve7(null);
|
|
7261
|
+
}, timeoutMs);
|
|
7262
|
+
pending.set(id, {
|
|
7263
|
+
key,
|
|
7264
|
+
resolve: (value) => {
|
|
7265
|
+
clearTimeout(timer2);
|
|
7266
|
+
resolve7(value);
|
|
7267
|
+
}
|
|
7268
|
+
});
|
|
7269
|
+
const sent = [...args];
|
|
7270
|
+
while (sent.length > 0 && sent[sent.length - 1] === void 0) sent.pop();
|
|
7271
|
+
send(ws, { type: "call", id, method, profile, args: sent });
|
|
7272
|
+
});
|
|
7273
|
+
}
|
|
7274
|
+
function remoteAgentCallbacks() {
|
|
7275
|
+
return {
|
|
7276
|
+
// Fire-and-forget on the Data side exactly as the in-process call was:
|
|
7277
|
+
// the reply lands in Supabase later, via Realtime, not in this response.
|
|
7278
|
+
onChatMessage: (msg) => {
|
|
7279
|
+
void callHost("onChatMessage", [msg]);
|
|
7280
|
+
},
|
|
7281
|
+
isAgentThinking: async (threadId) => await callHost("isAgentThinking", [threadId]) ?? false,
|
|
7282
|
+
getAgentActivities: async (threadId) => await callHost("getAgentActivities", [threadId]) ?? [],
|
|
7283
|
+
getBackgroundTasks: async (threadId) => await callHost("getBackgroundTasks", [threadId]) ?? [],
|
|
7284
|
+
cancelAgentRun: async (threadId) => await callHost("cancelAgentRun", [threadId]) ?? false,
|
|
7285
|
+
regenerateAgentRun: async (threadId, stoppedReplyId) => await callHost("regenerateAgentRun", [threadId, stoppedReplyId]) ?? false,
|
|
7286
|
+
listAgentRuns: async () => await callHost("listAgentRuns", []) ?? [],
|
|
7287
|
+
// `null` (no Host, or no answer in time) passes through: the extractor
|
|
7288
|
+
// reads it as a failed call and retries the thread next sweep.
|
|
7289
|
+
completeMemoryExtraction: (req) => callHost("completeMemoryExtraction", [req], MEMORY_EXTRACTION_TIMEOUT_MS),
|
|
7290
|
+
// `null` passes through: channel-suggest.ts tells "no Host" from "old Host".
|
|
7291
|
+
suggestChannelField: (req) => callHost("suggestChannelField", [req], MEMORY_EXTRACTION_TIMEOUT_MS),
|
|
7292
|
+
// Deliberately passes `null` through rather than defaulting to `[]`: with
|
|
7293
|
+
// no Host connected, claiming every folder is fine would be a guess.
|
|
7294
|
+
listMissingCwds: () => callHost("listMissingCwds", []),
|
|
7295
|
+
// Unlike listMissingCwds, `[]` is a fine fallback here: this only feeds
|
|
7296
|
+
// the "running" badge next to a profile name in the switcher, so with no
|
|
7297
|
+
// Host connected, showing nobody as running is a reasonable default
|
|
7298
|
+
// rather than a false claim of certainty either way.
|
|
7299
|
+
listRunningProfiles: async () => await callHost("listRunningProfiles", []) ?? [],
|
|
7300
|
+
// `null` (no Host) falls back to `offlineAgentIdentities` in api.ts.
|
|
7301
|
+
getAgentIdentities: (viewer) => callHost("getAgentIdentities", [viewer]),
|
|
7302
|
+
// Reading the doc and its assets can only happen where the channel's
|
|
7303
|
+
// real folder is, so this goes to the Host; the DB and R2 work stays here
|
|
7304
|
+
// (doc-share-publish.ts). `null` with no recorded failure means the Host
|
|
7305
|
+
// answered but has no such method: an install from before the split.
|
|
7306
|
+
// Longer timeout because the reply carries the assets' bytes.
|
|
7307
|
+
readDocShareBundle: async (req) => {
|
|
7308
|
+
const bundle = await callHost("readDocShareBundle", [req], DOCS_CALL_TIMEOUT_MS);
|
|
7309
|
+
if (bundle) return bundle;
|
|
7310
|
+
return getHostCallFailure("readDocShareBundle") ? { status: "host-unavailable" } : { status: "host-outdated" };
|
|
7311
|
+
},
|
|
7312
|
+
// Empty is a fine fallback for a discovery list: no Host connected means
|
|
7313
|
+
// no skills to offer, not a fabricated claim about what's available.
|
|
7314
|
+
listChannelSkills: async (args) => await callHost("listChannelSkills", [args]) ?? [],
|
|
7315
|
+
// Same reasoning as listChannelSkills — this only feeds the Docs pane's
|
|
7316
|
+
// List view/search, so an empty result reads as "nothing found yet".
|
|
7317
|
+
listFlatDocs: async (args) => await callHost("listFlatDocs", [args]) ?? [],
|
|
7318
|
+
// `localDefaults()` mirrors what `loadDashboardSettings()` itself returns
|
|
7319
|
+
// for a missing/corrupt file, so "no Host connected" reads the same as a
|
|
7320
|
+
// freshly provisioned workspace rather than as broken settings.
|
|
7321
|
+
getLocalDashboardSettings: async () => await callHost("getLocalDashboardSettings", []) ?? localDefaults(),
|
|
7322
|
+
// A write: no honest empty-ish fallback, so `null` (callHost's own
|
|
7323
|
+
// no-Host/timeout result) surfaces as a 503 on the Data side rather than
|
|
7324
|
+
// a fabricated success (see readDocShareBundle).
|
|
7325
|
+
saveLocalDashboardSettings: (patch) => callHost("saveLocalDashboardSettings", [patch]),
|
|
7326
|
+
// Same posture as saveLocalDashboardSettings: `null` becomes a 503.
|
|
7327
|
+
writeSkill: (ref, write) => callHost("writeSkill", [ref, write]),
|
|
7328
|
+
// Same posture as writeSkill: `null` becomes a 503.
|
|
7329
|
+
outputStylesRequest: (req) => callHost("outputStylesRequest", [req]),
|
|
7330
|
+
// Submitting a Claude code waits on the CLI to mint the token.
|
|
7331
|
+
providerLoginRequest: (req) => callHost("providerLoginRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7332
|
+
// Same posture again. Longer timeout: a first translation of a doc runs a
|
|
7333
|
+
// model call on the Host before it answers.
|
|
7334
|
+
docsRequest: (req) => callHost("docsRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7335
|
+
hostRequest: (req) => callHost("hostRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7336
|
+
// `null` (no Host connected) is passed through rather than defaulting to
|
|
7337
|
+
// `[]` — see listSessions's doc comment on AgentCallbacks.
|
|
7338
|
+
listSessions: () => callHost("listSessions", []),
|
|
7339
|
+
// `claude mcp list` health-checks every server, which takes seconds.
|
|
7340
|
+
listMcpServers: () => callHost("listMcpServers", [], DOCS_CALL_TIMEOUT_MS),
|
|
7341
|
+
upgradeHost: () => callHost("upgradeHost", []),
|
|
7342
|
+
// Both need this machine's disk and CLI history, so `null` (no Host)
|
|
7343
|
+
// surfaces as a 503 rather than an empty scan or a fake success.
|
|
7344
|
+
// A first scan walks every CLI transcript on a cold disk, so it gets the
|
|
7345
|
+
// long timeout; linking can create and seed several folders.
|
|
7346
|
+
scanOnboarding: (slug) => callHost("scanOnboarding", [slug], DOCS_CALL_TIMEOUT_MS),
|
|
7347
|
+
linkProjectFolders: (slug, items2) => callHost("linkProjectFolders", [slug, items2], DOCS_CALL_TIMEOUT_MS),
|
|
7348
|
+
// A first scan or a long transcript walks a lot of disk: the long timeout.
|
|
7349
|
+
sessionImportRequest: (req) => callHost("sessionImportRequest", [req], DOCS_CALL_TIMEOUT_MS),
|
|
7350
|
+
getHostCallFailure: (method) => getHostCallFailure(method),
|
|
7351
|
+
isHostOnline: (profile) => isHostConnected(profile),
|
|
7352
|
+
getHostOfflineReason,
|
|
7353
|
+
getHostCliVersion,
|
|
7354
|
+
getHostPinnedModel
|
|
7355
|
+
};
|
|
7356
|
+
}
|
|
7357
|
+
function send(ws, msg) {
|
|
7358
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(encodeWireMessage(msg));
|
|
7359
|
+
}
|
|
6848
7360
|
|
|
6849
7361
|
// ../api/src/dashboard/unique-channel-name.ts
|
|
6850
7362
|
function uniqueChannelName(raw, taken) {
|
|
@@ -7038,11 +7550,11 @@ function createOnboardingRouter(agent) {
|
|
|
7038
7550
|
const ctx = await resolveAuthContext(c);
|
|
7039
7551
|
if (ctx?.role !== "admin") return c.json({ pending: false });
|
|
7040
7552
|
const greetedAt = await getWorkspaceGreetedAt(ctx.workspaceId);
|
|
7041
|
-
const
|
|
7042
|
-
if (!
|
|
7553
|
+
const pending2 = !!ctx.projectsSetupAt && !greetedAt;
|
|
7554
|
+
if (!pending2) return c.json({ pending: pending2, channelId: null, threadId: null });
|
|
7043
7555
|
const general = await ensureGeneralChannel();
|
|
7044
7556
|
const threadId = await ensureGreetingThread(ctx.workspaceId, general.id, ctx.name?.trim() || ctx.handle);
|
|
7045
|
-
return c.json({ pending, channelId: general.id, threadId });
|
|
7557
|
+
return c.json({ pending: pending2, channelId: general.id, threadId });
|
|
7046
7558
|
});
|
|
7047
7559
|
app.post("/greeting", async (c) => {
|
|
7048
7560
|
const ctx = await resolveAuthContext(c);
|
|
@@ -7875,13 +8387,13 @@ function createContinuousChatRouter() {
|
|
|
7875
8387
|
};
|
|
7876
8388
|
});
|
|
7877
8389
|
const activeSince = Date.now() - ACTIVE_TOPIC_DAYS * 864e5;
|
|
7878
|
-
const
|
|
8390
|
+
const pending2 = replies.filter(
|
|
7879
8391
|
(r) => !tags.has(r.id) && isHumanAuthor(r.author) && Date.parse(r.created_at) >= activeSince && !backfilling.has(r.id)
|
|
7880
8392
|
).slice(0, BACKFILL_PER_REQUEST);
|
|
7881
|
-
if (
|
|
7882
|
-
for (const r of
|
|
8393
|
+
if (pending2.length) {
|
|
8394
|
+
for (const r of pending2) backfilling.add(r.id);
|
|
7883
8395
|
void (async () => {
|
|
7884
|
-
for (const r of
|
|
8396
|
+
for (const r of pending2) {
|
|
7885
8397
|
await tagReply({ channel, replyId: r.id, author: r.author, body: r.body }).catch(
|
|
7886
8398
|
() => {
|
|
7887
8399
|
}
|
|
@@ -7895,7 +8407,7 @@ function createContinuousChatRouter() {
|
|
|
7895
8407
|
messages.filter((m) => m.topic && Date.parse(m.created_at) >= activeSince).map((m) => m.topic)
|
|
7896
8408
|
)
|
|
7897
8409
|
];
|
|
7898
|
-
return c.json({ messages, topics: activeTopics, pendingTags:
|
|
8410
|
+
return c.json({ messages, topics: activeTopics, pendingTags: pending2.length });
|
|
7899
8411
|
});
|
|
7900
8412
|
app.patch("/replies/:replyId/topic", async (c) => {
|
|
7901
8413
|
if (!await isFeatureEnabled(c, "continuous-chat"))
|
|
@@ -7916,6 +8428,31 @@ function createContinuousChatRouter() {
|
|
|
7916
8428
|
return app;
|
|
7917
8429
|
}
|
|
7918
8430
|
|
|
8431
|
+
// ../api/src/dashboard/reply-language.ts
|
|
8432
|
+
var UNDETERMINED = "und";
|
|
8433
|
+
var BACKFILL_CONCURRENCY = 8;
|
|
8434
|
+
async function detectAndStore(replyId, body) {
|
|
8435
|
+
const lang = await detectSourceLanguage("", body) ?? UNDETERMINED;
|
|
8436
|
+
const { error: error2 } = await getSupabaseClient().from("thread_replies").update({ lang }).eq("id", replyId);
|
|
8437
|
+
if (error2) console.error(`Reply language not stored (${replyId}):`, error2.message);
|
|
8438
|
+
return lang;
|
|
8439
|
+
}
|
|
8440
|
+
function recordReplyLanguage(replyId, body) {
|
|
8441
|
+
void detectAndStore(replyId, body).catch(
|
|
8442
|
+
(err) => console.error(`Reply language detection failed (${replyId}):`, err)
|
|
8443
|
+
);
|
|
8444
|
+
}
|
|
8445
|
+
async function backfillReplyLanguages(replies) {
|
|
8446
|
+
const unknown = replies.filter((r) => r.lang == null);
|
|
8447
|
+
for (let i = 0; i < unknown.length; i += BACKFILL_CONCURRENCY) {
|
|
8448
|
+
await Promise.all(
|
|
8449
|
+
unknown.slice(i, i + BACKFILL_CONCURRENCY).map(async (r) => {
|
|
8450
|
+
r.lang = await detectAndStore(r.id, r.body).catch(() => null);
|
|
8451
|
+
})
|
|
8452
|
+
);
|
|
8453
|
+
}
|
|
8454
|
+
}
|
|
8455
|
+
|
|
7919
8456
|
// ../api/src/dashboard/thread-translate.ts
|
|
7920
8457
|
import { createHash as createHash4 } from "crypto";
|
|
7921
8458
|
|
|
@@ -8019,6 +8556,7 @@ Rules:
|
|
|
8019
8556
|
- Translate meaning, not words. These are people talking, not prose to be polished. Keep the speaker's register: a terse message stays terse, a casual one stays casual, a rude one stays rude. Do not make anyone sound more formal, more complete, or more articulate than they wrote.
|
|
8020
8557
|
- A short reply ("\u597D\u554A", "same", "nope") is translated as the natural equivalent in ${languageName}, using the context to see what it is answering. Never expand it into a full sentence the speaker did not write.
|
|
8021
8558
|
- Keep the Markdown exactly as it is: same heading levels, list nesting, table shape, link and image syntax, blockquotes, and order. Do not add, merge, split, or reorder anything.
|
|
8559
|
+
- A line like \`[BUTTONS: A | B | C]\` holds quick-reply button labels: keep the \`[BUTTONS:\` marker, the \` | \` separators and the closing \`]\` exactly, and translate each label. Never put \`|\` or \`]\` inside a translated label.
|
|
8022
8560
|
- Do NOT translate: text inside fenced or inline code blocks, URLs, file paths, command names, or @mentions and /skill tokens. Leave them byte-for-byte identical.
|
|
8023
8561
|
- Keep established technical terms in English where a fluent speaker of ${languageName} would keep them in English rather than reaching for a translated coinage.
|
|
8024
8562
|
- Use the punctuation conventions of ${languageName}, including full-width punctuation for Chinese and Japanese. Use ordinary ASCII hyphens, never typographic or non-breaking hyphen variants.
|
|
@@ -8135,17 +8673,25 @@ async function translateCached(lang, scope, messages, contextFor) {
|
|
|
8135
8673
|
const missing = keyed.filter((m) => !cachedOf(m));
|
|
8136
8674
|
const fresh = /* @__PURE__ */ new Map();
|
|
8137
8675
|
const freshKey = (m) => `${m.kind}:${m.id}`;
|
|
8138
|
-
|
|
8676
|
+
for (const m of missing) {
|
|
8677
|
+
if (isSourceLanguage(lang, m.lang ?? null)) {
|
|
8678
|
+
fresh.set(freshKey(m), { id: m.id, body: m.body, passthrough: true });
|
|
8679
|
+
}
|
|
8680
|
+
}
|
|
8681
|
+
const toModel = missing.filter((m) => !fresh.has(freshKey(m)));
|
|
8682
|
+
if (toModel.length > 0) {
|
|
8139
8683
|
if (await getTranslationTokensToday(scope.workspaceId) >= DAILY_TOKEN_LIMIT) {
|
|
8140
8684
|
throw new TranslationLimitError();
|
|
8141
8685
|
}
|
|
8142
|
-
const batches = batchMessages(
|
|
8686
|
+
const batches = batchMessages(toModel);
|
|
8143
8687
|
const results = await Promise.all(
|
|
8144
8688
|
batches.map((batch) => translateBatch(batch, contextFor(batch[0]), lang, scope))
|
|
8145
8689
|
);
|
|
8146
8690
|
batches.forEach(
|
|
8147
8691
|
(batch, b) => batch.forEach((m, i) => fresh.set(freshKey(m), results[b][i]))
|
|
8148
8692
|
);
|
|
8693
|
+
}
|
|
8694
|
+
if (missing.length > 0) {
|
|
8149
8695
|
await Promise.all(
|
|
8150
8696
|
kinds.map(
|
|
8151
8697
|
(kind) => putThreadTranslations(
|
|
@@ -8815,7 +9361,7 @@ function createChatRouter(agent = {}) {
|
|
|
8815
9361
|
if (!isTranslatableLanguage2(lang)) return c.json({ error: "unsupported language" }, 400);
|
|
8816
9362
|
const [thread, replies] = await Promise.all([
|
|
8817
9363
|
getSupabaseClient().from("threads").select("channel_id").eq("id", id).single(),
|
|
8818
|
-
getSupabaseClient().from("thread_replies").select("id, author, body").eq("thread_id", id).is("archived_at", null).order("created_at", { ascending: true }).limit(TRANSLATABLE_REPLIES_MAX)
|
|
9364
|
+
getSupabaseClient().from("thread_replies").select("id, author, body, lang").eq("thread_id", id).is("archived_at", null).order("created_at", { ascending: true }).limit(TRANSLATABLE_REPLIES_MAX)
|
|
8819
9365
|
]);
|
|
8820
9366
|
if (thread.error) return c.json({ error: "not found" }, 404);
|
|
8821
9367
|
if (replies.error) return c.json({ error: replies.error.message }, 500);
|
|
@@ -8823,10 +9369,15 @@ function createChatRouter(agent = {}) {
|
|
|
8823
9369
|
if (!channelId || !(await globalChannelMeta(c)).has(channelId)) {
|
|
8824
9370
|
return c.json({ error: "not found" }, 404);
|
|
8825
9371
|
}
|
|
8826
|
-
const
|
|
8827
|
-
(r) => ({ id: r.id, author: r.author, body: slackMrkdwnToMarkdown(r.body) })
|
|
8828
|
-
);
|
|
9372
|
+
const rows = replies.data ?? [];
|
|
8829
9373
|
try {
|
|
9374
|
+
await backfillReplyLanguages(rows);
|
|
9375
|
+
const messages = rows.map((r) => ({
|
|
9376
|
+
id: r.id,
|
|
9377
|
+
author: r.author,
|
|
9378
|
+
body: slackMrkdwnToMarkdown(r.body),
|
|
9379
|
+
lang: r.lang
|
|
9380
|
+
}));
|
|
8830
9381
|
const glossary = (await getChannelGlossaries([channelId])).get(channelId)?.terms ?? [];
|
|
8831
9382
|
const scope = { workspaceId: c.get("auth").workspaceId, glossary };
|
|
8832
9383
|
return c.json({ lang, messages: await translateThread(lang, scope, messages) });
|
|
@@ -9054,6 +9605,7 @@ function createChatRouter(agent = {}) {
|
|
|
9054
9605
|
effort: effortFromRow(reply["effort"])
|
|
9055
9606
|
});
|
|
9056
9607
|
askSupport(c, thread.id, input2.author, input2.body);
|
|
9608
|
+
recordReplyLanguage(reply.id, input2.body);
|
|
9057
9609
|
tagStoredReply(c, {
|
|
9058
9610
|
threadId: thread.id,
|
|
9059
9611
|
replyId: reply.id,
|
|
@@ -9178,6 +9730,7 @@ function createChatRouter(agent = {}) {
|
|
|
9178
9730
|
effort: effortFromRow(data.effort)
|
|
9179
9731
|
});
|
|
9180
9732
|
askSupport(c, threadId, input2.author, input2.body);
|
|
9733
|
+
recordReplyLanguage(data.id, input2.body);
|
|
9181
9734
|
tagStoredReply(c, {
|
|
9182
9735
|
threadId,
|
|
9183
9736
|
replyId: data.id,
|
|
@@ -9547,7 +10100,7 @@ function snippetAround(text, q) {
|
|
|
9547
10100
|
const end = Math.min(text.length, start + SNIPPET_LENGTH);
|
|
9548
10101
|
return `${start > 0 ? "\u2026" : ""}${text.slice(start, end).trim()}${end < text.length ? "\u2026" : ""}`;
|
|
9549
10102
|
}
|
|
9550
|
-
async function
|
|
10103
|
+
async function searchThreads2(q) {
|
|
9551
10104
|
const supabase = getSupabaseClient();
|
|
9552
10105
|
const { data, error: error2 } = await supabase.rpc("search_threads", { q, match_limit: 20 });
|
|
9553
10106
|
if (error2) {
|
|
@@ -9673,7 +10226,7 @@ function createSearchRouter() {
|
|
|
9673
10226
|
const q = c.req.query("q")?.trim();
|
|
9674
10227
|
if (!q) return c.json({ results: [] });
|
|
9675
10228
|
const [threadResults, channelResults, automationResults] = await Promise.all([
|
|
9676
|
-
|
|
10229
|
+
searchThreads2(q),
|
|
9677
10230
|
Promise.resolve(searchChannels(q)),
|
|
9678
10231
|
Promise.resolve(searchAutomations(q))
|
|
9679
10232
|
]);
|
|
@@ -9821,7 +10374,7 @@ function createDomainRouter() {
|
|
|
9821
10374
|
import { Hono as Hono17 } from "hono";
|
|
9822
10375
|
var GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
|
|
9823
10376
|
var MODEL2 = "whisper-large-v3-turbo";
|
|
9824
|
-
var MAX_AUDIO_BYTES =
|
|
10377
|
+
var MAX_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
9825
10378
|
var MAX_PROMPT_CHARS = 400;
|
|
9826
10379
|
var NO_SPEECH_THRESHOLD = 0.6;
|
|
9827
10380
|
function createTranscribeRouter() {
|
|
@@ -9832,7 +10385,7 @@ function createTranscribeRouter() {
|
|
|
9832
10385
|
const body = await c.req.parseBody().catch(() => null);
|
|
9833
10386
|
const file = body?.["file"];
|
|
9834
10387
|
if (!(file instanceof File)) return c.json({ error: "missing file" }, 400);
|
|
9835
|
-
if (file.size > MAX_AUDIO_BYTES) return c.json({ error: "audio
|
|
10388
|
+
if (file.size > MAX_AUDIO_BYTES) return c.json({ error: "audio too large" }, 400);
|
|
9836
10389
|
const form = new FormData();
|
|
9837
10390
|
form.append("file", file, file.name || "segment.wav");
|
|
9838
10391
|
form.append("model", MODEL2);
|
|
@@ -11620,8 +12173,8 @@ function createChannelGreetingRouter(agent) {
|
|
|
11620
12173
|
app.get("/:id/greeting", async (c) => {
|
|
11621
12174
|
const ctx = await resolveAuthContext(c);
|
|
11622
12175
|
const ch = findChannelById(c.req.param("id"));
|
|
11623
|
-
const
|
|
11624
|
-
if (!
|
|
12176
|
+
const pending2 = isWorkspaceOwner(ctx) && eligible(ch) && !ch.greetedAt && (agent.isHostOnline?.(ch.profile) ?? false);
|
|
12177
|
+
if (!pending2) return c.json({ pending: false, threadId: null });
|
|
11625
12178
|
const threadId = await ensureIntroThread(ch);
|
|
11626
12179
|
return c.json({ pending: !!threadId, threadId });
|
|
11627
12180
|
});
|
|
@@ -12733,7 +13286,7 @@ function registerDataRoutes(api, agent = {}) {
|
|
|
12733
13286
|
import { verify } from "crypto";
|
|
12734
13287
|
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
12735
13288
|
import { Hono as Hono33 } from "hono";
|
|
12736
|
-
var
|
|
13289
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12737
13290
|
function cleanText(value, max) {
|
|
12738
13291
|
if (typeof value !== "string") return null;
|
|
12739
13292
|
const trimmed = value.trim();
|
|
@@ -12804,18 +13357,18 @@ function createDeviceAuthRouter() {
|
|
|
12804
13357
|
app.post("/token", async (c) => {
|
|
12805
13358
|
const body = await readBody(c);
|
|
12806
13359
|
const code = typeof body["device_code"] === "string" ? body["device_code"] : "";
|
|
12807
|
-
const
|
|
12808
|
-
if (!
|
|
13360
|
+
const pending2 = code ? await getDeviceCodeBySecret(code) : null;
|
|
13361
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now()) {
|
|
12809
13362
|
return c.json({ error: "expired_token" }, 400);
|
|
12810
13363
|
}
|
|
12811
|
-
if (
|
|
12812
|
-
if (!
|
|
12813
|
-
const last =
|
|
12814
|
-
await markPolled(
|
|
13364
|
+
if (pending2.deniedAt) return c.json({ error: "access_denied" }, 400);
|
|
13365
|
+
if (!pending2.approvedBy) {
|
|
13366
|
+
const last = pending2.lastPolledAt ? Date.parse(pending2.lastPolledAt) : 0;
|
|
13367
|
+
await markPolled(pending2.id);
|
|
12815
13368
|
const tooSoon = Date.now() - last < (POLL_INTERVAL_S - 1) * 1e3;
|
|
12816
13369
|
return c.json({ error: tooSoon ? "slow_down" : "authorization_pending" }, 400);
|
|
12817
13370
|
}
|
|
12818
|
-
const device = await redeemDeviceCode(
|
|
13371
|
+
const device = await redeemDeviceCode(pending2);
|
|
12819
13372
|
if (!device) return c.json({ error: "expired_token" }, 400);
|
|
12820
13373
|
const { token, expiresInS } = await issueAccessToken(device.id);
|
|
12821
13374
|
return c.json({
|
|
@@ -12829,14 +13382,14 @@ function createDeviceAuthRouter() {
|
|
|
12829
13382
|
});
|
|
12830
13383
|
app.post("/challenge", async (c) => {
|
|
12831
13384
|
const body = await readBody(c);
|
|
12832
|
-
const deviceId = typeof body["device_id"] === "string" &&
|
|
13385
|
+
const deviceId = typeof body["device_id"] === "string" && UUID2.test(body["device_id"]) ? body["device_id"] : "";
|
|
12833
13386
|
const device = deviceId ? await getDevice(deviceId) : null;
|
|
12834
13387
|
if (!device || device.revokedAt) return c.json({ error: "unknown_device" }, 401);
|
|
12835
13388
|
return c.json({ nonce: await createChallenge(device.id) });
|
|
12836
13389
|
});
|
|
12837
13390
|
app.post("/refresh", async (c) => {
|
|
12838
13391
|
const body = await readBody(c);
|
|
12839
|
-
const deviceId = typeof body["device_id"] === "string" &&
|
|
13392
|
+
const deviceId = typeof body["device_id"] === "string" && UUID2.test(body["device_id"]) ? body["device_id"] : "";
|
|
12840
13393
|
const nonce = typeof body["nonce"] === "string" ? body["nonce"] : "";
|
|
12841
13394
|
const signature = typeof body["signature"] === "string" ? body["signature"] : "";
|
|
12842
13395
|
const device = deviceId ? await getDevice(deviceId) : null;
|
|
@@ -12868,22 +13421,22 @@ function createDeviceAuthRouter() {
|
|
|
12868
13421
|
const userId = await sessionUserId(c);
|
|
12869
13422
|
if (!userId) return c.json({ error: "not signed in" }, 401);
|
|
12870
13423
|
const userCode = normalizeUserCode(c.req.query("user_code") ?? "");
|
|
12871
|
-
const
|
|
12872
|
-
if (!
|
|
13424
|
+
const pending2 = userCode ? await getDeviceCodeByUserCode(userCode) : null;
|
|
13425
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now() || pending2.approvedBy || pending2.deniedAt) {
|
|
12873
13426
|
return c.json({ error: "That code is invalid, expired, or already used." }, 404);
|
|
12874
13427
|
}
|
|
12875
13428
|
const workspaces = await listAdminWorkspaces(userId);
|
|
12876
13429
|
const hosts2 = await listWorkspaceHosts(
|
|
12877
13430
|
workspaces.map((w) => w.id),
|
|
12878
|
-
|
|
13431
|
+
pending2.publicKey
|
|
12879
13432
|
);
|
|
12880
|
-
const bound = await boundWorkspaceIds(
|
|
13433
|
+
const bound = await boundWorkspaceIds(pending2.publicKey, userId);
|
|
12881
13434
|
return c.json({
|
|
12882
|
-
user_code:
|
|
12883
|
-
name:
|
|
12884
|
-
platform:
|
|
12885
|
-
ip:
|
|
12886
|
-
created_at:
|
|
13435
|
+
user_code: pending2.userCode,
|
|
13436
|
+
name: pending2.name,
|
|
13437
|
+
platform: pending2.platform,
|
|
13438
|
+
ip: pending2.requesterIp,
|
|
13439
|
+
created_at: pending2.createdAt,
|
|
12887
13440
|
// `host`: another machine this workspace already runs on, so it can't be
|
|
12888
13441
|
// picked. `bound`: this machine already serves it, so there's nothing to pick.
|
|
12889
13442
|
workspaces: workspaces.map((w) => ({ ...w, host: hosts2.get(w.id) ?? null, bound: bound.has(w.id) }))
|
|
@@ -12909,8 +13462,8 @@ function createDeviceAuthRouter() {
|
|
|
12909
13462
|
const userCode = normalizeUserCode(typeof body["user_code"] === "string" ? body["user_code"] : "");
|
|
12910
13463
|
const decision = body["decision"];
|
|
12911
13464
|
if (!userCode || decision !== "approve" && decision !== "deny") return c.json({ error: "invalid request" }, 400);
|
|
12912
|
-
const
|
|
12913
|
-
if (!
|
|
13465
|
+
const pending2 = await getDeviceCodeByUserCode(userCode);
|
|
13466
|
+
if (!pending2 || Date.parse(pending2.expiresAt) <= Date.now()) {
|
|
12914
13467
|
return c.json({ error: "That code is invalid or expired." }, 404);
|
|
12915
13468
|
}
|
|
12916
13469
|
let workspaceIds = [];
|
|
@@ -12921,22 +13474,22 @@ function createDeviceAuthRouter() {
|
|
|
12921
13474
|
if (workspaceIds.some((id) => !allowed.has(id))) {
|
|
12922
13475
|
return c.json({ error: "You can only add a device to workspaces you are an admin of." }, 403);
|
|
12923
13476
|
}
|
|
12924
|
-
if (!workspaceIds.length && !(await boundWorkspaceIds(
|
|
13477
|
+
if (!workspaceIds.length && !(await boundWorkspaceIds(pending2.publicKey, userId)).size) {
|
|
12925
13478
|
return c.json({ error: "Pick at least one workspace." }, 400);
|
|
12926
13479
|
}
|
|
12927
13480
|
}
|
|
12928
|
-
if ((await listWorkspaceHosts(workspaceIds,
|
|
13481
|
+
if ((await listWorkspaceHosts(workspaceIds, pending2.publicKey)).size) {
|
|
12929
13482
|
return c.json({ error: "That workspace already has a Host. Its Host cannot be replaced." }, 409);
|
|
12930
13483
|
}
|
|
12931
13484
|
const decided = await decideDeviceCode(
|
|
12932
|
-
|
|
13485
|
+
pending2.id,
|
|
12933
13486
|
userId,
|
|
12934
13487
|
decision === "approve" ? { approve: true, workspaceIds } : { approve: false }
|
|
12935
13488
|
);
|
|
12936
13489
|
if (!decided) {
|
|
12937
13490
|
return c.json({ error: "That code was already used." }, 409);
|
|
12938
13491
|
}
|
|
12939
|
-
await releaseStaleHosts(workspaceIds,
|
|
13492
|
+
await releaseStaleHosts(workspaceIds, pending2.publicKey);
|
|
12940
13493
|
return c.json({ ok: true });
|
|
12941
13494
|
});
|
|
12942
13495
|
return app;
|
|
@@ -14617,6 +15170,11 @@ import { join as join16 } from "path";
|
|
|
14617
15170
|
var running = false;
|
|
14618
15171
|
function startHostUpgrade() {
|
|
14619
15172
|
if (running) return { started: false };
|
|
15173
|
+
if (process.env.FLY_MACHINE_ID) {
|
|
15174
|
+
running = true;
|
|
15175
|
+
setTimeout(() => process.exit(0), 1e3);
|
|
15176
|
+
return { started: true };
|
|
15177
|
+
}
|
|
14620
15178
|
mkdirSync10(paths.LOG_DIR, { recursive: true });
|
|
14621
15179
|
const log5 = openSync3(join16(paths.LOG_DIR, "host-upgrade.log"), "a");
|
|
14622
15180
|
const child = spawn5(process.execPath, [process.argv[1] ?? "", "upgrade"], {
|
|
@@ -14815,7 +15373,7 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14815
15373
|
...CLI_VERSION ? { cliVersion: CLI_VERSION } : {},
|
|
14816
15374
|
...pinnedModel ? { pinnedModel } : {}
|
|
14817
15375
|
};
|
|
14818
|
-
|
|
15376
|
+
send2(ws, deviceId ? { type: "auth", signature, deviceId, ...version } : { type: "auth", signature, ...version });
|
|
14819
15377
|
return;
|
|
14820
15378
|
}
|
|
14821
15379
|
if (msg.type === "auth-failed") {
|
|
@@ -14835,11 +15393,11 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14835
15393
|
}
|
|
14836
15394
|
if (msg.type === "auth-ok") {
|
|
14837
15395
|
console.log("[host-socket] authenticated");
|
|
14838
|
-
setHostDbSender((out) =>
|
|
14839
|
-
|
|
15396
|
+
setHostDbSender((out) => send2(ws, out));
|
|
15397
|
+
send2(ws, { type: "host-config", configs: buildHostConfigSnapshot() });
|
|
14840
15398
|
if (configPushTimer) clearInterval(configPushTimer);
|
|
14841
15399
|
configPushTimer = setInterval(() => {
|
|
14842
|
-
|
|
15400
|
+
send2(ws, { type: "host-config", configs: buildHostConfigSnapshot() });
|
|
14843
15401
|
}, HOST_CONFIG_PUSH_INTERVAL_MS);
|
|
14844
15402
|
onAuthenticated?.();
|
|
14845
15403
|
if (msg.workspaces) onWorkspaces?.(msg.workspaces);
|
|
@@ -14853,8 +15411,8 @@ function connectHostSocket(url, callbacks, onAuthenticated, onWorkspaces) {
|
|
|
14853
15411
|
handlePluginSvgResult(msg.id, msg.url);
|
|
14854
15412
|
return;
|
|
14855
15413
|
}
|
|
14856
|
-
if (msg.type === "
|
|
14857
|
-
|
|
15414
|
+
if (msg.type === "action-result") {
|
|
15415
|
+
handleActionResult(msg.id, { value: msg.value, error: msg.error });
|
|
14858
15416
|
return;
|
|
14859
15417
|
}
|
|
14860
15418
|
if (msg.type === "attachment-url-result") {
|
|
@@ -14906,9 +15464,9 @@ async function handleCall(msg, callbacks, ws) {
|
|
|
14906
15464
|
try {
|
|
14907
15465
|
const handler = callbacks[msg.method];
|
|
14908
15466
|
const value = await handler?.(...msg.args);
|
|
14909
|
-
|
|
15467
|
+
send2(ws, { type: "result", id: msg.id, value: value ?? null });
|
|
14910
15468
|
} catch (err) {
|
|
14911
|
-
|
|
15469
|
+
send2(ws, { type: "call-error", id: msg.id, message: err.message });
|
|
14912
15470
|
}
|
|
14913
15471
|
});
|
|
14914
15472
|
}
|
|
@@ -14954,7 +15512,7 @@ async function handleLocalRelay(req, callbacks, token) {
|
|
|
14954
15512
|
);
|
|
14955
15513
|
return Response.json({ value: value ?? null });
|
|
14956
15514
|
}
|
|
14957
|
-
function
|
|
15515
|
+
function send2(ws, msg) {
|
|
14958
15516
|
if (ws.readyState === WebSocket2.OPEN) ws.send(encodeWireMessage(msg));
|
|
14959
15517
|
}
|
|
14960
15518
|
|
|
@@ -15157,15 +15715,12 @@ async function startHostDashboard(preferredPort, host) {
|
|
|
15157
15715
|
}
|
|
15158
15716
|
});
|
|
15159
15717
|
}
|
|
15160
|
-
app.post(
|
|
15718
|
+
app.post(LOCAL_ACTION_PATH, async (c) => {
|
|
15161
15719
|
if (!relayAuthorized(c.req.raw, relayToken)) return c.json({ error: "unauthorized" }, 401);
|
|
15162
15720
|
const body = await c.req.json().catch(() => null);
|
|
15163
|
-
if (!body || typeof body.
|
|
15164
|
-
return c.json({ error: "bad request" }, 400);
|
|
15165
|
-
}
|
|
15721
|
+
if (!body || typeof body.name !== "string") return c.json({ error: "bad request" }, 400);
|
|
15166
15722
|
try {
|
|
15167
|
-
|
|
15168
|
-
return c.json(res, res.url ? 200 : 400);
|
|
15723
|
+
return c.json(await requestAction(body.name, body.input, body.requester));
|
|
15169
15724
|
} catch (err) {
|
|
15170
15725
|
return c.json({ error: err.message }, 503);
|
|
15171
15726
|
}
|
|
@@ -15665,7 +16220,7 @@ async function main() {
|
|
|
15665
16220
|
break;
|
|
15666
16221
|
case "-v":
|
|
15667
16222
|
case "--version":
|
|
15668
|
-
printRaw("0.1.
|
|
16223
|
+
printRaw("0.1.62");
|
|
15669
16224
|
break;
|
|
15670
16225
|
case "-h":
|
|
15671
16226
|
case "--help":
|