@dsh-mobile/mobile-remote 3.4.1-beta.2 → 3.5.0-beta.1
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/README.md +1 -1
- package/docs/PRIVACY-POLICY.en.md +7 -2
- package/docs/PRIVACY-POLICY.md +7 -2
- package/docs/TERMS-OF-SERVICE.en.md +3 -2
- package/docs/TERMS-OF-SERVICE.md +3 -2
- package/lib/backup.js +30 -0
- package/lib/config.js +10 -0
- package/lib/host-plugins.js +290 -0
- package/lib/host-schedule.js +206 -0
- package/lib/host-team.js +89 -0
- package/lib/index.js +196 -3281
- package/lib/live-activity.js +351 -0
- package/lib/memory/context.js +17 -3
- package/lib/memory/decay.js +68 -4
- package/lib/memory/promises.js +116 -0
- package/lib/memory/routes.js +113 -1
- package/lib/memory/store.js +212 -13
- package/lib/memory/turn-hook.js +109 -0
- package/lib/phone-announce.js +6 -5
- package/lib/protocol.js +13 -0
- package/lib/routes/agents.js +405 -0
- package/lib/routes/app-state.js +178 -0
- package/lib/routes/backup.js +144 -0
- package/lib/routes/diagnostics.js +227 -0
- package/lib/routes/files.js +326 -0
- package/lib/routes/git.js +53 -0
- package/lib/routes/history.js +313 -0
- package/lib/routes/host-services.js +51 -0
- package/lib/routes/models.js +462 -0
- package/lib/routes/notifications.js +183 -0
- package/lib/routes/pairing.js +170 -0
- package/lib/routes/route-groups.js +20 -0
- package/lib/routes/send.js +341 -0
- package/lib/routes/sessions.js +462 -0
- package/lib/routes/toolbox.js +14 -0
- package/lib/routes/usage.js +211 -0
- package/lib/timeline.js +5 -1
- package/lib/toolbox.js +355 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -7,60 +7,69 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
import { protocolInfo } from "./protocol.js"; import { createPhoneActions } from "./phone-actions.js";
|
|
10
|
+
import { protocolInfo } from "./protocol.js"; import { createPhoneActions } from "./phone-actions.js"; import { attachLiveActivity } from "./live-activity.js";
|
|
11
11
|
import { networkInterfaces, hostname } from "node:os";
|
|
12
12
|
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { join, sep, resolve, basename } from "node:path";
|
|
13
|
+
import { ftruncateSync, mkdirSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs";
|
|
14
|
+
import { join, sep, resolve } from "node:path";
|
|
16
15
|
import { createServer as createHttpServer, request as httpRequest } from "node:http";
|
|
17
16
|
import { performance } from "node:perf_hooks";
|
|
18
17
|
import QRCode from "qrcode";
|
|
19
18
|
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
20
19
|
import { setSandboxMode } from "@deepseek-ai/dsh-sandbox-policy";
|
|
21
20
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
22
|
-
import { scopeTarget } from "@deepseek-ai/dsh-scope";
|
|
23
21
|
import { createTitleCache } from "./session-title-cache.js";
|
|
24
22
|
import { createSessionTitleRefresher, DEFAULT_TITLE_REFRESH_BUDGET_MS, DEFAULT_TITLE_REFRESH_CONCURRENCY } from "./session-title-refresh.js";
|
|
25
23
|
export { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage, usageWindowLabel } from "./account-usage.js";
|
|
26
24
|
import { createMemoryRoutes } from "./memory/routes.js";
|
|
27
25
|
import { openMemoryStore, wipeMemoryFiles } from "./memory/store.js";
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import { createMemoryContextProvider, installMemoryContext, MEMORY_CONTEXT_NAME } from "./memory/context.js";
|
|
26
|
+
import { createMemoryTurnHook } from "./memory/turn-hook.js";
|
|
27
|
+
import { createMemoryContextProvider, installMemoryContext } from "./memory/context.js";
|
|
31
28
|
import { createAssistantPrefs, modeBrief } from "./assistant-prefs.js";
|
|
32
29
|
import { activePersonaCard, createPersonaCardStore, createPersonaRoutes, personaPromptText } from "./persona-cards.js";
|
|
33
30
|
import { createGitReadService } from "./git-read-service.js";
|
|
34
31
|
import { createLoginRateLimiter } from "./rate-limit.js";
|
|
35
|
-
import { RPC_ENDPOINT_RENAMES, RPC_PAYLOAD_ADAPTER, RPC_STREAM_METHODS,
|
|
36
|
-
import { guardRes, sendJson, sendError, readBody, requireGet
|
|
37
|
-
import { AUTO as AUTO_TOKEN, effectiveAuthSetting, mobileRemoteStateDir, resolveAuthToken, resolveLanBridgeEnabled, resolveLanBridgePort,
|
|
38
|
-
import {
|
|
32
|
+
import { RPC_ENDPOINT_RENAMES, RPC_PAYLOAD_ADAPTER, RPC_STREAM_METHODS, projectionOf } from "./rpc-adapter.js";
|
|
33
|
+
import { guardRes, sendJson, sendError, readBody, requireGet } from "./http-util.js";
|
|
34
|
+
import { AUTO as AUTO_TOKEN, effectiveAuthSetting, mobileRemoteStateDir, resolveAuthToken, resolveLanBridgeEnabled, resolveLanBridgePort, formatConnectionBanner } from "./auto-config.js";
|
|
35
|
+
import { loadOrCreateIdentity, loadRetiredIdentities } from "./relay/identity.js";
|
|
39
36
|
import { DeviceStore } from "./relay/devices.js";
|
|
40
37
|
import { RelayConnector } from "./relay/connector.js"; import { P2pHost } from "./relay/p2p.js";
|
|
41
38
|
import { createRelayDemand } from "./relay/on-demand.js";
|
|
42
39
|
import { createHttpReplayer } from "./relay/serve.js";
|
|
43
|
-
import {
|
|
40
|
+
import { isAllowedRelayUrl } from "./relay/pairing.js";
|
|
44
41
|
import { acceptWebSocket, rejectUpgrade } from "./relay/ws-server.js";
|
|
45
|
-
import { pairingFingerprint as pairingFingerprintOf } from "./relay/fingerprint.js";
|
|
46
|
-
import { b64u as relayB64u } from "./relay/crypto.js";
|
|
47
42
|
|
|
48
43
|
export { Config, DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
|
|
49
44
|
import { DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
|
|
50
|
-
import {
|
|
51
|
-
import { FILE_RANGE_CAPABILITIES, clampText, ifNoneMatch, parseByteRange, fileMimeOf, mapBounded, normalizeServerPath, orderQrAddresses, pruneReceiptMap, receiptExpired, redactPathText, requestAbort, requestHeaderText, validateQuestionAnswers } from "./api-helpers.js";
|
|
45
|
+
import { FILE_RANGE_CAPABILITIES, clampText, mapBounded, normalizeServerPath, orderQrAddresses, pruneReceiptMap, receiptExpired, redactPathText, requestAbort, requestHeaderText, validateQuestionAnswers } from "./api-helpers.js";
|
|
52
46
|
import { capabilityState, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
|
|
53
47
|
import { pushToChannel as deliverPush } from "./push.js";
|
|
54
48
|
import { createProactiveScheduler } from "./proactive.js";
|
|
55
49
|
import { CHATTING_MS, DEFAULT_IDLE_MS, isUserIdle, pickMaterial } from "./proactive-material.js";
|
|
56
50
|
import { createReminderRoutes, createReminderStore } from "./reminders.js";
|
|
57
51
|
import { createBreakReminder, isUserActivityEvent } from "./break-reminder.js";
|
|
58
|
-
import {
|
|
59
|
-
import { buildRotation } from "./session-rotation.js";
|
|
60
|
-
import { inQuietHours, kindLabelOf, notifyBody, notifyHeadline, parseHm, quietHoursSuppress, shouldSuppressForQuietHours } from "./notify-copy.js";
|
|
52
|
+
import { kindLabelOf, notifyBody, notifyHeadline, parseHm, shouldSuppressForQuietHours } from "./notify-copy.js";
|
|
61
53
|
import { compareSessionsForList, latestMessageTimeOf, planMessageTimePrune } from "./session-list.js";
|
|
62
|
-
import { EVENT_TIMELINE_CAPABILITIES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage,
|
|
63
|
-
import {
|
|
54
|
+
import { EVENT_TIMELINE_CAPABILITIES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, summarizeEvent } from "./timeline.js";
|
|
55
|
+
import { SEEDED_PREFIX_ERROR_MESSAGE, classifyTurnOutlineReadError, createTurnOutlineQueue, raceWithDeadline, turnOutlineCapabilityOf, turnOutlineStateOf } from "./turn-outline.js";
|
|
56
|
+
import { handleAppStateRoutes } from "./routes/app-state.js";
|
|
57
|
+
import { handleBackupRoutes } from "./routes/backup.js";
|
|
58
|
+
import { handleGitRoutes } from "./routes/git.js";
|
|
59
|
+
import { handlePairingRoutes } from "./routes/pairing.js";
|
|
60
|
+
import { handleSendRoutes } from "./routes/send.js";
|
|
61
|
+
import { handleSessionsRoutes } from "./routes/sessions.js";
|
|
62
|
+
import { handleHistoryRoutes } from "./routes/history.js";
|
|
63
|
+
import { handleModelsRoutes } from "./routes/models.js";
|
|
64
|
+
import { handleNotificationsRoutes } from "./routes/notifications.js";
|
|
65
|
+
import { handleUsageRoutes } from "./routes/usage.js";
|
|
66
|
+
import { handleDiagnosticsRoutes } from "./routes/diagnostics.js";
|
|
67
|
+
import { handleFilesRoutes } from "./routes/files.js";
|
|
68
|
+
import { handleAgentsRoutes } from "./routes/agents.js";
|
|
69
|
+
import { handleHostServicesRoutes } from "./routes/host-services.js";
|
|
70
|
+
import { handleToolboxRoutes } from "./routes/toolbox.js";
|
|
71
|
+
import { createToolbox } from "./toolbox.js";
|
|
72
|
+
import { runRouteGroups } from "./routes/route-groups.js";
|
|
64
73
|
export { codexProxyUrl } from "./account-usage-query.js";
|
|
65
74
|
export { classifyFetchFailure, normalizeServerPath, orderQrAddresses, pruneReceiptMap, receiptExpired, redactPathText, requestAbort, requestHeaderText, safeFailureReason, validateQuestionAnswers } from "./api-helpers.js";
|
|
66
75
|
export { capabilityState, createInProcessPeer, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, liveRootAgents, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
|
|
@@ -70,6 +79,24 @@ export { MESSAGE_EVENT_TYPES, blocksToText, detailEventFor, isDetailVisibleType,
|
|
|
70
79
|
export { clampTurnOutline, classifyTurnOutlineReadError, createTurnOutlineQueue, raceWithDeadline, turnOutlineCapabilityOf, turnOutlineStateOf } from "./turn-outline.js";
|
|
71
80
|
|
|
72
81
|
|
|
82
|
+
const ROUTE_GROUPS = [
|
|
83
|
+
handleAppStateRoutes,
|
|
84
|
+
handleBackupRoutes,
|
|
85
|
+
handleGitRoutes,
|
|
86
|
+
handlePairingRoutes,
|
|
87
|
+
handleSendRoutes,
|
|
88
|
+
handleSessionsRoutes,
|
|
89
|
+
handleHistoryRoutes,
|
|
90
|
+
handleModelsRoutes,
|
|
91
|
+
handleNotificationsRoutes,
|
|
92
|
+
handleUsageRoutes,
|
|
93
|
+
handleDiagnosticsRoutes,
|
|
94
|
+
handleFilesRoutes,
|
|
95
|
+
handleAgentsRoutes, handleHostServicesRoutes,
|
|
96
|
+
handleToolboxRoutes,
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
|
|
73
100
|
export const name = "mobile-remote";
|
|
74
101
|
|
|
75
102
|
|
|
@@ -203,7 +230,7 @@ export function apply(ctx, configInput) {
|
|
|
203
230
|
wipe: () => (memoryStore ? 0 : wipeMemoryFiles(STATE_DIR)),
|
|
204
231
|
|
|
205
232
|
|
|
206
|
-
onDeleteAll: () =>
|
|
233
|
+
onDeleteAll: () => memoryTurns.clear(),
|
|
207
234
|
});
|
|
208
235
|
|
|
209
236
|
|
|
@@ -1685,7 +1712,8 @@ export function apply(ctx, configInput) {
|
|
|
1685
1712
|
}
|
|
1686
1713
|
}
|
|
1687
1714
|
};
|
|
1688
|
-
const phoneActions = createPhoneActions({ ctx, broadcast, phoneConnected: () => connections.size > 0, pcName: config.relay?.name });
|
|
1715
|
+
const phoneActions = createPhoneActions({ ctx, broadcast, phoneConnected: () => connections.size > 0, pcName: config.relay?.name }); const liveActivity = attachLiveActivity({ ctx, config, agentSessionId: (a) => agentSessionId(a), sessionTitleOf: (s) => sessionTitleOf(s), pending: () => [...pendingApprovals.values(), ...pendingQuestions.values()] });
|
|
1716
|
+
const toolbox = createToolbox({ ctx, broadcast, pcName: config.relay?.name });
|
|
1689
1717
|
|
|
1690
1718
|
|
|
1691
1719
|
const jobViews = (list) =>
|
|
@@ -1783,9 +1811,15 @@ export function apply(ctx, configInput) {
|
|
|
1783
1811
|
breakReminder.activity();
|
|
1784
1812
|
proactive.noteReaction();
|
|
1785
1813
|
};
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1814
|
+
const memoryTurns = createMemoryTurnHook({
|
|
1815
|
+
enabled: () => Boolean(config.memory?.enabled),
|
|
1816
|
+
getStore: getMemoryStore,
|
|
1817
|
+
getMode: () => assistantPrefs.get().mode,
|
|
1818
|
+
blocksToText,
|
|
1819
|
+
broadcast: (msg) => broadcast(msg),
|
|
1820
|
+
logger: ctx.logger,
|
|
1821
|
+
shortId: (sid) => shortSessionId(sid),
|
|
1822
|
+
});
|
|
1789
1823
|
|
|
1790
1824
|
const PENDING_FRAMES_MAX = 200;
|
|
1791
1825
|
const PENDING_FRAMES_TTL = 24 * 3600 * 1000;
|
|
@@ -1808,7 +1842,7 @@ export function apply(ctx, configInput) {
|
|
|
1808
1842
|
}
|
|
1809
1843
|
|
|
1810
1844
|
|
|
1811
|
-
res.dshVia = via; phoneActions.attach(res, req);
|
|
1845
|
+
res.dshVia = via; phoneActions.attach(res, req); toolbox.attach(res, req);
|
|
1812
1846
|
res.on("close", () => connections.delete(res));
|
|
1813
1847
|
|
|
1814
1848
|
res.on("error", () => connections.delete(res));
|
|
@@ -1857,53 +1891,10 @@ export function apply(ctx, configInput) {
|
|
|
1857
1891
|
|
|
1858
1892
|
if (isVisibleConversationMessage(event)) touchMessageTime(session.id, event.time);
|
|
1859
1893
|
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
if (event.type === "user/message") {
|
|
1864
|
-
try {
|
|
1865
|
-
pendingUserText.set(session.id, blocksToText(event.data?.message?.content));
|
|
1866
|
-
} catch {
|
|
1867
|
-
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1894
|
+
memoryTurns.onEvent(session, event);
|
|
1870
1895
|
|
|
1871
1896
|
|
|
1872
1897
|
if (isUserActivityEvent(session, event)) noteUserActivity({ typed: true });
|
|
1873
|
-
if (event.type === "turn/end") {
|
|
1874
|
-
const said = pendingUserText.get(session.id);
|
|
1875
|
-
pendingUserText.delete(session.id);
|
|
1876
|
-
|
|
1877
|
-
if (said && config.memory?.enabled) {
|
|
1878
|
-
try {
|
|
1879
|
-
const store = getMemoryStore();
|
|
1880
|
-
if (store) {
|
|
1881
|
-
const candidates = extractMemories({
|
|
1882
|
-
text: said,
|
|
1883
|
-
mode: assistantPrefs.get().mode,
|
|
1884
|
-
});
|
|
1885
|
-
if (candidates.length > 0) {
|
|
1886
|
-
const written = recordMemories({
|
|
1887
|
-
store,
|
|
1888
|
-
candidates,
|
|
1889
|
-
meta: {
|
|
1890
|
-
sessionId: session.id,
|
|
1891
|
-
|
|
1892
|
-
origin: session.header?.title ?? null,
|
|
1893
|
-
},
|
|
1894
|
-
});
|
|
1895
|
-
if (written > 0) {
|
|
1896
|
-
ctx.logger.info?.(`mobile-remote: 记住了 ${written} 条(会话 ${shortSessionId(session.id)})`);
|
|
1897
|
-
broadcast({ type: "memory/changed" });
|
|
1898
|
-
}
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
} catch (err) {
|
|
1902
|
-
|
|
1903
|
-
ctx.logger.warn(`mobile-remote: 记忆写入失败:${err?.message ?? err}`);
|
|
1904
|
-
}
|
|
1905
|
-
}
|
|
1906
|
-
}
|
|
1907
1898
|
|
|
1908
1899
|
if (event.type === "request/context" && Number.isInteger(event.data?.contextWindow)) {
|
|
1909
1900
|
contextWindowMap.set(session.id, event.data.contextWindow);
|
|
@@ -1971,7 +1962,7 @@ export function apply(ctx, configInput) {
|
|
|
1971
1962
|
|
|
1972
1963
|
if (payload.status === "running" && sessionId) cancelDone(sessionId);
|
|
1973
1964
|
|
|
1974
|
-
if (payload.status === "idle" && sessionId) releaseHeld(sessionId);
|
|
1965
|
+
if (payload.status === "idle" && sessionId) releaseHeld(sessionId); liveActivity.refresh();
|
|
1975
1966
|
};
|
|
1976
1967
|
|
|
1977
1968
|
|
|
@@ -2471,6 +2462,134 @@ export function apply(ctx, configInput) {
|
|
|
2471
2462
|
|
|
2472
2463
|
const turnOutlineQueue = createTurnOutlineQueue();
|
|
2473
2464
|
|
|
2465
|
+
|
|
2466
|
+
|
|
2467
|
+
const routeDeps = {
|
|
2468
|
+
get DROP_RESPONSE_HOOK() { return DROP_RESPONSE_HOOK; },
|
|
2469
|
+
get NOTIF_MAX() { return NOTIF_MAX; },
|
|
2470
|
+
get RECEIPT_TTL() { return RECEIPT_TTL; },
|
|
2471
|
+
get accountUsageCache() { return accountUsageCache; },
|
|
2472
|
+
set accountUsageCache(v) { accountUsageCache = v; },
|
|
2473
|
+
get accountUsageInFlight() { return accountUsageInFlight; },
|
|
2474
|
+
set accountUsageInFlight(v) { accountUsageInFlight = v; },
|
|
2475
|
+
get accountUsageLastForcedAt() { return accountUsageLastForcedAt; },
|
|
2476
|
+
set accountUsageLastForcedAt(v) { accountUsageLastForcedAt = v; },
|
|
2477
|
+
get actionEntries() { return actionEntries; },
|
|
2478
|
+
get activityMap() { return activityMap; },
|
|
2479
|
+
get agentSessionId() { return agentSessionId; },
|
|
2480
|
+
get apiRpc() { return apiRpc; },
|
|
2481
|
+
get applyPermissionPreset() { return applyPermissionPreset; },
|
|
2482
|
+
get approvalMode() { return approvalMode; },
|
|
2483
|
+
get assistantPrefs() { return assistantPrefs; },
|
|
2484
|
+
get authEnabled() { return authEnabled; },
|
|
2485
|
+
get balanceCache() { return balanceCache; },
|
|
2486
|
+
set balanceCache(v) { balanceCache = v; },
|
|
2487
|
+
get basePath() { return basePath; },
|
|
2488
|
+
get bodyError() { return bodyError; },
|
|
2489
|
+
get broadcast() { return broadcast; },
|
|
2490
|
+
get broadcastQueue() { return broadcastQueue; },
|
|
2491
|
+
get cachedOwnerPeer() { return cachedOwnerPeer; },
|
|
2492
|
+
set cachedOwnerPeer(v) { cachedOwnerPeer = v; },
|
|
2493
|
+
get catalogCache() { return catalogCache; },
|
|
2494
|
+
set catalogCache(v) { catalogCache = v; },
|
|
2495
|
+
get config() { return config; },
|
|
2496
|
+
get connect() { return connect; },
|
|
2497
|
+
get connections() { return connections; },
|
|
2498
|
+
get contextWindowMap() { return contextWindowMap; },
|
|
2499
|
+
get coreArchivedIds() { return coreArchivedIds; },
|
|
2500
|
+
get corpusIds() { return corpusIds; },
|
|
2501
|
+
get corpusObservedAt() { return corpusObservedAt; },
|
|
2502
|
+
set corpusObservedAt(v) { corpusObservedAt = v; },
|
|
2503
|
+
get ctx() { return ctx; },
|
|
2504
|
+
get dropConn() { return dropConn; },
|
|
2505
|
+
get enumerateSessionsShared() { return enumerateSessionsShared; },
|
|
2506
|
+
get error() { return error; },
|
|
2507
|
+
get eventBySeq() { return eventBySeq; },
|
|
2508
|
+
get eventsCapable() { return eventsCapable; },
|
|
2509
|
+
get eventsOf() { return eventsOf; },
|
|
2510
|
+
get failureDetail() { return failureDetail; },
|
|
2511
|
+
get finishApproval() { return finishApproval; },
|
|
2512
|
+
get finishQuestion() { return finishQuestion; },
|
|
2513
|
+
get firstAgent() { return firstAgent; },
|
|
2514
|
+
get gatewayPeer() { return gatewayPeer; },
|
|
2515
|
+
get getMemoryStore() { return getMemoryStore; },
|
|
2516
|
+
get gitRead() { return gitRead; },
|
|
2517
|
+
get handleMemory() { return handleMemory; },
|
|
2518
|
+
get handlePersona() { return handlePersona; },
|
|
2519
|
+
get handleReminders() { return handleReminders; },
|
|
2520
|
+
get heldContentOf() { return heldContentOf; },
|
|
2521
|
+
get heldOf() { return heldOf; },
|
|
2522
|
+
get heldQueue() { return heldQueue; },
|
|
2523
|
+
get ipv4Addresses() { return ipv4Addresses; },
|
|
2524
|
+
get jobViews() { return jobViews; },
|
|
2525
|
+
get lanBridgeListening() { return lanBridgeListening; },
|
|
2526
|
+
set lanBridgeListening(v) { lanBridgeListening = v; },
|
|
2527
|
+
get lanEnabled() { return lanEnabled; },
|
|
2528
|
+
get lanHost() { return lanHost; },
|
|
2529
|
+
get lanNoiseUrls() { return lanNoiseUrls; },
|
|
2530
|
+
get lanPort() { return lanPort; },
|
|
2531
|
+
get lastTypedAt() { return lastTypedAt; },
|
|
2532
|
+
set lastTypedAt(v) { lastTypedAt = v; },
|
|
2533
|
+
get listPersistedSubagents() { return listPersistedSubagents; },
|
|
2534
|
+
get loadDormantSession() { return loadDormantSession; },
|
|
2535
|
+
get localDesktopGate() { return localDesktopGate; },
|
|
2536
|
+
get messageTimeMap() { return messageTimeMap; },
|
|
2537
|
+
get mobileActions() { return mobileActions; },
|
|
2538
|
+
get name() { return name; },
|
|
2539
|
+
get newsCursor() { return newsCursor; },
|
|
2540
|
+
set newsCursor(v) { newsCursor = v; },
|
|
2541
|
+
get noteUserActivity() { return noteUserActivity; },
|
|
2542
|
+
get notifStore() { return notifStore; },
|
|
2543
|
+
get openRetiredRoom() { return openRetiredRoom; },
|
|
2544
|
+
get pendingApprovals() { return pendingApprovals; },
|
|
2545
|
+
get pendingFrames() { return pendingFrames; },
|
|
2546
|
+
get pendingQuestions() { return pendingQuestions; },
|
|
2547
|
+
get persistHeld() { return persistHeld; },
|
|
2548
|
+
get persistReceipts() { return persistReceipts; },
|
|
2549
|
+
get phoneActions() { return phoneActions; }, get liveActivity() { return liveActivity; },
|
|
2550
|
+
get pluginVersion() { return pluginVersion; },
|
|
2551
|
+
get toolbox() { return toolbox; },
|
|
2552
|
+
get presenceState() { return presenceState; },
|
|
2553
|
+
set presenceState(v) { presenceState = v; },
|
|
2554
|
+
get privateFirst() { return privateFirst; },
|
|
2555
|
+
get proactive() { return proactive; },
|
|
2556
|
+
get proactiveIdleMs() { return proactiveIdleMs; },
|
|
2557
|
+
get promptImage() { return promptImage; },
|
|
2558
|
+
get protectedPathError() { return protectedPathError; },
|
|
2559
|
+
get pruneReceipts() { return pruneReceipts; },
|
|
2560
|
+
get pushStatus() { return pushStatus; },
|
|
2561
|
+
get pushTracked() { return pushTracked; },
|
|
2562
|
+
get questionCancelledError() { return questionCancelledError; },
|
|
2563
|
+
get queueRowsOf() { return queueRowsOf; },
|
|
2564
|
+
get quietHoursConfigProblem() { return quietHoursConfigProblem; },
|
|
2565
|
+
get readIds() { return readIds; },
|
|
2566
|
+
get readJson() { return readJson; },
|
|
2567
|
+
get readSessionConfig() { return readSessionConfig; },
|
|
2568
|
+
get receiptKeyOf() { return receiptKeyOf; },
|
|
2569
|
+
get relay() { return relay; },
|
|
2570
|
+
set relay(v) { relay = v; },
|
|
2571
|
+
get relayPeerOf() { return relayPeerOf; },
|
|
2572
|
+
get remainingTitleBudgetMs() { return remainingTitleBudgetMs; },
|
|
2573
|
+
get removeCredential() { return removeCredential; },
|
|
2574
|
+
get resolveSessionTitles() { return resolveSessionTitles; },
|
|
2575
|
+
get resumeDormantAgent() { return resumeDormantAgent; },
|
|
2576
|
+
get returned() { return returned; },
|
|
2577
|
+
set returned(v) { returned = v; },
|
|
2578
|
+
get runtimeForm() { return runtimeForm; },
|
|
2579
|
+
get runtimeMetrics() { return runtimeMetrics; },
|
|
2580
|
+
get scheduleMessageBackfill() { return scheduleMessageBackfill; },
|
|
2581
|
+
get scheduleReadPersist() { return scheduleReadPersist; },
|
|
2582
|
+
get sendReceipts() { return sendReceipts; },
|
|
2583
|
+
get sessionTitleOf() { return sessionTitleOf; },
|
|
2584
|
+
get shortSessionId() { return shortSessionId; },
|
|
2585
|
+
get todosView() { return todosView; },
|
|
2586
|
+
get tokenInfo() { return tokenInfo; },
|
|
2587
|
+
get touchActivity() { return touchActivity; },
|
|
2588
|
+
get turnOutlineQueue() { return turnOutlineQueue; },
|
|
2589
|
+
get unarchiveCore() { return unarchiveCore; },
|
|
2590
|
+
get writeFdFully() { return writeFdFully; },
|
|
2591
|
+
};
|
|
2592
|
+
|
|
2474
2593
|
const handleApi = async (req, res, url, rest) => {
|
|
2475
2594
|
if (!hostAllowed(req)) {
|
|
2476
2595
|
error(res, 403, "host-not-allowed");
|
|
@@ -2529,3211 +2648,7 @@ export function apply(ctx, configInput) {
|
|
|
2529
2648
|
|
|
2530
2649
|
if ((method !== "GET" && method !== "HEAD") && rest !== "/presence" && rest !== "/assistant") noteUserActivity();
|
|
2531
2650
|
}
|
|
2532
|
-
|
|
2533
|
-
if (rest === "/bootstrap") {
|
|
2534
|
-
if (requireGet(method, res)) return;
|
|
2535
|
-
const agents = ctx.get("agents");
|
|
2536
|
-
const sessions = ctx.get("sessions");
|
|
2537
|
-
|
|
2538
|
-
const agentList = agents
|
|
2539
|
-
? agents.list().map((agent) => {
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
const sid = agentSessionId(agent);
|
|
2544
|
-
const s = sessions?.get(sid);
|
|
2545
|
-
return {
|
|
2546
|
-
id: agent.id,
|
|
2547
|
-
sessionId: sid,
|
|
2548
|
-
status: agent.status,
|
|
2549
|
-
hasPending: agent.inbox?.hasPending ?? false,
|
|
2550
|
-
title: sessionTitleOf(s) ?? shortSessionId(sid),
|
|
2551
|
-
};
|
|
2552
|
-
})
|
|
2553
|
-
: [];
|
|
2554
|
-
const sessionList = sessions
|
|
2555
|
-
? sessions.list().map((session) => ({ id: session.id, createdAt: session.header.createdAt, cwd: session.header.cwd, title: sessionTitleOf(session) ?? shortSessionId(session.id) }))
|
|
2556
|
-
: [];
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
const urls = lanBridgeListening
|
|
2560
|
-
? [...privateFirst(ipv4Addresses()).map((ip) => `http://${ip}:${lanPort}`), `http://127.0.0.1:${ctx.webServer.port}`]
|
|
2561
|
-
: [...privateFirst(ipv4Addresses()), "127.0.0.1"].map((ip) => `http://${ip}:${ctx.webServer.port}`);
|
|
2562
|
-
sendJson(res, 200, {
|
|
2563
|
-
ok: true,
|
|
2564
|
-
auth: { enabled: authEnabled },
|
|
2565
|
-
server: { port: ctx.webServer.port, urls, path: basePath },
|
|
2566
|
-
plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
|
|
2567
|
-
|
|
2568
|
-
...protocolInfo(phoneActions.features()),
|
|
2569
|
-
capabilities: {
|
|
2570
|
-
eventTimeline: EVENT_TIMELINE_CAPABILITIES,
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
turnOutline: turnOutlineCapabilityOf(ctx),
|
|
2574
|
-
|
|
2575
|
-
fileRange: FILE_RANGE_CAPABILITIES,
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
...(lanNoiseUrls().length > 0 ? { lanNoise: { version: 1, urls: lanNoiseUrls() } } : {}),
|
|
2579
|
-
|
|
2580
|
-
hold: {
|
|
2581
|
-
version: 1,
|
|
2582
|
-
onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? 120_000) || 0),
|
|
2583
|
-
offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0),
|
|
2584
|
-
},
|
|
2585
|
-
},
|
|
2586
|
-
agents: agentList,
|
|
2587
|
-
sessions: sessionList,
|
|
2588
|
-
});
|
|
2589
|
-
return;
|
|
2590
|
-
}
|
|
2591
|
-
|
|
2592
|
-
if (rest === "/phone-action-result" && await phoneActions.handle(req, res, method)) return;
|
|
2593
|
-
|
|
2594
|
-
if (rest === "/persona" || rest.startsWith("/persona/")) {
|
|
2595
|
-
if (await handlePersona(req, res, rest, method)) return;
|
|
2596
|
-
}
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
if (rest === "/presence") {
|
|
2604
|
-
if (requirePost(method, res)) return;
|
|
2605
|
-
const body = await readJson(req, res);
|
|
2606
|
-
if (body === undefined) return;
|
|
2607
|
-
if (body?.state === "background") {
|
|
2608
|
-
|
|
2609
|
-
presenceState = "background";
|
|
2610
|
-
sendJson(res, 200, { ok: true });
|
|
2611
|
-
return;
|
|
2612
|
-
}
|
|
2613
|
-
if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\" or \"background\"");
|
|
2614
|
-
const wasBackground = presenceState === "background";
|
|
2615
|
-
presenceState = "foreground";
|
|
2616
|
-
const t = Date.now();
|
|
2617
|
-
const idleMs = proactiveIdleMs();
|
|
2618
|
-
const awayMs = Number.isFinite(body.awayMs) && body.awayMs >= 0 ? body.awayMs : null;
|
|
2619
|
-
const wasAway = (awayMs === null || awayMs >= idleMs) && t - lastTypedAt >= idleMs;
|
|
2620
|
-
if (wasAway) {
|
|
2621
|
-
returned = { at: t, since: Math.max(lastTypedAt, awayMs === null ? 0 : t - awayMs, newsCursor) };
|
|
2622
|
-
if (config.proactive?.enabled) setImmediate(() => void proactive.tick());
|
|
2623
|
-
} else if (wasBackground && config.proactive?.enabled) {
|
|
2624
|
-
setImmediate(() => void proactive.tick());
|
|
2625
|
-
}
|
|
2626
|
-
noteUserActivity();
|
|
2627
|
-
sendJson(res, 200, { ok: true, returned: wasAway });
|
|
2628
|
-
return;
|
|
2629
|
-
}
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
if (rest === "/reminders" || rest.startsWith("/reminders/")) {
|
|
2633
|
-
if (await handleReminders(req, res, rest, method)) return;
|
|
2634
|
-
}
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
if (rest === "/memory" || rest.startsWith("/memory/")) {
|
|
2638
|
-
await handleMemory(req, res, url, rest, method);
|
|
2639
|
-
return;
|
|
2640
|
-
}
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
if (rest === "/assistant") {
|
|
2648
|
-
if (method === "GET") {
|
|
2649
|
-
sendJson(res, 200, { ok: true, ...assistantPrefs.get() });
|
|
2650
|
-
return;
|
|
2651
|
-
}
|
|
2652
|
-
if (method === "PATCH" || method === "POST") {
|
|
2653
|
-
let body;
|
|
2654
|
-
try {
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
body = JSON.parse(await readBody(req));
|
|
2658
|
-
} catch {
|
|
2659
|
-
return error(res, 400, "bad-request", "请求体不是合法 JSON");
|
|
2660
|
-
}
|
|
2661
|
-
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
2662
|
-
return error(res, 400, "bad-request", "请求体必须是对象");
|
|
2663
|
-
}
|
|
2664
|
-
try {
|
|
2665
|
-
const { changed, ...next } = assistantPrefs.set({
|
|
2666
|
-
mode: body.mode,
|
|
2667
|
-
persona: body.persona,
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
quietHours: body.quietHours,
|
|
2671
|
-
|
|
2672
|
-
breakReminder: body.breakReminder,
|
|
2673
|
-
|
|
2674
|
-
personaCard: body.personaCard,
|
|
2675
|
-
});
|
|
2676
|
-
if (changed) noteUserActivity();
|
|
2677
|
-
sendJson(res, 200, { ok: true, ...next });
|
|
2678
|
-
} catch (err) {
|
|
2679
|
-
|
|
2680
|
-
error(res, 400, "bad-request", err?.message ?? "invalid value");
|
|
2681
|
-
}
|
|
2682
|
-
return;
|
|
2683
|
-
}
|
|
2684
|
-
sendError(res, 405, "method-not-allowed");
|
|
2685
|
-
return;
|
|
2686
|
-
}
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
if (rest === "/backup") {
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
let passphrase;
|
|
2699
|
-
if (method === "POST") {
|
|
2700
|
-
const body = await readJson(req, res);
|
|
2701
|
-
if (body === undefined) return;
|
|
2702
|
-
passphrase = body?.passphrase;
|
|
2703
|
-
const problem = passphraseProblem(passphrase);
|
|
2704
|
-
if (problem) return error(res, 400, "weak-passphrase", problem);
|
|
2705
|
-
} else if (method !== "GET" && method !== "HEAD") {
|
|
2706
|
-
sendError(res, 405, "method-not-allowed");
|
|
2707
|
-
return;
|
|
2708
|
-
}
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
let store = null;
|
|
2713
|
-
try {
|
|
2714
|
-
store = getMemoryStore();
|
|
2715
|
-
} catch (err) {
|
|
2716
|
-
return error(
|
|
2717
|
-
res,
|
|
2718
|
-
503,
|
|
2719
|
-
"memory-unavailable",
|
|
2720
|
-
`记忆库打不开,无法生成完整备份:${err?.message ?? err}`,
|
|
2721
|
-
);
|
|
2722
|
-
}
|
|
2723
|
-
const backup = buildBackup({
|
|
2724
|
-
|
|
2725
|
-
store,
|
|
2726
|
-
prefs: assistantPrefs,
|
|
2727
|
-
});
|
|
2728
|
-
sendJson(res, 200, passphrase === undefined ? backup : await encryptBackup(backup, passphrase));
|
|
2729
|
-
return;
|
|
2730
|
-
}
|
|
2731
|
-
if (rest === "/backup/restore") {
|
|
2732
|
-
if (method !== "POST") {
|
|
2733
|
-
sendError(res, 405, "method-not-allowed");
|
|
2734
|
-
return;
|
|
2735
|
-
}
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
const tooLarge = () =>
|
|
2743
|
-
sendJson(
|
|
2744
|
-
res,
|
|
2745
|
-
413,
|
|
2746
|
-
{ error: "payload-too-large", detail: "备份文件超过 32 MiB 上限 / the backup is larger than the 32 MiB limit" },
|
|
2747
|
-
{ connection: "keep-alive" },
|
|
2748
|
-
);
|
|
2749
|
-
const declaredLength = Number(req.headers["content-length"]);
|
|
2750
|
-
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_BODY_BYTES) return tooLarge();
|
|
2751
|
-
let raw;
|
|
2752
|
-
try {
|
|
2753
|
-
raw = await readBody(req, MAX_RESTORE_BODY_BYTES);
|
|
2754
|
-
} catch (err) {
|
|
2755
|
-
if (err?.status === 413) return tooLarge();
|
|
2756
|
-
return error(res, 400, "bad-request", "请求体读取失败 / the request body could not be read");
|
|
2757
|
-
}
|
|
2758
|
-
let payload;
|
|
2759
|
-
try {
|
|
2760
|
-
payload = JSON.parse(raw);
|
|
2761
|
-
} catch {
|
|
2762
|
-
return error(res, 400, "bad-request", "请求体不是合法 JSON");
|
|
2763
|
-
}
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
let passphrase = req.headers["x-backup-passphrase"];
|
|
2767
|
-
if (payload && typeof payload === "object" && payload.format === undefined && payload.backup !== undefined) {
|
|
2768
|
-
passphrase = payload.passphrase ?? passphrase;
|
|
2769
|
-
payload = payload.backup;
|
|
2770
|
-
}
|
|
2771
|
-
if (isEncryptedBackup(payload)) {
|
|
2772
|
-
try {
|
|
2773
|
-
payload = await decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
|
|
2774
|
-
} catch (err) {
|
|
2775
|
-
return error(res, 400, err?.code ?? "bad-backup", err?.message ?? "备份解不开");
|
|
2776
|
-
}
|
|
2777
|
-
} else if (typeof passphrase === "string" && passphrase !== "") {
|
|
2778
|
-
|
|
2779
|
-
return error(res, 400, "not-encrypted", "这份备份没有设口令,和输入的口令对不上 / this backup is not protected by a passphrase; check that it is the right file");
|
|
2780
|
-
}
|
|
2781
|
-
const dryRun = url.searchParams.get("dryRun") === "1";
|
|
2782
|
-
|
|
2783
|
-
let store = null;
|
|
2784
|
-
try {
|
|
2785
|
-
store = getMemoryStore();
|
|
2786
|
-
} catch (err) {
|
|
2787
|
-
|
|
2788
|
-
return error(res, 503, "memory-unavailable", `记忆库打不开:${err?.message ?? err}`);
|
|
2789
|
-
}
|
|
2790
|
-
if (dryRun) {
|
|
2791
|
-
const plan = planRestore(payload, { store, prefs: assistantPrefs });
|
|
2792
|
-
if (!plan.ok) {
|
|
2793
|
-
return error(res, 400, "bad-backup", plan.error ?? "备份不合法");
|
|
2794
|
-
}
|
|
2795
|
-
|
|
2796
|
-
sendJson(res, 200, {
|
|
2797
|
-
ok: true,
|
|
2798
|
-
dryRun: true,
|
|
2799
|
-
backupVersion: plan.backupVersion,
|
|
2800
|
-
createdAt: plan.createdAt,
|
|
2801
|
-
counts: plan.counts,
|
|
2802
|
-
skipped: plan.skipped.slice(0, 50),
|
|
2803
|
-
assistant: plan.assistant,
|
|
2804
|
-
});
|
|
2805
|
-
return;
|
|
2806
|
-
}
|
|
2807
|
-
const result = applyRestore(payload, { store, prefs: assistantPrefs });
|
|
2808
|
-
if (!result.ok) {
|
|
2809
|
-
return error(res, 400, "bad-backup", result.error ?? "备份不合法");
|
|
2810
|
-
}
|
|
2811
|
-
sendJson(res, 200, { ok: true, ...result });
|
|
2812
|
-
return;
|
|
2813
|
-
}
|
|
2814
|
-
|
|
2815
|
-
if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/graph", "/git/commit", "/git/worktree", "/git/preview"]).has(rest)) {
|
|
2816
|
-
if (requireGet(method, res)) return;
|
|
2817
|
-
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
2818
|
-
if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
|
|
2819
|
-
try {
|
|
2820
|
-
let value;
|
|
2821
|
-
if (rest === "/git/capabilities") value = { git: await gitRead.capabilitiesForSession(sessionId) };
|
|
2822
|
-
else if (rest === "/git/repository") value = await gitRead.repositoryForSession(sessionId);
|
|
2823
|
-
else {
|
|
2824
|
-
const repositoryId = url.searchParams.get("repositoryId") ?? "";
|
|
2825
|
-
if (!repositoryId) return error(res, 400, "bad-request", "repositoryId is required");
|
|
2826
|
-
if (rest === "/git/branches") value = await gitRead.branches(sessionId, repositoryId);
|
|
2827
|
-
else if (rest === "/git/worktree") value = await gitRead.worktree(sessionId, repositoryId);
|
|
2828
|
-
else if (rest === "/git/preview") value = await gitRead.preview(sessionId, repositoryId, { kind: url.searchParams.get("kind"), snapshotId: url.searchParams.get("snapshotId"), path: url.searchParams.get("path"), oid: url.searchParams.get("oid") });
|
|
2829
|
-
else if (rest === "/git/graph") {
|
|
2830
|
-
let tips;
|
|
2831
|
-
const rawTips = url.searchParams.get("tips");
|
|
2832
|
-
if (rawTips !== null) {
|
|
2833
|
-
try { tips = JSON.parse(rawTips); } catch { return error(res, 400, "bad-request", "tips must be JSON"); }
|
|
2834
|
-
}
|
|
2835
|
-
value = await gitRead.graph(sessionId, repositoryId, { tips, snapshotId: url.searchParams.get("snapshotId") ?? undefined, cursor: url.searchParams.get("cursor") ?? undefined, limit: url.searchParams.get("limit") ?? undefined });
|
|
2836
|
-
} else if (rest === "/git/commit") value = await gitRead.commit(sessionId, repositoryId, url.searchParams.get("oid") ?? "", { filesCursor: url.searchParams.get("filesCursor") ?? undefined, filesLimit: url.searchParams.get("filesLimit") ?? undefined });
|
|
2837
|
-
else return error(res, 404, "not-found");
|
|
2838
|
-
}
|
|
2839
|
-
sendJson(res, 200, { ok: true, ...value });
|
|
2840
|
-
} catch (err) {
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
const known = new Set(["session-not-found", "workspace-not-allowed", "not-git-repository", "git-provider-unavailable", "repository-not-authorized", "graph-stale", "graph-tip-invalid", "graph-too-many-tips", "invalid-oid", "invalid-files-cursor", "git-command-failed", "git-output-too-large", "provider-incompatible", "preview-invalid", "preview-file-not-found"]);
|
|
2844
|
-
const code = known.has(err?.code) ? err.code : "git-provider-unavailable";
|
|
2845
|
-
const status = Number(err?.status);
|
|
2846
|
-
ctx.logger.warn?.(`mobile-remote: Git read failed (${code}): ${err?.message ?? err}`);
|
|
2847
|
-
return error(res, Number.isInteger(status) && status >= 400 && status <= 599 ? status : 503, code);
|
|
2848
|
-
}
|
|
2849
|
-
return;
|
|
2850
|
-
}
|
|
2851
|
-
|
|
2852
|
-
if (rest === "/qr-config") {
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
if (requireGet(method, res)) return;
|
|
2858
|
-
const gate = localDesktopGate(req);
|
|
2859
|
-
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
const qrUrls = lanBridgeListening
|
|
2863
|
-
? [...privateFirst(ipv4Addresses())].map((ip) => `http://${ip}:${lanPort}${basePath}`)
|
|
2864
|
-
: [...privateFirst(ipv4Addresses()), "127.0.0.1"].map((ip) => `http://${ip}:${ctx.webServer.port}${basePath}`);
|
|
2865
|
-
sendJson(res, 200, {
|
|
2866
|
-
ok: true,
|
|
2867
|
-
urls: qrUrls,
|
|
2868
|
-
token: config.authToken,
|
|
2869
|
-
path: basePath,
|
|
2870
|
-
});
|
|
2871
|
-
return;
|
|
2872
|
-
}
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
if (rest === "/relay/status") {
|
|
2876
|
-
if (requireGet(method, res)) return;
|
|
2877
|
-
const gate = localDesktopGate(req);
|
|
2878
|
-
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2879
|
-
sendJson(res, 200, {
|
|
2880
|
-
ok: true,
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
enabled: relay?.remote === true,
|
|
2884
|
-
lanNoise: lanNoiseUrls().length > 0,
|
|
2885
|
-
...(relay
|
|
2886
|
-
? {
|
|
2887
|
-
|
|
2888
|
-
standby: !relay.demand.active,
|
|
2889
|
-
roomId: relay.identity.roomId,
|
|
2890
|
-
publicKey: relayB64u.enc(relay.identity.x.pub),
|
|
2891
|
-
relays: relay.connector.status(),
|
|
2892
|
-
devices: relay.devices.list(),
|
|
2893
|
-
pendingPairings: relay.devices.pendingPairings(),
|
|
2894
|
-
}
|
|
2895
|
-
: {}),
|
|
2896
|
-
});
|
|
2897
|
-
return;
|
|
2898
|
-
}
|
|
2899
|
-
if (rest === "/relay/pairing") {
|
|
2900
|
-
if (requirePost(method, res)) return;
|
|
2901
|
-
const gate = localDesktopGate(req);
|
|
2902
|
-
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2903
|
-
const body = await readJson(req, res, 4096);
|
|
2904
|
-
if (body === undefined) return;
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
const lanOnly = body?.mode === "lan";
|
|
2909
|
-
if (lanOnly) {
|
|
2910
|
-
if (!relay || lanNoiseUrls().length === 0) return error(res, 409, "lan-noise-unavailable", "局域网加密通道不可用(LAN 桥没有在监听)/ the encrypted LAN path is not available (the LAN bridge is not listening)");
|
|
2911
|
-
} else if (!relay?.remote) {
|
|
2912
|
-
return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
|
|
2913
|
-
}
|
|
2914
|
-
|
|
2915
|
-
if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
|
|
2916
|
-
const { otp, expiresAt } = relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined, { relay: !lanOnly });
|
|
2917
|
-
relay.demand.sync();
|
|
2918
|
-
|
|
2919
|
-
const uri = buildPairingUri({ relays: lanOnly ? [] : relay.urls, roomId: relay.identity.roomId, pcPub: relay.identity.x.pub, otp, name: relay.name, lan: lanNoiseUrls() });
|
|
2920
|
-
const qr = await QRCode.toDataURL(uri, { width: 512, margin: 1, errorCorrectionLevel: "M" });
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
const fingerprint = pairingFingerprintOf(relay.identity.x.pub);
|
|
2925
|
-
|
|
2926
|
-
sendJson(res, 200, { ok: true, uri, qr, fingerprint, expiresAt }, { "cache-control": "no-store" });
|
|
2927
|
-
return;
|
|
2928
|
-
}
|
|
2929
|
-
if (rest === "/relay/revoke") {
|
|
2930
|
-
if (requirePost(method, res)) return;
|
|
2931
|
-
const gate = localDesktopGate(req);
|
|
2932
|
-
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2933
|
-
if (!relay) return error(res, 409, "relay-disabled", "未启用中继");
|
|
2934
|
-
const body = await readJson(req, res, 1024);
|
|
2935
|
-
if (body === undefined) return;
|
|
2936
|
-
if (typeof body?.id !== "string" || body.id === "") return error(res, 400, "bad-request", "缺少设备 id");
|
|
2937
|
-
if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
|
|
2938
|
-
if (!relay.devices.list().some((d) => d.id === body.id)) return sendJson(res, 200, { ok: true, revoked: false });
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
const result = { ok: true, revoked: false, relayKeyRotated: false, tokenRotated: false, repairRequired: 0 };
|
|
2951
|
-
relay.rotating = true;
|
|
2952
|
-
try {
|
|
2953
|
-
relay.devices.cancelPairings();
|
|
2954
|
-
result.revoked = relay.devices.revoke(body.id);
|
|
2955
|
-
for (const device of relay.devices.list()) {
|
|
2956
|
-
if (relay.devices.revoke(device.id)) result.repairRequired += 1;
|
|
2957
|
-
}
|
|
2958
|
-
relay.demand?.sync();
|
|
2959
|
-
const acknowledged = await relay.connector.settled();
|
|
2960
|
-
if (!acknowledged) ctx.logger.warn("mobile-remote: the relay did not confirm every disconnect in time; rotating anyway");
|
|
2961
|
-
relay.connector.stop();
|
|
2962
|
-
|
|
2963
|
-
const until = Date.now() + RETIRED_ROOM_MS;
|
|
2964
|
-
retireIdentity(join(mobileRemoteStateDir(), "relay"), relay.identity, until);
|
|
2965
|
-
openRetiredRoom({ identity: relay.identity, until });
|
|
2966
|
-
const next = rotateIdentity(join(mobileRemoteStateDir(), "relay"));
|
|
2967
|
-
relay.connector.identity = next;
|
|
2968
|
-
relay.identity = next;
|
|
2969
|
-
result.relayKeyRotated = true;
|
|
2970
|
-
if (relay.demand) relay.demand.sync();
|
|
2971
|
-
else relay.connector.start();
|
|
2972
|
-
} catch (err) {
|
|
2973
|
-
ctx.logger.warn(`mobile-remote: relay key rotation after revoke failed: ${err?.message ?? err}`);
|
|
2974
|
-
} finally {
|
|
2975
|
-
relay.rotating = false;
|
|
2976
|
-
}
|
|
2977
|
-
if (tokenInfo.auto) {
|
|
2978
|
-
try {
|
|
2979
|
-
config.authToken = rotateAuthToken().token;
|
|
2980
|
-
result.tokenRotated = true;
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
for (const conn of [...connections]) if (conn.dshVia === "token") dropConn(conn);
|
|
2985
|
-
} catch (err) {
|
|
2986
|
-
ctx.logger.warn(`mobile-remote: access token rotation after revoke failed: ${err?.message ?? err}`);
|
|
2987
|
-
}
|
|
2988
|
-
} else if (authEnabled) {
|
|
2989
|
-
result.tokenRotationSkipped = "configured";
|
|
2990
|
-
ctx.logger.warn(
|
|
2991
|
-
"mobile-remote: a device was revoked; change authToken in your config, it may still be on that phone / 已撤销设备:请在配置里更换 authToken,旧口令可能还在那台手机上",
|
|
2992
|
-
);
|
|
2993
|
-
}
|
|
2994
|
-
sendJson(res, 200, result);
|
|
2995
|
-
return;
|
|
2996
|
-
}
|
|
2997
|
-
|
|
2998
|
-
if (rest === "/send") {
|
|
2999
|
-
if (requirePost(method, res)) return;
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
const declaredLength = Number(req.headers["content-length"]);
|
|
3004
|
-
if (Number.isFinite(declaredLength) && declaredLength > 64 * 1024 * 1024) {
|
|
3005
|
-
return error(res, 413, "payload-too-large", "request body exceeds 64MB limit");
|
|
3006
|
-
}
|
|
3007
|
-
const body = await readJson(req, res, 64 * 1024 * 1024);
|
|
3008
|
-
if (body === undefined) return;
|
|
3009
|
-
const text = typeof body?.text === "string" ? body.text : "";
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
const images = Array.isArray(body?.images)
|
|
3015
|
-
? body.images.slice(0, 20)
|
|
3016
|
-
.filter((im) => im && typeof im?.data === "string" && im.data !== "" && typeof im?.mediaType === "string")
|
|
3017
|
-
.map((im) => {
|
|
3018
|
-
const real = sniffImageType(im.data);
|
|
3019
|
-
if (real && real !== im.mediaType) {
|
|
3020
|
-
ctx.logger.warn?.(`mobile-remote: /send 图片类型纠正 ${im.mediaType} → ${real}(声明与字节不符,按字节纠正)`);
|
|
3021
|
-
return { ...im, mediaType: real };
|
|
3022
|
-
}
|
|
3023
|
-
return im;
|
|
3024
|
-
})
|
|
3025
|
-
: [];
|
|
3026
|
-
if (text.trim() === "" && images.length === 0) return error(res, 400, "empty-text");
|
|
3027
|
-
|
|
3028
|
-
const requestId = typeof body?.requestId === "string" && body.requestId !== "" ? body.requestId : undefined;
|
|
3029
|
-
if (requestId !== undefined && !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) {
|
|
3030
|
-
return error(res, 400, "bad-request", "invalid requestId");
|
|
3031
|
-
}
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
const steer = body?.mode === "steer";
|
|
3038
|
-
const agents = ctx.get("agents");
|
|
3039
|
-
if (!agents) return error(res, 503, "agents-unavailable");
|
|
3040
|
-
const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
|
|
3041
|
-
let target = sessionId ? agents.get(sessionId) : firstRootAgent(agents);
|
|
3042
|
-
|
|
3043
|
-
let configDegraded = false;
|
|
3044
|
-
if (!target && sessionId) {
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
const resumed = await resumeDormantAgent(sessionId);
|
|
3048
|
-
if (resumed) {
|
|
3049
|
-
target = resumed.agent;
|
|
3050
|
-
configDegraded = configDegraded || resumed.configDegraded;
|
|
3051
|
-
}
|
|
3052
|
-
}
|
|
3053
|
-
if (!target) return error(res, sessionId ? 404 : 503, sessionId ? "session-not-found" : "no-live-agent");
|
|
3054
|
-
const receiptKey = requestId ? receiptKeyOf(sessionId, target.id, requestId) : null;
|
|
3055
|
-
if (receiptKey) {
|
|
3056
|
-
|
|
3057
|
-
if (pruneReceipts()) persistReceipts();
|
|
3058
|
-
let existing = sendReceipts.get(receiptKey);
|
|
3059
|
-
if (existing && receiptExpired(existing.at, Date.now(), RECEIPT_TTL)) {
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
sendReceipts.delete(receiptKey);
|
|
3063
|
-
persistReceipts();
|
|
3064
|
-
existing = undefined;
|
|
3065
|
-
}
|
|
3066
|
-
if (existing) {
|
|
3067
|
-
if (existing.status === "done" || existing.status === "error") {
|
|
3068
|
-
|
|
3069
|
-
return sendJson(res, 200, existing.result ?? { ok: true });
|
|
3070
|
-
}
|
|
3071
|
-
return error(res, 409, "receipt-pending", "同一请求正在处理中");
|
|
3072
|
-
}
|
|
3073
|
-
sendReceipts.set(receiptKey, { status: "in-progress", result: null, at: Date.now() });
|
|
3074
|
-
persistReceipts();
|
|
3075
|
-
}
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3079
|
-
const finalize = (res, status, resultBody) => {
|
|
3080
|
-
if (receiptKey) {
|
|
3081
|
-
sendReceipts.delete(receiptKey);
|
|
3082
|
-
sendReceipts.set(receiptKey, { status: status >= 400 ? "error" : "done", result: resultBody, at: Date.now() });
|
|
3083
|
-
pruneReceipts();
|
|
3084
|
-
persistReceipts();
|
|
3085
|
-
}
|
|
3086
|
-
if (DROP_RESPONSE_HOOK) {
|
|
3087
|
-
guardRes(res);
|
|
3088
|
-
res.destroy();
|
|
3089
|
-
return;
|
|
3090
|
-
}
|
|
3091
|
-
sendJson(res, status, configDegraded ? { ...resultBody, configDegraded: true } : resultBody);
|
|
3092
|
-
};
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
const content = text.trim() !== ""
|
|
3096
|
-
? [{ type: "text", text }, ...images.map((im) => ({ type: "image", mediaType: im.mediaType, data: im.data, ...(typeof im.name === "string" && im.name !== "" ? { name: im.name } : {}) }))]
|
|
3097
|
-
: images.map((im) => ({ type: "image", mediaType: im.mediaType, data: im.data, ...(typeof im.name === "string" && im.name !== "" ? { name: im.name } : {}) }));
|
|
3098
|
-
const hasImages = images.length > 0;
|
|
3099
|
-
|
|
3100
|
-
ctx.logger.info?.(`mobile-remote: /send hit → ${target.id} text=${text.length}B imgs=${images.length} steer=${steer} status=${target.status}`);
|
|
3101
|
-
const prompt = (mode) => promptImage(target.id, mode, content);
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
let message;
|
|
3106
|
-
try {
|
|
3107
|
-
message = createUserMessage({ content: [{ type: "text", text }], source: { kind: "user" } });
|
|
3108
|
-
} catch (err) {
|
|
3109
|
-
ctx.logger.warn(`mobile-remote: /send 消息体构造失败:${failureDetail(err)}`);
|
|
3110
|
-
finalize(res, 500, { error: "send-failed", detail: failureDetail(err) });
|
|
3111
|
-
return;
|
|
3112
|
-
}
|
|
3113
|
-
|
|
3114
|
-
try {
|
|
3115
|
-
if (steer && target.status !== "idle" && typeof target.steer === "function") {
|
|
3116
|
-
if (hasImages) {
|
|
3117
|
-
await prompt("steer");
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "steer", note: "image-prompt" });
|
|
3121
|
-
} else {
|
|
3122
|
-
target.steer(message);
|
|
3123
|
-
finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "steer" });
|
|
3124
|
-
}
|
|
3125
|
-
} else if (target.status === "running") {
|
|
3126
|
-
|
|
3127
|
-
const heldEntry = hasImages
|
|
3128
|
-
? { id: message.id, text, images, at: Date.now() }
|
|
3129
|
-
: { id: message.id, text, at: Date.now() };
|
|
3130
|
-
heldQueue.set(target.id, [...heldOf(target.id), heldEntry]);
|
|
3131
|
-
persistHeld();
|
|
3132
|
-
broadcastQueue(target.id);
|
|
3133
|
-
finalize(res, 200, {
|
|
3134
|
-
ok: true,
|
|
3135
|
-
|
|
3136
|
-
...(hasImages ? { accepted: true } : {}),
|
|
3137
|
-
agentId: target.id,
|
|
3138
|
-
messageId: message.id,
|
|
3139
|
-
mode: "queued",
|
|
3140
|
-
note: steer ? "steer-degraded-held" : "held-until-idle",
|
|
3141
|
-
});
|
|
3142
|
-
} else {
|
|
3143
|
-
if (steer && target.status === "idle") {
|
|
3144
|
-
|
|
3145
|
-
if (hasImages) {
|
|
3146
|
-
await prompt("queue");
|
|
3147
|
-
finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "followup", note: "image-prompt" });
|
|
3148
|
-
} else {
|
|
3149
|
-
target.followup(message);
|
|
3150
|
-
finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "followup", note: "agent-idle-followup" });
|
|
3151
|
-
}
|
|
3152
|
-
return;
|
|
3153
|
-
}
|
|
3154
|
-
if (hasImages) {
|
|
3155
|
-
await prompt("queue");
|
|
3156
|
-
finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "followup", note: "image-prompt" });
|
|
3157
|
-
} else {
|
|
3158
|
-
target.followup(message);
|
|
3159
|
-
finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "followup" });
|
|
3160
|
-
}
|
|
3161
|
-
}
|
|
3162
|
-
} catch (err) {
|
|
3163
|
-
ctx.logger.warn(`mobile-remote: send 失败:${err?.message ?? err}`);
|
|
3164
|
-
|
|
3165
|
-
const failure = { error: "send-failed", detail: failureDetail(err) };
|
|
3166
|
-
return finalize(res, 500, failure);
|
|
3167
|
-
}
|
|
3168
|
-
return;
|
|
3169
|
-
}
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
if (rest === "/send-receipt") {
|
|
3173
|
-
if (requireGet(method, res)) return;
|
|
3174
|
-
const sessionId = url.searchParams.get("sessionId") ?? undefined;
|
|
3175
|
-
const requestId = url.searchParams.get("requestId");
|
|
3176
|
-
if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
|
|
3177
|
-
const rootId = firstRootAgent(ctx.get("agents"))?.id;
|
|
3178
|
-
const key = receiptKeyOf(sessionId, rootId, requestId);
|
|
3179
|
-
|
|
3180
|
-
if (pruneReceipts()) persistReceipts();
|
|
3181
|
-
let entry = sendReceipts.get(key);
|
|
3182
|
-
if (entry && receiptExpired(entry.at, Date.now(), RECEIPT_TTL)) {
|
|
3183
|
-
|
|
3184
|
-
sendReceipts.delete(key);
|
|
3185
|
-
persistReceipts();
|
|
3186
|
-
entry = undefined;
|
|
3187
|
-
}
|
|
3188
|
-
if (!entry) return error(res, 404, "receipt-not-found", "该回执不存在或已过期");
|
|
3189
|
-
if (entry.status === "in-progress") return sendJson(res, 200, { ok: true, receipt: { status: "in-progress", result: null } });
|
|
3190
|
-
return sendJson(res, 200, { ok: true, receipt: { status: entry.status, result: entry.result ?? null } });
|
|
3191
|
-
}
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
if (rest === "/attachment") {
|
|
3195
|
-
if (requireGet(method, res)) return;
|
|
3196
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3197
|
-
const attachmentId = url.searchParams.get("attachmentId");
|
|
3198
|
-
if (!sessionId || !attachmentId) return error(res, 400, "bad-request", "sessionId/attachmentId required");
|
|
3199
|
-
try {
|
|
3200
|
-
const value = await apiRpc("session.attachment", { sessionId, attachmentId }, 30_000);
|
|
3201
|
-
const ref = value?.attachment;
|
|
3202
|
-
if (!ref || typeof value?.data !== "string" || value.data === "") return error(res, 404, "attachment-not-found");
|
|
3203
|
-
const buf = Buffer.from(value.data, "base64");
|
|
3204
|
-
guardRes(res);
|
|
3205
|
-
res.writeHead(200, {
|
|
3206
|
-
"content-type": typeof ref.mediaType === "string" ? ref.mediaType : "image/jpeg",
|
|
3207
|
-
"content-length": buf.length,
|
|
3208
|
-
"cache-control": "private, max-age=3600",
|
|
3209
|
-
|
|
3210
|
-
"connection": "close",
|
|
3211
|
-
"x-attachment-meta": JSON.stringify({
|
|
3212
|
-
width: Number.isFinite(ref.width) ? ref.width : 0,
|
|
3213
|
-
height: Number.isFinite(ref.height) ? ref.height : 0,
|
|
3214
|
-
bytes: Number.isFinite(ref.bytes) ? ref.bytes : buf.length,
|
|
3215
|
-
name: typeof ref.name === "string" ? ref.name : null,
|
|
3216
|
-
}),
|
|
3217
|
-
});
|
|
3218
|
-
res.end(buf);
|
|
3219
|
-
} catch (err) {
|
|
3220
|
-
return error(res, ...rpcError(err, "attachment-failed"));
|
|
3221
|
-
}
|
|
3222
|
-
return;
|
|
3223
|
-
}
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
if (rest === "/queue") {
|
|
3228
|
-
if (requireGet(method, res)) return;
|
|
3229
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3230
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
3231
|
-
const sessions = ctx.get("sessions");
|
|
3232
|
-
const agents = ctx.get("agents");
|
|
3233
|
-
const agent = agents ? agents.get(sessionId) : undefined;
|
|
3234
|
-
if (!agent && !sessions?.get(sessionId)) return error(res, 404, "session-not-found");
|
|
3235
|
-
|
|
3236
|
-
sendJson(res, 200, { ok: true, queue: queueRowsOf(sessionId) });
|
|
3237
|
-
return;
|
|
3238
|
-
}
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
if (rest === "/messages") {
|
|
3243
|
-
if (requirePost(method, res)) return;
|
|
3244
|
-
const body = await readJson(req, res);
|
|
3245
|
-
if (body === undefined) return;
|
|
3246
|
-
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
3247
|
-
const itemId = typeof body?.itemId === "string" ? body.itemId : "";
|
|
3248
|
-
const action = body?.action;
|
|
3249
|
-
if (!sessionId || !itemId) return error(res, 400, "bad-request", "sessionId/itemId required");
|
|
3250
|
-
if (!action || !["edit", "remove", "steer"].includes(action.kind)) {
|
|
3251
|
-
return error(res, 400, "bad-request", "action.kind must be edit | remove | steer");
|
|
3252
|
-
}
|
|
3253
|
-
if (action.kind === "edit") {
|
|
3254
|
-
|
|
3255
|
-
if (!Array.isArray(action.content) || action.content.length === 0) {
|
|
3256
|
-
return error(res, 400, "bad-request", "edit requires non-empty content");
|
|
3257
|
-
}
|
|
3258
|
-
if (!action.content.some((b) => b?.type === "text" && typeof b.text === "string")) {
|
|
3259
|
-
return error(res, 400, "bad-request", "edit requires at least one text block");
|
|
3260
|
-
}
|
|
3261
|
-
}
|
|
3262
|
-
|
|
3263
|
-
const held = [...heldOf(sessionId)];
|
|
3264
|
-
const heldIdx = held.findIndex((m) => m.id === itemId);
|
|
3265
|
-
if (heldIdx !== -1) {
|
|
3266
|
-
const agents = ctx.get("agents");
|
|
3267
|
-
const agent = agents?.get(sessionId);
|
|
3268
|
-
try {
|
|
3269
|
-
if (action.kind === "edit") {
|
|
3270
|
-
const newText = action.content.filter((b) => b?.type === "text").map((b) => b.text).join("");
|
|
3271
|
-
held[heldIdx] = { ...held[heldIdx], text: newText, at: Date.now() };
|
|
3272
|
-
} else if (action.kind === "remove") {
|
|
3273
|
-
held.splice(heldIdx, 1);
|
|
3274
|
-
} else {
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
if (!agent) {
|
|
3281
|
-
return error(res, 409, "steer-unavailable", "会话当前不在内存中,无法插队(消息仍在排队,稍后会自动释放)");
|
|
3282
|
-
}
|
|
3283
|
-
const item = held.splice(heldIdx, 1)[0];
|
|
3284
|
-
if (item.images?.length) {
|
|
3285
|
-
|
|
3286
|
-
const running = agent.status !== "idle" && typeof agent.steer === "function";
|
|
3287
|
-
await promptImage(sessionId, running ? "steer" : "queue", heldContentOf(item));
|
|
3288
|
-
} else {
|
|
3289
|
-
const message = createUserMessage({ content: [{ type: "text", text: item.text }], source: { kind: "user" } });
|
|
3290
|
-
if (agent.status !== "idle" && typeof agent.steer === "function") {
|
|
3291
|
-
agent.steer(message);
|
|
3292
|
-
} else {
|
|
3293
|
-
agent.followup(message);
|
|
3294
|
-
}
|
|
3295
|
-
}
|
|
3296
|
-
}
|
|
3297
|
-
heldQueue.set(sessionId, held);
|
|
3298
|
-
persistHeld();
|
|
3299
|
-
broadcastQueue(sessionId);
|
|
3300
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
3301
|
-
} catch (err) {
|
|
3302
|
-
return error(res, 500, "queue-hold-failed", failureDetail(err));
|
|
3303
|
-
}
|
|
3304
|
-
return;
|
|
3305
|
-
}
|
|
3306
|
-
try {
|
|
3307
|
-
const value = await apiRpc("session.updateQueue", { sessionId, itemId, action });
|
|
3308
|
-
sendJson(res, 200, { ok: true, ...(value ?? {}) });
|
|
3309
|
-
} catch (err) {
|
|
3310
|
-
ctx.logger.warn(`mobile-remote: updateQueue failed: ${err?.message ?? err}`);
|
|
3311
|
-
return error(res, ...rpcError(err, "update-queue-failed"));
|
|
3312
|
-
}
|
|
3313
|
-
return;
|
|
3314
|
-
}
|
|
3315
|
-
|
|
3316
|
-
if (rest === "/sessions" && method === "POST") {
|
|
3317
|
-
|
|
3318
|
-
const body = await readJson(req, res);
|
|
3319
|
-
if (body === undefined) return;
|
|
3320
|
-
const agents = ctx.get("agents");
|
|
3321
|
-
if (!agents) return error(res, 503, "agents-unavailable");
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
let cwd;
|
|
3325
|
-
try {
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
if (typeof body.cwd === "string" && body.cwd !== "") cwd = normalizeServerPath(body.cwd);
|
|
3329
|
-
if (!cwd) {
|
|
3330
|
-
const registry = ctx.get("workspaceRegistry");
|
|
3331
|
-
const workspaces = registry?.list?.();
|
|
3332
|
-
if (workspaces && workspaces.length > 0) cwd = workspaces[0].path;
|
|
3333
|
-
}
|
|
3334
|
-
if (!cwd) {
|
|
3335
|
-
for (const agent of agents.list()) {
|
|
3336
|
-
if (agent.session?.header?.cwd) { cwd = agent.session.header.cwd; break; }
|
|
3337
|
-
}
|
|
3338
|
-
}
|
|
3339
|
-
if (!cwd) cwd = process.cwd();
|
|
3340
|
-
} catch {
|
|
3341
|
-
cwd = process.cwd();
|
|
3342
|
-
}
|
|
3343
|
-
const agentPresets = ctx.get("agentPresets");
|
|
3344
|
-
let preset = typeof body.preset === "string" && body.preset !== "" ? body.preset : undefined;
|
|
3345
|
-
if (preset === undefined && agentPresets) preset = agentPresets.defaultId;
|
|
3346
|
-
if (preset === undefined) return error(res, 400, "invalid-preset", "no preset available");
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
let setup;
|
|
3353
|
-
if (agentPresets) {
|
|
3354
|
-
let composed;
|
|
3355
|
-
try {
|
|
3356
|
-
composed = await agentPresets.resolve(preset);
|
|
3357
|
-
} catch (err) {
|
|
3358
|
-
return error(res, 500, "preset-resolve-failed", err?.message ?? String(err));
|
|
3359
|
-
}
|
|
3360
|
-
if (typeof composed?.id === "string" && composed.id !== "") preset = composed.id;
|
|
3361
|
-
if (typeof agentPresets.mount === "function") {
|
|
3362
|
-
setup = async (agentCtx) => { await agentPresets.mount(agentCtx, composed.id); };
|
|
3363
|
-
} else {
|
|
3364
|
-
ctx.logger.warn("mobile-remote: agentPresets.mount 不可用(旧版 DSH),会话将以无预设组装方式创建");
|
|
3365
|
-
}
|
|
3366
|
-
}
|
|
3367
|
-
|
|
3368
|
-
const explicitModel = body.model !== undefined || body.provider !== undefined;
|
|
3369
|
-
if (explicitModel && (typeof body.provider !== "string" || !body.provider || typeof body.model !== "string" || !body.model)) {
|
|
3370
|
-
return error(res, 400, "bad-request", "provider and model required together");
|
|
3371
|
-
}
|
|
3372
|
-
if (body.reasoningEffort !== undefined && (typeof body.reasoningEffort !== "string" || !body.reasoningEffort)) {
|
|
3373
|
-
return error(res, 400, "bad-request", "invalid reasoningEffort");
|
|
3374
|
-
}
|
|
3375
|
-
let selected = explicitModel ? { provider: body.provider, model: body.model } : undefined;
|
|
3376
|
-
if (!selected) {
|
|
3377
|
-
try {
|
|
3378
|
-
selected = (await apiRpc("session.models", {}))?.default;
|
|
3379
|
-
} catch (err) {
|
|
3380
|
-
return error(res, ...rpcError(err, "model-catalog-unavailable"));
|
|
3381
|
-
}
|
|
3382
|
-
}
|
|
3383
|
-
if (!selected?.provider || !selected?.model) return error(res, 400, "no-model-available", "当前部署未配置默认模型,无法创建会话");
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
let sessionWorkspace = null;
|
|
3391
|
-
const workspaceRegistry = ctx.get("workspaceRegistry");
|
|
3392
|
-
if (workspaceRegistry && cwd) {
|
|
3393
|
-
let exact = null;
|
|
3394
|
-
try {
|
|
3395
|
-
exact = (await workspaceRegistry.resolveByPath?.(cwd)) ?? null;
|
|
3396
|
-
} catch {
|
|
3397
|
-
exact = null;
|
|
3398
|
-
}
|
|
3399
|
-
if (!exact && typeof workspaceRegistry.create === "function") {
|
|
3400
|
-
try {
|
|
3401
|
-
exact = await workspaceRegistry.create(cwd);
|
|
3402
|
-
} catch {
|
|
3403
|
-
return error(res, 400, "cwd-not-a-directory", `工作目录不可用:${cwd}`);
|
|
3404
|
-
}
|
|
3405
|
-
}
|
|
3406
|
-
if (exact?.path) {
|
|
3407
|
-
|
|
3408
|
-
sessionWorkspace = exact;
|
|
3409
|
-
cwd = exact.path;
|
|
3410
|
-
} else if (typeof workspaceRegistry.create !== "function") {
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
const sepChar = cwd.includes("\\") ? "\\" : "/";
|
|
3414
|
-
let p = cwd;
|
|
3415
|
-
while (p.includes(sepChar)) {
|
|
3416
|
-
p = p.slice(0, p.lastIndexOf(sepChar));
|
|
3417
|
-
if (!p || p.length <= 2) break;
|
|
3418
|
-
try {
|
|
3419
|
-
sessionWorkspace = (await workspaceRegistry.resolveByPath?.(p)) ?? null;
|
|
3420
|
-
if (sessionWorkspace) break;
|
|
3421
|
-
} catch {
|
|
3422
|
-
break;
|
|
3423
|
-
}
|
|
3424
|
-
}
|
|
3425
|
-
}
|
|
3426
|
-
}
|
|
3427
|
-
const sessionId = randomUUID();
|
|
3428
|
-
|
|
3429
|
-
if (typeof body.permissionPreset === "string" && body.permissionPreset === "danger-full-access" && body.confirmDanger !== true) {
|
|
3430
|
-
return error(res, 400, "risk-confirmation-required", "选择完全访问需显式确认风险");
|
|
3431
|
-
}
|
|
3432
|
-
try {
|
|
3433
|
-
const handle = await agents.create({
|
|
3434
|
-
sessionId,
|
|
3435
|
-
meta: { cwd, agentPreset: preset },
|
|
3436
|
-
agentOptions: { provider: selected.provider, model: selected.model },
|
|
3437
|
-
...(setup !== undefined ? { setup } : {}),
|
|
3438
|
-
});
|
|
3439
|
-
try {
|
|
3440
|
-
const effort = body.reasoningEffort ?? (explicitModel ? undefined : selected.reasoningEffort);
|
|
3441
|
-
await apiRpc("session.selectModel", {
|
|
3442
|
-
sessionId, provider: selected.provider, model: selected.model,
|
|
3443
|
-
...(effort === undefined ? {} : { reasoningEffort: effort }),
|
|
3444
|
-
});
|
|
3445
|
-
if (typeof body.permissionPreset === "string") applyPermissionPreset(handle.agent.session, body.permissionPreset);
|
|
3446
|
-
} catch (err) {
|
|
3447
|
-
try { await handle?.dispose?.(); } catch { }
|
|
3448
|
-
return error(res, ...rpcError(err, "session-configuration-failed"));
|
|
3449
|
-
}
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
if (sessionWorkspace) {
|
|
3454
|
-
try {
|
|
3455
|
-
await sessionWorkspace.attachSession(sessionId);
|
|
3456
|
-
} catch (err) {
|
|
3457
|
-
ctx.logger.warn?.(`mobile-remote: 会话 ${sessionId} 未能附着到工作区 ${sessionWorkspace.path}:${err?.message ?? err}`);
|
|
3458
|
-
}
|
|
3459
|
-
}
|
|
3460
|
-
sendJson(res, 200, { ok: true, sessionId, agentId: handle.agent.id, preset });
|
|
3461
|
-
} catch (err) {
|
|
3462
|
-
return error(res, 500, "session-create-failed", failureDetail(err));
|
|
3463
|
-
}
|
|
3464
|
-
return;
|
|
3465
|
-
}
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
if (rest === "/sessions/rotation") {
|
|
3473
|
-
if (requireGet(method, res)) return;
|
|
3474
|
-
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
3475
|
-
if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
|
|
3476
|
-
const sessions = ctx.get("sessions");
|
|
3477
|
-
if (!sessions) return error(res, 503, "sessions-unavailable");
|
|
3478
|
-
|
|
3479
|
-
const lastMessageAt = messageTimeMap.get(sessionId) ?? 0;
|
|
3480
|
-
const handle = sessions.get?.(sessionId) ?? null;
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
const busy = handle?.agent?.busy === true;
|
|
3484
|
-
|
|
3485
|
-
let events = handle?.events ?? [];
|
|
3486
|
-
let sessionTitle = "";
|
|
3487
|
-
try {
|
|
3488
|
-
const header = handle?.header ?? sessions.get?.(sessionId)?.header ?? null;
|
|
3489
|
-
sessionTitle = typeof header?.title === "string" ? header.title : "";
|
|
3490
|
-
} catch {
|
|
3491
|
-
|
|
3492
|
-
}
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
if (!Array.isArray(events) || events.length === 0) {
|
|
3496
|
-
const query = ctx.get("sessionQuery");
|
|
3497
|
-
if (query?.readSession) {
|
|
3498
|
-
try {
|
|
3499
|
-
const loaded = await loadDormantSession(query, sessionId);
|
|
3500
|
-
if (loaded.ok) events = loaded.snapshot.events ?? [];
|
|
3501
|
-
} catch {
|
|
3502
|
-
|
|
3503
|
-
}
|
|
3504
|
-
}
|
|
3505
|
-
}
|
|
3506
|
-
|
|
3507
|
-
sendJson(res, 200, {
|
|
3508
|
-
ok: true,
|
|
3509
|
-
sessionId,
|
|
3510
|
-
...buildRotation({ events, lastMessageAt, busy, sessionTitle }),
|
|
3511
|
-
});
|
|
3512
|
-
return;
|
|
3513
|
-
}
|
|
3514
|
-
|
|
3515
|
-
if (rest === "/sessions") {
|
|
3516
|
-
if (requireGet(method, res)) return;
|
|
3517
|
-
const sessions = ctx.get("sessions");
|
|
3518
|
-
if (!sessions) return error(res, 503, "sessions-unavailable");
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
const signal = requestAbort(res);
|
|
3523
|
-
|
|
3524
|
-
const budgetStartedAt = performance.now();
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
const query = ctx.get("sessionQuery");
|
|
3528
|
-
let records = null;
|
|
3529
|
-
if (query?.listSessions) {
|
|
3530
|
-
const enumeration = await enumerateSessionsShared(query, signal);
|
|
3531
|
-
if (!enumeration.ok) {
|
|
3532
|
-
|
|
3533
|
-
if (signal.aborted) return;
|
|
3534
|
-
if (enumeration.timedOut) return error(res, 504, "sessions-timeout");
|
|
3535
|
-
} else records = enumeration.records;
|
|
3536
|
-
}
|
|
3537
|
-
const list = [];
|
|
3538
|
-
const archived = coreArchivedIds();
|
|
3539
|
-
if (records) {
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
corpusIds.clear();
|
|
3544
|
-
for (const r of records) if (r?.header?.id) corpusIds.add(r.header.id);
|
|
3545
|
-
corpusObservedAt = Date.now();
|
|
3546
|
-
|
|
3547
|
-
const dormant = records.filter((r) => !sessions.get(r.header.id));
|
|
3548
|
-
const titleMap = await resolveSessionTitles(
|
|
3549
|
-
dormant.map((r) => r?.header?.id).filter((id) => typeof id === "string" && id !== ""),
|
|
3550
|
-
signal,
|
|
3551
|
-
remainingTitleBudgetMs(budgetStartedAt),
|
|
3552
|
-
);
|
|
3553
|
-
if (signal.aborted) return;
|
|
3554
|
-
for (const r of records) {
|
|
3555
|
-
const live = sessions.get(r.header.id);
|
|
3556
|
-
|
|
3557
|
-
const title = (live ? sessionTitleOf(live) : titleMap.get(r.header.id)) ?? shortSessionId(r.header.id);
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
const header = live?.header ?? r.header;
|
|
3562
|
-
list.push({
|
|
3563
|
-
id: r.header.id,
|
|
3564
|
-
createdAt: r.header.createdAt,
|
|
3565
|
-
cwd: r.header.cwd,
|
|
3566
|
-
live: r.live,
|
|
3567
|
-
title,
|
|
3568
|
-
archived: archived.has(r.header.id),
|
|
3569
|
-
lastActivity: activityMap.get(r.header.id) ?? null,
|
|
3570
|
-
lastMessageAt: messageTimeMap.get(r.header.id) ?? null,
|
|
3571
|
-
...(header?.origin === "subagent" ? { origin: "subagent" } : {}),
|
|
3572
|
-
...(typeof header?.parentSession === "string" && header.parentSession !== ""
|
|
3573
|
-
? { parentSession: header.parentSession }
|
|
3574
|
-
: {}),
|
|
3575
|
-
});
|
|
3576
|
-
}
|
|
3577
|
-
} else {
|
|
3578
|
-
for (const session of sessions.list()) {
|
|
3579
|
-
|
|
3580
|
-
const h = session?.header;
|
|
3581
|
-
list.push({
|
|
3582
|
-
id: session?.id ?? "",
|
|
3583
|
-
createdAt: h?.createdAt,
|
|
3584
|
-
cwd: h?.cwd,
|
|
3585
|
-
live: true,
|
|
3586
|
-
|
|
3587
|
-
title: sessionTitleOf(session) ?? shortSessionId(session?.id ?? ""),
|
|
3588
|
-
archived: archived.has(session?.id),
|
|
3589
|
-
lastActivity: activityMap.get(session?.id) ?? null,
|
|
3590
|
-
lastMessageAt: messageTimeMap.get(session?.id) ?? null,
|
|
3591
|
-
...(h?.origin === "subagent" ? { origin: "subagent" } : {}),
|
|
3592
|
-
...(typeof h?.parentSession === "string" && h.parentSession !== ""
|
|
3593
|
-
? { parentSession: h.parentSession }
|
|
3594
|
-
: {}),
|
|
3595
|
-
});
|
|
3596
|
-
}
|
|
3597
|
-
}
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
list.sort(compareSessionsForList);
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
if (signal.aborted) return;
|
|
3604
|
-
|
|
3605
|
-
scheduleMessageBackfill(list.filter((row) => row.lastMessageAt === null).map((row) => row.id));
|
|
3606
|
-
sendJson(res, 200, { ok: true, sessions: list });
|
|
3607
|
-
return;
|
|
3608
|
-
}
|
|
3609
|
-
|
|
3610
|
-
if (rest === "/sessions/touch") {
|
|
3611
|
-
|
|
3612
|
-
if (requirePost(method, res)) return;
|
|
3613
|
-
const body = await readJson(req, res);
|
|
3614
|
-
if (body === undefined) return;
|
|
3615
|
-
if (typeof body?.sessionId !== "string" || body.sessionId === "") return error(res, 400, "missing-sessionId");
|
|
3616
|
-
|
|
3617
|
-
touchActivity(body.sessionId);
|
|
3618
|
-
sendJson(res, 200, { ok: true, lastActivity: activityMap.get(body.sessionId) });
|
|
3619
|
-
return;
|
|
3620
|
-
}
|
|
3621
|
-
|
|
3622
|
-
if (rest === "/sessions/archive" || rest === "/sessions/unarchive") {
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
if (requirePost(method, res)) return;
|
|
3626
|
-
const archive = rest === "/sessions/archive";
|
|
3627
|
-
const body = await readJson(req, res);
|
|
3628
|
-
if (body === undefined) return;
|
|
3629
|
-
if (typeof body?.sessionId !== "string" || body.sessionId === "") return error(res, 400, "missing-sessionId");
|
|
3630
|
-
try {
|
|
3631
|
-
if (archive) {
|
|
3632
|
-
await apiRpc("workspace.archiveSession", { sessionId: body.sessionId });
|
|
3633
|
-
} else {
|
|
3634
|
-
await unarchiveCore(body.sessionId);
|
|
3635
|
-
}
|
|
3636
|
-
} catch (err) {
|
|
3637
|
-
return error(res, ...rpcError(err, "archive-failed"));
|
|
3638
|
-
}
|
|
3639
|
-
sendJson(res, 200, { ok: true, archived: archive });
|
|
3640
|
-
return;
|
|
3641
|
-
}
|
|
3642
|
-
|
|
3643
|
-
if (rest === "/sessions/fork") {
|
|
3644
|
-
|
|
3645
|
-
if (requirePost(method, res)) return;
|
|
3646
|
-
const body = await readJson(req, res);
|
|
3647
|
-
if (body === undefined) return;
|
|
3648
|
-
if (typeof body?.sessionId !== "string" || body.sessionId === "") return error(res, 400, "missing-sessionId");
|
|
3649
|
-
try {
|
|
3650
|
-
const child = await apiRpc("session.fork", {
|
|
3651
|
-
sessionId: body.sessionId,
|
|
3652
|
-
...(typeof body.atSeq === "number" && Number.isFinite(body.atSeq) ? { atSeq: body.atSeq } : {}),
|
|
3653
|
-
});
|
|
3654
|
-
sendJson(res, 200, { ok: true, sessionId: child.sessionId });
|
|
3655
|
-
} catch (err) {
|
|
3656
|
-
return error(res, ...rpcError(err, "fork-failed"));
|
|
3657
|
-
}
|
|
3658
|
-
return;
|
|
3659
|
-
}
|
|
3660
|
-
|
|
3661
|
-
if (rest === "/feedback") {
|
|
3662
|
-
|
|
3663
|
-
if (method === "GET" || method === "HEAD") {
|
|
3664
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3665
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
3666
|
-
const service = ctx.get("messageFeedback");
|
|
3667
|
-
if (!service?.list) return error(res, 503, "feedback-unavailable");
|
|
3668
|
-
try {
|
|
3669
|
-
const result = await service.list({ sessionId });
|
|
3670
|
-
if (!result?.ok) return error(res, 404, "session-not-found", result?.error?.message);
|
|
3671
|
-
sendJson(res, 200, { ok: true, items: result.value.items });
|
|
3672
|
-
} catch (err) {
|
|
3673
|
-
return error(res, 500, "feedback-failed", err?.message ?? "feedback failed");
|
|
3674
|
-
}
|
|
3675
|
-
return;
|
|
3676
|
-
}
|
|
3677
|
-
if (method === "POST") {
|
|
3678
|
-
const body = await readJson(req, res);
|
|
3679
|
-
if (body === undefined) return;
|
|
3680
|
-
if (typeof body?.sessionId !== "string" || body.sessionId === "") return error(res, 400, "missing-sessionId");
|
|
3681
|
-
if (typeof body?.messageId !== "string" || body.messageId === "") return error(res, 400, "missing-messageId");
|
|
3682
|
-
if (body?.rating !== "positive" && body?.rating !== "negative" && body?.rating !== "none") {
|
|
3683
|
-
return error(res, 400, "invalid-rating");
|
|
3684
|
-
}
|
|
3685
|
-
const service = ctx.get("messageFeedback");
|
|
3686
|
-
if (!service?.put) return error(res, 503, "feedback-unavailable");
|
|
3687
|
-
try {
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
let ifVersion = typeof body.ifVersion === "string" ? body.ifVersion : undefined;
|
|
3691
|
-
if (ifVersion === undefined && typeof service.list === "function") {
|
|
3692
|
-
try {
|
|
3693
|
-
const listed = await service.list({ sessionId: body.sessionId });
|
|
3694
|
-
if (listed?.ok) {
|
|
3695
|
-
const existing = (listed.value?.items ?? []).find((i) => i.messageId === body.messageId);
|
|
3696
|
-
ifVersion = existing?.version ?? null;
|
|
3697
|
-
}
|
|
3698
|
-
} catch {
|
|
3699
|
-
ifVersion = null;
|
|
3700
|
-
}
|
|
3701
|
-
}
|
|
3702
|
-
|
|
3703
|
-
if (body.rating === "none") {
|
|
3704
|
-
if (typeof service.delete !== "function") return error(res, 503, "feedback-unavailable");
|
|
3705
|
-
const del = await service.delete({
|
|
3706
|
-
sessionId: body.sessionId,
|
|
3707
|
-
messageId: body.messageId,
|
|
3708
|
-
ifVersion,
|
|
3709
|
-
});
|
|
3710
|
-
if (!del?.ok) {
|
|
3711
|
-
const code = del?.error?.code;
|
|
3712
|
-
|
|
3713
|
-
const status = code === "version-conflict" ? 409 : code === "session-not-found" ? 404 : 400;
|
|
3714
|
-
return error(res, status, code ?? "feedback-failed", del?.error?.message ?? "feedback remove failed");
|
|
3715
|
-
}
|
|
3716
|
-
|
|
3717
|
-
sendJson(res, 200, { ok: true, removed: del?.value?.absent !== true });
|
|
3718
|
-
return;
|
|
3719
|
-
}
|
|
3720
|
-
const result = await service.put({
|
|
3721
|
-
sessionId: body.sessionId,
|
|
3722
|
-
messageId: body.messageId,
|
|
3723
|
-
rating: body.rating,
|
|
3724
|
-
ifVersion,
|
|
3725
|
-
});
|
|
3726
|
-
if (!result?.ok) {
|
|
3727
|
-
const code = result?.error?.code;
|
|
3728
|
-
return error(res, code === "target-not-found" ? 404 : 409, code ?? "feedback-failed", result?.error?.message ?? "feedback failed");
|
|
3729
|
-
}
|
|
3730
|
-
sendJson(res, 200, { ok: true, item: result.value });
|
|
3731
|
-
} catch (err) {
|
|
3732
|
-
return error(res, 500, "feedback-failed", err?.message ?? "feedback failed");
|
|
3733
|
-
}
|
|
3734
|
-
return;
|
|
3735
|
-
}
|
|
3736
|
-
return error(res, 405, "method-not-allowed");
|
|
3737
|
-
}
|
|
3738
|
-
|
|
3739
|
-
if (rest === "/sessions/stop") {
|
|
3740
|
-
|
|
3741
|
-
if (requirePost(method, res)) return;
|
|
3742
|
-
const body = await readJson(req, res);
|
|
3743
|
-
if (body === undefined) return;
|
|
3744
|
-
if (typeof body?.sessionId !== "string" || body.sessionId === "") return error(res, 400, "missing-sessionId");
|
|
3745
|
-
try {
|
|
3746
|
-
await apiRpc("session.cancel", { sessionId: body.sessionId });
|
|
3747
|
-
} catch (err) {
|
|
3748
|
-
return error(res, ...rpcError(err, "cancel-failed"));
|
|
3749
|
-
}
|
|
3750
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
3751
|
-
return;
|
|
3752
|
-
}
|
|
3753
|
-
|
|
3754
|
-
if (rest === "/event-detail") {
|
|
3755
|
-
if (requireGet(method, res)) return;
|
|
3756
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3757
|
-
const seq = url.searchParams.get("seq");
|
|
3758
|
-
const seqNumber = Number(seq);
|
|
3759
|
-
if (!sessionId || seq === null || seq.trim() === "") return error(res, 400, "bad-request", "missing sessionId or seq");
|
|
3760
|
-
if (!Number.isSafeInteger(seqNumber) || seqNumber < 0 || Object.is(seqNumber, -0)) return error(res, 400, "bad-request", "seq must be a non-negative integer");
|
|
3761
|
-
const sessions = ctx.get("sessions");
|
|
3762
|
-
if (!sessions) return error(res, 503, "sessions-unavailable");
|
|
3763
|
-
let session = sessions.get(sessionId);
|
|
3764
|
-
const query = ctx.get("sessionQuery");
|
|
3765
|
-
let event = null;
|
|
3766
|
-
let degraded = false;
|
|
3767
|
-
|
|
3768
|
-
if (query?.readEvent) {
|
|
3769
|
-
try {
|
|
3770
|
-
const read = await query.readEvent({ sessionId, seq: seqNumber });
|
|
3771
|
-
const candidate = read?.target ?? read?.event ?? read?.value ?? read;
|
|
3772
|
-
const candidateSession = read?.session ?? read?.header;
|
|
3773
|
-
const candidateSessionId = candidate?.sessionId ?? read?.sessionId ?? candidateSession?.id ?? candidateSession?.sessionId;
|
|
3774
|
-
const candidateIdentityMatches = candidate?.sessionId === undefined || candidate.sessionId === sessionId;
|
|
3775
|
-
const sourceIdentityMatches = candidateSession === undefined || candidateSessionId === sessionId;
|
|
3776
|
-
if (candidate?.type) {
|
|
3777
|
-
if (Number(candidate.seq) === seqNumber && candidateIdentityMatches && sourceIdentityMatches && isTimelineRecord(candidate) && isDetailVisibleType(candidate.type)) event = candidate;
|
|
3778
|
-
else return error(res, 404, "event-not-found");
|
|
3779
|
-
}
|
|
3780
|
-
} catch (err) {
|
|
3781
|
-
|
|
3782
|
-
ctx.logger.warn(`mobile-remote: event-detail readEvent failed (${sessionId}/${seqNumber}): ${err?.message ?? err}`);
|
|
3783
|
-
const classified = classifyEventDetailReadError(err);
|
|
3784
|
-
const snapshotEvent = session ? eventBySeq(session, seqNumber) : null;
|
|
3785
|
-
if (snapshotEvent) {
|
|
3786
|
-
event = snapshotEvent;
|
|
3787
|
-
} else if (!session && classified.seeded && typeof query.readSurface === "function") {
|
|
3788
|
-
try {
|
|
3789
|
-
const surface = await query.readSurface(sessionId);
|
|
3790
|
-
session = { events: surface?.events ?? [] };
|
|
3791
|
-
degraded = true;
|
|
3792
|
-
} catch (surfaceErr) {
|
|
3793
|
-
ctx.logger.warn(`mobile-remote: event-detail readSurface failed (${sessionId}/${seqNumber}): ${surfaceErr?.message ?? surfaceErr}`);
|
|
3794
|
-
return error(res, 500, "event-read-failed", "事件详情读取失败");
|
|
3795
|
-
}
|
|
3796
|
-
} else {
|
|
3797
|
-
return error(res, classified.status ?? 500, classified.code ?? "event-read-failed", classified.detail ?? "事件详情读取失败");
|
|
3798
|
-
}
|
|
3799
|
-
}
|
|
3800
|
-
}
|
|
3801
|
-
if (!session && !event && query?.readSession) {
|
|
3802
|
-
try {
|
|
3803
|
-
const snapshot = await query.readSession(sessionId);
|
|
3804
|
-
session = { events: snapshot?.events ?? [] };
|
|
3805
|
-
} catch (err) {
|
|
3806
|
-
ctx.logger.warn(`mobile-remote: event-detail readSession failed (${sessionId}/${seqNumber}): ${err?.message ?? err}`);
|
|
3807
|
-
const classified = classifyEventDetailReadError(err);
|
|
3808
|
-
if (classified.seeded && typeof query.readSurface === "function") {
|
|
3809
|
-
try {
|
|
3810
|
-
const surface = await query.readSurface(sessionId);
|
|
3811
|
-
session = { events: surface?.events ?? [] };
|
|
3812
|
-
degraded = true;
|
|
3813
|
-
} catch (surfaceErr) {
|
|
3814
|
-
ctx.logger.warn(`mobile-remote: event-detail readSurface failed (${sessionId}/${seqNumber}): ${surfaceErr?.message ?? surfaceErr}`);
|
|
3815
|
-
return error(res, 500, "event-read-failed", "事件详情读取失败");
|
|
3816
|
-
}
|
|
3817
|
-
} else {
|
|
3818
|
-
return error(res, classified.status ?? 500, classified.code ?? "event-read-failed", classified.detail ?? "事件详情读取失败");
|
|
3819
|
-
}
|
|
3820
|
-
}
|
|
3821
|
-
}
|
|
3822
|
-
if (!session && !event) return error(res, 404, "session-not-found");
|
|
3823
|
-
event ??= eventBySeq(session, seqNumber);
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
if (event && (!isTimelineRecord(event) || !isDetailVisibleType(event.type))) event = null;
|
|
3827
|
-
if (!event) return error(res, 404, "event-not-found");
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
const detailEvent = detailEventFor(event);
|
|
3832
|
-
if (Buffer.byteLength(JSON.stringify(detailEvent), "utf8") > EVENT_DETAIL_MAX_BYTES) {
|
|
3833
|
-
return error(res, 413, "event-detail-too-large", "event detail exceeds 8 MiB");
|
|
3834
|
-
}
|
|
3835
|
-
sendJson(res, 200, {
|
|
3836
|
-
ok: true,
|
|
3837
|
-
sessionId,
|
|
3838
|
-
event: detailEvent,
|
|
3839
|
-
...(degraded ? { degraded: true, detailMode: "current-surface" } : {}),
|
|
3840
|
-
});
|
|
3841
|
-
return;
|
|
3842
|
-
}
|
|
3843
|
-
|
|
3844
|
-
if (rest === "/history") {
|
|
3845
|
-
if (requireGet(method, res)) return;
|
|
3846
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3847
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
3848
|
-
const sessions = ctx.get("sessions");
|
|
3849
|
-
if (!sessions) return error(res, 503, "sessions-unavailable");
|
|
3850
|
-
let session = sessions.get(sessionId);
|
|
3851
|
-
let degraded = false;
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
if (!session) {
|
|
3856
|
-
const query = ctx.get("sessionQuery");
|
|
3857
|
-
if (query?.readSession) {
|
|
3858
|
-
const loaded = await loadDormantSession(query, sessionId);
|
|
3859
|
-
if (loaded.notFound) return error(res, 404, "session-not-found");
|
|
3860
|
-
if (loaded.corrupt) {
|
|
3861
|
-
ctx.logger.warn?.(`mobile-remote: 休眠会话损坏(${sessionId}):${failureDetail(loaded.error)}`);
|
|
3862
|
-
return error(res, 500, "session-corrupt", "存储的会话存在但回放校验失败");
|
|
3863
|
-
}
|
|
3864
|
-
if (loaded.failed) {
|
|
3865
|
-
ctx.logger.warn?.(`mobile-remote: 休眠会话读取失败(${sessionId}):${failureDetail(loaded.error)}(${loaded.error?.code ?? "unknown"})`);
|
|
3866
|
-
return error(res, 500, "session-read-failed", "会话存在但历史读取失败");
|
|
3867
|
-
}
|
|
3868
|
-
if (loaded.ok) {
|
|
3869
|
-
session = { events: loaded.snapshot.events };
|
|
3870
|
-
degraded = loaded.degraded === true;
|
|
3871
|
-
}
|
|
3872
|
-
}
|
|
3873
|
-
}
|
|
3874
|
-
if (!session) return error(res, 404, "session-not-found");
|
|
3875
|
-
const afterParam = url.searchParams.get("after");
|
|
3876
|
-
const beforeParam = url.searchParams.get("before");
|
|
3877
|
-
const parseCursor = (raw, label) => {
|
|
3878
|
-
if (raw === null) return null;
|
|
3879
|
-
const value = Number(raw);
|
|
3880
|
-
if (raw.trim() === "" || !Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {
|
|
3881
|
-
throw Object.assign(new Error(`${label} must be a non-negative integer`), { status: 400, code: "bad-request" });
|
|
3882
|
-
}
|
|
3883
|
-
return value;
|
|
3884
|
-
};
|
|
3885
|
-
let after;
|
|
3886
|
-
let before;
|
|
3887
|
-
try {
|
|
3888
|
-
after = parseCursor(afterParam, "after");
|
|
3889
|
-
before = parseCursor(beforeParam, "before");
|
|
3890
|
-
} catch (e) {
|
|
3891
|
-
return error(res, e.status ?? 400, e.code ?? "bad-request", e.message);
|
|
3892
|
-
}
|
|
3893
|
-
const limitRaw = url.searchParams.get("limit");
|
|
3894
|
-
const limitValue = limitRaw === null ? 500 : Number(limitRaw);
|
|
3895
|
-
if (!Number.isSafeInteger(limitValue) || limitValue < 1) return error(res, 400, "bad-request", "limit must be a positive integer");
|
|
3896
|
-
const limit = Math.min(limitValue, 1000);
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
3905
|
-
const surface = eventsOf(session).filter(isTimelineRecord);
|
|
3906
|
-
let events;
|
|
3907
|
-
let hasMore = false;
|
|
3908
|
-
if (afterParam !== null) {
|
|
3909
|
-
|
|
3910
|
-
const candidates = surface.filter((event) => event.seq > after);
|
|
3911
|
-
hasMore = candidates.length > limit;
|
|
3912
|
-
events = candidates.slice(0, limit);
|
|
3913
|
-
} else if (beforeParam !== null) {
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
const candidates = surface.filter((event) => event.seq < before);
|
|
3918
|
-
hasMore = candidates.length > limit;
|
|
3919
|
-
events = candidates.slice(-limit);
|
|
3920
|
-
} else {
|
|
3921
|
-
|
|
3922
|
-
hasMore = surface.length > limit;
|
|
3923
|
-
events = surface.slice(-limit);
|
|
3924
|
-
}
|
|
3925
|
-
sendJson(res, 200, {
|
|
3926
|
-
ok: true,
|
|
3927
|
-
sessionId,
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
...(degraded ? { degraded: true, historyMode: "current-surface" } : {}),
|
|
3931
|
-
after: events.length ? events[events.length - 1].seq : 0,
|
|
3932
|
-
hasMore,
|
|
3933
|
-
events: events.map(summarizeEvent),
|
|
3934
|
-
});
|
|
3935
|
-
return;
|
|
3936
|
-
}
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
if (rest === "/turn-outline") {
|
|
3941
|
-
if (requireGet(method, res)) return;
|
|
3942
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
3943
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
const requestAbort = new AbortController();
|
|
3949
|
-
const onClientGone = () => {
|
|
3950
|
-
if (!requestAbort.signal.aborted) {
|
|
3951
|
-
requestAbort.abort(Object.assign(new Error("client disconnected"), { name: "AbortError" }));
|
|
3952
|
-
}
|
|
3953
|
-
};
|
|
3954
|
-
const onResClose = () => {
|
|
3955
|
-
if (res.writableEnded !== true) onClientGone();
|
|
3956
|
-
};
|
|
3957
|
-
res.on?.("close", onResClose);
|
|
3958
|
-
req.on?.("aborted", onClientGone);
|
|
3959
|
-
|
|
3960
|
-
const clientGone = () =>
|
|
3961
|
-
requestAbort.signal.aborted === true || req.aborted === true || res.destroyed === true;
|
|
3962
|
-
|
|
3963
|
-
const respondJson = (body) => {
|
|
3964
|
-
if (clientGone()) return;
|
|
3965
|
-
sendJson(res, 200, body);
|
|
3966
|
-
};
|
|
3967
|
-
const respondError = (status, code, detail) => {
|
|
3968
|
-
if (clientGone()) return;
|
|
3969
|
-
error(res, status, code, detail);
|
|
3970
|
-
};
|
|
3971
|
-
const query = ctx.get("sessionQuery");
|
|
3972
|
-
if (!query || typeof query.observeSession !== "function") {
|
|
3973
|
-
|
|
3974
|
-
return respondJson({ ok: true, sessionId, state: "capability-missing", turns: [] });
|
|
3975
|
-
}
|
|
3976
|
-
const envelope = { ok: true, sessionId, state: "capability-missing", turns: [] };
|
|
3977
|
-
let failure = null;
|
|
3978
|
-
try {
|
|
3979
|
-
const timeoutMs = config.turnOutlineTimeoutMs ?? TURN_OUTLINE_TIMEOUT_MS;
|
|
3980
|
-
const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), requestAbort.signal]);
|
|
3981
|
-
const disposeQuietly = (lease) => {
|
|
3982
|
-
try {
|
|
3983
|
-
lease?.[Symbol.dispose]?.();
|
|
3984
|
-
} catch {
|
|
3985
|
-
|
|
3986
|
-
}
|
|
3987
|
-
};
|
|
3988
|
-
|
|
3989
|
-
|
|
3990
|
-
const outcome = await raceWithDeadline(
|
|
3991
|
-
turnOutlineQueue.run(
|
|
3992
|
-
() => query.observeSession(sessionId, { projectionMode: "all", signal }),
|
|
3993
|
-
{ signal },
|
|
3994
|
-
),
|
|
3995
|
-
{ deadlineMs: timeoutMs, signal, onLate: disposeQuietly },
|
|
3996
|
-
);
|
|
3997
|
-
if (outcome.status === "timedOut") {
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
return respondJson({ ok: true, sessionId, state: "read-failed", code: "turn-outline-timeout", degraded: true, turns: [] });
|
|
4001
|
-
}
|
|
4002
|
-
if (outcome.status === "failed") {
|
|
4003
|
-
failure = outcome.error;
|
|
4004
|
-
} else {
|
|
4005
|
-
const lease = outcome.value;
|
|
4006
|
-
try {
|
|
4007
|
-
const mapped = turnOutlineStateOf(lease?.projections);
|
|
4008
|
-
Object.assign(envelope, mapped);
|
|
4009
|
-
} finally {
|
|
4010
|
-
disposeQuietly(lease);
|
|
4011
|
-
}
|
|
4012
|
-
}
|
|
4013
|
-
} catch (err) {
|
|
4014
|
-
failure = err;
|
|
4015
|
-
}
|
|
4016
|
-
if (failure !== null) {
|
|
4017
|
-
ctx.logger.warn?.(`mobile-remote: turn-outline 读取失败(${sessionId}):${redactPathText(failure?.message ?? failure)}`);
|
|
4018
|
-
if (failure?.code === "TURN_OUTLINE_BUSY") {
|
|
4019
|
-
|
|
4020
|
-
return respondJson({ ok: true, sessionId, state: "read-failed", code: "turn-outline-busy", degraded: true, turns: [] });
|
|
4021
|
-
}
|
|
4022
|
-
const classified = classifyTurnOutlineReadError(failure);
|
|
4023
|
-
if (classified.timeout === true) {
|
|
4024
|
-
|
|
4025
|
-
return respondJson({ ok: true, sessionId, state: "read-failed", code: "turn-outline-timeout", degraded: true, turns: [] });
|
|
4026
|
-
}
|
|
4027
|
-
if (classified.seeded) {
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
return respondJson({ ok: true, sessionId, state: "read-failed", code: "turn-outline-unavailable", degraded: true, turns: [] });
|
|
4032
|
-
}
|
|
4033
|
-
return respondError(classified.status ?? 500, classified.code ?? "turn-outline-read-failed", classified.detail ?? "轮次大纲读取失败");
|
|
4034
|
-
}
|
|
4035
|
-
respondJson(envelope);
|
|
4036
|
-
return;
|
|
4037
|
-
}
|
|
4038
|
-
|
|
4039
|
-
if (rest === "/events") {
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
if (method !== "GET") return error(res, 405, "method-not-allowed");
|
|
4043
|
-
connect(res, relayPeerOf(req) !== null ? "relay" : "token", req);
|
|
4044
|
-
return;
|
|
4045
|
-
}
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
if (rest === "/catalog") {
|
|
4049
|
-
if (requireGet(method, res)) return;
|
|
4050
|
-
|
|
4051
|
-
const now = Date.now();
|
|
4052
|
-
if (url.searchParams.get("refresh") !== "1" && catalogCache && now - catalogCache.at < 15000) {
|
|
4053
|
-
sendJson(res, 200, catalogCache.body);
|
|
4054
|
-
return;
|
|
4055
|
-
}
|
|
4056
|
-
const agents = ctx.get("agents");
|
|
4057
|
-
const first = firstAgent(agents);
|
|
4058
|
-
const models = [];
|
|
4059
|
-
|
|
4060
|
-
const reasoningEfforts = new Set();
|
|
4061
|
-
let deploymentDefault;
|
|
4062
|
-
const pushModels = async (provider, list) => {
|
|
4063
|
-
for (const model of list ?? []) {
|
|
4064
|
-
models.push({
|
|
4065
|
-
provider,
|
|
4066
|
-
id: model.id,
|
|
4067
|
-
name: model.name ?? model.id,
|
|
4068
|
-
...(model.description === void 0 ? {} : { description: model.description }),
|
|
4069
|
-
...(model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow }),
|
|
4070
|
-
...(model.reasoning === undefined ? {} : { reasoning: {
|
|
4071
|
-
efforts: (model.reasoning.efforts ?? []).map(({ id, name, description }) => ({ id, name, ...(description === undefined ? {} : { description }) })),
|
|
4072
|
-
...(model.reasoning.defaultEffort === undefined ? {} : { defaultEffort: model.reasoning.defaultEffort }),
|
|
4073
|
-
} }),
|
|
4074
|
-
|
|
4075
|
-
...(llmRef ? { imageSupported: await imageSupportedOf(provider, model.id) } : {}),
|
|
4076
|
-
});
|
|
4077
|
-
for (const effort of model.reasoning?.efforts ?? []) reasoningEfforts.add(effort.id);
|
|
4078
|
-
}
|
|
4079
|
-
};
|
|
4080
|
-
const llmRef = ctx.get("llm");
|
|
4081
|
-
|
|
4082
|
-
const imageSupportedCache = new Map();
|
|
4083
|
-
const imageSupportedOf = async (provider, modelId) => {
|
|
4084
|
-
const key = `${provider}/${modelId}`;
|
|
4085
|
-
if (imageSupportedCache.has(key)) return imageSupportedCache.get(key);
|
|
4086
|
-
let ok = false;
|
|
4087
|
-
try {
|
|
4088
|
-
const info = await llmRef.resolveModelInfo(provider, modelId);
|
|
4089
|
-
ok = Array.isArray(info?.inputModalities) && info.inputModalities.includes("image");
|
|
4090
|
-
} catch {
|
|
4091
|
-
ok = false;
|
|
4092
|
-
}
|
|
4093
|
-
imageSupportedCache.set(key, ok);
|
|
4094
|
-
return ok;
|
|
4095
|
-
};
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
const imageLimitsDefaults = {
|
|
4101
|
-
maxImageBytes: 20 * 1024 * 1024,
|
|
4102
|
-
maxImagesPerMessage: 20,
|
|
4103
|
-
maxMessageImageBytes: 200 * 1024 * 1024,
|
|
4104
|
-
maxImagePixels: 64e6,
|
|
4105
|
-
maxImageDimension: 8192,
|
|
4106
|
-
mediaTypes: ["image/png", "image/jpeg", "image/webp", "image/gif"],
|
|
4107
|
-
};
|
|
4108
|
-
let imageLimitsCache = { at: 0, value: null };
|
|
4109
|
-
const imageLimitsOf = async (sessionId) => {
|
|
4110
|
-
if (imageLimitsCache.value && Date.now() - imageLimitsCache.at < 5 * 60 * 1000) return imageLimitsCache.value;
|
|
4111
|
-
try {
|
|
4112
|
-
const value = await apiRpc("session.control", {}, 15000);
|
|
4113
|
-
const limits = projectionOf(value, sessionId)?.imageLimits ?? null;
|
|
4114
|
-
if (limits && typeof limits === "object") {
|
|
4115
|
-
imageLimitsCache = { at: Date.now(), value: { ...imageLimitsDefaults, ...limits } };
|
|
4116
|
-
return imageLimitsCache.value;
|
|
4117
|
-
}
|
|
4118
|
-
} catch {
|
|
4119
|
-
|
|
4120
|
-
}
|
|
4121
|
-
return imageLimitsDefaults;
|
|
4122
|
-
};
|
|
4123
|
-
let providers = [];
|
|
4124
|
-
try {
|
|
4125
|
-
const llm = ctx.get("llm");
|
|
4126
|
-
if (first) {
|
|
4127
|
-
const directory = await apiRpc("session.models", { sessionId: first.id });
|
|
4128
|
-
deploymentDefault = directory?.default;
|
|
4129
|
-
for (const group of directory?.groups ?? []) await pushModels(group.id, group.models);
|
|
4130
|
-
} else if (llm) {
|
|
4131
|
-
|
|
4132
|
-
try {
|
|
4133
|
-
const directory = await apiRpc("session.models", {});
|
|
4134
|
-
deploymentDefault = directory?.default;
|
|
4135
|
-
for (const group of directory?.groups ?? []) await pushModels(group.id, group.models);
|
|
4136
|
-
} catch {
|
|
4137
|
-
for (const p of await llm.listProviders()) {
|
|
4138
|
-
await pushModels(p.id, await llm.listModels(p.id));
|
|
4139
|
-
}
|
|
4140
|
-
}
|
|
4141
|
-
}
|
|
4142
|
-
if (llm) {
|
|
4143
|
-
|
|
4144
|
-
let registered = [];
|
|
4145
|
-
let configurable = [];
|
|
4146
|
-
try {
|
|
4147
|
-
registered = await llm.listProviders();
|
|
4148
|
-
configurable = await llm.listConfigurableProviders();
|
|
4149
|
-
} catch {
|
|
4150
|
-
|
|
4151
|
-
}
|
|
4152
|
-
const dormantIds = new Set(
|
|
4153
|
-
configurable.filter((c) => !registered.some((r) => r.id === c.provider)).map((c) => c.provider)
|
|
4154
|
-
);
|
|
4155
|
-
providers = [
|
|
4156
|
-
...registered.map((p) => ({ id: p.id, name: p.name, dormant: false })),
|
|
4157
|
-
...configurable
|
|
4158
|
-
.filter((c) => dormantIds.has(c.provider))
|
|
4159
|
-
.map((c) => ({ id: c.provider, name: c.displayName, dormant: true })),
|
|
4160
|
-
];
|
|
4161
|
-
}
|
|
4162
|
-
} catch {
|
|
4163
|
-
|
|
4164
|
-
}
|
|
4165
|
-
const permissionPresets = ctx.get("permissionPresets");
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
const presetSpecs = permissionPresets?.presets;
|
|
4169
|
-
const presetEntries = presetSpecs && typeof presetSpecs === "object"
|
|
4170
|
-
? Object.entries(presetSpecs).map(([id, spec]) => ({ id, name: spec?.name ?? id, description: spec?.description }))
|
|
4171
|
-
: [];
|
|
4172
|
-
const permissionList = [
|
|
4173
|
-
{ id: "read-only", name: "Read Only", description: "只读 · 拒绝一切写入操作" },
|
|
4174
|
-
...presetEntries.filter((entry) => entry.id !== "read-only"),
|
|
4175
|
-
];
|
|
4176
|
-
const agentPresets = [];
|
|
4177
|
-
try {
|
|
4178
|
-
const presets = ctx.get("agentPresets");
|
|
4179
|
-
if (presets) {
|
|
4180
|
-
for (const preset of await presets.list()) {
|
|
4181
|
-
agentPresets.push({ id: preset.id, name: preset.name ?? preset.id, description: preset.description ?? "" });
|
|
4182
|
-
}
|
|
4183
|
-
}
|
|
4184
|
-
} catch {
|
|
4185
|
-
|
|
4186
|
-
}
|
|
4187
|
-
const defaults = {
|
|
4188
|
-
provider: deploymentDefault?.provider,
|
|
4189
|
-
model: deploymentDefault?.model,
|
|
4190
|
-
reasoningEffort: deploymentDefault?.reasoningEffort,
|
|
4191
|
-
permissionPreset: permissionPresets?.defaultSettings?.()?.defaultPreset,
|
|
4192
|
-
agentPreset: ctx.get("agentPresets")?.defaultId,
|
|
4193
|
-
};
|
|
4194
|
-
|
|
4195
|
-
const imageLimits = first ? await imageLimitsOf(first.id) : imageLimitsDefaults;
|
|
4196
|
-
catalogCache = { at: now, body: {
|
|
4197
|
-
ok: true,
|
|
4198
|
-
models,
|
|
4199
|
-
providers,
|
|
4200
|
-
reasoningEfforts: [...reasoningEfforts],
|
|
4201
|
-
permissionPresets: permissionList,
|
|
4202
|
-
agentPresets,
|
|
4203
|
-
defaults,
|
|
4204
|
-
imageLimits,
|
|
4205
|
-
} };
|
|
4206
|
-
sendJson(res, 200, catalogCache.body);
|
|
4207
|
-
return;
|
|
4208
|
-
}
|
|
4209
|
-
|
|
4210
|
-
|
|
4211
|
-
if (rest === "/llm-providers") {
|
|
4212
|
-
const llm = ctx.get("llm");
|
|
4213
|
-
if (!llm) return error(res, 503, "llm-unavailable");
|
|
4214
|
-
const settings = ctx.get("settings");
|
|
4215
|
-
const credentials = ctx.get("credentials");
|
|
4216
|
-
if (method === "GET" || method === "HEAD") {
|
|
4217
|
-
let registered = [];
|
|
4218
|
-
let configurable = [];
|
|
4219
|
-
try {
|
|
4220
|
-
registered = await llm.listProviders();
|
|
4221
|
-
configurable = await llm.listConfigurableProviders();
|
|
4222
|
-
} catch {
|
|
4223
|
-
|
|
4224
|
-
}
|
|
4225
|
-
const rows = [];
|
|
4226
|
-
const seen = new Set();
|
|
4227
|
-
for (const p of registered) {
|
|
4228
|
-
rows.push({ id: p.id, name: p.name, dormant: false, settingsNs: null, settingsPath: [], baseURL: null, apiKeyRef: null, keyConfigured: false, keyWritable: false, catalogModels: null });
|
|
4229
|
-
seen.add(p.id);
|
|
4230
|
-
}
|
|
4231
|
-
for (const c of configurable) {
|
|
4232
|
-
const row = rows.find((r) => r.id === c.provider);
|
|
4233
|
-
const entry = row ?? { id: c.provider, name: c.displayName, dormant: true, settingsNs: c.settingsNs, settingsPath: c.settingsPath ?? [], baseURL: null, apiKeyRef: null, keyConfigured: false, keyWritable: false, catalogModels: null };
|
|
4234
|
-
entry.settingsNs = c.settingsNs;
|
|
4235
|
-
entry.settingsPath = c.settingsPath ?? [];
|
|
4236
|
-
if (settings && entry.settingsNs) {
|
|
4237
|
-
try {
|
|
4238
|
-
|
|
4239
|
-
|
|
4240
|
-
const section = readSettingsSection(settings, entry.settingsNs);
|
|
4241
|
-
let prof = section;
|
|
4242
|
-
for (const k of entry.settingsPath) prof = prof?.[k];
|
|
4243
|
-
if (prof && typeof prof === "object") {
|
|
4244
|
-
entry.baseURL = typeof prof.baseURL === "string" ? prof.baseURL : null;
|
|
4245
|
-
entry.apiKeyRef = typeof prof.apiKeyEnv === "string" && prof.apiKeyEnv !== "" ? prof.apiKeyEnv : null;
|
|
4246
|
-
entry.catalogModels = Array.isArray(prof.models)
|
|
4247
|
-
? prof.models.map((m) => ({ id: m.id, name: m.name ?? m.id }))
|
|
4248
|
-
: null;
|
|
4249
|
-
}
|
|
4250
|
-
} catch {
|
|
4251
|
-
|
|
4252
|
-
}
|
|
4253
|
-
}
|
|
4254
|
-
if (credentials && entry.apiKeyRef) {
|
|
4255
|
-
try {
|
|
4256
|
-
const info = await credentials.describe(credentialRef(entry.apiKeyRef));
|
|
4257
|
-
entry.keyConfigured = info?.configured ?? false;
|
|
4258
|
-
entry.keyWritable = info?.writable ?? false;
|
|
4259
|
-
} catch {
|
|
4260
|
-
|
|
4261
|
-
}
|
|
4262
|
-
}
|
|
4263
|
-
if (row) Object.assign(row, entry);
|
|
4264
|
-
else rows.push(entry);
|
|
4265
|
-
}
|
|
4266
|
-
sendJson(res, 200, { ok: true, providers: rows });
|
|
4267
|
-
return;
|
|
4268
|
-
}
|
|
4269
|
-
if (method === "POST") {
|
|
4270
|
-
const body = await readJson(req, res);
|
|
4271
|
-
if (body === undefined) return;
|
|
4272
|
-
const provider = typeof body.provider === "string" ? body.provider : "";
|
|
4273
|
-
const ns = typeof body.settingsNs === "string" ? body.settingsNs : "";
|
|
4274
|
-
const baseURL = typeof body.baseURL === "string" ? body.baseURL.trim() : "";
|
|
4275
|
-
const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
|
|
4276
|
-
|
|
4277
|
-
let configurable = [];
|
|
4278
|
-
try {
|
|
4279
|
-
configurable = await llm.listConfigurableProviders();
|
|
4280
|
-
} catch {
|
|
4281
|
-
|
|
4282
|
-
}
|
|
4283
|
-
const dir = configurable.find((c) => c.provider === provider && c.settingsNs === ns);
|
|
4284
|
-
if (!dir) return error(res, 400, "unknown-provider", "提供商不在可配置目录中");
|
|
4285
|
-
if (!settings) return error(res, 503, "settings-unavailable");
|
|
4286
|
-
if (baseURL === "") return error(res, 400, "baseURL-required");
|
|
4287
|
-
const path = dir.settingsPath ?? [];
|
|
4288
|
-
|
|
4289
|
-
let ref = null;
|
|
4290
|
-
let existingProfile = null;
|
|
4291
|
-
try {
|
|
4292
|
-
|
|
4293
|
-
const section = readSettingsSection(settings, ns);
|
|
4294
|
-
let prof = section;
|
|
4295
|
-
for (const k of path) prof = prof?.[k];
|
|
4296
|
-
if (prof && typeof prof === "object") {
|
|
4297
|
-
existingProfile = prof;
|
|
4298
|
-
if (typeof prof.apiKeyEnv === "string" && prof.apiKeyEnv !== "") ref = prof.apiKeyEnv;
|
|
4299
|
-
}
|
|
4300
|
-
} catch {}
|
|
4301
|
-
|
|
4302
|
-
const normalizeModels = (list) =>
|
|
4303
|
-
list
|
|
4304
|
-
.map((m) =>
|
|
4305
|
-
typeof m === "string"
|
|
4306
|
-
? { id: m }
|
|
4307
|
-
: { id: String(m?.id ?? ""), ...(typeof m?.name === "string" && m.name !== "" ? { name: m.name } : {}) }
|
|
4308
|
-
)
|
|
4309
|
-
.filter((m) => m.id !== "");
|
|
4310
|
-
const models = Array.isArray(body.models) && body.models.length > 0 ? normalizeModels(body.models) : null;
|
|
4311
|
-
let ops;
|
|
4312
|
-
let keyRemovalError = false;
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
try {
|
|
4316
|
-
if (path.length === 0) {
|
|
4317
|
-
|
|
4318
|
-
ops = [{ op: "set", path: ["baseURL"], value: baseURL }];
|
|
4319
|
-
if (models) ops.push({ op: "set", path: ["models"], value: models });
|
|
4320
|
-
if (apiKey !== "" || body.removeKey === true) {
|
|
4321
|
-
if (!credentials) return error(res, 503, "credentials-unavailable");
|
|
4322
|
-
ref = ref ?? deriveKeyRef(provider);
|
|
4323
|
-
ops.push({ op: "set", path: ["apiKeyEnv"], value: ref });
|
|
4324
|
-
if (apiKey !== "") await credentials.set(credentialRef(ref), apiKey);
|
|
4325
|
-
else keyRemovalError = await removeCredential(credentials, ref);
|
|
4326
|
-
}
|
|
4327
|
-
} else {
|
|
4328
|
-
|
|
4329
|
-
if (apiKey !== "" || body.removeKey === true) {
|
|
4330
|
-
if (!credentials) return error(res, 503, "credentials-unavailable");
|
|
4331
|
-
ref = ref ?? deriveKeyRef(provider);
|
|
4332
|
-
if (apiKey !== "") await credentials.set(credentialRef(ref), apiKey);
|
|
4333
|
-
else keyRemovalError = await removeCredential(credentials, ref);
|
|
4334
|
-
}
|
|
4335
|
-
const profile = {
|
|
4336
|
-
...(existingProfile && typeof existingProfile === "object" ? existingProfile : {}),
|
|
4337
|
-
...(typeof body.displayName === "string" && body.displayName !== "" ? { displayName: body.displayName } : {}),
|
|
4338
|
-
...(typeof body.api === "string" && body.api !== "" ? { api: body.api } : {}),
|
|
4339
|
-
baseURL,
|
|
4340
|
-
...(models ? { models } : {}),
|
|
4341
|
-
};
|
|
4342
|
-
if (apiKey !== "" || body.removeKey === true) {
|
|
4343
|
-
if (apiKey !== "") profile.apiKeyEnv = ref;
|
|
4344
|
-
else delete profile.apiKeyEnv;
|
|
4345
|
-
}
|
|
4346
|
-
ops = [{ op: "set", path, value: profile }];
|
|
4347
|
-
}
|
|
4348
|
-
await settings.mutate(ns, ops);
|
|
4349
|
-
} catch (err) {
|
|
4350
|
-
ctx.logger.warn(`mobile-remote: llm-providers 写入失败:${err?.message ?? err}`);
|
|
4351
|
-
return error(res, err?.status ?? 400, "provider-write-failed", failureDetail(err));
|
|
4352
|
-
}
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
sendJson(res, 200, { ok: true, provider, apiKeyRef: ref, keyConfigured: apiKey !== "", ...(keyRemovalError ? { keyRemovalError: true } : {}) });
|
|
4356
|
-
return;
|
|
4357
|
-
}
|
|
4358
|
-
return error(res, 405, "method-not-allowed");
|
|
4359
|
-
}
|
|
4360
|
-
|
|
4361
|
-
if (rest === "/llm-providers/probe") {
|
|
4362
|
-
if (requirePost(method, res)) return;
|
|
4363
|
-
const llm = ctx.get("llm");
|
|
4364
|
-
if (!llm) return error(res, 503, "llm-unavailable");
|
|
4365
|
-
const body = await readJson(req, res);
|
|
4366
|
-
if (body === undefined) return;
|
|
4367
|
-
const ns = typeof body.settingsNs === "string" ? body.settingsNs : "";
|
|
4368
|
-
const baseURL = typeof body.baseURL === "string" ? body.baseURL.trim() : "";
|
|
4369
|
-
const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
|
|
4370
|
-
if (ns === "" || baseURL === "") return error(res, 400, "bad-request", "settingsNs 与 baseURL 必填");
|
|
4371
|
-
|
|
4372
|
-
let configurable = [];
|
|
4373
|
-
try {
|
|
4374
|
-
configurable = await llm.listConfigurableProviders();
|
|
4375
|
-
} catch {
|
|
4376
|
-
|
|
4377
|
-
}
|
|
4378
|
-
if (!configurable.some((c) => c.settingsNs === ns)) return error(res, 400, "unknown-namespace");
|
|
4379
|
-
try {
|
|
4380
|
-
let discovered = null;
|
|
4381
|
-
let usedFallback = false;
|
|
4382
|
-
try {
|
|
4383
|
-
discovered = await llm.discoverModels(ns, {
|
|
4384
|
-
baseURL,
|
|
4385
|
-
...(typeof body.protocol === "string" && body.protocol !== "" ? { protocol: body.protocol } : {}),
|
|
4386
|
-
...(apiKey !== "" ? { credential: apiKey } : {}),
|
|
4387
|
-
});
|
|
4388
|
-
} catch (err) {
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
if (String(err?.message ?? err).includes("no model discovery")) {
|
|
4392
|
-
usedFallback = true;
|
|
4393
|
-
const headers = { accept: "application/json", ...(apiKey !== "" ? { authorization: `Bearer ${apiKey}` } : {}) };
|
|
4394
|
-
const resp = await fetch(`${baseURL.replace(/\/+$/, "")}/models`, { headers, signal: AbortSignal.timeout(10_000) });
|
|
4395
|
-
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
|
4396
|
-
const j = await resp.json();
|
|
4397
|
-
discovered = (Array.isArray(j?.data) ? j.data : []).map((m) => ({
|
|
4398
|
-
id: typeof m.id === "string" ? m.id : String(m.id ?? ""),
|
|
4399
|
-
...(typeof m.name === "string" ? { name: m.name } : {}),
|
|
4400
|
-
...(typeof m.contextWindow === "number" ? { contextWindow: m.contextWindow } : {}),
|
|
4401
|
-
}));
|
|
4402
|
-
} else {
|
|
4403
|
-
throw err;
|
|
4404
|
-
}
|
|
4405
|
-
}
|
|
4406
|
-
sendJson(res, 200, { ok: true, models: discovered ?? [], fallback: usedFallback });
|
|
4407
|
-
} catch (err) {
|
|
4408
|
-
const raw = String(err?.message ?? err);
|
|
4409
|
-
|
|
4410
|
-
const friendly =
|
|
4411
|
-
/(^|\s)(401|403)\b|answered 401|answered 403|HTTP 401|HTTP 403/.test(raw)
|
|
4412
|
-
? "API Key 无效或未填写:请在该条目填入有效的 API Key 后重试(探测不会携带已保存的密钥);DeepSeek 官方模型内置可用,无需探测"
|
|
4413
|
-
: /could not reach|fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|ERR_CONNECTION|ERR_SOCKET|ETIMEDOUT|timed out|timeout/i.test(raw)
|
|
4414
|
-
? "无法连接该端点:请检查网络与 baseURL(需以 http:// 或 https:// 开头并含主机名,如 https://api.deepseek.com)"
|
|
4415
|
-
: /404|not found/i.test(raw)
|
|
4416
|
-
? "该端点没有 /models 接口(HTTP 404):请确认 baseURL 为该服务的 API 根地址,或改用手动输入模型"
|
|
4417
|
-
: null;
|
|
4418
|
-
|
|
4419
|
-
return error(res, 400, "probe-failed", redactPathText(friendly ? `${friendly}(原始错误:${raw})` : raw));
|
|
4420
|
-
}
|
|
4421
|
-
return;
|
|
4422
|
-
}
|
|
4423
|
-
|
|
4424
|
-
if (rest === "/session-config") {
|
|
4425
|
-
let sessionId = url.searchParams.get("sessionId");
|
|
4426
|
-
let body;
|
|
4427
|
-
if (method === "POST") {
|
|
4428
|
-
body = await readJson(req, res);
|
|
4429
|
-
if (body === undefined) return;
|
|
4430
|
-
if (typeof body?.sessionId === "string") sessionId = body.sessionId;
|
|
4431
|
-
}
|
|
4432
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
4433
|
-
if (method === "GET" || method === "HEAD") {
|
|
4434
|
-
const config = await readSessionConfig(sessionId);
|
|
4435
|
-
sendJson(res, 200, { ok: true, sessionId, config });
|
|
4436
|
-
return;
|
|
4437
|
-
}
|
|
4438
|
-
if (method === "POST") {
|
|
4439
|
-
const sessions = ctx.get("sessions");
|
|
4440
|
-
const session = sessions?.get(sessionId);
|
|
4441
|
-
const modelConfigPatch = body.model !== undefined || body.provider !== undefined || body.reasoningEffort !== undefined || body.resetReasoningEffort !== undefined;
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
if (!session && (!modelConfigPatch || body.permissionPreset !== undefined)) return error(res, 404, "session-not-found");
|
|
4445
|
-
if (modelConfigPatch) {
|
|
4446
|
-
if (body.resetReasoningEffort !== undefined && body.resetReasoningEffort !== true) return error(res, 400, "bad-request", "invalid resetReasoningEffort");
|
|
4447
|
-
if (body.resetReasoningEffort === true && body.reasoningEffort !== undefined) return error(res, 400, "bad-request", "choose effort or reset, not both");
|
|
4448
|
-
const explicitModel = body.model !== undefined || body.provider !== undefined;
|
|
4449
|
-
if (explicitModel && (typeof body.provider !== "string" || !body.provider || typeof body.model !== "string" || !body.model)) {
|
|
4450
|
-
return error(res, 400, "bad-request", "provider and model required together");
|
|
4451
|
-
}
|
|
4452
|
-
if (body.reasoningEffort !== undefined && (typeof body.reasoningEffort !== "string" || !body.reasoningEffort)) {
|
|
4453
|
-
return error(res, 400, "bad-request", "invalid reasoningEffort");
|
|
4454
|
-
}
|
|
4455
|
-
|
|
4456
|
-
const current = explicitModel ? undefined : await readSessionConfig(sessionId);
|
|
4457
|
-
const provider = explicitModel ? body.provider : current?.provider;
|
|
4458
|
-
const model = explicitModel ? body.model : current?.model;
|
|
4459
|
-
if (!provider || !model) return error(res, 409, "model-selection-unavailable", "无法确认待生效模型,请重新选择模型");
|
|
4460
|
-
try {
|
|
4461
|
-
await apiRpc("session.selectModel", {
|
|
4462
|
-
sessionId, provider, model,
|
|
4463
|
-
|
|
4464
|
-
...(body.reasoningEffort === undefined ? {} : { reasoningEffort: body.reasoningEffort }),
|
|
4465
|
-
});
|
|
4466
|
-
} catch (err) {
|
|
4467
|
-
return error(res, ...rpcError(err, "model-select-failed"));
|
|
4468
|
-
}
|
|
4469
|
-
}
|
|
4470
|
-
if (body.permissionPreset !== undefined) {
|
|
4471
|
-
if (body.permissionPreset === "danger-full-access" && body.confirmDanger !== true) {
|
|
4472
|
-
return error(res, 400, "risk-confirmation-required", "选择完全访问需显式确认风险");
|
|
4473
|
-
}
|
|
4474
|
-
try {
|
|
4475
|
-
applyPermissionPreset(session, body.permissionPreset);
|
|
4476
|
-
} catch (err) {
|
|
4477
|
-
return error(res, err.status ?? 400, "permission-apply-failed", err.message);
|
|
4478
|
-
}
|
|
4479
|
-
}
|
|
4480
|
-
const config = await readSessionConfig(sessionId);
|
|
4481
|
-
sendJson(res, 200, { ok: true, sessionId, config });
|
|
4482
|
-
return;
|
|
4483
|
-
}
|
|
4484
|
-
return error(res, 405, "method-not-allowed");
|
|
4485
|
-
}
|
|
4486
|
-
|
|
4487
|
-
if (rest === "/notifications") {
|
|
4488
|
-
if (requireGet(method, res)) return;
|
|
4489
|
-
const items = [...notifStore.values()]
|
|
4490
|
-
.sort((a, b) => b.time - a.time)
|
|
4491
|
-
.map((n) => ({ ...n, unread: !readIds.has(n.id) }));
|
|
4492
|
-
sendJson(res, 200, { ok: true, unread: items.filter((n) => n.unread).length, items: items.slice(0, NOTIF_MAX) });
|
|
4493
|
-
return;
|
|
4494
|
-
}
|
|
4495
|
-
|
|
4496
|
-
if (rest === "/notifications/read") {
|
|
4497
|
-
if (requirePost(method, res)) return;
|
|
4498
|
-
const body = await readJson(req, res);
|
|
4499
|
-
if (body === undefined) return;
|
|
4500
|
-
if (body?.all === true) {
|
|
4501
|
-
for (const id of notifStore.keys()) readIds.add(id);
|
|
4502
|
-
} else if (Array.isArray(body?.ids)) {
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
for (const id of body.ids.slice(0, 500)) {
|
|
4506
|
-
const s = String(id);
|
|
4507
|
-
if (notifStore.has(s)) readIds.add(s);
|
|
4508
|
-
}
|
|
4509
|
-
} else {
|
|
4510
|
-
return error(res, 400, "bad-request", "expected { ids } or { all: true }");
|
|
4511
|
-
}
|
|
4512
|
-
scheduleReadPersist();
|
|
4513
|
-
sendJson(res, 200, { ok: true });
|
|
4514
|
-
return;
|
|
4515
|
-
}
|
|
4516
|
-
|
|
4517
|
-
if (rest === "/notifications/delete") {
|
|
4518
|
-
if (requirePost(method, res)) return;
|
|
4519
|
-
const body = await readJson(req, res);
|
|
4520
|
-
if (body === undefined) return;
|
|
4521
|
-
|
|
4522
|
-
|
|
4523
|
-
if (body?.all === true) {
|
|
4524
|
-
for (const id of notifStore.keys()) readIds.delete(id);
|
|
4525
|
-
notifStore.clear();
|
|
4526
|
-
} else if (Array.isArray(body?.ids)) {
|
|
4527
|
-
|
|
4528
|
-
for (const id of body.ids.slice(0, 500)) {
|
|
4529
|
-
notifStore.delete(String(id));
|
|
4530
|
-
readIds.delete(String(id));
|
|
4531
|
-
}
|
|
4532
|
-
} else {
|
|
4533
|
-
return error(res, 400, "bad-request", "expected { ids } or { all: true }");
|
|
4534
|
-
}
|
|
4535
|
-
scheduleReadPersist();
|
|
4536
|
-
broadcast({ type: "notifications/changed" });
|
|
4537
|
-
sendJson(res, 200, { ok: true });
|
|
4538
|
-
return;
|
|
4539
|
-
}
|
|
4540
|
-
|
|
4541
|
-
if (rest === "/push-test") {
|
|
4542
|
-
|
|
4543
|
-
|
|
4544
|
-
if (requirePost(method, res)) return;
|
|
4545
|
-
const results = [];
|
|
4546
|
-
for (const target of config.pushUrls) {
|
|
4547
|
-
const outcome = await pushTracked(target, "test", "🔔 测试通知", "配置验证", "收到即说明该通道配置正确(来自 DSH Remote)", "");
|
|
4548
|
-
results.push({ name: target.name, format: target.format, ok: outcome.ok, ...(outcome.ok ? {} : { error: outcome.error }) });
|
|
4549
|
-
}
|
|
4550
|
-
sendJson(res, 200, { ok: true, channels: results.length, results });
|
|
4551
|
-
return;
|
|
4552
|
-
}
|
|
4553
|
-
|
|
4554
|
-
if (rest === "/respond") {
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
if (requirePost(method, res)) return;
|
|
4570
|
-
const body = await readJson(req, res);
|
|
4571
|
-
if (body === undefined) return;
|
|
4572
|
-
const rpcId = typeof body?.rpcId === "string" ? body.rpcId : "";
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
const claimedSessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
4577
|
-
const sessionOwns = (entry) => {
|
|
4578
|
-
if (claimedSessionId === "") {
|
|
4579
|
-
ctx.logger.warn?.(`mobile-remote: /respond 缺少 sessionId(宽容接受,请升级 App):kind=${body?.kind} rpcId=${rpcId}`);
|
|
4580
|
-
return true;
|
|
4581
|
-
}
|
|
4582
|
-
return claimedSessionId === entry.sessionId;
|
|
4583
|
-
};
|
|
4584
|
-
if (body?.kind === "question") {
|
|
4585
|
-
const qPhoneId = typeof body?.questionId === "string" ? body.questionId : "";
|
|
4586
|
-
const qById = qPhoneId === "" ? undefined : pendingQuestions.get(qPhoneId);
|
|
4587
|
-
const qByRpc = rpcId === "" ? undefined : [...pendingQuestions.values()].find((e) => e.rpcId === rpcId);
|
|
4588
|
-
|
|
4589
|
-
if (qById && qByRpc && qById !== qByRpc) return error(res, 400, "interaction-mismatch", "questionId 与 rpcId 指向不同问询");
|
|
4590
|
-
const qEntry = qById ?? qByRpc;
|
|
4591
|
-
if (qEntry) {
|
|
4592
|
-
if (!sessionOwns(qEntry)) return error(res, 400, "session-mismatch", "问询不属于该会话");
|
|
4593
|
-
if (!Array.isArray(body?.answers)) return error(res, 400, "bad-request", "question respond expects answers[]");
|
|
4594
|
-
if (!Array.isArray(qEntry.questions) || qEntry.questions.length === 0) {
|
|
4595
|
-
|
|
4596
|
-
|
|
4597
|
-
ctx.logger.warn?.(`mobile-remote: /respond 待办条目缺少 questions(${qEntry.phoneId}),answer 无法校验`);
|
|
4598
|
-
}
|
|
4599
|
-
const validation = validateQuestionAnswers(qEntry.questions, body.answers);
|
|
4600
|
-
if (!validation.ok) return error(res, 400, validation.code, validation.detail);
|
|
4601
|
-
finishQuestion(qEntry, { answers: body.answers });
|
|
4602
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
4603
|
-
return;
|
|
4604
|
-
}
|
|
4605
|
-
if (!Array.isArray(body?.answers)) return error(res, 400, "bad-request", "question respond expects answers[]");
|
|
4606
|
-
} else if (body?.kind === "approval") {
|
|
4607
|
-
const outcome = typeof body?.outcome === "string" ? body.outcome : "";
|
|
4608
|
-
const aPhoneId = typeof body?.approvalId === "string" ? body.approvalId : "";
|
|
4609
|
-
const aById = aPhoneId === "" ? undefined : pendingApprovals.get(aPhoneId);
|
|
4610
|
-
const aByRpc = rpcId === "" ? undefined : [...pendingApprovals.values()].find((e) => e.rpcId === rpcId);
|
|
4611
|
-
if (aById && aByRpc && aById !== aByRpc) return error(res, 400, "interaction-mismatch", "approvalId 与 rpcId 指向不同审批");
|
|
4612
|
-
const aEntry = aById ?? aByRpc;
|
|
4613
|
-
if (aEntry) {
|
|
4614
|
-
if (!sessionOwns(aEntry)) return error(res, 400, "session-mismatch", "审批不属于该会话");
|
|
4615
|
-
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
if (outcome !== "allowed-once" && outcome !== "rejected") {
|
|
4619
|
-
return error(res, 400, "approval-outcome-invalid", "outcome 必须是 allowed-once | rejected");
|
|
4620
|
-
}
|
|
4621
|
-
finishApproval(aEntry, outcome);
|
|
4622
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
4623
|
-
return;
|
|
4624
|
-
}
|
|
4625
|
-
} else if (body?.kind === "cancel") {
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
const cancelEntry = [...pendingApprovals.values()].find((e) => e.rpcId === rpcId)
|
|
4630
|
-
?? [...pendingQuestions.values()].find((e) => e.rpcId === rpcId);
|
|
4631
|
-
if (cancelEntry) {
|
|
4632
|
-
if (!sessionOwns(cancelEntry)) return error(res, 400, "session-mismatch", "待办不属于该会话");
|
|
4633
|
-
if (pendingApprovals.has(cancelEntry.phoneId)) finishApproval(cancelEntry, "cancelled");
|
|
4634
|
-
else finishQuestion(cancelEntry, questionCancelledError(), { reject: true });
|
|
4635
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
4636
|
-
return;
|
|
4637
|
-
}
|
|
4638
|
-
}
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
return error(res, 404, "respond-not-pending", "该待办不在本地清单中(可能已由另一端先答,或已超时)");
|
|
4643
|
-
}
|
|
4644
|
-
|
|
4645
|
-
if (rest === "/actions") {
|
|
4646
|
-
if (requireGet(method, res)) return;
|
|
4647
|
-
sendJson(res, 200, { ok: true, actions: mobileActions.list() });
|
|
4648
|
-
return;
|
|
4649
|
-
}
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
if (rest === "/account-usage") {
|
|
4653
|
-
if (requireGet(method, res)) return;
|
|
4654
|
-
const now = Date.now();
|
|
4655
|
-
const forceRefresh = url.searchParams.get("refresh") === "1";
|
|
4656
|
-
if ((!forceRefresh || (now - accountUsageLastForcedAt < 2_000)) && accountUsageCache && now - accountUsageCache.at < 60_000) {
|
|
4657
|
-
sendJson(res, 200, accountUsageCache.body);
|
|
4658
|
-
return;
|
|
4659
|
-
}
|
|
4660
|
-
if (!accountUsageInFlight) {
|
|
4661
|
-
if (forceRefresh) accountUsageLastForcedAt = now;
|
|
4662
|
-
|
|
4663
|
-
const timezoneOffsetSeconds = Number(url.searchParams.get("tz"));
|
|
4664
|
-
accountUsageInFlight = queryAccountUsage(ctx, {
|
|
4665
|
-
locale: url.searchParams.get("lang") ?? undefined,
|
|
4666
|
-
timezoneOffsetSeconds: Number.isFinite(timezoneOffsetSeconds) ? timezoneOffsetSeconds : undefined,
|
|
4667
|
-
}).then((body) => {
|
|
4668
|
-
if (body.failedCount === 0) accountUsageCache = { at: Date.now(), body };
|
|
4669
|
-
else accountUsageCache = null;
|
|
4670
|
-
return body;
|
|
4671
|
-
}).finally(() => {
|
|
4672
|
-
accountUsageInFlight = null;
|
|
4673
|
-
});
|
|
4674
|
-
}
|
|
4675
|
-
try {
|
|
4676
|
-
sendJson(res, 200, await accountUsageInFlight);
|
|
4677
|
-
} catch {
|
|
4678
|
-
|
|
4679
|
-
return error(res, 502, "account-usage-failed");
|
|
4680
|
-
}
|
|
4681
|
-
return;
|
|
4682
|
-
}
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
if (rest === "/balance") {
|
|
4686
|
-
if (requireGet(method, res)) return;
|
|
4687
|
-
const now = Date.now();
|
|
4688
|
-
|
|
4689
|
-
if (balanceCache && now - balanceCache.at < 60000) {
|
|
4690
|
-
sendJson(res, 200, balanceCache.body);
|
|
4691
|
-
return;
|
|
4692
|
-
}
|
|
4693
|
-
|
|
4694
|
-
const account = await queryDeepSeekAccountBalance(ctx);
|
|
4695
|
-
if (account.status === "ready" && account.wallets.length > 0) {
|
|
4696
|
-
balanceCache = {
|
|
4697
|
-
at: now,
|
|
4698
|
-
body: {
|
|
4699
|
-
ok: true,
|
|
4700
|
-
balance: {
|
|
4701
|
-
is_available: true,
|
|
4702
|
-
balance_infos: account.wallets.map((wallet) => ({
|
|
4703
|
-
currency: wallet.currency,
|
|
4704
|
-
total_balance: wallet.balance,
|
|
4705
|
-
})),
|
|
4706
|
-
},
|
|
4707
|
-
...(account.bonusWallets.length > 0 ? {
|
|
4708
|
-
bonus_infos: account.bonusWallets.map((wallet) => ({
|
|
4709
|
-
currency: wallet.currency,
|
|
4710
|
-
total_balance: wallet.balance,
|
|
4711
|
-
})),
|
|
4712
|
-
} : {}),
|
|
4713
|
-
topUpUrl: account.links?.topUpUrl ?? "https://platform.deepseek.com/top_up",
|
|
4714
|
-
},
|
|
4715
|
-
};
|
|
4716
|
-
sendJson(res, 200, balanceCache.body);
|
|
4717
|
-
return;
|
|
4718
|
-
}
|
|
4719
|
-
let key;
|
|
4720
|
-
try {
|
|
4721
|
-
const credentials = ctx.get("credentials");
|
|
4722
|
-
if (credentials?.resolve) {
|
|
4723
|
-
const resolved = await credentials.resolve(credentialRef("DEEPSEEK_API_KEY"));
|
|
4724
|
-
key = resolved?.value;
|
|
4725
|
-
}
|
|
4726
|
-
} catch {
|
|
4727
|
-
|
|
4728
|
-
}
|
|
4729
|
-
if (!key) key = process.env.DEEPSEEK_API_KEY;
|
|
4730
|
-
if (!key) {
|
|
4731
|
-
if (account.status === "failed") return error(res, 502, "balance-failed", account.failedReason ?? "账号余额查询失败");
|
|
4732
|
-
return error(res, 400, "no-api-key", "未登录 DeepSeek 账号,也没有配置 DEEPSEEK_API_KEY(电脑端 设置 → 模型 里填写,或登录账号)");
|
|
4733
|
-
}
|
|
4734
|
-
try {
|
|
4735
|
-
const response = await fetch("https://api.deepseek.com/user/balance", {
|
|
4736
|
-
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
|
|
4737
|
-
signal: AbortSignal.timeout(15_000),
|
|
4738
|
-
});
|
|
4739
|
-
if (!response.ok) {
|
|
4740
|
-
if (balanceCache) {
|
|
4741
|
-
balanceCache.body.stale = true;
|
|
4742
|
-
sendJson(res, 200, balanceCache.body);
|
|
4743
|
-
return;
|
|
4744
|
-
}
|
|
4745
|
-
return error(res, 502, "balance-failed", `DeepSeek API HTTP ${response.status}`);
|
|
4746
|
-
}
|
|
4747
|
-
const data = await response.json();
|
|
4748
|
-
balanceCache = { at: now, body: { ok: true, balance: data } };
|
|
4749
|
-
sendJson(res, 200, balanceCache.body);
|
|
4750
|
-
} catch (err) {
|
|
4751
|
-
if (balanceCache) {
|
|
4752
|
-
balanceCache.body.stale = true;
|
|
4753
|
-
sendJson(res, 200, balanceCache.body);
|
|
4754
|
-
return;
|
|
4755
|
-
}
|
|
4756
|
-
return error(res, 502, "balance-failed", err.message);
|
|
4757
|
-
}
|
|
4758
|
-
return;
|
|
4759
|
-
}
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
if (rest === "/usage") {
|
|
4763
|
-
if (requireGet(method, res)) return;
|
|
4764
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
4765
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
4766
|
-
const sessions = ctx.get("sessions");
|
|
4767
|
-
const session = sessions?.get(sessionId);
|
|
4768
|
-
if (!session) return error(res, 404, "session-not-found");
|
|
4769
|
-
const total = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0, messages: 0 };
|
|
4770
|
-
let lastUsage = null;
|
|
4771
|
-
const usageEvents = eventsOf(session);
|
|
4772
|
-
for (const event of usageEvents) {
|
|
4773
|
-
if (event.type !== "assistant/message" || event.data?.usage === void 0) continue;
|
|
4774
|
-
const u = event.data.usage;
|
|
4775
|
-
total.inputTokens += u.inputTokens ?? 0;
|
|
4776
|
-
total.outputTokens += u.outputTokens ?? 0;
|
|
4777
|
-
total.cacheReadTokens += u.cacheReadTokens ?? 0;
|
|
4778
|
-
total.cacheWriteTokens += u.cacheWriteTokens ?? 0;
|
|
4779
|
-
total.reasoningTokens += u.reasoningTokens ?? 0;
|
|
4780
|
-
total.messages += 1;
|
|
4781
|
-
lastUsage = u;
|
|
4782
|
-
}
|
|
4783
|
-
const billed = total.inputTokens + total.cacheReadTokens + total.cacheWriteTokens;
|
|
4784
|
-
total.cacheHitRate = billed > 0 ? total.cacheReadTokens / billed : 0;
|
|
4785
|
-
|
|
4786
|
-
if (lastUsage) {
|
|
4787
|
-
total.pressureTokens = (lastUsage.inputTokens ?? 0) + (lastUsage.cacheReadTokens ?? 0) + (lastUsage.cacheWriteTokens ?? 0);
|
|
4788
|
-
}
|
|
4789
|
-
|
|
4790
|
-
let contextWindow = contextWindowMap.get(sessionId);
|
|
4791
|
-
if (contextWindow === undefined) {
|
|
4792
|
-
for (let i = usageEvents.length - 1; i >= 0; i--) {
|
|
4793
|
-
const event = usageEvents[i];
|
|
4794
|
-
if (event.type === "request/context" && Number.isInteger(event.data?.contextWindow)) {
|
|
4795
|
-
contextWindow = event.data.contextWindow;
|
|
4796
|
-
break;
|
|
4797
|
-
}
|
|
4798
|
-
}
|
|
4799
|
-
}
|
|
4800
|
-
sendJson(res, 200, {
|
|
4801
|
-
ok: true,
|
|
4802
|
-
sessionId,
|
|
4803
|
-
usage: total,
|
|
4804
|
-
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
4805
|
-
});
|
|
4806
|
-
return;
|
|
4807
|
-
}
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
|
|
4811
|
-
if (rest === "/defaults") {
|
|
4812
|
-
if (requirePost(method, res)) return;
|
|
4813
|
-
const body = await readJson(req, res);
|
|
4814
|
-
if (body === undefined) return;
|
|
4815
|
-
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
if (typeof body.permissionPreset === "string" && body.permissionPreset !== "") {
|
|
4820
|
-
if (body.permissionPreset === "danger-full-access" && body.confirmDanger !== true) {
|
|
4821
|
-
return error(res, 400, "risk-confirmation-required", "选择完全访问需显式确认风险");
|
|
4822
|
-
}
|
|
4823
|
-
const permissionPresets = ctx.get("permissionPresets");
|
|
4824
|
-
if (!permissionPresets) return error(res, 503, "permission-service-unavailable", "权限服务不可用");
|
|
4825
|
-
if (!Array.isArray(permissionPresets.names) || !permissionPresets.names.includes(body.permissionPreset)) {
|
|
4826
|
-
return error(res, 400, "unknown-permission-preset", `unknown permission preset "${body.permissionPreset}"`);
|
|
4827
|
-
}
|
|
4828
|
-
}
|
|
4829
|
-
try {
|
|
4830
|
-
if (typeof body.agentPreset === "string" && body.agentPreset !== "") {
|
|
4831
|
-
await apiRpc("settings.update", { ns: "agent-presets", patch: { default: body.agentPreset } });
|
|
4832
|
-
}
|
|
4833
|
-
if (typeof body.permissionPreset === "string" && body.permissionPreset !== "") {
|
|
4834
|
-
await apiRpc("settings.update", { ns: "permission", patch: { defaultPreset: body.permissionPreset } });
|
|
4835
|
-
}
|
|
4836
|
-
sendJson(res, 200, { ok: true });
|
|
4837
|
-
} catch (e) {
|
|
4838
|
-
error(res, ...rpcError(e, "update-failed"));
|
|
4839
|
-
}
|
|
4840
|
-
return;
|
|
4841
|
-
}
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
if (rest === "/diagnostics") {
|
|
4845
|
-
if (requireGet(method, res)) return;
|
|
4846
|
-
|
|
4847
|
-
const probe = (name) => {
|
|
4848
|
-
try {
|
|
4849
|
-
return ctx.get(name) !== undefined;
|
|
4850
|
-
} catch {
|
|
4851
|
-
return false;
|
|
4852
|
-
}
|
|
4853
|
-
};
|
|
4854
|
-
const services = {
|
|
4855
|
-
webServer: !!(ctx.webServer && typeof ctx.webServer.register === "function"),
|
|
4856
|
-
agents: probe("agents"),
|
|
4857
|
-
sessions: probe("sessions"),
|
|
4858
|
-
llm: probe("llm"),
|
|
4859
|
-
permissionPresets: probe("permissionPresets"),
|
|
4860
|
-
agentPresets: probe("agentPresets"),
|
|
4861
|
-
workspaceRegistry: probe("workspaceRegistry"),
|
|
4862
|
-
approval: probe("approval"),
|
|
4863
|
-
credentials: probe("credentials"),
|
|
4864
|
-
messageFeedback: probe("messageFeedback"),
|
|
4865
|
-
userQuestions: probe("userQuestions"),
|
|
4866
|
-
};
|
|
4867
|
-
const checks = { modelsRpc: false, sessionsList: false, directories: false, workspaces: false, notifications: false, actions: false };
|
|
4868
|
-
try {
|
|
4869
|
-
const agents = ctx.get("agents");
|
|
4870
|
-
|
|
4871
|
-
const sid = firstAgent(agents)?.id;
|
|
4872
|
-
if (sid) {
|
|
4873
|
-
const directory = await apiRpc("session.models", { sessionId: sid });
|
|
4874
|
-
checks.modelsRpc = Array.isArray(directory?.groups) && directory.groups.length > 0;
|
|
4875
|
-
}
|
|
4876
|
-
} catch { }
|
|
4877
|
-
try {
|
|
4878
|
-
checks.sessionsList = (ctx.get("sessions")?.list?.().length ?? 0) >= 0;
|
|
4879
|
-
} catch { }
|
|
4880
|
-
try {
|
|
4881
|
-
const entries = await readdir(process.cwd(), { withFileTypes: true });
|
|
4882
|
-
checks.directories = entries.some((entry) => entry.isDirectory());
|
|
4883
|
-
} catch { }
|
|
4884
|
-
try {
|
|
4885
|
-
checks.workspaces = (ctx.get("workspaceRegistry")?.list?.().length ?? 0) > 0;
|
|
4886
|
-
} catch { }
|
|
4887
|
-
checks.notifications = notifStore.size >= 0;
|
|
4888
|
-
checks.actions = actionEntries.size >= 0;
|
|
4889
|
-
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
4893
|
-
|
|
4894
|
-
checks.pendingFrames = pendingFrames.size;
|
|
4895
|
-
checks.pendingApprovals = pendingApprovals.size;
|
|
4896
|
-
checks.pendingQuestions = pendingQuestions.size;
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
for (const target of config.pushUrls) {
|
|
4900
|
-
const status = pushStatus.get(target.name);
|
|
4901
|
-
checks[`push:${target.name}`] = status
|
|
4902
|
-
? `${status.ok ? "ok" : "fail"} ${new Date(status.at).toLocaleTimeString("zh-CN", { hour12: false })}${status.ok ? "" : ` · ${status.error}`}`
|
|
4903
|
-
: "idle(尚未投递)";
|
|
4904
|
-
}
|
|
4905
|
-
|
|
4906
|
-
|
|
4907
|
-
checks.approvalMode = approvalMode;
|
|
4908
|
-
checks.remoteEvents = eventsCapable();
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
const jobsSvc = ctx.get("jobs");
|
|
4915
|
-
const settingsSvc = ctx.get("settings");
|
|
4916
|
-
const gatewaySvc = ctx.get("typertGateway");
|
|
4917
|
-
const presetsSvc = ctx.get("permissionPresets");
|
|
4918
|
-
const workspaceSvc = ctx.get("workspaceRegistry");
|
|
4919
|
-
|
|
4920
|
-
let connectionSvc;
|
|
4921
|
-
try {
|
|
4922
|
-
connectionSvc = ctx.get("connection");
|
|
4923
|
-
} catch {
|
|
4924
|
-
connectionSvc = undefined;
|
|
4925
|
-
}
|
|
4926
|
-
const peerSource = hostPeerSource(gatewaySvc, connectionSvc);
|
|
4927
|
-
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
const eventsPeerProbe = (() => {
|
|
4931
|
-
if (!gatewaySvc) return { state: "missing" };
|
|
4932
|
-
if (!wireStreamTakesControl(gatewaySvc)) return { state: "ok" };
|
|
4933
|
-
if (peerSource === "operatorPeer") return { state: "ok" };
|
|
4934
|
-
if (peerSource === "createPeer") {
|
|
4935
|
-
|
|
4936
|
-
const peer = gatewayPeer();
|
|
4937
|
-
return peer && peer === cachedOwnerPeer
|
|
4938
|
-
? { state: "ok" }
|
|
4939
|
-
: { state: "drift", reason: "gateway-peer-source-missing" };
|
|
4940
|
-
}
|
|
4941
|
-
return { state: "drift", reason: "gateway-peer-source-missing" };
|
|
4942
|
-
})();
|
|
4943
|
-
|
|
4944
|
-
|
|
4945
|
-
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
const settingsProbeNamespaces = new Set(["llm-openai-codex", "llm-pi-ai"]);
|
|
4949
|
-
try {
|
|
4950
|
-
for (const provider of ctx.get("llm")?.listConfigurableProviders?.() ?? []) {
|
|
4951
|
-
if (typeof provider?.settingsNs === "string" && provider.settingsNs !== "") {
|
|
4952
|
-
settingsProbeNamespaces.add(provider.settingsNs);
|
|
4953
|
-
}
|
|
4954
|
-
}
|
|
4955
|
-
} catch {
|
|
4956
|
-
|
|
4957
|
-
}
|
|
4958
|
-
const settingsReadProbe = (() => {
|
|
4959
|
-
if (!settingsSvc) return { state: "missing" };
|
|
4960
|
-
for (const ns of settingsProbeNamespaces) {
|
|
4961
|
-
const result = readSettingsSectionStrict(settingsSvc, ns);
|
|
4962
|
-
|
|
4963
|
-
if (!result.ok) return { state: "drift", reason: result.reason };
|
|
4964
|
-
}
|
|
4965
|
-
return { state: "ok" };
|
|
4966
|
-
})();
|
|
4967
|
-
const hostCapabilities = {
|
|
4968
|
-
"jobs.callerShape": capabilityState(jobsSvc, (s) => typeof s.list === "function" && typeof s.kill === "function"),
|
|
4969
|
-
"jobs.eventsApi": capabilityState(jobsSvc, (s) => typeof s.events?.subscribe === "function" || typeof s.onJobsChanged === "function"),
|
|
4970
|
-
"settings.read": settingsReadProbe.state,
|
|
4971
|
-
"gateway.wireStream": capabilityState(gatewaySvc, (s) => typeof s.openWireStream === "function"),
|
|
4972
|
-
"permissionPresets.apply": capabilityState(presetsSvc, (s) => Array.isArray(s.names) && typeof s.apply === "function"),
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
"permissionPresets.catalog": capabilityState(presetsSvc, (s) => s.presets !== null && typeof s.presets === "object"),
|
|
4978
|
-
"workspaceRegistry.stateWrite": capabilityState(workspaceSvc, (s) => typeof s.enqueueOperation === "function" && typeof s.requireState === "function" && typeof s.setState === "function"),
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
"gateway.eventsPeer": eventsPeerProbe.state,
|
|
4983
|
-
};
|
|
4984
|
-
checks.hostCapabilities = hostCapabilities;
|
|
4985
|
-
|
|
4986
|
-
checks.hostGeneration = {
|
|
4987
|
-
jobsCaller: jobsSvc ? (jobsNeedsSessionId(jobsSvc) ? "sessionId" : "agent") : "unknown",
|
|
4988
|
-
settingsRead: settingsSvc ? (typeof settingsSvc.get === "function" ? "get" : typeof settingsSvc.describe === "function" ? "describe" : "unknown") : "unknown",
|
|
4989
|
-
wireStreamArgs: gatewaySvc ? (wireStreamTakesControl(gatewaySvc) ? "controlArg" : "legacyArg") : "unknown",
|
|
4990
|
-
|
|
4991
|
-
eventsPeer: !gatewaySvc
|
|
4992
|
-
? "unknown"
|
|
4993
|
-
: !wireStreamTakesControl(gatewaySvc)
|
|
4994
|
-
? "legacy"
|
|
4995
|
-
: eventsPeerProbe.state === "ok"
|
|
4996
|
-
? peerSource
|
|
4997
|
-
: "none",
|
|
4998
|
-
};
|
|
4999
|
-
|
|
5000
|
-
const degradedCaps = Object.entries(hostCapabilities).filter(([, state]) => state !== "ok");
|
|
5001
|
-
|
|
5002
|
-
const hostCapabilityReasons = {};
|
|
5003
|
-
if (settingsReadProbe.reason) hostCapabilityReasons["settings.read"] = settingsReadProbe.reason;
|
|
5004
|
-
|
|
5005
|
-
if (eventsPeerProbe.reason) hostCapabilityReasons["gateway.eventsPeer"] = eventsPeerProbe.reason;
|
|
5006
|
-
if (Object.keys(hostCapabilityReasons).length > 0) checks.hostCapabilityReasons = hostCapabilityReasons;
|
|
5007
|
-
const capabilityNote = degradedCaps.length === 0
|
|
5008
|
-
? ""
|
|
5009
|
-
: `宿主能力非全绿:${degradedCaps.map(([name, state]) => `${name}=${state}${hostCapabilityReasons[name] ? `(${hostCapabilityReasons[name]})` : ""}`).join("、")}——对应功能会明确报错或跳过,不会静默伪装成功(ADR 0017)`;
|
|
5010
|
-
const approvalNote = approvalMode === "both" && eventsCapable()
|
|
5011
|
-
? "approvalMode=both:桌面 GUI 与手机同卡、先答生效($events 双端呈现,v3.1.3)"
|
|
5012
|
-
: approvalMode === "both"
|
|
5013
|
-
? "approvalMode=both 但 $events 通道不可用 → 按 mobile 语义降级(手机在线独占,桌面不弹);看 checks.hostCapabilities.gateway.eventsPeer 与运行日志(0.2.1+ 的进程内开流需要活 Peer;该通道本身要求宿主 0.1.2-rc.1+ / 桌面 v2.0.5+)"
|
|
5014
|
-
: approvalMode === "desktop"
|
|
5015
|
-
? "approvalMode=desktop:审批/问询只走桌面 GUI,手机不弹卡"
|
|
5016
|
-
: "approvalMode=mobile:手机在线独占审批/问询(v3.1.2 行为),离线交桌面 GUI";
|
|
5017
|
-
sendJson(res, 200, {
|
|
5018
|
-
ok: true,
|
|
5019
|
-
plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
|
|
5020
|
-
runtime: {
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5024
|
-
form: runtimeForm(ctx),
|
|
5025
|
-
host: ctx.webServer.host,
|
|
5026
|
-
port: ctx.webServer.port,
|
|
5027
|
-
cwd: process.cwd(),
|
|
5028
|
-
authEnabled,
|
|
5029
|
-
|
|
5030
|
-
lanBridge: { enabled: lanEnabled, host: lanHost, port: lanPort, listening: lanBridgeListening },
|
|
5031
|
-
|
|
5032
|
-
metrics: runtimeMetrics(),
|
|
5033
|
-
},
|
|
5034
|
-
services,
|
|
5035
|
-
checks,
|
|
5036
|
-
notes: [
|
|
5037
|
-
approvalNote,
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
"skill-catalog: 移动端新建会话已随预设装配注入技能目录(v3.1.0 起);若目录缺失请重启插件并查看本诊断",
|
|
5042
|
-
|
|
5043
|
-
...(capabilityNote ? [capabilityNote] : []),
|
|
5044
|
-
...(quietHoursConfigProblem ? [quietHoursConfigProblem] : []),
|
|
5045
|
-
],
|
|
5046
|
-
});
|
|
5047
|
-
return;
|
|
5048
|
-
}
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
if (rest === "/workspaces") {
|
|
5052
|
-
if (requireGet(method, res)) return;
|
|
5053
|
-
const registry = ctx.get("workspaceRegistry");
|
|
5054
|
-
const workspaces = registry?.list?.() ?? [];
|
|
5055
|
-
sendJson(res, 200, {
|
|
5056
|
-
ok: true,
|
|
5057
|
-
|
|
5058
|
-
workspaces: workspaces.map((w) => ({
|
|
5059
|
-
id: w.id,
|
|
5060
|
-
path: w.path,
|
|
5061
|
-
title: w.title,
|
|
5062
|
-
sessionIds: [...(w.sessionIds ?? [])],
|
|
5063
|
-
})),
|
|
5064
|
-
});
|
|
5065
|
-
return;
|
|
5066
|
-
}
|
|
5067
|
-
|
|
5068
|
-
if (rest === "/directories") {
|
|
5069
|
-
if (method === "POST") {
|
|
5070
|
-
|
|
5071
|
-
const body = await readJson(req, res);
|
|
5072
|
-
if (body === undefined) return;
|
|
5073
|
-
const parent = typeof body.path === "string" && body.path !== "" ? normalizeServerPath(body.path) : undefined;
|
|
5074
|
-
const name = typeof body.name === "string" ? body.name.trim() : "";
|
|
5075
|
-
if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name)) return error(res, 400, "invalid-name", "文件夹名不合法");
|
|
5076
|
-
|
|
5077
|
-
const shown = parent ? join(parent, name) : name;
|
|
5078
|
-
|
|
5079
|
-
let target;
|
|
5080
|
-
try {
|
|
5081
|
-
target = join(realPathOf(parent ?? "."), name);
|
|
5082
|
-
} catch {
|
|
5083
|
-
return protectedPathError(res);
|
|
5084
|
-
}
|
|
5085
|
-
if (isProtectedPath(target)) return protectedPathError(res);
|
|
5086
|
-
try {
|
|
5087
|
-
mkdirSync(target, { recursive: false });
|
|
5088
|
-
sendJson(res, 200, { ok: true, path: shown });
|
|
5089
|
-
} catch (err) {
|
|
5090
|
-
return error(res, 400, "mkdir-failed", failureDetail(err));
|
|
5091
|
-
}
|
|
5092
|
-
return;
|
|
5093
|
-
}
|
|
5094
|
-
if (requireGet(method, res)) return;
|
|
5095
|
-
const path = url.searchParams.get("path");
|
|
5096
|
-
|
|
5097
|
-
if (!path || path === "") {
|
|
5098
|
-
let roots = [];
|
|
5099
|
-
if (process.platform === "win32") {
|
|
5100
|
-
for (let letter = 65; letter <= 90; letter++) {
|
|
5101
|
-
const drive = String.fromCharCode(letter) + ":\\";
|
|
5102
|
-
if (existsSync(drive)) roots.push(drive);
|
|
5103
|
-
}
|
|
5104
|
-
} else {
|
|
5105
|
-
roots = ["/"];
|
|
5106
|
-
}
|
|
5107
|
-
|
|
5108
|
-
sendJson(res, 200, { ok: true, path: "", dirs: roots, sep });
|
|
5109
|
-
return;
|
|
5110
|
-
}
|
|
5111
|
-
|
|
5112
|
-
const base = normalizeServerPath(path);
|
|
5113
|
-
|
|
5114
|
-
let listed;
|
|
5115
|
-
try {
|
|
5116
|
-
listed = realPathOf(base);
|
|
5117
|
-
} catch {
|
|
5118
|
-
return protectedPathError(res);
|
|
5119
|
-
}
|
|
5120
|
-
if (isProtectedPath(listed)) return protectedPathError(res);
|
|
5121
|
-
try {
|
|
5122
|
-
const entries = await readdir(listed, { withFileTypes: true });
|
|
5123
|
-
const dirs = entries
|
|
5124
|
-
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
5125
|
-
.map((entry) => entry.name)
|
|
5126
|
-
.sort((a, b) => a.localeCompare(b, "zh-CN"));
|
|
5127
|
-
|
|
5128
|
-
const files = entries
|
|
5129
|
-
.filter((entry) => entry.isFile() && !entry.name.startsWith("."))
|
|
5130
|
-
.map((entry) => entry.name)
|
|
5131
|
-
.sort((a, b) => a.localeCompare(b, "zh-CN"));
|
|
5132
|
-
|
|
5133
|
-
const fileEntries = entries
|
|
5134
|
-
.filter((entry) => entry.isFile() && !entry.name.startsWith("."))
|
|
5135
|
-
.map((entry) => {
|
|
5136
|
-
let size = null;
|
|
5137
|
-
let mtimeMs = null;
|
|
5138
|
-
try {
|
|
5139
|
-
const st = statSync(join(listed, entry.name));
|
|
5140
|
-
size = st.size;
|
|
5141
|
-
mtimeMs = st.mtimeMs;
|
|
5142
|
-
} catch {
|
|
5143
|
-
|
|
5144
|
-
}
|
|
5145
|
-
return { name: entry.name, size, mtimeMs, mime: fileMimeOf(entry.name) };
|
|
5146
|
-
})
|
|
5147
|
-
.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
|
|
5148
|
-
sendJson(res, 200, { ok: true, path: base, dirs, files, fileEntries });
|
|
5149
|
-
} catch (err) {
|
|
5150
|
-
return error(res, 400, "directory-unreadable", failureDetail(err));
|
|
5151
|
-
}
|
|
5152
|
-
return;
|
|
5153
|
-
}
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
|
|
5157
|
-
|
|
5158
|
-
|
|
5159
|
-
|
|
5160
|
-
if (rest === "/files" && (method === "GET" || method === "HEAD")) {
|
|
5161
|
-
const path = url.searchParams.get("path");
|
|
5162
|
-
if (!path || path === "") return error(res, 400, "bad-request", "missing path");
|
|
5163
|
-
const target = resolve(normalizeServerPath(path));
|
|
5164
|
-
if (isProtectedPath(target)) return protectedPathError(res);
|
|
5165
|
-
|
|
5166
|
-
|
|
5167
|
-
|
|
5168
|
-
|
|
5169
|
-
|
|
5170
|
-
let fd;
|
|
5171
|
-
try {
|
|
5172
|
-
fd = openSync(target, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
|
|
5173
|
-
} catch (err) {
|
|
5174
|
-
return error(res, 404, "file-not-found", failureDetail(err));
|
|
5175
|
-
}
|
|
5176
|
-
let fdOwned = true;
|
|
5177
|
-
const closeFd = () => {
|
|
5178
|
-
if (!fdOwned) return;
|
|
5179
|
-
fdOwned = false;
|
|
5180
|
-
try {
|
|
5181
|
-
closeSync(fd);
|
|
5182
|
-
} catch {
|
|
5183
|
-
|
|
5184
|
-
}
|
|
5185
|
-
};
|
|
5186
|
-
try {
|
|
5187
|
-
const st = fstatSync(fd);
|
|
5188
|
-
if (isProtectedFile(st)) {
|
|
5189
|
-
closeFd();
|
|
5190
|
-
return protectedPathError(res);
|
|
5191
|
-
}
|
|
5192
|
-
if (!st.isFile()) {
|
|
5193
|
-
closeFd();
|
|
5194
|
-
return error(res, 400, "not-a-file", "path is not a file");
|
|
5195
|
-
}
|
|
5196
|
-
|
|
5197
|
-
if (!isStillAt(target, st)) {
|
|
5198
|
-
closeFd();
|
|
5199
|
-
return isProtectedPath(target) ? protectedPathError(res) : error(res, 409, "file-changed", "the file changed while it was being opened; try again");
|
|
5200
|
-
}
|
|
5201
|
-
const name = basename(target);
|
|
5202
|
-
|
|
5203
|
-
const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
|
|
5204
|
-
const lastModified = new Date(st.mtimeMs).toUTCString();
|
|
5205
|
-
guardRes(res);
|
|
5206
|
-
if (ifNoneMatch(req, etag)) {
|
|
5207
|
-
closeFd();
|
|
5208
|
-
res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
|
|
5209
|
-
res.end();
|
|
5210
|
-
return;
|
|
5211
|
-
}
|
|
5212
|
-
const range = parseByteRange(requestHeaderText(req, "range"), st.size);
|
|
5213
|
-
if (range && range.invalid) {
|
|
5214
|
-
closeFd();
|
|
5215
|
-
res.writeHead(416, {
|
|
5216
|
-
"accept-ranges": "bytes",
|
|
5217
|
-
"content-range": `bytes */${st.size}`,
|
|
5218
|
-
"content-length": "0",
|
|
5219
|
-
etag,
|
|
5220
|
-
"cache-control": "no-store",
|
|
5221
|
-
connection: "close",
|
|
5222
|
-
});
|
|
5223
|
-
res.end();
|
|
5224
|
-
return;
|
|
5225
|
-
}
|
|
5226
|
-
const start = range ? range.start : 0;
|
|
5227
|
-
const end = range ? range.end : st.size - 1;
|
|
5228
|
-
const length = st.size === 0 ? 0 : end - start + 1;
|
|
5229
|
-
const headers = {
|
|
5230
|
-
"content-type": fileMimeOf(name),
|
|
5231
|
-
"content-length": String(length),
|
|
5232
|
-
"content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
5233
|
-
"cache-control": "no-store",
|
|
5234
|
-
"accept-ranges": "bytes",
|
|
5235
|
-
etag,
|
|
5236
|
-
"last-modified": lastModified,
|
|
5237
|
-
|
|
5238
|
-
connection: "close",
|
|
5239
|
-
...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
|
|
5240
|
-
};
|
|
5241
|
-
res.writeHead(range ? 206 : 200, headers);
|
|
5242
|
-
if (method === "HEAD" || st.size === 0) {
|
|
5243
|
-
closeFd();
|
|
5244
|
-
res.end();
|
|
5245
|
-
return;
|
|
5246
|
-
}
|
|
5247
|
-
fdOwned = false;
|
|
5248
|
-
const source = createReadStream(null, { fd, start, end, autoClose: true });
|
|
5249
|
-
|
|
5250
|
-
res.on("close", () => {
|
|
5251
|
-
try {
|
|
5252
|
-
source.destroy();
|
|
5253
|
-
} catch {
|
|
5254
|
-
|
|
5255
|
-
}
|
|
5256
|
-
});
|
|
5257
|
-
source.on("error", () => {
|
|
5258
|
-
try {
|
|
5259
|
-
res.destroy();
|
|
5260
|
-
} catch {
|
|
5261
|
-
|
|
5262
|
-
}
|
|
5263
|
-
});
|
|
5264
|
-
source.pipe(res);
|
|
5265
|
-
} catch (err) {
|
|
5266
|
-
closeFd();
|
|
5267
|
-
return error(res, 404, "file-not-found", failureDetail(err));
|
|
5268
|
-
}
|
|
5269
|
-
return;
|
|
5270
|
-
}
|
|
5271
|
-
if (rest === "/files/upload" && method === "POST") {
|
|
5272
|
-
|
|
5273
|
-
const body = await readJson(req, res, 64 * 1024 * 1024);
|
|
5274
|
-
if (body === undefined) return;
|
|
5275
|
-
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
5276
|
-
|
|
5277
|
-
if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|\0]/.test(name) || name.length > 255) {
|
|
5278
|
-
return error(res, 400, "invalid-name", "文件名不合法");
|
|
5279
|
-
}
|
|
5280
|
-
if (typeof body?.data !== "string" || body.data === "") return error(res, 400, "bad-request", "missing data(base64)");
|
|
5281
|
-
let dir;
|
|
5282
|
-
const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
|
|
5283
|
-
if (sessionId) {
|
|
5284
|
-
|
|
5285
|
-
|
|
5286
|
-
|
|
5287
|
-
const agent = ctx.get("agents")?.get(sessionId);
|
|
5288
|
-
if (!agent) return error(res, 404, "session-not-found");
|
|
5289
|
-
dir = agent.session?.header?.cwd;
|
|
5290
|
-
if (typeof dir !== "string" || dir === "") return error(res, 404, "workspace-not-found", "会话没有可用工作区");
|
|
5291
|
-
} else {
|
|
5292
|
-
const registry = ctx.get("workspaceRegistry");
|
|
5293
|
-
dir = registry?.list?.()?.[0]?.path;
|
|
5294
|
-
}
|
|
5295
|
-
if (typeof dir !== "string" || dir === "") return error(res, 503, "no-workspace", "无法确定目标目录(无工作区)");
|
|
5296
|
-
const target = join(resolve(normalizeServerPath(dir)), name);
|
|
5297
|
-
if (isProtectedPath(target)) return protectedPathError(res);
|
|
5298
|
-
try {
|
|
5299
|
-
const buf = Buffer.from(body.data, "base64");
|
|
5300
|
-
if (buf.length === 0) return error(res, 400, "bad-request", "empty payload");
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
try {
|
|
5305
|
-
const existing = lstatSync(target);
|
|
5306
|
-
if (existing.isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
5307
|
-
if (!existing.isFile()) return error(res, 400, "not-a-file", "path is not a file");
|
|
5308
|
-
} catch {
|
|
5309
|
-
|
|
5310
|
-
}
|
|
5311
|
-
|
|
5312
|
-
|
|
5313
|
-
const base = fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
|
|
5314
|
-
let fd;
|
|
5315
|
-
let created = false;
|
|
5316
|
-
try {
|
|
5317
|
-
try {
|
|
5318
|
-
fd = openSync(target, base | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o644);
|
|
5319
|
-
created = true;
|
|
5320
|
-
} catch (err) {
|
|
5321
|
-
if (err?.code !== "EEXIST") throw err;
|
|
5322
|
-
fd = openSync(target, base);
|
|
5323
|
-
}
|
|
5324
|
-
} catch (err) {
|
|
5325
|
-
if (err?.code === "ELOOP" || err?.code === "EMLINK") return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
5326
|
-
if (err?.code === "ENXIO") return error(res, 400, "not-a-file", "path is not a file");
|
|
5327
|
-
throw err;
|
|
5328
|
-
}
|
|
5329
|
-
let refusal;
|
|
5330
|
-
let st;
|
|
5331
|
-
try {
|
|
5332
|
-
st = fstatSync(fd);
|
|
5333
|
-
if (isProtectedFile(st)) refusal = "protected";
|
|
5334
|
-
else if (!st.isFile()) refusal = "not-a-file";
|
|
5335
|
-
|
|
5336
|
-
else if (!isStillAt(target, st)) refusal = isProtectedPath(target) ? "protected" : "changed";
|
|
5337
|
-
if (!refusal) writeFdFully(fd, buf);
|
|
5338
|
-
} finally {
|
|
5339
|
-
closeSync(fd);
|
|
5340
|
-
}
|
|
5341
|
-
if (refusal) {
|
|
5342
|
-
if (created) removeCreatedEntry(target, st);
|
|
5343
|
-
if (refusal === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
|
|
5344
|
-
if (refusal === "changed") return error(res, 409, "file-changed", "the folder changed while the file was being written; try again");
|
|
5345
|
-
return protectedPathError(res);
|
|
5346
|
-
}
|
|
5347
|
-
sendJson(res, 200, { ok: true, path: target, bytes: buf.length });
|
|
5348
|
-
} catch (err) {
|
|
5349
|
-
ctx.logger.warn(`mobile-remote: /files/upload 写入失败:${err?.message ?? err}`);
|
|
5350
|
-
return error(res, 400, "write-failed", failureDetail(err));
|
|
5351
|
-
}
|
|
5352
|
-
return;
|
|
5353
|
-
}
|
|
5354
|
-
|
|
5355
|
-
const actionMatch = /^\/actions\/([^/]+)\/invoke$/.exec(rest); if (actionMatch && method === "POST") {
|
|
5356
|
-
let id;
|
|
5357
|
-
try {
|
|
5358
|
-
|
|
5359
|
-
id = decodeURIComponent(actionMatch[1]);
|
|
5360
|
-
} catch (err) {
|
|
5361
|
-
return bodyError(err, res);
|
|
5362
|
-
}
|
|
5363
|
-
const entry = actionEntries.get(id);
|
|
5364
|
-
if (!entry) return error(res, 404, "action-not-found");
|
|
5365
|
-
const body = await readJson(req, res);
|
|
5366
|
-
if (body === undefined) return;
|
|
5367
|
-
try {
|
|
5368
|
-
await entry.handler(body?.args ?? {});
|
|
5369
|
-
} catch (err) {
|
|
5370
|
-
ctx.logger.warn(`mobile-remote: /actions/${id} 执行失败:${err?.message ?? err}`);
|
|
5371
|
-
return error(res, 500, "action-failed", failureDetail(err));
|
|
5372
|
-
}
|
|
5373
|
-
sendJson(res, 200, { ok: true, accepted: true });
|
|
5374
|
-
return;
|
|
5375
|
-
}
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
if (rest === "/jobs") {
|
|
5379
|
-
if (requireGet(method, res)) return;
|
|
5380
|
-
const jobs = ctx.get("jobs");
|
|
5381
|
-
if (!jobs) return error(res, 503, "jobs-unavailable");
|
|
5382
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
5383
|
-
const agents = ctx.get("agents");
|
|
5384
|
-
const agent = sessionId && agents ? agents.get(sessionId) : undefined;
|
|
5385
|
-
if (sessionId && !agent) return error(res, 404, "session-not-found");
|
|
5386
|
-
const views = jobViews(jobs.list(jobsCallerFor(jobs, agent, sessionId ?? undefined)));
|
|
5387
|
-
sendJson(res, 200, { ok: true, sessionId: sessionId ?? null, jobs: views });
|
|
5388
|
-
return;
|
|
5389
|
-
}
|
|
5390
|
-
|
|
5391
|
-
if (rest === "/todos") {
|
|
5392
|
-
if (requireGet(method, res)) return;
|
|
5393
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
5394
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
5395
|
-
const agents = ctx.get("agents");
|
|
5396
|
-
const session = agents?.get?.(sessionId)?.session;
|
|
5397
|
-
|
|
5398
|
-
const todos = session ? todosView(session) : null;
|
|
5399
|
-
sendJson(res, 200, { ok: true, sessionId, todos });
|
|
5400
|
-
return;
|
|
5401
|
-
}
|
|
5402
|
-
if (rest === "/jobs/kill") {
|
|
5403
|
-
if (requirePost(method, res)) return;
|
|
5404
|
-
const body = await readJson(req, res);
|
|
5405
|
-
if (body === undefined) return;
|
|
5406
|
-
const jobs = ctx.get("jobs");
|
|
5407
|
-
if (!jobs) return error(res, 503, "jobs-unavailable");
|
|
5408
|
-
const jobId = typeof body.jobId === "string" ? body.jobId : "";
|
|
5409
|
-
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
5410
|
-
if (!jobId) return error(res, 400, "jobId-required");
|
|
5411
|
-
const agents = ctx.get("agents");
|
|
5412
|
-
const agent = sessionId && agents ? agents.get(sessionId) : undefined;
|
|
5413
|
-
try {
|
|
5414
|
-
await jobs.kill(jobId, jobsCallerFor(jobs, agent, sessionId), "mobile-remote: user cancelled");
|
|
5415
|
-
sendJson(res, 200, { ok: true });
|
|
5416
|
-
} catch (err) {
|
|
5417
|
-
return error(res, 400, "job-kill-failed", err?.message ?? String(err));
|
|
5418
|
-
}
|
|
5419
|
-
return;
|
|
5420
|
-
}
|
|
5421
|
-
if (rest === "/subagents") {
|
|
5422
|
-
if (requireGet(method, res)) return;
|
|
5423
|
-
const parentSessionId = url.searchParams.get("parentSessionId");
|
|
5424
|
-
if (!parentSessionId) return error(res, 400, "parentSessionId-required");
|
|
5425
|
-
const agents = ctx.get("agents");
|
|
5426
|
-
const sessions = ctx.get("sessions");
|
|
5427
|
-
const subagentsSvc = ctx.get("subagents");
|
|
5428
|
-
const agent = agents?.get(parentSessionId);
|
|
5429
|
-
|
|
5430
|
-
const signal = requestAbort(res);
|
|
5431
|
-
const parent = sessions?.get?.(parentSessionId);
|
|
5432
|
-
const hasCatalog = typeof subagentsSvc?.listChildren === "function";
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
|
|
5436
|
-
|
|
5437
|
-
|
|
5438
|
-
|
|
5439
|
-
|
|
5440
|
-
|
|
5441
|
-
|
|
5442
|
-
|
|
5443
|
-
|
|
5444
|
-
|
|
5445
|
-
|
|
5446
|
-
|
|
5447
|
-
let catalogRows = null;
|
|
5448
|
-
let catalogDegraded = false;
|
|
5449
|
-
if (hasCatalog) {
|
|
5450
|
-
try {
|
|
5451
|
-
const rows = await subagentsSvc.listChildren(parentSessionId);
|
|
5452
|
-
if (Array.isArray(rows)) catalogRows = rows;
|
|
5453
|
-
} catch {
|
|
5454
|
-
catalogRows = null;
|
|
5455
|
-
}
|
|
5456
|
-
}
|
|
5457
|
-
if (catalogRows === null) {
|
|
5458
|
-
const persisted = await listPersistedSubagents(parentSessionId, signal);
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
if (signal.aborted) return;
|
|
5462
|
-
if (persisted?.timedOut) return error(res, 504, "subagents-timeout");
|
|
5463
|
-
if (persisted === null) {
|
|
5464
|
-
|
|
5465
|
-
} else if (!persisted.parentExists) {
|
|
5466
|
-
return error(res, 404, "session-not-found");
|
|
5467
|
-
} else {
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
catalogRows = persisted.entries.map((entry) => ({
|
|
5471
|
-
id: entry.id,
|
|
5472
|
-
title: entry.title,
|
|
5473
|
-
createdAt: entry.createdAt,
|
|
5474
|
-
}));
|
|
5475
|
-
catalogDegraded = true;
|
|
5476
|
-
}
|
|
5477
|
-
}
|
|
5478
|
-
if (catalogRows === null && (agent || parent)) {
|
|
5479
|
-
catalogRows = (sessions?.list?.() ?? [])
|
|
5480
|
-
.map((session) => ({ session, header: session?.header ?? {} }))
|
|
5481
|
-
.filter(({ header }) => header.origin === "subagent" && header.parentSession === parentSessionId)
|
|
5482
|
-
.map(({ session, header }) => ({ id: session?.id ?? header.id, createdAt: header.createdAt }));
|
|
5483
|
-
catalogDegraded = true;
|
|
5484
|
-
}
|
|
5485
|
-
if (catalogRows === null) return error(res, 404, "session-not-found");
|
|
5486
|
-
|
|
5487
|
-
const rows = catalogRows.map((row) => {
|
|
5488
|
-
const id = typeof row?.id === "string" && row.id !== "" ? row.id : "";
|
|
5489
|
-
const live = agents?.get?.(id);
|
|
5490
|
-
const session = sessions?.get?.(id);
|
|
5491
|
-
const createdAt = typeof row?.createdAt === "number"
|
|
5492
|
-
? row.createdAt
|
|
5493
|
-
: (typeof session?.header?.createdAt === "number" ? session.header.createdAt : undefined);
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
const label = typeof row?.label === "string" && row.label !== "" ? row.label : undefined;
|
|
5499
|
-
const rowTitle = typeof row?.title === "string" && row.title !== "" ? row.title : undefined;
|
|
5500
|
-
const liveTitle = sessionTitleOf(session);
|
|
5501
|
-
return { id, live, createdAt, label, rowTitle, liveTitle, mode: row?.mode };
|
|
5502
|
-
}).filter((row) => row.id !== "");
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
|
|
5507
|
-
const needPersistedTitle = rows.filter((row) => !row.label && !row.rowTitle && !row.liveTitle).map((row) => row.id);
|
|
5508
|
-
const persistedTitleMap = needPersistedTitle.length > 0
|
|
5509
|
-
? await resolveSessionTitles(needPersistedTitle, signal)
|
|
5510
|
-
: new Map();
|
|
5511
|
-
if (signal.aborted) return;
|
|
5512
|
-
const entries = rows
|
|
5513
|
-
.map((row) => ({
|
|
5514
|
-
id: row.id,
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
kind: row.mode === "unknown" ? "diagnostic" : "child",
|
|
5520
|
-
|
|
5521
|
-
status: row.mode === "unknown"
|
|
5522
|
-
? "unsupported"
|
|
5523
|
-
: (typeof row.live?.status === "string" && row.live.status !== ""
|
|
5524
|
-
? (row.live.status === "running" ? "running" : "inactive")
|
|
5525
|
-
: "inactive"),
|
|
5526
|
-
title: row.label ?? row.rowTitle ?? row.liveTitle ?? persistedTitleMap.get(row.id) ?? shortSessionId(row.id),
|
|
5527
|
-
...(row.createdAt === undefined ? {} : { createdAt: row.createdAt }),
|
|
5528
|
-
}))
|
|
5529
|
-
.sort((a, b) => {
|
|
5530
|
-
const ta = typeof a.createdAt === "number" ? a.createdAt : Number.NEGATIVE_INFINITY;
|
|
5531
|
-
const tb = typeof b.createdAt === "number" ? b.createdAt : Number.NEGATIVE_INFINITY;
|
|
5532
|
-
if (ta !== tb) return tb - ta;
|
|
5533
|
-
return String(a.id).localeCompare(String(b.id));
|
|
5534
|
-
});
|
|
5535
|
-
sendJson(res, 200, {
|
|
5536
|
-
ok: true,
|
|
5537
|
-
parentAvailable: !!agent,
|
|
5538
|
-
|
|
5539
|
-
...(catalogDegraded ? { catalogDegraded: true } : {}),
|
|
5540
|
-
subagents: entries,
|
|
5541
|
-
});
|
|
5542
|
-
return;
|
|
5543
|
-
}
|
|
5544
|
-
if (rest === "/subagents/interrupt") {
|
|
5545
|
-
if (requirePost(method, res)) return;
|
|
5546
|
-
const body = await readJson(req, res);
|
|
5547
|
-
if (body === undefined) return;
|
|
5548
|
-
const parentSessionId = typeof body.parentSessionId === "string" ? body.parentSessionId : "";
|
|
5549
|
-
const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
|
|
5550
|
-
if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
|
|
5551
|
-
try {
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
try {
|
|
5555
|
-
await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
|
|
5556
|
-
} catch (err) {
|
|
5557
|
-
if (!isEndpointUnavailable(err)) throw err;
|
|
5558
|
-
await apiRpc("subagent.interruptByParent", { parentSessionId, childSessionId, mode: "continuable" });
|
|
5559
|
-
}
|
|
5560
|
-
sendJson(res, 200, { ok: true });
|
|
5561
|
-
} catch (err) {
|
|
5562
|
-
return error(res, ...rpcError(err, "subagent-interrupt-failed"));
|
|
5563
|
-
}
|
|
5564
|
-
return;
|
|
5565
|
-
}
|
|
5566
|
-
if (rest === "/commands") {
|
|
5567
|
-
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
const agents = ctx.get("agents");
|
|
5571
|
-
const commands = ctx.get("commands");
|
|
5572
|
-
if (method === "GET" || method === "HEAD") {
|
|
5573
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
5574
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
5575
|
-
let agent = agents ? agents.get(sessionId) : undefined;
|
|
5576
|
-
if (!commands) {
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
sendJson(res, 200, { ok: true, commands: [], unavailable: true });
|
|
5580
|
-
return;
|
|
5581
|
-
}
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
if (!agent) agent = (await resumeDormantAgent(sessionId))?.agent;
|
|
5585
|
-
|
|
5586
|
-
if (!agent) return error(res, 404, "session-not-found", `session not found: ${sessionId}`);
|
|
5587
|
-
try {
|
|
5588
|
-
const list = commands.list(agent);
|
|
5589
|
-
sendJson(res, 200, {
|
|
5590
|
-
ok: true,
|
|
5591
|
-
commands: (list ?? []).map((c) => ({
|
|
5592
|
-
name: c.name,
|
|
5593
|
-
description: c.description,
|
|
5594
|
-
...(c.input ? { input: c.input } : {}),
|
|
5595
|
-
})),
|
|
5596
|
-
});
|
|
5597
|
-
} catch (err) {
|
|
5598
|
-
return error(res, 400, "commands-list-failed", err?.message ?? String(err));
|
|
5599
|
-
}
|
|
5600
|
-
return;
|
|
5601
|
-
}
|
|
5602
|
-
if (method === "POST") {
|
|
5603
|
-
const body = await readJson(req, res);
|
|
5604
|
-
if (body === undefined) return;
|
|
5605
|
-
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
5606
|
-
const line = typeof body.line === "string" ? body.line : "";
|
|
5607
|
-
if (!sessionId) return error(res, 400, "missing-sessionId");
|
|
5608
|
-
if (!line || !line.startsWith("/")) return error(res, 400, "bad-request", "line must start with /");
|
|
5609
|
-
let agent = sessionId && agents ? agents.get(sessionId) : undefined;
|
|
5610
|
-
if (!commands) return error(res, 503, "commands-unavailable", "commands service not available in this DSH");
|
|
5611
|
-
|
|
5612
|
-
if (!agent) agent = (await resumeDormantAgent(sessionId))?.agent;
|
|
5613
|
-
|
|
5614
|
-
if (!agent) return error(res, 404, "session-not-found", `session not found: ${sessionId}`);
|
|
5615
|
-
try {
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
const result = await commands.execute(agent, line, [], AbortSignal.timeout(180000));
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
if (result === undefined) {
|
|
5625
|
-
return error(res, 404, "command-not-found", `unknown or malformed command: ${line}`);
|
|
5626
|
-
}
|
|
5627
|
-
sendJson(res, 200, { ok: true, result });
|
|
5628
|
-
} catch (err) {
|
|
5629
|
-
return error(res, ...rpcError(err, "commands-execute-failed"));
|
|
5630
|
-
}
|
|
5631
|
-
return;
|
|
5632
|
-
}
|
|
5633
|
-
return error(res, 405, "method-not-allowed");
|
|
5634
|
-
}
|
|
5635
|
-
if (rest === "/goal") {
|
|
5636
|
-
const agents = ctx.get("agents");
|
|
5637
|
-
if (method === "GET" || method === "HEAD") {
|
|
5638
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
5639
|
-
|
|
5640
|
-
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
5641
|
-
const agent = agents ? agents.get(sessionId) : undefined;
|
|
5642
|
-
const goals = ctx.get("goals");
|
|
5643
|
-
if (!goals || !agent) return error(res, 503, "goal-unavailable");
|
|
5644
|
-
try {
|
|
5645
|
-
const current = await goals.get(agent);
|
|
5646
|
-
sendJson(res, 200, { ok: true, goal: current ?? null });
|
|
5647
|
-
} catch (err) {
|
|
5648
|
-
return error(res, 400, "goal-get-failed", err?.message ?? String(err));
|
|
5649
|
-
}
|
|
5650
|
-
return;
|
|
5651
|
-
}
|
|
5652
|
-
if (method === "POST") {
|
|
5653
|
-
const body = await readJson(req, res);
|
|
5654
|
-
if (body === undefined) return;
|
|
5655
|
-
const action = typeof body.action === "string" ? body.action : "";
|
|
5656
|
-
const goals = ctx.get("goals");
|
|
5657
|
-
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
5658
|
-
const agent = sessionId && agents ? agents.get(sessionId) : undefined;
|
|
5659
|
-
if (!sessionId || !agent) return error(res, 400, "sessionId-required");
|
|
5660
|
-
if (!goals) return error(res, 503, "goal-unavailable");
|
|
5661
|
-
try {
|
|
5662
|
-
|
|
5663
|
-
const current = await goals.get(agent);
|
|
5664
|
-
switch (action) {
|
|
5665
|
-
case "create": {
|
|
5666
|
-
const objective = typeof body.objective === "string" ? body.objective : "";
|
|
5667
|
-
if (!objective) return error(res, 400, "objective-required");
|
|
5668
|
-
|
|
5669
|
-
const rounds = body.maxGoalRounds;
|
|
5670
|
-
if (rounds !== undefined && (!Number.isInteger(rounds) || rounds < 1 || rounds > 10000)) {
|
|
5671
|
-
return error(res, 400, "maxGoalRounds-invalid", "maxGoalRounds must be an integer 1-10000");
|
|
5672
|
-
}
|
|
5673
|
-
await apiRpc("goal.create", {
|
|
5674
|
-
sessionId,
|
|
5675
|
-
objective,
|
|
5676
|
-
...(rounds === undefined ? {} : { maxGoalRounds: rounds }),
|
|
5677
|
-
});
|
|
5678
|
-
break;
|
|
5679
|
-
}
|
|
5680
|
-
case "pause":
|
|
5681
|
-
case "resume":
|
|
5682
|
-
case "complete": {
|
|
5683
|
-
if (!current) return error(res, 400, "no-active-goal");
|
|
5684
|
-
await apiRpc(`goal.${action}`, {
|
|
5685
|
-
sessionId,
|
|
5686
|
-
ref: { id: current.id, revision: current.revision },
|
|
5687
|
-
});
|
|
5688
|
-
break;
|
|
5689
|
-
}
|
|
5690
|
-
default:
|
|
5691
|
-
return error(res, 400, "bad-action");
|
|
5692
|
-
}
|
|
5693
|
-
sendJson(res, 200, { ok: true });
|
|
5694
|
-
} catch (err) {
|
|
5695
|
-
return error(res, ...rpcError(err, "goal-failed"));
|
|
5696
|
-
}
|
|
5697
|
-
return;
|
|
5698
|
-
}
|
|
5699
|
-
return error(res, 405, "method-not-allowed");
|
|
5700
|
-
}
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
5704
|
-
|
|
5705
|
-
|
|
5706
|
-
if (rest === "/dev/approval-test") {
|
|
5707
|
-
if (requirePost(method, res)) return;
|
|
5708
|
-
|
|
5709
|
-
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
const gate = localDesktopGate(req, { relayGuard: false });
|
|
5714
|
-
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
5715
|
-
const body = await readJson(req, res);
|
|
5716
|
-
if (body === undefined) return;
|
|
5717
|
-
const agents = ctx.get("agents");
|
|
5718
|
-
if (!agents) return error(res, 503, "agents-unavailable");
|
|
5719
|
-
const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
|
|
5720
|
-
const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstRootAgent(agents);
|
|
5721
|
-
if (!agent) return error(res, 404, "no-live-agent");
|
|
5722
|
-
const synthetic = {
|
|
5723
|
-
agent,
|
|
5724
|
-
toolName: "write",
|
|
5725
|
-
callId: `dev-${Date.now().toString(36)}`,
|
|
5726
|
-
reason: "合成测试:验证手机审批卡链路(等待手机批准/拒绝)",
|
|
5727
|
-
};
|
|
5728
|
-
const outcome = await ctx.waterfall(
|
|
5729
|
-
scopeTarget(agent, agent),
|
|
5730
|
-
"approval/request",
|
|
5731
|
-
synthetic,
|
|
5732
|
-
() => Promise.resolve("unavailable"),
|
|
5733
|
-
);
|
|
5734
|
-
sendJson(res, 200, { ok: true, synthetic: true, outcome });
|
|
5735
|
-
return;
|
|
5736
|
-
}
|
|
2651
|
+
if (await runRouteGroups(ROUTE_GROUPS, routeDeps, req, res, url, rest, method)) return;
|
|
5737
2652
|
|
|
5738
2653
|
error(res, 404, "not-found");
|
|
5739
2654
|
};
|
|
@@ -6663,7 +3578,7 @@ export function apply(ctx, configInput) {
|
|
|
6663
3578
|
}),
|
|
6664
3579
|
] : [];
|
|
6665
3580
|
const unsubscribeSession = ctx.on("session/event", onSessionEvent);
|
|
6666
|
-
const unsubscribeStatus = ctx.on("agent/status", onAgentStatus); phoneActions.register();
|
|
3581
|
+
const unsubscribeStatus = ctx.on("agent/status", onAgentStatus); phoneActions.register(); toolbox.register();
|
|
6667
3582
|
|
|
6668
3583
|
const unsubscribeDisposed = ctx.on("agent/disposed", ({ agent }) => {
|
|
6669
3584
|
const sid = agentSessionId(agent);
|
|
@@ -6671,7 +3586,7 @@ export function apply(ctx, configInput) {
|
|
|
6671
3586
|
cancelDone(sid);
|
|
6672
3587
|
activityMap.delete(sid);
|
|
6673
3588
|
|
|
6674
|
-
|
|
3589
|
+
memoryTurns.forget(sid);
|
|
6675
3590
|
contextWindowMap.delete(sid);
|
|
6676
3591
|
titleCache.delete(sid);
|
|
6677
3592
|
lastNeedsAnswerAt.delete(sid);
|
|
@@ -6813,7 +3728,7 @@ export function apply(ctx, configInput) {
|
|
|
6813
3728
|
lanServer = null;
|
|
6814
3729
|
lanBridgeListening = false;
|
|
6815
3730
|
unsubscribeSession();
|
|
6816
|
-
unsubscribeStatus();
|
|
3731
|
+
unsubscribeStatus(); liveActivity.close();
|
|
6817
3732
|
unsubscribeDisposed?.();
|
|
6818
3733
|
clearInterval(pruneTimer);
|
|
6819
3734
|
clearInterval(heldSweepTimer);
|