@agentknight/client 0.9.62 → 0.9.68
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 +15 -4
- package/dist/chunks/{aad-relay-login-PN2MTPBR.js → aad-relay-login-L62PTGIW.js} +4 -2
- package/dist/chunks/{chunk-GH26GIXM.js → chunk-2QZOJ6EF.js} +5 -0
- package/dist/chunks/{chunk-GEXDYCVI.js → chunk-SKD2IHTR.js} +19 -3
- package/dist/chunks/{chunk-45JUQL5I.js → chunk-XKAM5VR7.js} +1 -1
- package/dist/chunks/{local-sessions-T4LOKU66.js → local-sessions-T42JRA5W.js} +1 -1
- package/dist/chunks/start-client-X3D5JWHW.js +4171 -0
- package/dist/cli.js +2 -2
- package/dist/upgrade-worker.js +7 -2
- package/package.json +4 -4
- package/dist/chunks/start-client-WXBAFWLA.js +0 -4069
|
@@ -1,4069 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
readAppVersion,
|
|
4
|
-
toErrorDetails
|
|
5
|
-
} from "./chunk-45JUQL5I.js";
|
|
6
|
-
import {
|
|
7
|
-
claimUpgradeStartup,
|
|
8
|
-
fileHash,
|
|
9
|
-
restartEnvironment
|
|
10
|
-
} from "./chunk-ANVWLKOO.js";
|
|
11
|
-
import {
|
|
12
|
-
clearClientConfiguration,
|
|
13
|
-
defaultClientHome,
|
|
14
|
-
defaultPairingPagePort,
|
|
15
|
-
normalizeClientEnvironment
|
|
16
|
-
} from "./chunk-CNWBK4LE.js";
|
|
17
|
-
import {
|
|
18
|
-
startRuntimeControl
|
|
19
|
-
} from "./chunk-WMAAFZJ3.js";
|
|
20
|
-
import {
|
|
21
|
-
readLastUpgrade,
|
|
22
|
-
readOptionalJson,
|
|
23
|
-
writePrivateJson
|
|
24
|
-
} from "./chunk-SPZWIFFP.js";
|
|
25
|
-
import {
|
|
26
|
-
RelayCredentialStoreError,
|
|
27
|
-
createRelayCredentialStore,
|
|
28
|
-
normalizeRelayOrigin,
|
|
29
|
-
readAadAccount,
|
|
30
|
-
sameRelayCredential,
|
|
31
|
-
validateRelayCredentialSlots
|
|
32
|
-
} from "./chunk-GEXDYCVI.js";
|
|
33
|
-
import {
|
|
34
|
-
MicrosoftEnrollmentFailureSchema,
|
|
35
|
-
MicrosoftMutationResultSchema,
|
|
36
|
-
MobileAuthorizationIdSchema,
|
|
37
|
-
MobileAuthorizationListResultSchema,
|
|
38
|
-
MobileIdentityPublicKeySchema,
|
|
39
|
-
PairingStatusRequestSchema,
|
|
40
|
-
PcAccountRequestSchema,
|
|
41
|
-
PcAccountResultSchema,
|
|
42
|
-
PcBrowserAuthorizationCallbackSchema,
|
|
43
|
-
PcBrowserAuthorizationStartRequestSchema,
|
|
44
|
-
PcBrowserAuthorizationStartResultSchema,
|
|
45
|
-
PcBrowserRedirectUriSchema,
|
|
46
|
-
PcEnrollmentExchangeResultSchema,
|
|
47
|
-
RELAY_AUTH_DISCOVERY_PATH,
|
|
48
|
-
RelayAuthDiscoverySchema,
|
|
49
|
-
RelayAuthenticationSchema,
|
|
50
|
-
SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH,
|
|
51
|
-
SessionTimelinePageRequestSchema,
|
|
52
|
-
SessionTimelinePageSchema
|
|
53
|
-
} from "./chunk-GH26GIXM.js";
|
|
54
|
-
|
|
55
|
-
// src/start-client.ts
|
|
56
|
-
import { readFileSync } from "node:fs";
|
|
57
|
-
import { resolve } from "node:path";
|
|
58
|
-
import { parseEnv } from "node:util";
|
|
59
|
-
import pino2 from "pino";
|
|
60
|
-
|
|
61
|
-
// src/config.ts
|
|
62
|
-
import { z } from "zod";
|
|
63
|
-
import {
|
|
64
|
-
AgentSelectionSchema,
|
|
65
|
-
CODING_AGENT_IDS,
|
|
66
|
-
SessionImageRelayUrlSchema,
|
|
67
|
-
SessionImagesConfigSchema
|
|
68
|
-
} from "@agentknight/sdk/configuration";
|
|
69
|
-
var BooleanStringSchema = z.enum(["true", "false"]).default("false").transform((value) => value === "true");
|
|
70
|
-
var EnabledBooleanStringSchema = z.enum(["true", "false"]).default("true").transform((value) => value === "true");
|
|
71
|
-
var OptionalPathSchema = z.preprocess(
|
|
72
|
-
(value) => typeof value === "string" && value.trim() === "" ? void 0 : value,
|
|
73
|
-
z.string().trim().min(1).optional()
|
|
74
|
-
);
|
|
75
|
-
var AcpArgumentsSchema = z.string().default("[]").transform((value, context) => {
|
|
76
|
-
let decoded;
|
|
77
|
-
try {
|
|
78
|
-
decoded = JSON.parse(value);
|
|
79
|
-
} catch (error) {
|
|
80
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
81
|
-
context.addIssue({ code: "custom", message: "AGENTKNIGHT_ACP_ARGS must be a JSON array of strings" });
|
|
82
|
-
return z.NEVER;
|
|
83
|
-
}
|
|
84
|
-
const parsed = z.array(z.string()).max(128).safeParse(decoded);
|
|
85
|
-
if (!parsed.success) {
|
|
86
|
-
context.addIssue({ code: "custom", message: "AGENTKNIGHT_ACP_ARGS must be a JSON array of strings" });
|
|
87
|
-
return z.NEVER;
|
|
88
|
-
}
|
|
89
|
-
return parsed.data;
|
|
90
|
-
});
|
|
91
|
-
var EnvironmentSchema = z.object({
|
|
92
|
-
RELAY_URL: z.url(),
|
|
93
|
-
RELAY_TOKEN: z.string().min(24).optional(),
|
|
94
|
-
RELAY_AUTH: z.enum(["auto", "token", "microsoft", "aad"]).optional(),
|
|
95
|
-
RELAY_AAD_TENANT_ID: z.string().optional(),
|
|
96
|
-
RELAY_AAD_CLIENT_ID: z.string().optional(),
|
|
97
|
-
RELAY_AAD_API_CLIENT_ID: z.string().optional(),
|
|
98
|
-
USER_ID: z.string().trim().min(1).max(256).default("admin"),
|
|
99
|
-
AGENTKNIGHT_MACHINE_NAME: z.string().trim().min(1).max(120).optional(),
|
|
100
|
-
AGENTKNIGHT_HOME: z.string().trim().min(1).optional(),
|
|
101
|
-
AGENTKNIGHT_WORKSPACE_ROOT: z.string().trim().min(1).optional(),
|
|
102
|
-
AGENTKNIGHT_CODING_AGENT: z.enum(["managed", ...CODING_AGENT_IDS]).default("managed"),
|
|
103
|
-
AGENTKNIGHT_GROUP_CHAT_ENABLED: EnabledBooleanStringSchema,
|
|
104
|
-
AGENTKNIGHT_PEER_CHAT_ENABLED: EnabledBooleanStringSchema,
|
|
105
|
-
PI_CODING_AGENT_DIR: OptionalPathSchema,
|
|
106
|
-
AGENTKNIGHT_CODEX_COMMAND: OptionalPathSchema,
|
|
107
|
-
AGENTKNIGHT_CLAUDE_COMMAND: OptionalPathSchema,
|
|
108
|
-
AGENTKNIGHT_ACP_COMMAND: OptionalPathSchema,
|
|
109
|
-
AGENTKNIGHT_ACP_ARGS: AcpArgumentsSchema,
|
|
110
|
-
SESSION_REFRESH_INTERVAL_MS: z.coerce.number().int().min(5e3).max(36e5).default(3e4),
|
|
111
|
-
HEARTBEAT_INTERVAL_MS: z.coerce.number().int().min(5e3).max(12e4).default(15e3),
|
|
112
|
-
LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
|
|
113
|
-
SHOW_PAIRING_QR: BooleanStringSchema,
|
|
114
|
-
PAIRING_PAGE_ENABLED: EnabledBooleanStringSchema,
|
|
115
|
-
PAIRING_PAGE_PORT: z.coerce.number().int().min(1024).max(65535).default(defaultPairingPagePort),
|
|
116
|
-
PC_AGENT_EXIT_AFTER_SNAPSHOT: BooleanStringSchema,
|
|
117
|
-
SNAPSHOT_SUPPRESSION_ENABLED: EnabledBooleanStringSchema,
|
|
118
|
-
TIMELINE_COMPRESSION_ENABLED: BooleanStringSchema,
|
|
119
|
-
TIMELINE_INCREMENTAL_ENABLED: EnabledBooleanStringSchema,
|
|
120
|
-
SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE: BooleanStringSchema,
|
|
121
|
-
SESSION_IMAGES_STORAGE_ACCOUNT: SessionImagesConfigSchema.shape.storageAccount.optional(),
|
|
122
|
-
SESSION_IMAGES_STORAGE_CONTAINER: SessionImagesConfigSchema.shape.storageContainer.optional(),
|
|
123
|
-
SECURE_MESSAGE_PACKET_BUDGET: z.coerce.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).default(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH)
|
|
124
|
-
}).superRefine((value, context) => {
|
|
125
|
-
if (value.SESSION_IMAGES_STORAGE_CONTAINER !== void 0 && value.SESSION_IMAGES_STORAGE_ACCOUNT === void 0) {
|
|
126
|
-
context.addIssue({
|
|
127
|
-
code: "custom",
|
|
128
|
-
path: ["SESSION_IMAGES_STORAGE_ACCOUNT"],
|
|
129
|
-
message: "An explicit legacy image container requires its storage account."
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
if (value.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE) {
|
|
133
|
-
if (!SessionImageRelayUrlSchema.safeParse(value.RELAY_URL).success) {
|
|
134
|
-
context.addIssue({
|
|
135
|
-
code: "custom",
|
|
136
|
-
path: ["RELAY_URL"],
|
|
137
|
-
message: "Session images require an HTTPS Relay origin without a path, credentials, query or fragment"
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
if (value.RELAY_AUTH === "token" && value.RELAY_TOKEN === void 0) {
|
|
142
|
-
context.addIssue({ code: "custom", path: ["RELAY_TOKEN"], message: "Token authentication requires RELAY_TOKEN" });
|
|
143
|
-
}
|
|
144
|
-
if (value.AGENTKNIGHT_CODING_AGENT === "acp" && value.AGENTKNIGHT_ACP_COMMAND === void 0) {
|
|
145
|
-
context.addIssue({
|
|
146
|
-
code: "custom",
|
|
147
|
-
path: ["AGENTKNIGHT_ACP_COMMAND"],
|
|
148
|
-
message: "ACP requires an installed agent executable in AGENTKNIGHT_ACP_COMMAND"
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
});
|
|
152
|
-
function codingAgentConfig(environment) {
|
|
153
|
-
switch (environment.AGENTKNIGHT_CODING_AGENT) {
|
|
154
|
-
case "managed":
|
|
155
|
-
return {
|
|
156
|
-
kind: "managed",
|
|
157
|
-
...environment.AGENTKNIGHT_CODEX_COMMAND === void 0 ? {} : { codexCommand: environment.AGENTKNIGHT_CODEX_COMMAND },
|
|
158
|
-
...environment.AGENTKNIGHT_CLAUDE_COMMAND === void 0 ? {} : { claudeCommand: environment.AGENTKNIGHT_CLAUDE_COMMAND },
|
|
159
|
-
...environment.PI_CODING_AGENT_DIR === void 0 ? {} : { piDirectory: environment.PI_CODING_AGENT_DIR },
|
|
160
|
-
...environment.AGENTKNIGHT_ACP_COMMAND === void 0 ? {} : {
|
|
161
|
-
acp: { command: environment.AGENTKNIGHT_ACP_COMMAND, args: environment.AGENTKNIGHT_ACP_ARGS }
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
case "copilot":
|
|
165
|
-
return { kind: "copilot" };
|
|
166
|
-
case "pi":
|
|
167
|
-
return {
|
|
168
|
-
kind: "pi",
|
|
169
|
-
...environment.PI_CODING_AGENT_DIR === void 0 ? {} : { agentDirectory: environment.PI_CODING_AGENT_DIR }
|
|
170
|
-
};
|
|
171
|
-
case "codex":
|
|
172
|
-
return {
|
|
173
|
-
kind: "codex",
|
|
174
|
-
...environment.AGENTKNIGHT_CODEX_COMMAND === void 0 ? {} : { command: environment.AGENTKNIGHT_CODEX_COMMAND }
|
|
175
|
-
};
|
|
176
|
-
case "claude":
|
|
177
|
-
return {
|
|
178
|
-
kind: "claude",
|
|
179
|
-
...environment.AGENTKNIGHT_CLAUDE_COMMAND === void 0 ? {} : { command: environment.AGENTKNIGHT_CLAUDE_COMMAND }
|
|
180
|
-
};
|
|
181
|
-
case "acp":
|
|
182
|
-
if (environment.AGENTKNIGHT_ACP_COMMAND === void 0) {
|
|
183
|
-
throw new Error("AGENTKNIGHT_ACP_COMMAND is required");
|
|
184
|
-
}
|
|
185
|
-
return {
|
|
186
|
-
kind: "acp",
|
|
187
|
-
command: environment.AGENTKNIGHT_ACP_COMMAND,
|
|
188
|
-
args: environment.AGENTKNIGHT_ACP_ARGS
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
function loadConfig(environment = process.env, options = {}) {
|
|
193
|
-
let startup = loadStartupConfig(environment, options);
|
|
194
|
-
if (startup.relayAuthentication.mode === "auto" && options.relayCredential !== void 0) {
|
|
195
|
-
const discovered = RelayAuthenticationSchema.safeParse(options.relayCredential.authentication);
|
|
196
|
-
if (!discovered.success) throw new Error("Relay authentication discovery must finish before connecting.");
|
|
197
|
-
const authentication = discovered.data;
|
|
198
|
-
startup = loadStartupConfig({
|
|
199
|
-
...environment,
|
|
200
|
-
RELAY_AUTH: authentication.mode,
|
|
201
|
-
...authentication.mode === "aad" ? {
|
|
202
|
-
RELAY_AAD_TENANT_ID: authentication.tenantId,
|
|
203
|
-
RELAY_AAD_CLIENT_ID: authentication.clientId,
|
|
204
|
-
RELAY_AAD_API_CLIENT_ID: authentication.apiClientId
|
|
205
|
-
} : {}
|
|
206
|
-
}, options);
|
|
207
|
-
}
|
|
208
|
-
const { relayAuthentication, ...settings2 } = startup;
|
|
209
|
-
if (relayAuthentication.mode === "token") {
|
|
210
|
-
return { ...settings2, relayToken: relayAuthentication.token, userId: relayAuthentication.userId };
|
|
211
|
-
}
|
|
212
|
-
if (options.relayCredential === void 0) {
|
|
213
|
-
throw new Error("Sign in with Microsoft on the local AgentKnight page before connecting to Relay.");
|
|
214
|
-
}
|
|
215
|
-
if (relayAuthentication.mode === "aad" && options.relayCredential.relayAuthorization === void 0) {
|
|
216
|
-
throw new Error("AAD requires an OS-broker token provider. Sign in again.");
|
|
217
|
-
}
|
|
218
|
-
return {
|
|
219
|
-
...settings2,
|
|
220
|
-
relayToken: z.string().min(relayAuthentication.mode === "aad" ? 1 : 32).max(relayAuthentication.mode === "aad" ? 32768 : 4096).parse(options.relayCredential.token),
|
|
221
|
-
...options.relayCredential.relayAuthorization === void 0 ? {} : {
|
|
222
|
-
relayAuthorization: options.relayCredential.relayAuthorization
|
|
223
|
-
},
|
|
224
|
-
userId: z.string().min(1).max(256).parse(options.relayCredential.user.userId)
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
function loadStartupConfig(environment = process.env, options = {}) {
|
|
228
|
-
const normalizedEnvironment = normalizeClientEnvironment(environment);
|
|
229
|
-
const initialSelection = options.agents === void 0 ? void 0 : AgentSelectionSchema.parse({ agents: options.agents });
|
|
230
|
-
const startupEnvironment = ["auto", "microsoft", "aad"].includes(normalizedEnvironment.RELAY_AUTH ?? "") ? { ...normalizedEnvironment, RELAY_TOKEN: void 0, USER_ID: void 0 } : normalizedEnvironment;
|
|
231
|
-
const parsed = EnvironmentSchema.parse(initialSelection === void 0 ? startupEnvironment : { ...startupEnvironment, AGENTKNIGHT_CODING_AGENT: "managed" });
|
|
232
|
-
const engine = codingAgentConfig(parsed);
|
|
233
|
-
let aad;
|
|
234
|
-
if (parsed.RELAY_AUTH === "aad") {
|
|
235
|
-
const id = z.uuid().transform((value) => value.toLowerCase());
|
|
236
|
-
aad = {
|
|
237
|
-
mode: "aad",
|
|
238
|
-
tenantId: id.parse(parsed.RELAY_AAD_TENANT_ID),
|
|
239
|
-
clientId: id.parse(parsed.RELAY_AAD_CLIENT_ID),
|
|
240
|
-
apiClientId: id.parse(parsed.RELAY_AAD_API_CLIENT_ID)
|
|
241
|
-
};
|
|
242
|
-
if (!SessionImageRelayUrlSchema.safeParse(parsed.RELAY_URL).success || aad.clientId === aad.apiClientId || parsed.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE) {
|
|
243
|
-
throw new Error("AAD requires an HTTPS Relay origin, independent API/native applications, and cloud images disabled.");
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
return {
|
|
247
|
-
relayUrl: parsed.RELAY_URL,
|
|
248
|
-
relayAuthentication: aad ?? (parsed.RELAY_AUTH === "microsoft" ? { mode: "microsoft" } : parsed.RELAY_AUTH === "auto" || parsed.RELAY_TOKEN === void 0 ? { mode: "auto" } : { mode: "token", token: parsed.RELAY_TOKEN, userId: parsed.USER_ID }),
|
|
249
|
-
...parsed.AGENTKNIGHT_MACHINE_NAME === void 0 ? {} : { machineName: parsed.AGENTKNIGHT_MACHINE_NAME },
|
|
250
|
-
...parsed.AGENTKNIGHT_WORKSPACE_ROOT === void 0 ? {} : { workspaceRoot: parsed.AGENTKNIGHT_WORKSPACE_ROOT },
|
|
251
|
-
dataDirectory: parsed.AGENTKNIGHT_HOME ?? defaultClientHome(),
|
|
252
|
-
refreshIntervalMs: parsed.SESSION_REFRESH_INTERVAL_MS,
|
|
253
|
-
heartbeatIntervalMs: parsed.HEARTBEAT_INTERVAL_MS,
|
|
254
|
-
logLevel: parsed.LOG_LEVEL,
|
|
255
|
-
showPairingQr: parsed.SHOW_PAIRING_QR,
|
|
256
|
-
pairingPageEnabled: parsed.PAIRING_PAGE_ENABLED,
|
|
257
|
-
pairingPagePort: parsed.PAIRING_PAGE_PORT,
|
|
258
|
-
exitAfterSnapshot: parsed.PC_AGENT_EXIT_AFTER_SNAPSHOT,
|
|
259
|
-
codingAgent: engine.kind === "managed" && initialSelection !== void 0 ? { ...engine, initialSelection } : engine,
|
|
260
|
-
groupChatEnabled: parsed.AGENTKNIGHT_GROUP_CHAT_ENABLED,
|
|
261
|
-
peerChatEnabled: parsed.AGENTKNIGHT_PEER_CHAT_ENABLED,
|
|
262
|
-
snapshotSuppressionEnabled: parsed.SNAPSHOT_SUPPRESSION_ENABLED,
|
|
263
|
-
timelineCompressionEnabled: parsed.TIMELINE_COMPRESSION_ENABLED,
|
|
264
|
-
timelineIncrementalEnabled: parsed.TIMELINE_INCREMENTAL_ENABLED,
|
|
265
|
-
secureMessagePacketBudget: parsed.SECURE_MESSAGE_PACKET_BUDGET,
|
|
266
|
-
sessionImagesEnabled: parsed.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE,
|
|
267
|
-
...parsed.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE && parsed.SESSION_IMAGES_STORAGE_ACCOUNT !== void 0 ? { sessionImages: {
|
|
268
|
-
allowUnencryptedStorage: true,
|
|
269
|
-
storageAccount: parsed.SESSION_IMAGES_STORAGE_ACCOUNT,
|
|
270
|
-
storageContainer: parsed.SESSION_IMAGES_STORAGE_CONTAINER ?? "session-images"
|
|
271
|
-
} } : {}
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// src/pairing-page.ts
|
|
276
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
277
|
-
import { createServer } from "node:http";
|
|
278
|
-
import QRCode from "qrcode";
|
|
279
|
-
import { AgentSelectionSchema as AgentSelectionSchema2 } from "@agentknight/sdk/configuration";
|
|
280
|
-
|
|
281
|
-
// src/agent-selection-page.ts
|
|
282
|
-
import { codingAgentPresentation } from "@agentknight/sdk/configuration";
|
|
283
|
-
|
|
284
|
-
// src/local-page-html.ts
|
|
285
|
-
function escapeHtml(value) {
|
|
286
|
-
return value.replace(/[&<>"']/g, (character) => {
|
|
287
|
-
switch (character) {
|
|
288
|
-
case "&":
|
|
289
|
-
return "&";
|
|
290
|
-
case "<":
|
|
291
|
-
return "<";
|
|
292
|
-
case ">":
|
|
293
|
-
return ">";
|
|
294
|
-
case '"':
|
|
295
|
-
return """;
|
|
296
|
-
case "'":
|
|
297
|
-
return "'";
|
|
298
|
-
default:
|
|
299
|
-
return character;
|
|
300
|
-
}
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
function relayDisplayUrl(value) {
|
|
304
|
-
let url;
|
|
305
|
-
try {
|
|
306
|
-
url = new URL(value);
|
|
307
|
-
} catch {
|
|
308
|
-
return "\u2014";
|
|
309
|
-
}
|
|
310
|
-
if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) return "\u2014";
|
|
311
|
-
url.username = "";
|
|
312
|
-
url.password = "";
|
|
313
|
-
url.search = "";
|
|
314
|
-
url.hash = "";
|
|
315
|
-
return url.href;
|
|
316
|
-
}
|
|
317
|
-
function relayAccountUrl(value) {
|
|
318
|
-
let url;
|
|
319
|
-
try {
|
|
320
|
-
url = new URL(relayDisplayUrl(value));
|
|
321
|
-
} catch {
|
|
322
|
-
return void 0;
|
|
323
|
-
}
|
|
324
|
-
if (url.protocol === "wss:") url.protocol = "https:";
|
|
325
|
-
if (url.protocol === "ws:") url.protocol = "http:";
|
|
326
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname))) {
|
|
327
|
-
return void 0;
|
|
328
|
-
}
|
|
329
|
-
return new URL("/account", url).href;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// src/session-markdown.ts
|
|
333
|
-
import MarkdownIt from "markdown-it";
|
|
334
|
-
var markdown = new MarkdownIt({ html: false, breaks: true });
|
|
335
|
-
markdown.validateLink = (value) => {
|
|
336
|
-
try {
|
|
337
|
-
const url = new URL(value);
|
|
338
|
-
return ["https:", "http:"].includes(url.protocol) && !url.username && !url.password;
|
|
339
|
-
} catch {
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => {
|
|
344
|
-
const token = tokens[index];
|
|
345
|
-
if (token === void 0) throw new Error("Missing Markdown link token");
|
|
346
|
-
token.attrSet("target", "_blank");
|
|
347
|
-
token.attrSet("rel", "noopener noreferrer");
|
|
348
|
-
return renderer.renderToken(tokens, index, options);
|
|
349
|
-
};
|
|
350
|
-
markdown.renderer.rules.image = (tokens, index) => {
|
|
351
|
-
const token = tokens[index];
|
|
352
|
-
if (token === void 0) throw new Error("Missing Markdown image token");
|
|
353
|
-
const source = String(token.attrGet("src") ?? "");
|
|
354
|
-
const label = escapeHtml(token.content || "\u56FE\u7247");
|
|
355
|
-
return markdown.validateLink(source) ? `<a class="image-link" href="${escapeHtml(source)}" target="_blank" rel="noopener noreferrer">${label} \u2197</a>` : label;
|
|
356
|
-
};
|
|
357
|
-
markdown.renderer.rules.table_open = () => '<div class="table-scroll" tabindex="0" role="region" aria-label="\u8868\u683C"><table>';
|
|
358
|
-
markdown.renderer.rules.table_close = () => "</table></div>";
|
|
359
|
-
function renderSessionMarkdown(content) {
|
|
360
|
-
return markdown.render(content);
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// src/local-page-i18n.ts
|
|
364
|
-
import { createInstance } from "i18next";
|
|
365
|
-
|
|
366
|
-
// src/locales/en.json
|
|
367
|
-
var en_default = {
|
|
368
|
-
"settings.images": "Azure Blob images (not end-to-end encrypted)",
|
|
369
|
-
"settings.imagesError": "Could not save image storage settings. Try again.",
|
|
370
|
-
"settings.imagesUnavailable": "This Relay does not offer image storage. Reconnect and try again.",
|
|
371
|
-
language: "Language",
|
|
372
|
-
refresh: "Refresh",
|
|
373
|
-
retry: "Retry",
|
|
374
|
-
cancel: "Cancel",
|
|
375
|
-
details: "Details",
|
|
376
|
-
account: "Relay account",
|
|
377
|
-
"account.work": "Microsoft work account",
|
|
378
|
-
"account.personal": "Microsoft account",
|
|
379
|
-
"account.fallback": "Account {{id}}",
|
|
380
|
-
"account.legacy": "Legacy account",
|
|
381
|
-
"account.admin": "Administrator",
|
|
382
|
-
"account.user": "User",
|
|
383
|
-
"account.view": "View account",
|
|
384
|
-
"account.signedIn": "Signed in",
|
|
385
|
-
"account.connecting": "Connecting",
|
|
386
|
-
"account.disconnected": "Disconnected",
|
|
387
|
-
"account.error": "Sign-in error",
|
|
388
|
-
"account.unknown": "Status unknown",
|
|
389
|
-
"account.unavailable": "Could not update sign-in status. Refresh the page.",
|
|
390
|
-
"account.failure.disconnected": "The Relay connection was interrupted.",
|
|
391
|
-
"account.failure.invalid": "The Relay returned invalid account information.",
|
|
392
|
-
"account.failure.unsupported": "This Relay does not support account information. Upgrade the Relay.",
|
|
393
|
-
"account.failure.expired": "Your sign-in credential has expired. Sign in again.",
|
|
394
|
-
"account.failure.tls": "Could not read account information securely. Enable HTTPS certificate verification.",
|
|
395
|
-
"account.failure.read": "Could not read account information. Try refreshing later.",
|
|
396
|
-
"account.failure.connection": "Could not read account information. Check the Relay connection and refresh.",
|
|
397
|
-
"relay.connecting": "Connecting\u2026",
|
|
398
|
-
"relay.reconnect": "Reconnect",
|
|
399
|
-
"relay.disconnect": "Disconnect",
|
|
400
|
-
"relay.disconnecting": "Disconnecting\u2026",
|
|
401
|
-
"relay.statusError": "Could not update the Relay connection status. Refresh the page.",
|
|
402
|
-
"relay.reconnectError": "Could not reconnect to the Relay. Try again.",
|
|
403
|
-
"relay.disconnectError": "Could not disconnect from the Relay. Try again.",
|
|
404
|
-
deployment: "Deployment",
|
|
405
|
-
"deployment.version": "Version",
|
|
406
|
-
"deployment.upgraded": "Last upgraded",
|
|
407
|
-
"deployment.noUpgrade": "No record",
|
|
408
|
-
"deployment.config": "Configuration",
|
|
409
|
-
"deployment.environment": "Process environment",
|
|
410
|
-
"deployment.relay": "Relay URL",
|
|
411
|
-
agents: "Agent sync",
|
|
412
|
-
"agents.sync": "Sync",
|
|
413
|
-
"agents.enable": "Sync",
|
|
414
|
-
"agents.enableName": "Sync {{name}}",
|
|
415
|
-
"agents.connected": "Connected",
|
|
416
|
-
"agents.unavailable": "Unavailable",
|
|
417
|
-
"agents.single": "Single-agent mode",
|
|
418
|
-
"agents.empty": "No configurable agents",
|
|
419
|
-
"agents.dirty": "Unsaved changes",
|
|
420
|
-
"agents.saving": "Syncing\u2026",
|
|
421
|
-
"agents.saved": "Synced",
|
|
422
|
-
"agents.busy": "Sync is in progress. Try again shortly.",
|
|
423
|
-
"agents.saveError": "Could not sync. Try again.",
|
|
424
|
-
"agents.httpError": "Sync failed (HTTP {{status}}). Try again.",
|
|
425
|
-
"settings.group": "Agent group chat",
|
|
426
|
-
"settings.peer": "Cross-PC agent communication",
|
|
427
|
-
"settings.busy": "Settings are being saved. Try again shortly.",
|
|
428
|
-
"settings.groupError": "Could not save group chat settings. Refresh and try again.",
|
|
429
|
-
"settings.peerError": "Could not save cross-PC settings. Refresh and try again.",
|
|
430
|
-
pairing: "Pair a phone",
|
|
431
|
-
"pairing.qr": "Pairing QR code",
|
|
432
|
-
"pairing.text": "Pairing string",
|
|
433
|
-
"pairing.copy": "Copy",
|
|
434
|
-
"pairing.copied": "Copied",
|
|
435
|
-
"pairing.copyError": "Could not copy. Select the pairing string and copy it manually.",
|
|
436
|
-
"pairing.show": "Show QR code",
|
|
437
|
-
"pairing.refresh": "Refresh QR code",
|
|
438
|
-
"pairing.hide": "Hide",
|
|
439
|
-
"pairing.success": "Paired",
|
|
440
|
-
"pairing.invalid": "This QR code is no longer valid. Generate a new one.",
|
|
441
|
-
"pairing.expired": "This QR code has expired. Generate a new one.",
|
|
442
|
-
"pairing.statusError": "Could not confirm pairing status. Retrying.",
|
|
443
|
-
"pairing.generateError": "Could not generate a QR code. Try again.",
|
|
444
|
-
"pairing.offline": "The Relay is not connected. Reconnect and try again.",
|
|
445
|
-
clients: "Devices",
|
|
446
|
-
"clients.empty": "No pending or authorized devices",
|
|
447
|
-
"clients.pending": "Pending approval",
|
|
448
|
-
"clients.online": "Online",
|
|
449
|
-
"clients.offline": "Offline",
|
|
450
|
-
"clients.review": "Review",
|
|
451
|
-
"clients.reject": "Reject",
|
|
452
|
-
"clients.revoke": "Revoke access",
|
|
453
|
-
"clients.revokeConfirm": "Revoke access for {{name}}?",
|
|
454
|
-
"clients.loadError": "Could not update device authorizations. Refresh and try again.",
|
|
455
|
-
"clients.uncertain": "The result is unconfirmed. Refresh the device list before trying again.",
|
|
456
|
-
"clients.unsupported": "Device management requires an upgraded PC and Relay.",
|
|
457
|
-
"clients.allowTitle": "Allow device to connect?",
|
|
458
|
-
"clients.code": "Verification code",
|
|
459
|
-
"clients.allow": "Allow connection",
|
|
460
|
-
"clients.dismiss": "Not now",
|
|
461
|
-
sessions: "Sessions",
|
|
462
|
-
"sessions.count_one": "{{count}} session",
|
|
463
|
-
"sessions.count_other": "{{count}} sessions",
|
|
464
|
-
"sessions.noDirectory": "No directory",
|
|
465
|
-
"sessions.empty": "No local sessions",
|
|
466
|
-
session: "Session",
|
|
467
|
-
"session.you": "You",
|
|
468
|
-
"session.subagent": "Subagent",
|
|
469
|
-
"session.assistant": "Assistant",
|
|
470
|
-
"session.activities_one": "{{count}} activity",
|
|
471
|
-
"session.activities_other": "{{count}} activities",
|
|
472
|
-
"session.tasks_one": "{{count}} task",
|
|
473
|
-
"session.tasks_other": "{{count}} tasks",
|
|
474
|
-
"session.running": "Running",
|
|
475
|
-
"session.completed": "Completed",
|
|
476
|
-
"session.failed": "Failed",
|
|
477
|
-
"session.todo.pending": "Pending",
|
|
478
|
-
"session.todo.in_progress": "In progress",
|
|
479
|
-
"session.todo.done": "Done",
|
|
480
|
-
"session.plan": "Plan",
|
|
481
|
-
"session.planDeleted": "Plan deleted",
|
|
482
|
-
"session.navigation": "Session navigation",
|
|
483
|
-
"session.back": "Back to sessions",
|
|
484
|
-
"session.refresh": "Refresh latest",
|
|
485
|
-
"session.info": "View session information",
|
|
486
|
-
"session.machine": "Computer",
|
|
487
|
-
"session.agent": "Agent",
|
|
488
|
-
"session.directory": "Working directory",
|
|
489
|
-
"session.id": "Session ID",
|
|
490
|
-
"session.loadError": "Could not load session",
|
|
491
|
-
"session.reload": "Reload",
|
|
492
|
-
"session.older": "Load earlier messages",
|
|
493
|
-
"session.messages": "Session messages",
|
|
494
|
-
"session.empty": "No messages yet",
|
|
495
|
-
"session.emptyBody": "Messages will appear here when the session starts.",
|
|
496
|
-
"session.end": "Jump to end",
|
|
497
|
-
"session.missing": "This session was not found. Return to the list and refresh.",
|
|
498
|
-
"session.expired": "History has changed. Refresh the latest messages and try again.",
|
|
499
|
-
"session.unavailable": "Could not read this session. Try again or check the agent in the session list.",
|
|
500
|
-
"login.title": "Microsoft sign-in",
|
|
501
|
-
"login.connect": "Connect to Relay",
|
|
502
|
-
"login.confirm": "Confirm computer sign-in",
|
|
503
|
-
"login.launch": "Start AgentKnight",
|
|
504
|
-
"login.work": "Sign in with a work or school account",
|
|
505
|
-
"login.personal": "Sign in with a personal Microsoft account",
|
|
506
|
-
"login.signIn": "Sign in with Microsoft",
|
|
507
|
-
"login.retry": "Retry sign-in",
|
|
508
|
-
"login.continue": "Continue with Microsoft",
|
|
509
|
-
"login.discovering": "Detecting sign-in method\u2026",
|
|
510
|
-
"login.starting": "Signing in\u2026",
|
|
511
|
-
"login.confirming": "Confirming credentials\u2026",
|
|
512
|
-
"login.connecting": "Connecting\u2026",
|
|
513
|
-
"login.cancelling": "Cancelling\u2026",
|
|
514
|
-
"login.pollError": "Could not update sign-in status. Retrying.",
|
|
515
|
-
"login.error": "Microsoft sign-in failed. Try again.",
|
|
516
|
-
"login.error.discovery": "Could not detect the Relay sign-in method. Check its address and your connection.",
|
|
517
|
-
"login.error.automatic": "This Relay does not support automatic sign-in. Upgrade it or configure authentication explicitly.",
|
|
518
|
-
"login.error.secure": "Could not connect securely. Check the Relay address and your connection.",
|
|
519
|
-
"login.error.response": "The Relay returned an invalid sign-in response. Check its configuration.",
|
|
520
|
-
"login.error.browser": "This Relay does not support browser sign-in. Ask its administrator to upgrade it.",
|
|
521
|
-
"login.error.expired": "This sign-in request has expired. Sign in again.",
|
|
522
|
-
"login.error.unauthorized": "This account is not authorized. Contact the Relay administrator.",
|
|
523
|
-
"login.error.rateLimit": "Too many sign-in attempts. Try again later.",
|
|
524
|
-
"login.error.issued": "This sign-in request has already been used. Retry sign-in to safely start a new request.",
|
|
525
|
-
"login.error.exchange": "The credential exchange result is unknown. Retry sign-in to safely cancel the previous request.",
|
|
526
|
-
"login.error.confirmation": "Credential confirmation is unverified. Credentials are saved; retry to continue confirmation.",
|
|
527
|
-
"login.error.confirmationService": "The Relay confirmation service is unavailable. Credentials are saved; ask its administrator to restore the service.",
|
|
528
|
-
"login.error.revoked": "The saved Relay credential is no longer authorized. Sign in again.",
|
|
529
|
-
"login.error.verification": "The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification.",
|
|
530
|
-
"login.error.cleanup": "Sign-in cancellation is unverified. Retry, or restart AgentKnight after the request expires.",
|
|
531
|
-
"login.error.cancelled": "Sign-in was cancelled. Sign in again.",
|
|
532
|
-
"login.error.closed": "The sign-in service is closed. Restart AgentKnight.",
|
|
533
|
-
"login.error.identity": "The Relay credential belongs to a different computer or account. Check the configuration before signing in again.",
|
|
534
|
-
"login.error.store": "Could not access system credential storage. Unlock it and restart AgentKnight.",
|
|
535
|
-
"login.error.linuxStore": "Start or unlock a Secret Service keyring (such as GNOME Keyring) in the same user's D-Bus session, then retry. Credentials will not fall back to files or an in-memory keyring.",
|
|
536
|
-
"login.error.invalidCredential": "The saved Relay credential is invalid. Recover it in your system credential manager before signing in.",
|
|
537
|
-
"login.error.conflict": "Another Relay account or enrollment is saved on this computer. Resolve the conflict in your system credential manager.",
|
|
538
|
-
"login.error.retention": "The system did not retain the credential. Unlock credential storage and restart AgentKnight.",
|
|
539
|
-
"login.error.origin": "Use an HTTPS Relay origin without a path or credentials. HTTP is allowed only for literal loopback addresses.",
|
|
540
|
-
"login.error.platform": "Microsoft sign-in requires Windows Credential Manager, macOS Keychain, or Linux Secret Service. Use a supported system.",
|
|
541
|
-
"login.error.capacity": "The Relay credential exceeds system storage capacity. Existing credentials were not changed. Contact the Relay administrator."
|
|
542
|
-
};
|
|
543
|
-
|
|
544
|
-
// src/locales/zh-CN.json
|
|
545
|
-
var zh_CN_default = {
|
|
546
|
-
"settings.images": "Azure Blob \u56FE\u7247\uFF08\u975E\u7AEF\u5230\u7AEF\u52A0\u5BC6\uFF09",
|
|
547
|
-
"settings.imagesError": "\u65E0\u6CD5\u4FDD\u5B58\u56FE\u7247\u5B58\u50A8\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002",
|
|
548
|
-
"settings.imagesUnavailable": "\u6B64 Relay \u672A\u63D0\u4F9B\u56FE\u7247\u5B58\u50A8\uFF0C\u8BF7\u91CD\u8FDE\u540E\u91CD\u8BD5\u3002",
|
|
549
|
-
language: "\u8BED\u8A00",
|
|
550
|
-
refresh: "\u5237\u65B0",
|
|
551
|
-
retry: "\u91CD\u8BD5",
|
|
552
|
-
cancel: "\u53D6\u6D88",
|
|
553
|
-
details: "\u8BE6\u60C5",
|
|
554
|
-
account: "Relay \u8D26\u6237",
|
|
555
|
-
"account.work": "Microsoft \u5DE5\u4F5C\u8D26\u6237",
|
|
556
|
-
"account.personal": "Microsoft \u8D26\u6237",
|
|
557
|
-
"account.fallback": "\u8D26\u6237 {{id}}",
|
|
558
|
-
"account.legacy": "\u4F20\u7EDF\u8D26\u6237",
|
|
559
|
-
"account.admin": "\u7BA1\u7406\u5458",
|
|
560
|
-
"account.user": "\u666E\u901A\u7528\u6237",
|
|
561
|
-
"account.view": "\u67E5\u770B\u8D26\u6237",
|
|
562
|
-
"account.signedIn": "\u5DF2\u767B\u5F55",
|
|
563
|
-
"account.connecting": "\u8FDE\u63A5\u4E2D",
|
|
564
|
-
"account.disconnected": "\u5DF2\u65AD\u5F00",
|
|
565
|
-
"account.error": "\u767B\u5F55\u5F02\u5E38",
|
|
566
|
-
"account.unknown": "\u72B6\u6001\u672A\u77E5",
|
|
567
|
-
"account.unavailable": "\u65E0\u6CD5\u66F4\u65B0\u767B\u5F55\u72B6\u6001\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u3002",
|
|
568
|
-
"account.failure.disconnected": "Relay \u8FDE\u63A5\u5DF2\u65AD\u5F00\u3002",
|
|
569
|
-
"account.failure.invalid": "Relay \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8D26\u6237\u4FE1\u606F\u3002",
|
|
570
|
-
"account.failure.unsupported": "Relay \u5C1A\u4E0D\u652F\u6301\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u5347\u7EA7 Relay\u3002",
|
|
571
|
-
"account.failure.expired": "\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
|
|
572
|
-
"account.failure.tls": "\u65E0\u6CD5\u5B89\u5168\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u542F\u7528 HTTPS \u8BC1\u4E66\u9A8C\u8BC1\u3002",
|
|
573
|
-
"account.failure.read": "\u65E0\u6CD5\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0\u3002",
|
|
574
|
-
"account.failure.connection": "\u65E0\u6CD5\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5 Relay \u8FDE\u63A5\u540E\u5237\u65B0\u3002",
|
|
575
|
-
"relay.connecting": "\u8FDE\u63A5\u4E2D\u2026",
|
|
576
|
-
"relay.reconnect": "\u91CD\u8FDE",
|
|
577
|
-
"relay.disconnect": "\u65AD\u5F00\u8FDE\u63A5",
|
|
578
|
-
"relay.disconnecting": "\u6B63\u5728\u65AD\u5F00\u2026",
|
|
579
|
-
"relay.statusError": "\u65E0\u6CD5\u66F4\u65B0 Relay \u8FDE\u63A5\u72B6\u6001\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u3002",
|
|
580
|
-
"relay.reconnectError": "\u65E0\u6CD5\u91CD\u8FDE Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
581
|
-
"relay.disconnectError": "\u65E0\u6CD5\u65AD\u5F00 Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
582
|
-
deployment: "\u90E8\u7F72\u4FE1\u606F",
|
|
583
|
-
"deployment.version": "\u5F53\u524D\u7248\u672C",
|
|
584
|
-
"deployment.upgraded": "\u4E0A\u6B21\u5347\u7EA7",
|
|
585
|
-
"deployment.noUpgrade": "\u6682\u65E0\u8BB0\u5F55",
|
|
586
|
-
"deployment.config": "\u7528\u6237\u914D\u7F6E",
|
|
587
|
-
"deployment.environment": "\u8FDB\u7A0B\u73AF\u5883",
|
|
588
|
-
"deployment.relay": "Relay URL",
|
|
589
|
-
agents: "Agent \u540C\u6B65",
|
|
590
|
-
"agents.sync": "\u540C\u6B65",
|
|
591
|
-
"agents.enable": "\u5F00\u542F\u540C\u6B65",
|
|
592
|
-
"agents.enableName": "\u5F00\u542F\u540C\u6B65 {{name}}",
|
|
593
|
-
"agents.connected": "\u5DF2\u8FDE\u63A5",
|
|
594
|
-
"agents.unavailable": "\u4E0D\u53EF\u7528",
|
|
595
|
-
"agents.single": "\u5F53\u524D\u4E3A\u5355 Agent \u6A21\u5F0F",
|
|
596
|
-
"agents.empty": "\u6CA1\u6709\u53EF\u914D\u7F6E\u7684 Agent",
|
|
597
|
-
"agents.dirty": "\u5F85\u540C\u6B65",
|
|
598
|
-
"agents.saving": "\u540C\u6B65\u4E2D\u2026",
|
|
599
|
-
"agents.saved": "\u5DF2\u540C\u6B65",
|
|
600
|
-
"agents.busy": "\u6B63\u5728\u540C\u6B65\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
601
|
-
"agents.saveError": "\u540C\u6B65\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
|
|
602
|
-
"agents.httpError": "\u540C\u6B65\u5931\u8D25\uFF08HTTP {{status}}\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u3002",
|
|
603
|
-
"settings.group": "Agent \u7FA4\u804A",
|
|
604
|
-
"settings.peer": "Agent \u7684\u8DE8 PC \u901A\u4FE1",
|
|
605
|
-
"settings.busy": "\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
606
|
-
"settings.groupError": "\u7FA4\u804A\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002",
|
|
607
|
-
"settings.peerError": "\u8DE8 PC \u901A\u4FE1\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002",
|
|
608
|
-
pairing: "\u624B\u673A\u914D\u5BF9",
|
|
609
|
-
"pairing.qr": "\u914D\u5BF9\u4E8C\u7EF4\u7801",
|
|
610
|
-
"pairing.text": "\u914D\u5BF9\u5B57\u7B26\u4E32",
|
|
611
|
-
"pairing.copy": "\u590D\u5236",
|
|
612
|
-
"pairing.copied": "\u5DF2\u590D\u5236",
|
|
613
|
-
"pairing.copyError": "\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u914D\u5BF9\u5B57\u7B26\u4E32\u624B\u52A8\u590D\u5236\u3002",
|
|
614
|
-
"pairing.show": "\u663E\u793A\u4E8C\u7EF4\u7801",
|
|
615
|
-
"pairing.refresh": "\u5237\u65B0\u4E8C\u7EF4\u7801",
|
|
616
|
-
"pairing.hide": "\u9690\u85CF",
|
|
617
|
-
"pairing.success": "\u914D\u5BF9\u6210\u529F",
|
|
618
|
-
"pairing.invalid": "\u4E8C\u7EF4\u7801\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u663E\u793A\u3002",
|
|
619
|
-
"pairing.expired": "\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u663E\u793A\u3002",
|
|
620
|
-
"pairing.statusError": "\u65E0\u6CD5\u786E\u8BA4\u914D\u5BF9\u72B6\u6001\uFF0C\u6B63\u5728\u91CD\u8BD5\u3002",
|
|
621
|
-
"pairing.generateError": "\u65E0\u6CD5\u751F\u6210\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u91CD\u8BD5\u3002",
|
|
622
|
-
"pairing.offline": "Relay \u5C1A\u672A\u8FDE\u63A5\uFF0C\u8BF7\u91CD\u8FDE\u540E\u91CD\u8BD5\u3002",
|
|
623
|
-
clients: "\u8BBE\u5907",
|
|
624
|
-
"clients.empty": "\u6CA1\u6709\u5F85\u6279\u51C6\u6216\u5DF2\u6388\u6743\u7684\u5BA2\u6237\u7AEF",
|
|
625
|
-
"clients.pending": "\u5F85\u6279\u51C6",
|
|
626
|
-
"clients.online": "\u5728\u7EBF",
|
|
627
|
-
"clients.offline": "\u79BB\u7EBF",
|
|
628
|
-
"clients.review": "\u67E5\u770B\u8BF7\u6C42",
|
|
629
|
-
"clients.reject": "\u62D2\u7EDD",
|
|
630
|
-
"clients.revoke": "\u64A4\u9500\u6388\u6743",
|
|
631
|
-
"clients.revokeConfirm": "\u64A4\u9500 {{name}} \u7684\u8BBF\u95EE\u6388\u6743\uFF1F",
|
|
632
|
-
"clients.loadError": "\u65E0\u6CD5\u66F4\u65B0\u5BA2\u6237\u7AEF\u6388\u6743\uFF0C\u8BF7\u5237\u65B0\u91CD\u8BD5\u3002",
|
|
633
|
-
"clients.uncertain": "\u64CD\u4F5C\u7ED3\u679C\u5F85\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u5BA2\u6237\u7AEF\u5217\u8868\u3002",
|
|
634
|
-
"clients.unsupported": "\u5BA2\u6237\u7AEF\u7BA1\u7406\u9700\u8981\u5347\u7EA7 PC \u548C Relay\u3002",
|
|
635
|
-
"clients.allowTitle": "\u5141\u8BB8\u8BBE\u5907\u8FDE\u63A5\uFF1F",
|
|
636
|
-
"clients.code": "\u6838\u5BF9\u7801",
|
|
637
|
-
"clients.allow": "\u5141\u8BB8\u8FDE\u63A5",
|
|
638
|
-
"clients.dismiss": "\u6682\u4E0D\u5904\u7406",
|
|
639
|
-
sessions: "\u4F1A\u8BDD",
|
|
640
|
-
"sessions.count_one": "{{count}} \u4E2A\u4F1A\u8BDD",
|
|
641
|
-
"sessions.count_other": "{{count}} \u4E2A\u4F1A\u8BDD",
|
|
642
|
-
"sessions.noDirectory": "\u672A\u63D0\u4F9B\u76EE\u5F55",
|
|
643
|
-
"sessions.empty": "\u6CA1\u6709\u672C\u5730\u4F1A\u8BDD",
|
|
644
|
-
session: "\u4F1A\u8BDD",
|
|
645
|
-
"session.you": "\u4F60",
|
|
646
|
-
"session.subagent": "\u5B50 Agent",
|
|
647
|
-
"session.assistant": "\u52A9\u624B",
|
|
648
|
-
"session.activities_one": "{{count}} \u9879\u6D3B\u52A8",
|
|
649
|
-
"session.activities_other": "{{count}} \u9879\u6D3B\u52A8",
|
|
650
|
-
"session.tasks_one": "{{count}} \u9879\u4EFB\u52A1",
|
|
651
|
-
"session.tasks_other": "{{count}} \u9879\u4EFB\u52A1",
|
|
652
|
-
"session.running": "\u8FDB\u884C\u4E2D",
|
|
653
|
-
"session.completed": "\u5DF2\u5B8C\u6210",
|
|
654
|
-
"session.failed": "\u5931\u8D25",
|
|
655
|
-
"session.todo.pending": "\u5F85\u5904\u7406",
|
|
656
|
-
"session.todo.in_progress": "\u8FDB\u884C\u4E2D",
|
|
657
|
-
"session.todo.done": "\u5DF2\u5B8C\u6210",
|
|
658
|
-
"session.plan": "\u8BA1\u5212",
|
|
659
|
-
"session.planDeleted": "\u8BA1\u5212\u5DF2\u5220\u9664",
|
|
660
|
-
"session.navigation": "\u4F1A\u8BDD\u5BFC\u822A",
|
|
661
|
-
"session.back": "\u8FD4\u56DE\u4F1A\u8BDD\u5217\u8868",
|
|
662
|
-
"session.refresh": "\u5237\u65B0\u6700\u65B0",
|
|
663
|
-
"session.info": "\u67E5\u770B\u4F1A\u8BDD\u4FE1\u606F",
|
|
664
|
-
"session.machine": "\u7535\u8111",
|
|
665
|
-
"session.agent": "Agent",
|
|
666
|
-
"session.directory": "\u5DE5\u4F5C\u76EE\u5F55",
|
|
667
|
-
"session.id": "Session ID",
|
|
668
|
-
"session.loadError": "\u672A\u80FD\u52A0\u8F7D\u4F1A\u8BDD",
|
|
669
|
-
"session.reload": "\u91CD\u65B0\u52A0\u8F7D",
|
|
670
|
-
"session.older": "\u67E5\u770B\u66F4\u65E9\u6D88\u606F",
|
|
671
|
-
"session.messages": "\u4F1A\u8BDD\u6D88\u606F",
|
|
672
|
-
"session.empty": "\u8FD8\u6CA1\u6709\u6D88\u606F",
|
|
673
|
-
"session.emptyBody": "\u4F1A\u8BDD\u5F00\u59CB\u540E\uFF0C\u6D88\u606F\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002",
|
|
674
|
-
"session.end": "\u8DF3\u5230\u672B\u5C3E",
|
|
675
|
-
"session.missing": "\u627E\u4E0D\u5230\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u8BF7\u8FD4\u56DE\u5217\u8868\u5237\u65B0\u3002",
|
|
676
|
-
"session.expired": "\u5386\u53F2\u8BB0\u5F55\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u6700\u65B0\u6D88\u606F\u540E\u91CD\u8BD5\u3002",
|
|
677
|
-
"session.unavailable": "\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u8BD5\u6216\u8FD4\u56DE\u5217\u8868\u68C0\u67E5 Agent \u72B6\u6001\u3002",
|
|
678
|
-
"login.title": "Microsoft \u767B\u5F55",
|
|
679
|
-
"login.connect": "\u8FDE\u63A5 Relay",
|
|
680
|
-
"login.confirm": "\u786E\u8BA4\u7535\u8111\u767B\u5F55",
|
|
681
|
-
"login.launch": "\u542F\u52A8 AgentKnight",
|
|
682
|
-
"login.work": "\u4F7F\u7528\u5DE5\u4F5C\u6216\u5B66\u6821\u8D26\u6237\u767B\u5F55",
|
|
683
|
-
"login.personal": "\u4F7F\u7528 Microsoft \u4E2A\u4EBA\u8D26\u6237\u767B\u5F55",
|
|
684
|
-
"login.signIn": "\u4F7F\u7528 Microsoft \u767B\u5F55",
|
|
685
|
-
"login.retry": "\u91CD\u8BD5\u767B\u5F55",
|
|
686
|
-
"login.continue": "\u7EE7\u7EED Microsoft \u767B\u5F55",
|
|
687
|
-
"login.discovering": "\u6B63\u5728\u8BC6\u522B\u767B\u5F55\u65B9\u5F0F\u2026",
|
|
688
|
-
"login.starting": "\u6B63\u5728\u767B\u5F55\u2026",
|
|
689
|
-
"login.confirming": "\u6B63\u5728\u786E\u8BA4\u767B\u5F55\u51ED\u636E\u2026",
|
|
690
|
-
"login.connecting": "\u6B63\u5728\u8FDE\u63A5\u2026",
|
|
691
|
-
"login.cancelling": "\u6B63\u5728\u53D6\u6D88\u2026",
|
|
692
|
-
"login.pollError": "\u65E0\u6CD5\u66F4\u65B0\u767B\u5F55\u72B6\u6001\uFF0C\u6B63\u5728\u91CD\u8BD5\u3002",
|
|
693
|
-
"login.error": "Microsoft \u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
|
|
694
|
-
"login.error.discovery": "\u65E0\u6CD5\u8BC6\u522B Relay \u767B\u5F55\u65B9\u5F0F\uFF0C\u8BF7\u68C0\u67E5\u5730\u5740\u548C\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002",
|
|
695
|
-
"login.error.automatic": "\u6B64 Relay \u4E0D\u652F\u6301\u81EA\u52A8\u767B\u5F55\uFF0C\u8BF7\u5347\u7EA7 Relay \u6216\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u6307\u5B9A\u767B\u5F55\u65B9\u5F0F\u3002",
|
|
696
|
-
"login.error.secure": "\u65E0\u6CD5\u5B89\u5168\u8FDE\u63A5 Relay\uFF0C\u8BF7\u68C0\u67E5 Relay \u5730\u5740\u548C\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002",
|
|
697
|
-
"login.error.response": "Relay \u8FD4\u56DE\u7684\u767B\u5F55\u54CD\u5E94\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 Relay \u914D\u7F6E\u3002",
|
|
698
|
-
"login.error.browser": "\u6B64 Relay \u4E0D\u652F\u6301\u6D4F\u89C8\u5668\u767B\u5F55\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u5347\u7EA7 Relay \u540E\u91CD\u8BD5\u3002",
|
|
699
|
-
"login.error.expired": "\u767B\u5F55\u8BF7\u6C42\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
|
|
700
|
-
"login.error.unauthorized": "\u6B64\u8D26\u6237\u672A\u83B7 Relay \u6388\u6743\uFF0C\u8BF7\u8054\u7CFB Relay \u7BA1\u7406\u5458\u3002",
|
|
701
|
-
"login.error.rateLimit": "\u767B\u5F55\u5C1D\u8BD5\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
702
|
-
"login.error.issued": "\u6B64\u767B\u5F55\u8BF7\u6C42\u5DF2\u88AB\u4F7F\u7528\uFF0C\u8BF7\u91CD\u8BD5\u767B\u5F55\u4EE5\u5B89\u5168\u53D1\u8D77\u65B0\u8BF7\u6C42\u3002",
|
|
703
|
-
"login.error.exchange": "\u51ED\u636E\u4EA4\u6362\u7ED3\u679C\u672A\u77E5\uFF0C\u8BF7\u91CD\u8BD5\u767B\u5F55\u4EE5\u5B89\u5168\u53D6\u6D88\u539F\u8BF7\u6C42\u5E76\u91CD\u65B0\u767B\u5F55\u3002",
|
|
704
|
-
"login.error.confirmation": "\u51ED\u636E\u786E\u8BA4\u7ED3\u679C\u672A\u77E5\u3002\u51ED\u636E\u5DF2\u4FDD\u5B58\uFF0C\u91CD\u8BD5\u5C06\u7EE7\u7EED\u786E\u8BA4\u3002",
|
|
705
|
-
"login.error.confirmationService": "Relay \u786E\u8BA4\u670D\u52A1\u5F02\u5E38\u3002\u51ED\u636E\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u6062\u590D\u670D\u52A1\u540E\u91CD\u8BD5\u3002",
|
|
706
|
-
"login.error.revoked": "\u5DF2\u4FDD\u5B58\u7684 Relay \u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
|
|
707
|
-
"login.error.verification": "Relay \u65E0\u6CD5\u9A8C\u8BC1\u5DF2\u4FDD\u5B58\u7684\u51ED\u636E\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u542F\u7528 Microsoft \u51ED\u636E\u9A8C\u8BC1\u540E\u91CD\u8BD5\u3002",
|
|
708
|
-
"login.error.cleanup": "\u65E0\u6CD5\u786E\u8BA4\u767B\u5F55\u8BF7\u6C42\u662F\u5426\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u8BD5\uFF0C\u6216\u7B49\u5F85\u8BF7\u6C42\u8FC7\u671F\u540E\u91CD\u542F AgentKnight\u3002",
|
|
709
|
-
"login.error.cancelled": "\u767B\u5F55\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
|
|
710
|
-
"login.error.closed": "\u767B\u5F55\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u91CD\u542F AgentKnight \u540E\u91CD\u65B0\u767B\u5F55\u3002",
|
|
711
|
-
"login.error.identity": "Relay \u51ED\u636E\u4E0E\u6B64\u7535\u8111\u6216\u8D26\u6237\u4E0D\u5339\u914D\uFF0C\u8BF7\u68C0\u67E5 Relay \u914D\u7F6E\u540E\u91CD\u65B0\u767B\u5F55\u3002",
|
|
712
|
-
"login.error.store": "\u65E0\u6CD5\u8BBF\u95EE\u7CFB\u7EDF\u51ED\u636E\u5B58\u50A8\uFF0C\u8BF7\u89E3\u9501\u51ED\u636E\u5B58\u50A8\u5E76\u91CD\u542F AgentKnight\u3002",
|
|
713
|
-
"login.error.linuxStore": "\u8BF7\u5728\u540C\u4E00\u7528\u6237\u7684 D-Bus \u4F1A\u8BDD\u4E2D\u542F\u52A8\u6216\u89E3\u9501 Secret Service \u5BC6\u94A5\u73AF\uFF08\u5982 GNOME Keyring\uFF09\u540E\u91CD\u8BD5\u3002\u51ED\u636E\u4E0D\u4F1A\u964D\u7EA7\u4FDD\u5B58\u5230\u6587\u4EF6\u6216\u5185\u5B58\u5BC6\u94A5\u73AF\u3002",
|
|
714
|
-
"login.error.invalidCredential": "\u5DF2\u4FDD\u5B58\u7684 Relay \u51ED\u636E\u65E0\u6548\uFF0C\u8BF7\u5148\u5728\u7CFB\u7EDF\u51ED\u636E\u7BA1\u7406\u5668\u4E2D\u6062\u590D\u51ED\u636E\u518D\u767B\u5F55\u3002",
|
|
715
|
-
"login.error.conflict": "\u6B64\u7535\u8111\u5DF2\u4FDD\u5B58\u5176\u4ED6 Relay \u8D26\u6237\u6216\u767B\u5F55\u8BF7\u6C42\uFF0C\u8BF7\u5148\u5728\u7CFB\u7EDF\u51ED\u636E\u7BA1\u7406\u5668\u4E2D\u5904\u7406\u51B2\u7A81\u3002",
|
|
716
|
-
"login.error.retention": "\u7CFB\u7EDF\u672A\u80FD\u4FDD\u5B58\u767B\u5F55\u51ED\u636E\uFF0C\u8BF7\u89E3\u9501\u51ED\u636E\u5B58\u50A8\u5E76\u91CD\u542F AgentKnight\u3002",
|
|
717
|
-
"login.error.origin": "\u8BF7\u4F7F\u7528\u4E0D\u542B\u8DEF\u5F84\u6216\u51ED\u636E\u7684 HTTPS Relay \u5730\u5740\uFF1BHTTP \u4EC5\u5141\u8BB8\u672C\u673A\u56DE\u73AF IP \u5730\u5740\u3002",
|
|
718
|
-
"login.error.platform": "Microsoft \u767B\u5F55\u9700\u8981 Windows \u51ED\u636E\u7BA1\u7406\u5668\u3001macOS \u94A5\u5319\u4E32\u6216 Linux Secret Service\uFF0C\u8BF7\u4F7F\u7528\u53D7\u652F\u6301\u7684\u7CFB\u7EDF\u3002",
|
|
719
|
-
"login.error.capacity": "Relay \u51ED\u636E\u8D85\u51FA\u7CFB\u7EDF\u5B58\u50A8\u5BB9\u91CF\uFF0C\u539F\u51ED\u636E\u672A\u66F4\u6539\u3002\u8BF7\u8054\u7CFB Relay \u7BA1\u7406\u5458\u3002"
|
|
720
|
-
};
|
|
721
|
-
|
|
722
|
-
// src/local-page-i18n.ts
|
|
723
|
-
var localPageResources = { en: { translation: en_default }, "zh-CN": { translation: zh_CN_default } };
|
|
724
|
-
var i18n = createInstance();
|
|
725
|
-
void i18n.init({
|
|
726
|
-
resources: localPageResources,
|
|
727
|
-
lng: "zh-CN",
|
|
728
|
-
fallbackLng: "en",
|
|
729
|
-
initAsync: false,
|
|
730
|
-
keySeparator: false,
|
|
731
|
-
interpolation: { escapeValue: false }
|
|
732
|
-
});
|
|
733
|
-
function localPageTranslator(locale = "zh-CN") {
|
|
734
|
-
return (key, values = {}) => i18n.t(key, { ...values, lng: locale });
|
|
735
|
-
}
|
|
736
|
-
function localPageErrorPayload(error, locale) {
|
|
737
|
-
return typeof error === "string" ? { error } : { error: localPageTranslator(locale)(error.key), errorKey: error.key };
|
|
738
|
-
}
|
|
739
|
-
function isLocalPageLocale(value) {
|
|
740
|
-
return value === "zh-CN" || value === "en";
|
|
741
|
-
}
|
|
742
|
-
function resolveLocalPageLocale(cookie, acceptLanguage) {
|
|
743
|
-
const saved = cookie?.split(";").map((part) => part.trim()).find((part) => part.startsWith("ak-language="))?.slice(12);
|
|
744
|
-
if (isLocalPageLocale(saved)) return saved;
|
|
745
|
-
const languages = (acceptLanguage ?? "").split(",").map((entry, order) => {
|
|
746
|
-
const [tag = "", ...parameters] = entry.trim().split(";");
|
|
747
|
-
const quality = parameters.find((parameter) => parameter.trim().startsWith("q="));
|
|
748
|
-
return { tag: tag.toLowerCase(), quality: quality === void 0 ? 1 : Number(quality.trim().slice(2)), order };
|
|
749
|
-
}).filter((entry) => Number.isFinite(entry.quality) && entry.quality > 0 && entry.quality <= 1).sort((a, b) => b.quality - a.quality || a.order - b.order);
|
|
750
|
-
for (const { tag } of languages) {
|
|
751
|
-
if (tag === "zh" || tag.startsWith("zh-")) return "zh-CN";
|
|
752
|
-
if (tag === "en" || tag.startsWith("en-")) return "en";
|
|
753
|
-
}
|
|
754
|
-
return "zh-CN";
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
// src/local-page-layout.ts
|
|
758
|
-
var icons = {
|
|
759
|
-
back: '<path d="m12 5-7 7 7 7M5 12h14"/>',
|
|
760
|
-
refresh: '<path d="M20 7v5h-5M4 17v-5h5"/><path d="M6.1 7a7 7 0 0 1 11.6-1L20 9M4 15l2.3 3A7 7 0 0 0 18 17"/>',
|
|
761
|
-
folder: '<path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v10H3Z"/>',
|
|
762
|
-
info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7v1"/>',
|
|
763
|
-
chat: '<path d="M21 11a8 8 0 0 1-8 8H5l-3 3V11a8 8 0 0 1 8-8h3a8 8 0 0 1 8 8Z"/><path d="M7 9h9M7 13h6"/>',
|
|
764
|
-
agent: '<path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5Z"/>',
|
|
765
|
-
chevron: '<path d="m9 5 7 7-7 7"/>',
|
|
766
|
-
down: '<path d="M12 4v16m-6-6 6 6 6-6"/>',
|
|
767
|
-
file: '<path d="M14 2H5v20h14V7l-5-5Zm0 0v6h5M8 13h8M8 17h6"/>',
|
|
768
|
-
check: '<path d="m5 12 4 4L19 6"/>',
|
|
769
|
-
warning: '<path d="m12 3 10 18H2L12 3Zm0 6v5m0 3v1"/>',
|
|
770
|
-
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
|
|
771
|
-
phone: '<rect x="6" y="2" width="12" height="20" rx="3"/><path d="M10 18h4"/>',
|
|
772
|
-
devices: '<rect x="3" y="3" width="14" height="11" rx="2"/><path d="M6 19h8M10 14v5"/><rect x="16" y="10" width="6" height="12" rx="1"/>',
|
|
773
|
-
network: '<rect x="8" y="2" width="8" height="6" rx="1"/><rect x="2" y="16" width="8" height="6" rx="1"/><rect x="14" y="16" width="8" height="6" rx="1"/><path d="M12 8v4M6 16v-4h12v4"/>',
|
|
774
|
-
cloud: '<path d="M6 18a4 4 0 1 1 .8-7.9 6 6 0 0 1 11.5-1.6A5 5 0 0 1 18 18H6Z"/>',
|
|
775
|
-
disconnect: '<path d="M7 3v4m10-4v4M5 7h14v4a7 7 0 0 1-7 7v4M5 11a7 7 0 0 0 3 5M3 3l18 18"/>',
|
|
776
|
-
qr: '<rect x="3" y="3" width="6" height="6" rx="1"/><rect x="15" y="3" width="6" height="6" rx="1"/><rect x="3" y="15" width="6" height="6" rx="1"/><path d="M15 15h3v3h3M15 21h3M21 15v1"/>'
|
|
777
|
-
};
|
|
778
|
-
function localPageIcon(name) {
|
|
779
|
-
return `<svg class="ui-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icons[name]}</svg>`;
|
|
780
|
-
}
|
|
781
|
-
function localPageLabels(locale = "zh-CN") {
|
|
782
|
-
const t = localPageTranslator(locale);
|
|
783
|
-
const mark = (key, values) => `data-i18n="${key}"${values === void 0 ? "" : ` data-i18n-values="${escapeHtml(JSON.stringify(values))}"`}`;
|
|
784
|
-
const label = (key, values) => `<span ${mark(key, values)}>${escapeHtml(t(key, values))}</span>`;
|
|
785
|
-
const actionLabel = (key) => `<span data-action-label ${mark(key)}>${escapeHtml(t(key))}</span>`;
|
|
786
|
-
const attribute = (name, key, values) => `data-i18n-${name}="${key}" ${name}="${escapeHtml(t(key, values))}"${values === void 0 ? "" : ` data-i18n-values="${escapeHtml(JSON.stringify(values))}"`}`;
|
|
787
|
-
const error = (value) => value === void 0 ? "" : typeof value === "string" ? escapeHtml(value) : label(value.key);
|
|
788
|
-
return { t, mark, label, actionLabel, attribute, error };
|
|
789
|
-
}
|
|
790
|
-
var localPageAssets = `<link rel="stylesheet" href="/local-ui.css">
|
|
791
|
-
<script src="/local-ui.js" defer></script>`;
|
|
792
|
-
function renderLanguagePicker(locale = "zh-CN") {
|
|
793
|
-
const { attribute } = localPageLabels(locale);
|
|
794
|
-
return `<select class="select select-sm language-picker" ${attribute("aria-label", "language")} id="language-picker">
|
|
795
|
-
<option value="zh-CN"${locale === "zh-CN" ? " selected" : ""}>\u4E2D\u6587</option>
|
|
796
|
-
<option value="en"${locale === "en" ? " selected" : ""}>English</option>
|
|
797
|
-
</select>`;
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
// src/session-page.ts
|
|
801
|
-
function sessionPageUrl(sessionId, cursor) {
|
|
802
|
-
return `/session?${new URLSearchParams({ sessionId, ...cursor === void 0 ? {} : { cursor } })}`;
|
|
803
|
-
}
|
|
804
|
-
function renderSessionLink(session) {
|
|
805
|
-
return `<a class="session-link" href="${escapeHtml(sessionPageUrl(session.id))}">
|
|
806
|
-
<span class="session-symbol">${localPageIcon("chat")}</span><span class="session-label">
|
|
807
|
-
<span class="session-name">${escapeHtml(session.name || session.id)}</span></span>
|
|
808
|
-
<span class="session-chevron">${localPageIcon("chevron")}</span></a>`;
|
|
809
|
-
}
|
|
810
|
-
function renderSessionGroups(sessions, canRead, locale = "zh-CN") {
|
|
811
|
-
const { t, label, attribute } = localPageLabels(locale);
|
|
812
|
-
const groups = /* @__PURE__ */ new Map();
|
|
813
|
-
for (const session of sessions) {
|
|
814
|
-
const directory = session.workingDirectory || "";
|
|
815
|
-
const group = groups.get(directory);
|
|
816
|
-
if (group === void 0) groups.set(directory, [session]);
|
|
817
|
-
else group.push(session);
|
|
818
|
-
}
|
|
819
|
-
return `<ul class="session-folders">${[...groups].map(([directory, entries]) => {
|
|
820
|
-
const name = directory.split(/[\\/]/).filter(Boolean).at(-1) || directory;
|
|
821
|
-
return `<li><details class="session-folder"><summary>
|
|
822
|
-
<span class="folder-icon">${localPageIcon("folder")}</span><span class="folder-label">
|
|
823
|
-
<span class="folder-name">${name ? escapeHtml(name) : label("sessions.noDirectory")}</span>${directory && directory !== name ? `<span class="folder-path">${escapeHtml(directory)}</span>` : ""}</span>
|
|
824
|
-
<span class="folder-count" ${attribute("aria-label", "sessions.count", { count: entries.length })}>${entries.length}</span>
|
|
825
|
-
<span class="folder-chevron">${localPageIcon("chevron")}</span></summary>
|
|
826
|
-
<ul class="sessions" aria-label="${escapeHtml(directory || name || t("sessions.noDirectory"))}">${entries.map((session) => `<li class="session">${canRead ? renderSessionLink(session) : `<span class="session-name">${escapeHtml(session.name || session.id)}</span>`}</li>`).join("")}</ul>
|
|
827
|
-
</details></li>`;
|
|
828
|
-
}).join("") || `<li class="empty">${label("sessions.empty")}</li>`}</ul>`;
|
|
829
|
-
}
|
|
830
|
-
var statusLabels = { running: "session.running", completed: "session.completed", failed: "session.failed" };
|
|
831
|
-
function renderAttachments(attachments = []) {
|
|
832
|
-
return attachments.map((attachment) => {
|
|
833
|
-
const image = attachment.kind === "image" && attachment.data !== void 0 && /^(image\/(png|jpeg|gif|webp))$/.test(attachment.mimeType ?? "");
|
|
834
|
-
return `<figure class="${image ? "image-attachment" : "file-attachment"}">${image ? `<img loading="lazy" src="data:${escapeHtml(attachment.mimeType ?? "")};base64,${escapeHtml(attachment.data ?? "")}" alt="${escapeHtml(attachment.name)}">` : localPageIcon("file")}<figcaption>${escapeHtml(attachment.name)}${!image && attachment.uri ? `<span class="attachment-path">${escapeHtml(attachment.uri)}</span>` : ""}</figcaption></figure>`;
|
|
835
|
-
}).join("");
|
|
836
|
-
}
|
|
837
|
-
function renderItem(item, agentName, locale) {
|
|
838
|
-
const { label } = localPageLabels(locale);
|
|
839
|
-
const date = new Date(item.timestamp);
|
|
840
|
-
const time = `<time data-date-format="time" datetime="${escapeHtml(item.timestamp)}" title="${escapeHtml(
|
|
841
|
-
date.toLocaleString(locale, { hour12: false })
|
|
842
|
-
)}">${date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", hour12: false })}</time>`;
|
|
843
|
-
let content;
|
|
844
|
-
switch (item.kind) {
|
|
845
|
-
case "human-message":
|
|
846
|
-
content = `<header class="message-heading"><h2>${label("session.you")}</h2>${time}</header>
|
|
847
|
-
<div class="human-bubble"><div class="message-content plain-text">${escapeHtml(item.content)}</div>${renderAttachments(item.attachments)}</div>`;
|
|
848
|
-
break;
|
|
849
|
-
case "assistant-message": {
|
|
850
|
-
const name = item.actor === "subagent" ? label("session.subagent") : agentName ? escapeHtml(agentName) : label("session.assistant");
|
|
851
|
-
content = `<header class="message-heading"><span class="avatar">${localPageIcon("agent")}</span><h2>${name}</h2>${item.model ? `<span class="model">${escapeHtml(item.model)}</span>` : ""}${time}</header>
|
|
852
|
-
<div class="assistant-body"><div class="message-content markdown">${renderSessionMarkdown(item.content)}</div>${renderAttachments(item.attachments)}</div>`;
|
|
853
|
-
break;
|
|
854
|
-
}
|
|
855
|
-
case "activity-group":
|
|
856
|
-
content = `<details class="activity-details"><summary><span class="status-icon ${item.status}">${localPageIcon(
|
|
857
|
-
item.status === "completed" ? "check" : item.status === "failed" ? "warning" : "clock"
|
|
858
|
-
)}</span>${label("session.activities", { count: item.steps.length })}<span class="activity-status">${label(statusLabels[item.status])}</span>
|
|
859
|
-
<span class="disclosure">${localPageIcon("chevron")}</span></summary><ul class="steps">${item.steps.map((step) => `<li><div class="step-heading"><strong>${escapeHtml(step.name)}</strong><span class="step-status ${step.status}">${label(statusLabels[step.status])}</span></div>${[
|
|
860
|
-
"description" in step ? step.description : void 0,
|
|
861
|
-
"resultSummary" in step ? step.resultSummary : void 0,
|
|
862
|
-
"error" in step ? step.error : void 0
|
|
863
|
-
].map((value) => value ? `<div class="message-content plain-text">${escapeHtml(value)}</div>` : "").join("")}</li>`).join("")}</ul><div class="activity-time">${time}</div></details>`;
|
|
864
|
-
break;
|
|
865
|
-
case "notice":
|
|
866
|
-
content = `<div class="notice-content ${item.severity}">${localPageIcon(
|
|
867
|
-
item.severity === "success" ? "check" : item.severity === "error" || item.severity === "warning" ? "warning" : "info"
|
|
868
|
-
)}<div><header class="message-heading"><h2>${escapeHtml(item.title)}</h2>${time}</header>
|
|
869
|
-
<div class="message-content plain-text">${escapeHtml(item.content)}</div></div></div>`;
|
|
870
|
-
break;
|
|
871
|
-
case "plan-update":
|
|
872
|
-
content = `<details class="plan-details"><summary>${localPageIcon("file")}${label(item.operation === "deleted" ? "session.planDeleted" : "session.plan")}${item.todos.length ? `<span class="activity-status">${label("session.tasks", { count: item.todos.length })}</span>` : ""}<span class="disclosure">${localPageIcon("chevron")}</span></summary>
|
|
873
|
-
<div class="plan-body"><div class="message-content markdown">${renderSessionMarkdown(item.content)}</div><ul class="steps">${item.todos.map((todo) => `<li><div class="step-heading"><strong>${escapeHtml(todo.title)}</strong><span>${todo.status === "pending" || todo.status === "in_progress" || todo.status === "done" ? label(`session.todo.${todo.status}`) : escapeHtml(todo.status)}</span></div>${todo.description ? `<div class="message-content plain-text">${escapeHtml(todo.description)}</div>` : ""}</li>`).join("")}</ul>${time}</div></details>`;
|
|
874
|
-
break;
|
|
875
|
-
}
|
|
876
|
-
return `<li class="message ${item.kind}" id="item-${escapeHtml(item.id)}"><article>${content}</article></li>`;
|
|
877
|
-
}
|
|
878
|
-
function renderMessages(items, agentName, locale) {
|
|
879
|
-
let previousDate = "";
|
|
880
|
-
return items.map((item) => {
|
|
881
|
-
const date = new Date(item.timestamp).toLocaleDateString(locale, { year: "numeric", month: "long", day: "numeric" });
|
|
882
|
-
const divider = date === previousDate ? "" : `<li class="day-divider"><time data-date-format="day" datetime="${escapeHtml(item.timestamp)}">${escapeHtml(date)}</time></li>`;
|
|
883
|
-
previousDate = date;
|
|
884
|
-
return divider + renderItem(item, agentName, locale);
|
|
885
|
-
}).join("");
|
|
886
|
-
}
|
|
887
|
-
function renderSessionPage(input) {
|
|
888
|
-
const locale = input.locale ?? "zh-CN";
|
|
889
|
-
const { label, attribute, error: renderError } = localPageLabels(locale);
|
|
890
|
-
const { session, page, error } = input;
|
|
891
|
-
const title = session?.name;
|
|
892
|
-
const latest = session === void 0 ? "/" : sessionPageUrl(session.id);
|
|
893
|
-
const project = session?.workingDirectory?.split(/[\\/]/).filter(Boolean).at(-1);
|
|
894
|
-
const hasMessages = page !== void 0 && page.items.length > 0;
|
|
895
|
-
return `<!doctype html>
|
|
896
|
-
<html lang="${locale}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
897
|
-
<title>${escapeHtml(title || localPageLabels(locale).t("session"))} \xB7 AgentKnight</title>
|
|
898
|
-
${localPageAssets}
|
|
899
|
-
<style>
|
|
900
|
-
.session-page { padding: 0; background: var(--panel); }
|
|
901
|
-
* { box-sizing: border-box; } body { margin: 0; } svg { display: block; width: 20px; height: 20px; flex-shrink: 0; }
|
|
902
|
-
a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }
|
|
903
|
-
:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; border-radius: 4px; }
|
|
904
|
-
.topbar { position: sticky; top: 0; z-index: 3; background: var(--panel); border-bottom: 1px solid var(--ui-border); }
|
|
905
|
-
nav { min-height: 64px; max-width: 1280px; margin: auto; padding: 12px 32px; display: flex; align-items: center; gap: 20px; }
|
|
906
|
-
.back { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); font-size: 14px; min-height: 36px; }
|
|
907
|
-
.nav-divider { height: 20px; width: 1px; background: var(--ui-border); }
|
|
908
|
-
.brand { display: inline-flex; align-items: center; gap: 9px; margin: 0; font-size: 14px; font-weight: 650; color: inherit; letter-spacing: -.3px; }
|
|
909
|
-
.machine { margin-left: auto; color: var(--muted); font-size: 12px; max-width: 30%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
910
|
-
.refresh { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px; padding: 8px 12px; border: 1px solid var(--ui-border); border-radius: 8px; color: inherit; font-size: 13px; }
|
|
911
|
-
.refresh:hover { background: var(--soft); text-decoration: none; } .refresh svg { width: 16px; height: 16px; }
|
|
912
|
-
main { max-width: 900px; margin: auto; padding: 38px 28px 80px; }
|
|
913
|
-
.session-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; padding-bottom: 28px; border-bottom: 1px solid var(--ui-border); }
|
|
914
|
-
.session-identity { min-width: 0; flex: 1; } h1 { font-size: clamp(21px, 3vw, 28px); line-height: 1.4; margin: 0 0 13px; letter-spacing: -.7px; overflow-wrap: anywhere; white-space: pre-line; font-weight: 650; }
|
|
915
|
-
.context { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; color: var(--muted); font-size: 12px; }
|
|
916
|
-
.context > span { display: inline-flex; align-items: center; gap: 6px; min-width: 0; overflow-wrap: anywhere; }
|
|
917
|
-
.context svg { width: 14px; height: 14px; } .context .agent-chip { padding: 4px 8px; background: var(--soft); border-radius: 6px; }
|
|
918
|
-
details > summary { cursor: pointer; list-style: none; } summary::-webkit-details-marker { display: none; }
|
|
919
|
-
.session-info { position: relative; flex-shrink: 0; }
|
|
920
|
-
.session-info > summary { width: 36px; height: 36px; display: grid; place-items: center; color: var(--muted); border-radius: 8px; }
|
|
921
|
-
.session-info > summary:hover, .session-info[open] > summary { background: var(--soft); color: var(--accent); }
|
|
922
|
-
.session-info:not([open]) .meta { display: none; }
|
|
923
|
-
.meta { position: absolute; z-index: 2; right: 0; top: 42px; width: 340px; max-width: calc(100vw - 48px); margin: 0; padding: 20px; background: var(--panel); border: 1px solid var(--ui-border); border-radius: 12px; box-shadow: var(--shadow); font-size: 13px; }
|
|
924
|
-
.meta div + div { margin-top: 16px; } dt { color: var(--muted); font-size: 12px; } dd { margin: 5px 0 0; line-height: 1.6; overflow-wrap: anywhere; }
|
|
925
|
-
.meta code { font-size: 12px; } .messages { list-style: none; padding: 0; margin: 0; }
|
|
926
|
-
.day-divider { display: flex; align-items: center; justify-content: center; gap: 16px; color: var(--muted); font-size: 11px; margin: 26px 0 32px; }
|
|
927
|
-
.day-divider::before, .day-divider::after { content: ""; height: 1px; width: 42px; background: var(--ui-border); }
|
|
928
|
-
.message { margin: 28px 0; min-width: 0; } .message-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 12px; min-width: 0; }
|
|
929
|
-
.message-heading h2 { font-size: 13px; font-weight: 650; margin: 0; overflow-wrap: anywhere; }
|
|
930
|
-
time, .model { color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
|
931
|
-
.model { overflow-wrap: anywhere; } .message-heading time { margin-left: auto; } .avatar { width: 30px; height: 30px; border: 1px solid var(--ui-border); border-radius: 9px; display: grid; place-items: center; background: var(--panel); color: var(--accent); }
|
|
932
|
-
.avatar svg { width: 17px; height: 17px; } .assistant-body { padding-left: 40px; }
|
|
933
|
-
.message-content { overflow-wrap: anywhere; font-size: 14px; line-height: 1.85; } .plain-text { white-space: pre-wrap; }
|
|
934
|
-
.human-message { margin-left: auto; width: fit-content; max-width: 85%; }
|
|
935
|
-
.human-message .message-heading { justify-content: flex-end; gap: 10px; margin: 0 4px 8px; }
|
|
936
|
-
.human-message .message-heading h2 { color: var(--muted); font-weight: 500; font-size: 12px; }
|
|
937
|
-
.human-message .message-heading time { margin-left: 0; }
|
|
938
|
-
.human-bubble { background: var(--human); padding: 16px 20px; border-radius: 16px 4px 16px 16px; }
|
|
939
|
-
.markdown > :first-child { margin-top: 0; } .markdown > :last-child { margin-bottom: 0; }
|
|
940
|
-
.markdown p { margin: 0 0 16px; } .markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5, .markdown h6 { font-weight: 650; line-height: 1.5; margin: 24px 0 12px; letter-spacing: 0; }
|
|
941
|
-
.markdown h1 { font-size: 22px; } .markdown h2 { font-size: 19px; } .markdown h3 { font-size: 16px; } .markdown h4, .markdown h5, .markdown h6 { font-size: 14px; }
|
|
942
|
-
.markdown ul, .markdown ol { list-style: revert; padding-left: 24px; margin: 12px 0 18px; } .markdown li { margin: 5px 0; }
|
|
943
|
-
.markdown blockquote { margin: 16px 0; padding: 2px 0 2px 16px; border-left: 3px solid var(--ui-border); color: var(--muted); } .markdown blockquote p:last-child { margin-bottom: 0; }
|
|
944
|
-
code, pre { font-family: "Cascadia Code", Consolas, monospace; font-size: 12px; }
|
|
945
|
-
.markdown :not(pre) > code { background: var(--soft); border: 1px solid var(--ui-border); padding: 2px 5px; border-radius: 5px; }
|
|
946
|
-
.markdown pre { overflow-x: auto; background: var(--soft); border: 1px solid var(--ui-border); padding: 18px 20px; border-radius: 10px; line-height: 1.7; margin: 18px 0; }
|
|
947
|
-
.markdown pre code { white-space: pre; overflow-wrap: normal; } .markdown a { text-decoration: underline; text-underline-offset: 3px; }
|
|
948
|
-
.markdown hr { border: 0; border-top: 1px solid var(--ui-border); margin: 24px 0; }
|
|
949
|
-
.table-scroll { overflow-x: auto; margin: 18px 0; border: 1px solid var(--ui-border); border-radius: 10px; }
|
|
950
|
-
table { border-collapse: collapse; width: 100%; font-size: 13px; } th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--ui-border); min-width: 100px; } th { background: var(--soft); font-weight: 600; } tr:last-child td { border-bottom: 0; }
|
|
951
|
-
.activity-group, .plan-update { margin: 16px 0 16px 40px; }
|
|
952
|
-
.activity-details, .plan-details { border: 1px solid var(--ui-border); border-radius: 10px; background: var(--panel); }
|
|
953
|
-
.activity-details > summary, .plan-details > summary { display: flex; align-items: center; gap: 9px; padding: 12px 14px; font-size: 12px; }
|
|
954
|
-
.activity-details summary:hover, .plan-details summary:hover { background: var(--soft); border-radius: 10px; }
|
|
955
|
-
summary svg { width: 16px; height: 16px; } .activity-status { color: var(--muted); margin-left: auto; }
|
|
956
|
-
.disclosure { color: var(--muted); } details[open] > summary .disclosure { transform: rotate(90deg); }
|
|
957
|
-
.completed { color: var(--success); } .failed { color: var(--danger); } .running { color: var(--accent); }
|
|
958
|
-
.steps { list-style: none; margin: 0; padding: 0 16px; } .steps li { padding: 12px 0; border-top: 1px solid var(--ui-border); }
|
|
959
|
-
.step-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; font-size: 12px; overflow-wrap: anywhere; }
|
|
960
|
-
.step-heading strong { font-family: "Cascadia Code", Consolas, monospace; font-weight: 500; }
|
|
961
|
-
.step-status { flex-shrink: 0; font-size: 11px; } .steps .message-content { font-size: 12px; color: var(--muted); margin-top: 8px; }
|
|
962
|
-
.activity-time { padding: 0 16px 12px; text-align: right; } .plan-body { padding: 8px 16px 16px; } .plan-body .steps { padding: 0; }
|
|
963
|
-
.notice { margin: 20px 0 20px 40px; } .notice-content { display: flex; gap: 10px; border-left: 2px solid var(--ui-border); padding: 2px 0 2px 14px; color: var(--muted); }
|
|
964
|
-
.notice-content > svg { width: 16px; height: 16px; margin-top: 2px; } .notice-content > div { flex: 1; min-width: 0; }
|
|
965
|
-
.notice .message-heading { margin-bottom: 4px; } .notice .message-heading h2 { font-size: 12px; } .notice .message-content { font-size: 12px; }
|
|
966
|
-
.notice-content.success > svg { color: var(--success); } .notice-content.warning > svg, .notice-content.error > svg { color: var(--danger); }
|
|
967
|
-
figure { margin: 16px 0 0; } img { display: block; max-width: 100%; max-height: 520px; object-fit: contain; border-radius: 10px; }
|
|
968
|
-
figcaption { font-size: 12px; overflow-wrap: anywhere; } .image-attachment figcaption { margin-top: 8px; color: var(--muted); }
|
|
969
|
-
.file-attachment { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid var(--ui-border); background: var(--panel); border-radius: 10px; }
|
|
970
|
-
.file-attachment > svg { color: var(--accent); } .file-attachment figcaption { min-width: 0; }
|
|
971
|
-
.attachment-path { display: block; color: var(--muted); font-size: 11px; margin-top: 4px; white-space: pre-wrap; }
|
|
972
|
-
.pager { display: flex; justify-content: center; margin: 24px 0 0; } .pager a { display: inline-flex; align-items: center; gap: 7px; padding: 8px 14px; border-radius: 20px; border: 1px solid var(--ui-border); font-size: 12px; color: var(--muted); background: var(--panel); }
|
|
973
|
-
.pager a:hover { background: var(--soft); color: var(--accent); text-decoration: none; } .pager svg { width: 14px; height: 14px; }
|
|
974
|
-
.state { display: flex; flex-direction: column; align-items: center; text-align: center; padding: 70px 20px; color: var(--muted); }
|
|
975
|
-
.state > svg { width: 36px; height: 36px; margin-bottom: 20px; } .state h2 { font-size: 16px; color: var(--color-base-content); margin: 0 0 8px; font-weight: 600; }
|
|
976
|
-
.state p { margin: 0; font-size: 13px; line-height: 1.8; max-width: 380px; } .state.error > svg { color: var(--danger); }
|
|
977
|
-
.state a { margin-top: 20px; font-size: 13px; border: 1px solid var(--ui-border); background: var(--panel); border-radius: 8px; padding: 9px 18px; }
|
|
978
|
-
.jump-latest { position: fixed; right: 28px; bottom: 24px; width: 38px; height: 38px; display: grid; place-items: center; background: var(--panel); color: var(--muted); border: 1px solid var(--ui-border); border-radius: 50%; box-shadow: var(--shadow); }
|
|
979
|
-
.jump-latest:hover { color: var(--accent); background: var(--soft); } #conversation-end { scroll-margin-bottom: 24px; }
|
|
980
|
-
@media (max-width: 600px) {
|
|
981
|
-
nav { padding: 10px 16px; gap: 12px; min-height: 58px; } .brand { font-size: 12px; }
|
|
982
|
-
.machine, .nav-divider { display: none; } .refresh { margin-left: auto; padding: 8px; } .refresh span { display: none; }
|
|
983
|
-
main { padding: 26px 18px 70px; } .session-heading { gap: 10px; padding-bottom: 22px; }
|
|
984
|
-
.assistant-body { padding-left: 0; } .human-message { max-width: 94%; } .human-bubble { padding: 14px 16px; }
|
|
985
|
-
.activity-group, .plan-update, .notice { margin-left: 0; } .message-content { font-size: 14px; }
|
|
986
|
-
.model { max-width: 45%; } .jump-latest { right: 16px; bottom: 16px; }
|
|
987
|
-
}
|
|
988
|
-
</style></head><body class="session-page">
|
|
989
|
-
<div class="topbar"><nav ${attribute("aria-label", "session.navigation")}>
|
|
990
|
-
<a class="back" href="/" ${attribute("aria-label", "session.back")}>${localPageIcon("back")}${label("sessions")}</a><span class="nav-divider" aria-hidden="true"></span>
|
|
991
|
-
<a class="brand" href="/"><span class="brand-mark" aria-hidden="true"></span>AgentKnight</a>
|
|
992
|
-
<span class="machine" title="${escapeHtml(input.machineName)}">${escapeHtml(input.machineName)}</span>
|
|
993
|
-
${renderLanguagePicker(locale)}
|
|
994
|
-
${session === void 0 ? "" : `<a class="refresh" href="${escapeHtml(latest)}" ${attribute("aria-label", "session.refresh")} ${attribute("title", "session.refresh")}>${localPageIcon("refresh")}${label("refresh")}</a>`}
|
|
995
|
-
</nav></div><main>
|
|
996
|
-
<div class="session-heading"><div class="session-identity"><h1>${title ? escapeHtml(title) : label("session")}</h1>
|
|
997
|
-
${session === void 0 ? "" : `<div class="context"><span class="agent-chip">${localPageIcon("agent")}${escapeHtml(session.agentName)}</span>${project ? `<span title="${escapeHtml(session.workingDirectory ?? "")}">${localPageIcon("folder")}${escapeHtml(project)}</span>` : ""}</div>`}</div>
|
|
998
|
-
${session === void 0 ? "" : `<details class="session-info"><summary ${attribute("aria-label", "session.info")} ${attribute("title", "session.info")}>${localPageIcon("info")}</summary><dl class="meta">
|
|
999
|
-
<div><dt>${label("session.machine")}</dt><dd>${escapeHtml(input.machineName)}</dd></div><div><dt>${label("session.agent")}</dt><dd>${escapeHtml(session.agentName)}</dd></div>${session.workingDirectory ? `<div><dt>${label("session.directory")}</dt><dd>${escapeHtml(session.workingDirectory)}</dd></div>` : ""}<div><dt>${label("session.id")}</dt><dd><code>${escapeHtml(session.id)}</code></dd></div></dl></details>`}</div>
|
|
1000
|
-
${error ? `<div class="state error" role="alert">${localPageIcon("warning")}<h2>${label("session.loadError")}</h2><p>${renderError(error)}</p><a href="${escapeHtml(latest)}">${label(session ? "session.reload" : "session.back")}</a></div>` : ""}
|
|
1001
|
-
${page === void 0 ? "" : `${page.hasMore && session && page.cursor ? `<div class="pager"><a href="${escapeHtml(sessionPageUrl(session.id, page.cursor))}">${localPageIcon("clock")}${label("session.older")}</a></div>` : ""}
|
|
1002
|
-
${hasMessages ? `<ol class="messages" ${attribute("aria-label", "session.messages")}>${renderMessages(page.items, session?.agentName, locale)}</ol>` : `<div class="state empty">${localPageIcon("chat")}<h2>${label("session.empty")}</h2><p>${label("session.emptyBody")}</p></div>`}`}
|
|
1003
|
-
<div id="conversation-end"></div></main>
|
|
1004
|
-
${hasMessages ? `<a class="jump-latest" href="#conversation-end" ${attribute("aria-label", "session.end")} ${attribute("title", "session.end")}>${localPageIcon("down")}</a>` : ""}
|
|
1005
|
-
</body></html>`;
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
// src/agent-selection-page.ts
|
|
1009
|
-
function renderChatToggle(id, enabled, error, token, locale) {
|
|
1010
|
-
if (enabled === void 0) return "";
|
|
1011
|
-
const { label, error: renderError } = localPageLabels(locale);
|
|
1012
|
-
return `
|
|
1013
|
-
<form id="${id}-form" class="chat-setting" method="post" action="/${id}-settings">
|
|
1014
|
-
<input type="hidden" name="token" value="${escapeHtml(token)}">
|
|
1015
|
-
<input id="${id}-value" type="hidden" name="enabled" value="${!enabled}">
|
|
1016
|
-
<div class="setting-row">
|
|
1017
|
-
<span id="${id}-label" class="setting-label">${localPageIcon(id === "group-chat" ? "chat" : id === "peer-chat" ? "network" : "cloud")}${label(id === "group-chat" ? "settings.group" : id === "peer-chat" ? "settings.peer" : "settings.images")}</span>
|
|
1018
|
-
<button id="${id}-toggle" class="toggle" type="submit" role="switch" aria-labelledby="${id}-label" aria-checked="${enabled}"><span aria-hidden="true"></span></button>
|
|
1019
|
-
</div>
|
|
1020
|
-
${id === "image" ? "" : `<p id="${id}-error" class="error" role="alert"${error ? "" : " hidden"}>${renderError(error)}</p>`}
|
|
1021
|
-
</form>`;
|
|
1022
|
-
}
|
|
1023
|
-
function renderAgentSelectionPage(input) {
|
|
1024
|
-
const locale = input.locale ?? "zh-CN";
|
|
1025
|
-
const { t, label, actionLabel, mark, attribute, error: renderError } = localPageLabels(locale);
|
|
1026
|
-
const account = input.account;
|
|
1027
|
-
const accountName = account === void 0 ? "" : account.method === "aad" && (!account.user || account.user.username === account.userId) ? label("account.work") : account.method === "microsoft" && (!account.user || account.user.username === `msa-${account.userId}`) ? label("account.personal") : !account.user ? label("account.fallback", { id: account.userId }) : escapeHtml(account.user.username);
|
|
1028
|
-
const accountUrl = input.deploymentInfo === void 0 ? void 0 : relayAccountUrl(input.deploymentInfo.relayUrl);
|
|
1029
|
-
const accountPanel = account === void 0 ? "" : `
|
|
1030
|
-
<details id="relay-account" class="account" data-state="${account.state}" ${attribute("aria-label", "account")}>
|
|
1031
|
-
<summary><span id="relay-account-name" class="account-name">${accountName}</span>
|
|
1032
|
-
<span class="badge badge-sm" id="relay-account-state" ${mark(account.state === "signed-in" ? "account.signedIn" : account.state === "connecting" ? "account.connecting" : account.state === "disconnected" ? "account.disconnected" : account.state === "error" ? "account.error" : "account.unknown")}>${t(account.state === "signed-in" ? "account.signedIn" : account.state === "connecting" ? "account.connecting" : account.state === "disconnected" ? "account.disconnected" : account.state === "error" ? "account.error" : "account.unknown")}</span></summary>
|
|
1033
|
-
<div class="account-content"><div class="account-meta"><span id="relay-account-method">${account.method === "aad" ? "Microsoft Entra ID" : account.method === "microsoft" ? "Microsoft" : label("account.legacy")}</span><span id="relay-account-role"${account.user === void 0 ? " hidden" : ""}>${label(account.user?.role === "admin" ? "account.admin" : "account.user")}</span>${accountUrl === void 0 ? "" : `<a id="relay-account-link" href="${escapeHtml(accountUrl)}" target="_blank" rel="noopener noreferrer"${account.method === "microsoft" ? "" : " hidden"}>${label("account.view")}</a>`}</div>
|
|
1034
|
-
<p id="relay-account-error" class="error"${account.error === void 0 ? " hidden" : ""}>${account.errorKey ? label(account.errorKey) : escapeHtml(account.error ?? "")}</p>
|
|
1035
|
-
</div>
|
|
1036
|
-
</details>`;
|
|
1037
|
-
const reconnect = input.relayState === void 0 ? "" : `
|
|
1038
|
-
<form id="relay-reconnect-form" method="post" action="/relay-reconnect" data-state="${input.relayState}">
|
|
1039
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
1040
|
-
<button id="relay-reconnect" class="btn btn-sm btn-ghost relay-action" type="submit"${input.relayState === "registered" ? " hidden" : ""}${input.relayState === "connecting" ? " disabled" : ""}>${localPageIcon("refresh")}${actionLabel(input.relayState === "connecting" ? "relay.connecting" : "relay.reconnect")}</button>
|
|
1041
|
-
<p id="relay-reconnect-error" class="error" role="alert"${input.reconnectError ? "" : " hidden"}>${renderError(input.reconnectError)}</p>
|
|
1042
|
-
</form>`;
|
|
1043
|
-
const disconnect = !input.canDisconnectRelay || input.relayState === void 0 ? "" : `
|
|
1044
|
-
<form id="relay-disconnect-form" method="post" action="/relay-disconnect">
|
|
1045
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
1046
|
-
<button id="relay-disconnect" class="btn btn-sm btn-ghost relay-action" type="submit"${input.relayState === "disconnected" ? " hidden" : ""}>${localPageIcon("disconnect")}${actionLabel("relay.disconnect")}</button>
|
|
1047
|
-
</form>`;
|
|
1048
|
-
const deployment = input.deploymentInfo;
|
|
1049
|
-
const upgradedAt = deployment?.upgradedAt;
|
|
1050
|
-
const upgradeTime = upgradedAt === void 0 ? void 0 : new Date(upgradedAt);
|
|
1051
|
-
const upgradeLabel = upgradeTime !== void 0 && Number.isFinite(upgradeTime.getTime()) ? upgradeTime.toLocaleString(locale, { hour12: false }) : upgradedAt;
|
|
1052
|
-
const deploymentPanel = deployment === void 0 ? "" : `
|
|
1053
|
-
<details class="deployment-details"><summary>${label("details")}</summary><dl class="deployment" ${attribute("aria-label", "deployment")}>
|
|
1054
|
-
<div><dt>${label("deployment.upgraded")}</dt><dd>${deployment.upgradedAt ? `<time data-date-format="full" datetime="${escapeHtml(deployment.upgradedAt)}">${escapeHtml(upgradeLabel ?? deployment.upgradedAt)}</time>` : label("deployment.noUpgrade")}</dd></div>
|
|
1055
|
-
<div><dt>${label("deployment.config")}</dt><dd>${deployment.configPath ? escapeHtml(deployment.configPath) : label("deployment.environment")}</dd></div>
|
|
1056
|
-
<div><dt>${label("deployment.relay")}</dt><dd>${escapeHtml(relayDisplayUrl(deployment.relayUrl))}</dd></div>
|
|
1057
|
-
</dl></details>`;
|
|
1058
|
-
const cards = input.agents?.map((agent) => {
|
|
1059
|
-
const presentation = codingAgentPresentation(agent.id);
|
|
1060
|
-
const name = agent.name.trim() || presentation.name;
|
|
1061
|
-
return `<section class="agent card">
|
|
1062
|
-
<div class="agent-heading">
|
|
1063
|
-
<span class="agent-icon">${presentation.icon}</span>
|
|
1064
|
-
<div class="agent-identity"><h3>${escapeHtml(name)}</h3>
|
|
1065
|
-
<span class="connection${agent.available ? " connected" : ""}">${label(agent.available ? "agents.connected" : "agents.unavailable")}</span>
|
|
1066
|
-
</div>
|
|
1067
|
-
<label class="expose">${label("agents.enable")}
|
|
1068
|
-
<input class="checkbox checkbox-sm" type="checkbox" name="agents" value="${escapeHtml(agent.id)}" ${attribute("aria-label", "agents.enableName", { name })}${agent.selected ? " checked" : ""}${!agent.available && !agent.selected ? " disabled" : ""}>
|
|
1069
|
-
</label>
|
|
1070
|
-
</div>
|
|
1071
|
-
${agent.error ? `<p class="error agent-error">${escapeHtml(agent.error)}</p>` : ""}
|
|
1072
|
-
<details${agent.selected ? " open" : ""}>
|
|
1073
|
-
<summary>${label("sessions")} <span class="count">${agent.sessions.length}</span></summary>
|
|
1074
|
-
${renderSessionGroups(agent.sessions, input.canReadSessions === true, locale)}
|
|
1075
|
-
</details>
|
|
1076
|
-
</section>`;
|
|
1077
|
-
}).join("");
|
|
1078
|
-
const chatSettings = renderChatToggle("group-chat", input.groupChatEnabled, input.groupChatError, input.token, locale) + renderChatToggle("peer-chat", input.peerChatEnabled, input.peerChatError, input.token, locale) + (input.imageSettings === void 0 ? "" : `<div id="image-settings"${input.imageSettings.available ? "" : " hidden"}>${renderChatToggle("image", input.imageSettings.enabled, void 0, input.token, locale)}</div>
|
|
1079
|
-
<p id="image-error" class="error" role="alert"${input.imageError ? "" : " hidden"}>${renderError(input.imageError)}</p>`);
|
|
1080
|
-
return `<!doctype html>
|
|
1081
|
-
<html lang="${locale}">
|
|
1082
|
-
<head>
|
|
1083
|
-
<meta charset="utf-8">
|
|
1084
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1085
|
-
<title>AgentKnight</title>
|
|
1086
|
-
${localPageAssets}
|
|
1087
|
-
<script src="/local-page.js" defer></script>
|
|
1088
|
-
</head>
|
|
1089
|
-
<body>
|
|
1090
|
-
<main>
|
|
1091
|
-
<header class="dashboard-header"><div><span class="brand"><span class="brand-mark" aria-hidden="true"></span>AgentKnight${deployment === void 0 ? "" : `<span id="app-version" ${attribute("aria-label", "deployment.version")}>${escapeHtml(deployment.version)}</span>`}</span><h1>${escapeHtml(input.machineName)}</h1></div><div class="header-actions">${accountPanel}${reconnect}${disconnect}${renderLanguagePicker(locale)}<a class="btn btn-sm btn-square btn-ghost" href="/" ${attribute("aria-label", "refresh")} ${attribute("title", "refresh")}>${localPageIcon("refresh")}</a></div></header>
|
|
1092
|
-
<div class="layout">
|
|
1093
|
-
<section aria-labelledby="agents-heading">
|
|
1094
|
-
${chatSettings ? `<div class="chat-settings">${chatSettings}</div>` : ""}
|
|
1095
|
-
${input.agents === void 0 ? `<div class="section-heading"><h2 id="agents-heading">${label("agents")}</h2></div>${input.sessions === void 0 ? `<p class="empty">${label("agents.single")}</p>` : renderSessionGroups(input.sessions, true, locale)}` : `<form id="selection-form" method="post" action="/selection">
|
|
1096
|
-
<div class="section-heading"><h2 id="agents-heading">${label("agents")}</h2>
|
|
1097
|
-
<div class="sync-actions"><span id="save-status" role="status" aria-live="polite"${input.saved ? ` ${mark("agents.saved")}` : ""}>${input.saved ? t("agents.saved") : ""}</span><button id="save-button" class="btn btn-primary" type="submit">${localPageIcon("refresh")}${actionLabel(input.error ? "retry" : "agents.sync")}</button></div>
|
|
1098
|
-
</div>
|
|
1099
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
1100
|
-
<fieldset>${cards || `<p class="empty">${label("agents.empty")}</p>`}</fieldset>
|
|
1101
|
-
<p id="save-error" class="error" role="alert"${input.error ? "" : " hidden"}>${renderError(input.error)}</p>
|
|
1102
|
-
</form>`}
|
|
1103
|
-
</section>
|
|
1104
|
-
<aside class="sidebar">
|
|
1105
|
-
<section class="pairing card" aria-labelledby="pairing-heading">
|
|
1106
|
-
<h2 id="pairing-heading" class="icon-heading">${localPageIcon("phone")}${label("pairing")}</h2>
|
|
1107
|
-
<div class="qr-area">
|
|
1108
|
-
<svg id="qr-placeholder" class="qr-placeholder" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="3" aria-hidden="true"${input.pairing ? " hidden" : ""}><rect x="8" y="8" width="18" height="18" rx="3"/><rect x="38" y="8" width="18" height="18" rx="3"/><rect x="8" y="38" width="18" height="18" rx="3"/><path d="M39 38h8v8h9M39 49v7h8M55 38v3"/></svg>
|
|
1109
|
-
<div id="pairing-qr" class="qr" role="img" ${attribute("aria-label", "pairing.qr")}${input.pairing ? ` data-expires-at="${input.pairing.expiresAt}"${input.pairing.statusId ? ` data-status-id="${escapeHtml(input.pairing.statusId)}"` : ""}` : " hidden"}>${input.pairing?.svg ?? ""}</div>
|
|
1110
|
-
<div id="pair-success" role="status" hidden><span class="pair-check" aria-hidden="true">\u2713</span>${label("pairing.success")}</div>
|
|
1111
|
-
</div>
|
|
1112
|
-
<div id="pairing-string" class="pairing-string"${input.pairing ? "" : " hidden"}>
|
|
1113
|
-
<input id="pairing-text" type="text" readonly spellcheck="false" ${attribute("aria-label", "pairing.text")} value="${escapeHtml(input.pairing?.uri ?? "")}">
|
|
1114
|
-
<button id="copy-pairing" class="btn btn-sm btn-ghost" type="button" aria-live="polite">${label("pairing.copy")}</button>
|
|
1115
|
-
</div>
|
|
1116
|
-
<form id="pairing-form" method="post" action="/pair">
|
|
1117
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
1118
|
-
<div class="pair-actions"><button id="show-qr" class="btn secondary" type="submit"${input.pairing ? " hidden" : ""}>${localPageIcon("qr")}${actionLabel("pairing.show")}</button><button id="refresh-qr" class="btn secondary" type="submit" formaction="/refresh"${input.pairing ? "" : " hidden"}>${localPageIcon("refresh")}${actionLabel("pairing.refresh")}</button><button ${mark("pairing.hide")} id="hide-qr" class="btn btn-ghost secondary" type="button"${input.pairing ? "" : " hidden"}>${t("pairing.hide")}</button></div>
|
|
1119
|
-
</form>
|
|
1120
|
-
<p id="pair-error" class="error" role="alert"${input.pairingError ? "" : " hidden"}${input.pairingError && input.relayState !== void 0 && input.relayState !== "registered" ? ' data-relay-offline="true"' : ""}>${renderError(input.pairingError)}</p>
|
|
1121
|
-
</section>
|
|
1122
|
-
${input.manageClients ? `<section id="clients-panel" class="pairing card">
|
|
1123
|
-
<div class="section-heading"><h2 class="icon-heading">${localPageIcon("devices")}${label("clients")}</h2><button id="refresh-clients" class="btn btn-sm btn-square btn-ghost" type="button" ${attribute("aria-label", "refresh")} ${attribute("title", "refresh")}>${localPageIcon("refresh")}</button></div>
|
|
1124
|
-
<input id="clients-token" type="hidden" value="${escapeHtml(input.token)}">
|
|
1125
|
-
<div id="clients-list" aria-live="polite"></div><p id="clients-error" class="error" role="alert" hidden></p>
|
|
1126
|
-
</section>` : ""}
|
|
1127
|
-
${deploymentPanel}
|
|
1128
|
-
</aside>
|
|
1129
|
-
</div>
|
|
1130
|
-
${input.manageClients ? `<dialog id="client-approval" class="modal" aria-labelledby="client-approval-title" aria-describedby="client-approval-device client-approval-code-label client-approval-code">
|
|
1131
|
-
<div class="modal-box">
|
|
1132
|
-
<div class="approval-icon" aria-hidden="true">${localPageIcon("phone")}</div>
|
|
1133
|
-
<h2 id="client-approval-title">${label("clients.allowTitle")}</h2>
|
|
1134
|
-
<p id="client-approval-device"></p>
|
|
1135
|
-
<div class="verification"><span id="client-approval-code-label">${label("clients.code")}</span><strong id="client-approval-code"></strong></div>
|
|
1136
|
-
<p id="client-approval-error" class="error" role="alert" hidden></p>
|
|
1137
|
-
<div class="modal-action"><button ${mark("clients.dismiss")} id="client-approval-dismiss" class="btn btn-ghost" type="button" autofocus>${t("clients.dismiss")}</button><button ${mark("clients.allow")} id="client-approval-confirm" class="btn btn-primary" type="button">${t("clients.allow")}</button></div>
|
|
1138
|
-
</div>
|
|
1139
|
-
</dialog>` : ""}
|
|
1140
|
-
</main>
|
|
1141
|
-
</body>
|
|
1142
|
-
</html>`;
|
|
1143
|
-
}
|
|
1144
|
-
var localPageScript = `
|
|
1145
|
-
(() => {
|
|
1146
|
-
const { t, text, failure, report } = localUI;
|
|
1147
|
-
const clientsPanel = document.querySelector('#clients-panel');
|
|
1148
|
-
if (clientsPanel) {
|
|
1149
|
-
const list = document.querySelector('#clients-list');
|
|
1150
|
-
const error = document.querySelector('#clients-error');
|
|
1151
|
-
const dialog = document.querySelector('#client-approval');
|
|
1152
|
-
const confirmButton = document.querySelector('#client-approval-confirm');
|
|
1153
|
-
const dismissButton = document.querySelector('#client-approval-dismiss');
|
|
1154
|
-
const dialogError = document.querySelector('#client-approval-error');
|
|
1155
|
-
const refreshButton = document.querySelector('#refresh-clients');
|
|
1156
|
-
const dismissed = new Set();
|
|
1157
|
-
let clients = [], current, fresh = false;
|
|
1158
|
-
let stopped = false, busy = false, deciding = false, timer, expiry, generation = 0, controller;
|
|
1159
|
-
const identity = client => JSON.stringify([client.requestId, client.publicKey, client.confirmationCode]);
|
|
1160
|
-
const pending = () => clients.filter(client => client.state === 'pending' && client.expiresAt > Date.now());
|
|
1161
|
-
const controls = () => {
|
|
1162
|
-
clientsPanel.querySelectorAll('button').forEach(button => { button.disabled = busy; });
|
|
1163
|
-
confirmButton.disabled = busy || !fresh || !pending().some(client => identity(client) === current);
|
|
1164
|
-
dismissButton.disabled = deciding;
|
|
1165
|
-
};
|
|
1166
|
-
const close = () => {
|
|
1167
|
-
clearTimeout(expiry);
|
|
1168
|
-
current = undefined;
|
|
1169
|
-
if (dialog.open) { dialog.close(); refreshButton.focus({ preventScroll: true }); }
|
|
1170
|
-
};
|
|
1171
|
-
const show = client => {
|
|
1172
|
-
if (!pending().some(candidate => identity(candidate) === identity(client))) return;
|
|
1173
|
-
current = identity(client);
|
|
1174
|
-
document.querySelector('#client-approval-device').textContent = client.deviceName;
|
|
1175
|
-
document.querySelector('#client-approval-code').textContent = client.confirmationCode;
|
|
1176
|
-
if (!fresh) text(dialogError, 'clients.loadError');
|
|
1177
|
-
dialogError.hidden = fresh;
|
|
1178
|
-
if (!dialog.open) dialog.showModal();
|
|
1179
|
-
clearTimeout(expiry);
|
|
1180
|
-
expiry = setTimeout(() => { close(); render(); }, Math.max(0, client.expiresAt - Date.now()));
|
|
1181
|
-
controls();
|
|
1182
|
-
};
|
|
1183
|
-
const next = () => {
|
|
1184
|
-
if (current && !pending().some(client => identity(client) === current)) close();
|
|
1185
|
-
if (!dialog.open && !stopped && !deciding && !document.hidden && fresh) {
|
|
1186
|
-
const client = pending().find(client => !dismissed.has(identity(client)));
|
|
1187
|
-
if (client) show(client);
|
|
1188
|
-
}
|
|
1189
|
-
};
|
|
1190
|
-
const dismiss = () => {
|
|
1191
|
-
if (deciding) return;
|
|
1192
|
-
if (current) dismissed.add(current);
|
|
1193
|
-
close();
|
|
1194
|
-
next();
|
|
1195
|
-
};
|
|
1196
|
-
dismissButton.addEventListener('click', dismiss);
|
|
1197
|
-
dialog.addEventListener('cancel', event => { event.preventDefault(); dismiss(); });
|
|
1198
|
-
confirmButton.addEventListener('click', () => {
|
|
1199
|
-
const client = pending().find(client => identity(client) === current);
|
|
1200
|
-
if (!busy && fresh && client) refresh({ requestId: client.requestId, publicKey: client.publicKey, action: 'approve' });
|
|
1201
|
-
});
|
|
1202
|
-
const render = () => {
|
|
1203
|
-
list.replaceChildren();
|
|
1204
|
-
const visible = clients.filter(client => client.state === 'active' || (client.state === 'pending' && client.expiresAt > Date.now()));
|
|
1205
|
-
const liveIdentities = new Set(pending().map(identity));
|
|
1206
|
-
for (const id of dismissed) if (!liveIdentities.has(id)) dismissed.delete(id);
|
|
1207
|
-
if (!visible.length) {
|
|
1208
|
-
const empty = document.createElement('p'); empty.className = 'empty';
|
|
1209
|
-
text(empty, 'clients.empty'); list.append(empty);
|
|
1210
|
-
}
|
|
1211
|
-
for (const client of visible) {
|
|
1212
|
-
const row = document.createElement('section'); row.className = 'device-row';
|
|
1213
|
-
const identity = document.createElement('div'); identity.className = 'agent-identity';
|
|
1214
|
-
const name = document.createElement('h3'); name.textContent = client.deviceName; identity.append(name);
|
|
1215
|
-
const status = document.createElement('span'); status.className = 'connection';
|
|
1216
|
-
text(status, client.state === 'pending' ? 'clients.pending' : client.online ? 'clients.online' : 'clients.offline');
|
|
1217
|
-
identity.append(status);
|
|
1218
|
-
if (client.lastSeenAt) {
|
|
1219
|
-
const last = document.createElement('time'); last.className = 'directory';
|
|
1220
|
-
last.dateTime = new Date(client.lastSeenAt).toISOString();
|
|
1221
|
-
last.dataset.dateFormat = 'full';
|
|
1222
|
-
last.textContent = new Date(client.lastSeenAt).toLocaleString(document.documentElement.lang, { hour12: false }); identity.append(last);
|
|
1223
|
-
}
|
|
1224
|
-
row.append(identity);
|
|
1225
|
-
const actions = document.createElement('div'); actions.className = 'device-actions';
|
|
1226
|
-
for (const action of client.state === 'pending' ? ['review', 'reject'] : ['revoke']) {
|
|
1227
|
-
const button = document.createElement('button'); button.type = 'button';
|
|
1228
|
-
button.className = 'btn btn-sm btn-ghost secondary';
|
|
1229
|
-
text(button, { review: 'clients.review', reject: 'clients.reject', revoke: 'clients.revoke' }[action]);
|
|
1230
|
-
button.addEventListener('click', () => {
|
|
1231
|
-
if (action === 'review') { show(client); return; }
|
|
1232
|
-
if (action === 'revoke' && !confirm(t('clients.revokeConfirm', { name: client.deviceName }))) return;
|
|
1233
|
-
refresh({ requestId: client.requestId, publicKey: client.publicKey, action });
|
|
1234
|
-
});
|
|
1235
|
-
actions.append(button);
|
|
1236
|
-
}
|
|
1237
|
-
row.append(actions);
|
|
1238
|
-
list.append(row);
|
|
1239
|
-
}
|
|
1240
|
-
next();
|
|
1241
|
-
controls();
|
|
1242
|
-
};
|
|
1243
|
-
const refresh = async decision => {
|
|
1244
|
-
if (stopped || busy || document.hidden) return;
|
|
1245
|
-
const navigation = generation;
|
|
1246
|
-
busy = true; clearTimeout(timer);
|
|
1247
|
-
deciding = Boolean(decision);
|
|
1248
|
-
controller = new AbortController();
|
|
1249
|
-
controls();
|
|
1250
|
-
try {
|
|
1251
|
-
const body = new URLSearchParams({ token: document.querySelector('#clients-token').value, ...decision });
|
|
1252
|
-
const response = await fetch(decision ? '/clients/decide' : '/clients', {
|
|
1253
|
-
method: 'POST', headers: { Accept: 'application/json' }, body,
|
|
1254
|
-
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]),
|
|
1255
|
-
});
|
|
1256
|
-
const result = await response.json();
|
|
1257
|
-
if (stopped || navigation !== generation) return;
|
|
1258
|
-
if (!response.ok || !Array.isArray(result.clients) || !result.clients.every(client =>
|
|
1259
|
-
client && typeof client.requestId === 'string' && typeof client.publicKey === 'string' &&
|
|
1260
|
-
typeof client.confirmationCode === 'string' && typeof client.deviceName === 'string' &&
|
|
1261
|
-
typeof client.expiresAt === 'number' && Number.isFinite(client.expiresAt) &&
|
|
1262
|
-
typeof client.state === 'string' && (client.state !== 'pending' ||
|
|
1263
|
-
(client.publicKey.length > 0 && client.confirmationCode.trim().length > 0)))) throw new Error('Invalid client authorization response');
|
|
1264
|
-
clients = result.clients;
|
|
1265
|
-
fresh = true;
|
|
1266
|
-
render();
|
|
1267
|
-
error.hidden = true;
|
|
1268
|
-
if (decision && dialog.open && pending().some(client =>
|
|
1269
|
-
identity(client) === current && client.requestId === decision.requestId && client.publicKey === decision.publicKey)) {
|
|
1270
|
-
text(dialogError, 'clients.uncertain');
|
|
1271
|
-
dialogError.hidden = false;
|
|
1272
|
-
}
|
|
1273
|
-
} catch (reason) {
|
|
1274
|
-
if (!stopped && navigation === generation) {
|
|
1275
|
-
fresh = false;
|
|
1276
|
-
text(error, decision ? 'clients.uncertain' : 'clients.loadError');
|
|
1277
|
-
error.hidden = false;
|
|
1278
|
-
if (dialog.open) { text(dialogError, decision ? 'clients.uncertain' : 'clients.loadError'); dialogError.hidden = false; }
|
|
1279
|
-
}
|
|
1280
|
-
} finally {
|
|
1281
|
-
if (!stopped && navigation === generation) {
|
|
1282
|
-
busy = false;
|
|
1283
|
-
deciding = false;
|
|
1284
|
-
next();
|
|
1285
|
-
controls();
|
|
1286
|
-
if (!document.hidden) timer = setTimeout(() => refresh(), 3000);
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
};
|
|
1290
|
-
refreshButton.addEventListener('click', () => refresh());
|
|
1291
|
-
addEventListener('pagehide', () => {
|
|
1292
|
-
stopped = true; generation++; clearTimeout(timer); controller?.abort(); busy = false; deciding = false; fresh = false; close();
|
|
1293
|
-
});
|
|
1294
|
-
addEventListener('pageshow', () => { if (stopped) { stopped = false; refresh(); } });
|
|
1295
|
-
document.addEventListener('visibilitychange', () => { clearTimeout(timer); if (!document.hidden) refresh(); });
|
|
1296
|
-
refresh();
|
|
1297
|
-
}
|
|
1298
|
-
const reconnectForm = document.querySelector('#relay-reconnect-form');
|
|
1299
|
-
if (reconnectForm) {
|
|
1300
|
-
const button = document.querySelector('#relay-reconnect');
|
|
1301
|
-
const disconnectForm = document.querySelector('#relay-disconnect-form');
|
|
1302
|
-
const disconnectButton = document.querySelector('#relay-disconnect');
|
|
1303
|
-
const error = document.querySelector('#relay-reconnect-error');
|
|
1304
|
-
let stopped = false;
|
|
1305
|
-
let timer;
|
|
1306
|
-
let generation = 0;
|
|
1307
|
-
let submitting = false;
|
|
1308
|
-
let state = reconnectForm.dataset.state;
|
|
1309
|
-
let failureState;
|
|
1310
|
-
const update = next => {
|
|
1311
|
-
if (!next || !['connecting', 'registered', 'disconnected', 'error'].includes(next.state)) throw new Error('Invalid Relay status');
|
|
1312
|
-
state = next.state;
|
|
1313
|
-
const imageSettings = document.querySelector('#image-settings');
|
|
1314
|
-
if (imageSettings) {
|
|
1315
|
-
imageSettings.hidden = !next.imageStorage?.available;
|
|
1316
|
-
const toggle = document.querySelector('#image-toggle');
|
|
1317
|
-
if (!toggle.disabled && next.imageStorage) {
|
|
1318
|
-
toggle.setAttribute('aria-checked', String(next.imageStorage.enabled));
|
|
1319
|
-
document.querySelector('#image-value').value = String(!next.imageStorage.enabled);
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
button.hidden = next.state === 'registered';
|
|
1323
|
-
button.disabled = next.state === 'connecting';
|
|
1324
|
-
text(button, next.state === 'connecting' ? 'relay.connecting' : 'relay.reconnect');
|
|
1325
|
-
if (disconnectButton) {
|
|
1326
|
-
disconnectButton.hidden = next.state === 'disconnected';
|
|
1327
|
-
disconnectButton.disabled = false;
|
|
1328
|
-
text(disconnectButton, 'relay.disconnect');
|
|
1329
|
-
}
|
|
1330
|
-
if (next.state === 'disconnected') conceal();
|
|
1331
|
-
const pairingError = document.querySelector('#pair-error');
|
|
1332
|
-
if (next.state === 'registered' && pairingError?.dataset.relayOffline === 'true') {
|
|
1333
|
-
pairingError.hidden = true;
|
|
1334
|
-
pairingError.textContent = '';
|
|
1335
|
-
delete pairingError.dataset.relayOffline;
|
|
1336
|
-
}
|
|
1337
|
-
};
|
|
1338
|
-
const poll = async () => {
|
|
1339
|
-
const current = generation;
|
|
1340
|
-
try {
|
|
1341
|
-
const response = await fetch('/relay-status', { cache: 'no-store', signal: AbortSignal.timeout(5000) });
|
|
1342
|
-
if (!response.ok) throw new Error('Relay status unavailable');
|
|
1343
|
-
const next = await response.json();
|
|
1344
|
-
if (!stopped && current === generation && !submitting) {
|
|
1345
|
-
update(next);
|
|
1346
|
-
if (next.state !== failureState) error.hidden = true;
|
|
1347
|
-
}
|
|
1348
|
-
} catch {
|
|
1349
|
-
if (!stopped && current === generation && !submitting) {
|
|
1350
|
-
text(error, 'relay.statusError');
|
|
1351
|
-
error.hidden = false;
|
|
1352
|
-
}
|
|
1353
|
-
} finally {
|
|
1354
|
-
if (!stopped && current === generation) timer = setTimeout(poll, 3000);
|
|
1355
|
-
}
|
|
1356
|
-
};
|
|
1357
|
-
const submit = async (event, form, actionButton, disconnecting) => {
|
|
1358
|
-
event.preventDefault();
|
|
1359
|
-
if (actionButton.disabled || submitting) return;
|
|
1360
|
-
const current = ++generation;
|
|
1361
|
-
clearTimeout(timer);
|
|
1362
|
-
submitting = true;
|
|
1363
|
-
button.disabled = true;
|
|
1364
|
-
if (disconnectButton) disconnectButton.disabled = true;
|
|
1365
|
-
text(actionButton, disconnecting ? 'relay.disconnecting' : 'relay.connecting');
|
|
1366
|
-
error.hidden = true;
|
|
1367
|
-
failureState = undefined;
|
|
1368
|
-
try {
|
|
1369
|
-
const response = await fetch(form.action, {
|
|
1370
|
-
method: 'POST', headers: { Accept: 'application/json' },
|
|
1371
|
-
body: new URLSearchParams(new FormData(form)), signal: AbortSignal.timeout(5000),
|
|
1372
|
-
});
|
|
1373
|
-
if (!response.ok) throw new Error('Relay reconnect failed');
|
|
1374
|
-
const next = await response.json();
|
|
1375
|
-
if (!stopped && current === generation) {
|
|
1376
|
-
update(next);
|
|
1377
|
-
if (actionButton.hidden) (button.hidden ? disconnectButton : button)?.focus();
|
|
1378
|
-
}
|
|
1379
|
-
} catch {
|
|
1380
|
-
if (!stopped && current === generation) {
|
|
1381
|
-
update({ state: disconnecting ? state : 'error' });
|
|
1382
|
-
failureState = state;
|
|
1383
|
-
text(error, disconnecting ? 'relay.disconnectError' : 'relay.reconnectError');
|
|
1384
|
-
error.hidden = false;
|
|
1385
|
-
}
|
|
1386
|
-
} finally {
|
|
1387
|
-
submitting = false;
|
|
1388
|
-
if (!stopped && current === generation) timer = setTimeout(poll, 1000);
|
|
1389
|
-
}
|
|
1390
|
-
};
|
|
1391
|
-
reconnectForm.addEventListener('submit', event => submit(event, reconnectForm, button, false));
|
|
1392
|
-
if (disconnectForm && disconnectButton) {
|
|
1393
|
-
disconnectForm.addEventListener('submit', event => submit(event, disconnectForm, disconnectButton, true));
|
|
1394
|
-
}
|
|
1395
|
-
addEventListener('pagehide', () => { stopped = true; generation++; clearTimeout(timer); });
|
|
1396
|
-
addEventListener('pageshow', () => { if (stopped) { stopped = false; timer = setTimeout(poll, 0); } });
|
|
1397
|
-
timer = setTimeout(poll, 1000);
|
|
1398
|
-
}
|
|
1399
|
-
const account = document.querySelector('#relay-account');
|
|
1400
|
-
if (account) {
|
|
1401
|
-
const name = document.querySelector('#relay-account-name');
|
|
1402
|
-
const accountLink = document.querySelector('#relay-account-link');
|
|
1403
|
-
const method = document.querySelector('#relay-account-method');
|
|
1404
|
-
const role = document.querySelector('#relay-account-role');
|
|
1405
|
-
const state = document.querySelector('#relay-account-state');
|
|
1406
|
-
const error = document.querySelector('#relay-account-error');
|
|
1407
|
-
let stopped = false;
|
|
1408
|
-
let timer;
|
|
1409
|
-
let navigationGeneration = 0;
|
|
1410
|
-
const poll = async () => {
|
|
1411
|
-
const generation = navigationGeneration;
|
|
1412
|
-
const isCurrent = () => !stopped && generation === navigationGeneration;
|
|
1413
|
-
try {
|
|
1414
|
-
const response = await fetch('/relay-account', { cache: 'no-store', signal: AbortSignal.timeout(5000) });
|
|
1415
|
-
if (!response.ok) throw new Error('Account unavailable');
|
|
1416
|
-
const next = await response.json();
|
|
1417
|
-
if (!isCurrent()) return;
|
|
1418
|
-
const generated = (next.method === 'aad' && (!next.user || next.user.username === next.userId))
|
|
1419
|
-
|| (next.method === 'microsoft' && (!next.user || next.user.username === 'msa-' + next.userId));
|
|
1420
|
-
if (generated) text(name, next.method === 'aad' ? 'account.work' : 'account.personal');
|
|
1421
|
-
else if (!next.user) text(name, 'account.fallback', { id: next.userId });
|
|
1422
|
-
else { delete name.dataset.i18n; name.textContent = next.user.username; }
|
|
1423
|
-
if (accountLink) accountLink.hidden = next.method !== 'microsoft';
|
|
1424
|
-
if (next.method === 'aad' || next.method === 'microsoft') {
|
|
1425
|
-
delete method.dataset.i18n;
|
|
1426
|
-
method.textContent = next.method === 'aad' ? 'Microsoft Entra ID' : 'Microsoft';
|
|
1427
|
-
} else text(method, 'account.legacy');
|
|
1428
|
-
role.hidden = !next.user;
|
|
1429
|
-
text(role, next.user?.role === 'admin' ? 'account.admin' : 'account.user');
|
|
1430
|
-
account.dataset.state = next.state;
|
|
1431
|
-
text(state, next.state === 'signed-in' ? 'account.signedIn' : next.state === 'connecting' ? 'account.connecting' : next.state === 'disconnected' ? 'account.disconnected' : next.state === 'error' ? 'account.error' : 'account.unknown');
|
|
1432
|
-
if (next.error) report(error, failure(next, 'account.unavailable'), 'account.unavailable');
|
|
1433
|
-
else { delete error.dataset.i18n; error.textContent = ''; }
|
|
1434
|
-
error.hidden = !next.error;
|
|
1435
|
-
} catch {
|
|
1436
|
-
if (!isCurrent()) return;
|
|
1437
|
-
account.dataset.state = 'error';
|
|
1438
|
-
text(state, 'account.unknown');
|
|
1439
|
-
text(error, 'account.unavailable');
|
|
1440
|
-
error.hidden = false;
|
|
1441
|
-
} finally {
|
|
1442
|
-
if (isCurrent()) timer = setTimeout(poll, 10000);
|
|
1443
|
-
}
|
|
1444
|
-
};
|
|
1445
|
-
addEventListener('pagehide', () => { stopped = true; navigationGeneration++; clearTimeout(timer); });
|
|
1446
|
-
addEventListener('pageshow', () => { if (stopped) { stopped = false; timer = setTimeout(poll, 0); } });
|
|
1447
|
-
timer = setTimeout(poll, 1000);
|
|
1448
|
-
}
|
|
1449
|
-
for (const [id, failureKey] of [
|
|
1450
|
-
['group-chat', 'settings.groupError'],
|
|
1451
|
-
['peer-chat', 'settings.peerError'],
|
|
1452
|
-
['image', 'settings.imagesError'],
|
|
1453
|
-
]) {
|
|
1454
|
-
const chatSettings = document.querySelector('#' + id + '-form');
|
|
1455
|
-
if (!chatSettings) continue;
|
|
1456
|
-
const toggle = document.querySelector('#' + id + '-toggle');
|
|
1457
|
-
const value = document.querySelector('#' + id + '-value');
|
|
1458
|
-
const error = document.querySelector('#' + id + '-error');
|
|
1459
|
-
chatSettings.addEventListener('submit', async event => {
|
|
1460
|
-
event.preventDefault();
|
|
1461
|
-
if (toggle.disabled) return;
|
|
1462
|
-
toggle.disabled = true;
|
|
1463
|
-
toggle.setAttribute('aria-busy', 'true');
|
|
1464
|
-
error.hidden = true;
|
|
1465
|
-
try {
|
|
1466
|
-
const response = await fetch(chatSettings.action, {
|
|
1467
|
-
method: 'POST', headers: { Accept: 'application/json' }, body: new URLSearchParams(new FormData(chatSettings)),
|
|
1468
|
-
});
|
|
1469
|
-
const result = await response.json();
|
|
1470
|
-
if (!response.ok || result?.ok !== true || typeof result.enabled !== 'boolean') {
|
|
1471
|
-
throw failure(result, failureKey);
|
|
1472
|
-
}
|
|
1473
|
-
toggle.setAttribute('aria-checked', String(result.enabled));
|
|
1474
|
-
value.value = String(!result.enabled);
|
|
1475
|
-
} catch (reason) {
|
|
1476
|
-
report(error, reason, failureKey);
|
|
1477
|
-
error.hidden = false;
|
|
1478
|
-
} finally {
|
|
1479
|
-
toggle.disabled = false;
|
|
1480
|
-
toggle.removeAttribute('aria-busy');
|
|
1481
|
-
}
|
|
1482
|
-
});
|
|
1483
|
-
}
|
|
1484
|
-
const form = document.querySelector('#selection-form');
|
|
1485
|
-
if (form) {
|
|
1486
|
-
const button = document.querySelector('#save-button');
|
|
1487
|
-
const status = document.querySelector('#save-status');
|
|
1488
|
-
const error = document.querySelector('#save-error');
|
|
1489
|
-
const fields = form.querySelector('fieldset');
|
|
1490
|
-
const selection = () => JSON.stringify([...form.querySelectorAll('[name=agents]:checked')].map(input => input.value).sort());
|
|
1491
|
-
let saved = selection();
|
|
1492
|
-
let saving = false;
|
|
1493
|
-
let acknowledged = status.textContent === t('agents.saved');
|
|
1494
|
-
const update = () => {
|
|
1495
|
-
const dirty = selection() !== saved;
|
|
1496
|
-
button.disabled = saving || (acknowledged && !dirty && error.hidden);
|
|
1497
|
-
if (!saving) {
|
|
1498
|
-
if (dirty) text(status, 'agents.dirty');
|
|
1499
|
-
else if (acknowledged) text(status, 'agents.saved');
|
|
1500
|
-
else { delete status.dataset.i18n; status.textContent = ''; }
|
|
1501
|
-
}
|
|
1502
|
-
};
|
|
1503
|
-
form.addEventListener('change', update);
|
|
1504
|
-
update();
|
|
1505
|
-
form.addEventListener('submit', async event => {
|
|
1506
|
-
event.preventDefault();
|
|
1507
|
-
if (button.disabled || saving) return;
|
|
1508
|
-
const body = new URLSearchParams(new FormData(form));
|
|
1509
|
-
const submitted = selection();
|
|
1510
|
-
saving = true;
|
|
1511
|
-
fields.disabled = true;
|
|
1512
|
-
button.disabled = true;
|
|
1513
|
-
text(status, 'agents.saving');
|
|
1514
|
-
error.hidden = true;
|
|
1515
|
-
try {
|
|
1516
|
-
const response = await fetch(form.action, { method: 'POST', headers: { Accept: 'application/json' }, body });
|
|
1517
|
-
const result = await response.json().catch(() => null);
|
|
1518
|
-
if (!response.ok || result?.ok !== true) throw failure(result, 'agents.httpError', { status: response.status });
|
|
1519
|
-
saved = submitted;
|
|
1520
|
-
acknowledged = true;
|
|
1521
|
-
text(button, 'agents.sync');
|
|
1522
|
-
text(status, 'agents.saved');
|
|
1523
|
-
} catch (reason) {
|
|
1524
|
-
report(error, reason, 'agents.saveError');
|
|
1525
|
-
error.hidden = false;
|
|
1526
|
-
text(button, 'retry');
|
|
1527
|
-
delete status.dataset.i18n;
|
|
1528
|
-
status.textContent = '';
|
|
1529
|
-
} finally {
|
|
1530
|
-
saving = false;
|
|
1531
|
-
fields.disabled = false;
|
|
1532
|
-
update();
|
|
1533
|
-
}
|
|
1534
|
-
});
|
|
1535
|
-
}
|
|
1536
|
-
const pairing = document.querySelector('#pairing-form');
|
|
1537
|
-
const qr = document.querySelector('#pairing-qr');
|
|
1538
|
-
const pairingText = document.querySelector('#pairing-text');
|
|
1539
|
-
const pairingString = document.querySelector('#pairing-string');
|
|
1540
|
-
const copyPairing = document.querySelector('#copy-pairing');
|
|
1541
|
-
const placeholder = document.querySelector('#qr-placeholder');
|
|
1542
|
-
const show = document.querySelector('#show-qr');
|
|
1543
|
-
const refresh = document.querySelector('#refresh-qr');
|
|
1544
|
-
const hide = document.querySelector('#hide-qr');
|
|
1545
|
-
const pairError = document.querySelector('#pair-error');
|
|
1546
|
-
const pairSuccess = document.querySelector('#pair-success');
|
|
1547
|
-
let expiry;
|
|
1548
|
-
let statusTimer;
|
|
1549
|
-
let statusGeneration = 0;
|
|
1550
|
-
let loading = false;
|
|
1551
|
-
const stopStatus = () => {
|
|
1552
|
-
clearTimeout(statusTimer);
|
|
1553
|
-
statusGeneration++;
|
|
1554
|
-
};
|
|
1555
|
-
const conceal = () => {
|
|
1556
|
-
clearTimeout(expiry);
|
|
1557
|
-
stopStatus();
|
|
1558
|
-
qr.replaceChildren();
|
|
1559
|
-
qr.hidden = true;
|
|
1560
|
-
if (pairingText) { pairingText.value = ''; pairingText.removeAttribute('value'); }
|
|
1561
|
-
if (pairingString) pairingString.hidden = true;
|
|
1562
|
-
if (copyPairing) { copyPairing.disabled = false; text(copyPairing, 'pairing.copy'); }
|
|
1563
|
-
delete qr.dataset.statusId;
|
|
1564
|
-
delete qr.dataset.expiresAt;
|
|
1565
|
-
placeholder.removeAttribute('hidden');
|
|
1566
|
-
pairSuccess.hidden = true;
|
|
1567
|
-
show.hidden = false;
|
|
1568
|
-
refresh.hidden = true;
|
|
1569
|
-
hide.hidden = true;
|
|
1570
|
-
};
|
|
1571
|
-
const watchStatus = statusId => {
|
|
1572
|
-
stopStatus();
|
|
1573
|
-
if (typeof statusId !== 'string') return;
|
|
1574
|
-
const generation = statusGeneration;
|
|
1575
|
-
const poll = async () => {
|
|
1576
|
-
try {
|
|
1577
|
-
const body = new URLSearchParams(new FormData(pairing));
|
|
1578
|
-
body.set('statusId', statusId);
|
|
1579
|
-
const response = await fetch('/pair/status', { method: 'POST', headers: { Accept: 'application/json' }, body });
|
|
1580
|
-
const result = await response.json();
|
|
1581
|
-
if (generation !== statusGeneration) return;
|
|
1582
|
-
if (!response.ok || !['pending', 'paired', 'unavailable'].includes(result?.state)) throw new Error('Pairing status unavailable');
|
|
1583
|
-
if (result.state === 'paired') {
|
|
1584
|
-
conceal();
|
|
1585
|
-
placeholder.setAttribute('hidden', '');
|
|
1586
|
-
pairSuccess.hidden = false;
|
|
1587
|
-
pairError.hidden = true;
|
|
1588
|
-
return;
|
|
1589
|
-
}
|
|
1590
|
-
if (result.state === 'unavailable') {
|
|
1591
|
-
conceal();
|
|
1592
|
-
text(pairError, 'pairing.invalid');
|
|
1593
|
-
pairError.hidden = false;
|
|
1594
|
-
return;
|
|
1595
|
-
}
|
|
1596
|
-
pairError.hidden = true;
|
|
1597
|
-
} catch {
|
|
1598
|
-
// A lost status response is not pairing success. Retry until this QR expires.
|
|
1599
|
-
if (generation !== statusGeneration) return;
|
|
1600
|
-
text(pairError, 'pairing.statusError');
|
|
1601
|
-
pairError.hidden = false;
|
|
1602
|
-
}
|
|
1603
|
-
if (generation === statusGeneration) statusTimer = setTimeout(poll, 1000);
|
|
1604
|
-
};
|
|
1605
|
-
statusTimer = setTimeout(poll, 1000);
|
|
1606
|
-
};
|
|
1607
|
-
const expire = expiresAt => {
|
|
1608
|
-
clearTimeout(expiry);
|
|
1609
|
-
expiry = setTimeout(() => {
|
|
1610
|
-
conceal();
|
|
1611
|
-
text(pairError, 'pairing.expired');
|
|
1612
|
-
pairError.hidden = false;
|
|
1613
|
-
}, Math.max(0, expiresAt - Date.now()));
|
|
1614
|
-
};
|
|
1615
|
-
if (qr.dataset.expiresAt) expire(Number(qr.dataset.expiresAt));
|
|
1616
|
-
if (qr.dataset.statusId) watchStatus(qr.dataset.statusId);
|
|
1617
|
-
if (typeof window !== 'undefined') window.addEventListener('pagehide', conceal);
|
|
1618
|
-
hide.addEventListener('click', conceal);
|
|
1619
|
-
copyPairing?.addEventListener('click', async () => {
|
|
1620
|
-
if (!pairingText?.value || pairingString.hidden || copyPairing.disabled) return;
|
|
1621
|
-
const generation = statusGeneration;
|
|
1622
|
-
copyPairing.disabled = true;
|
|
1623
|
-
try {
|
|
1624
|
-
await navigator.clipboard.writeText(pairingText.value);
|
|
1625
|
-
if (generation === statusGeneration) text(copyPairing, 'pairing.copied');
|
|
1626
|
-
} catch {
|
|
1627
|
-
if (generation === statusGeneration) {
|
|
1628
|
-
text(copyPairing, 'pairing.copy');
|
|
1629
|
-
text(pairError, 'pairing.copyError');
|
|
1630
|
-
pairError.hidden = false;
|
|
1631
|
-
}
|
|
1632
|
-
} finally {
|
|
1633
|
-
if (generation === statusGeneration) copyPairing.disabled = false;
|
|
1634
|
-
}
|
|
1635
|
-
});
|
|
1636
|
-
pairing.addEventListener('submit', async event => {
|
|
1637
|
-
event.preventDefault();
|
|
1638
|
-
if (loading) return;
|
|
1639
|
-
loading = true;
|
|
1640
|
-
show.disabled = refresh.disabled = hide.disabled = true;
|
|
1641
|
-
pairError.hidden = true;
|
|
1642
|
-
delete pairError.dataset.relayOffline;
|
|
1643
|
-
conceal();
|
|
1644
|
-
const generation = statusGeneration;
|
|
1645
|
-
const endpoint = event.submitter?.getAttribute('formaction') || pairing.action;
|
|
1646
|
-
try {
|
|
1647
|
-
const response = await fetch(endpoint, { method: 'POST', headers: { Accept: 'application/json' }, body: new URLSearchParams(new FormData(pairing)) });
|
|
1648
|
-
const result = await response.json().catch(() => null);
|
|
1649
|
-
if (generation !== statusGeneration) return;
|
|
1650
|
-
if (!response.ok || typeof result?.svg !== 'string' || typeof result?.expiresAt !== 'number') throw failure(result, 'pairing.generateError');
|
|
1651
|
-
qr.innerHTML = result.svg;
|
|
1652
|
-
if (pairingText) {
|
|
1653
|
-
if (typeof result.uri !== 'string' || !result.uri) throw failure(result, 'pairing.generateError');
|
|
1654
|
-
pairingText.value = result.uri;
|
|
1655
|
-
pairingString.hidden = false;
|
|
1656
|
-
}
|
|
1657
|
-
qr.hidden = false;
|
|
1658
|
-
placeholder.setAttribute('hidden', '');
|
|
1659
|
-
show.hidden = true;
|
|
1660
|
-
refresh.hidden = hide.hidden = false;
|
|
1661
|
-
expire(result.expiresAt);
|
|
1662
|
-
watchStatus(result.statusId);
|
|
1663
|
-
} catch (reason) {
|
|
1664
|
-
if (generation !== statusGeneration) return;
|
|
1665
|
-
conceal();
|
|
1666
|
-
report(pairError, reason, 'pairing.generateError');
|
|
1667
|
-
pairError.hidden = false;
|
|
1668
|
-
} finally {
|
|
1669
|
-
loading = false;
|
|
1670
|
-
show.disabled = refresh.disabled = hide.disabled = false;
|
|
1671
|
-
}
|
|
1672
|
-
});
|
|
1673
|
-
})();
|
|
1674
|
-
`;
|
|
1675
|
-
|
|
1676
|
-
// src/relay-login-page.ts
|
|
1677
|
-
var RELAY_LOGIN_ERROR = localPageTranslator()("login.error");
|
|
1678
|
-
var LOGIN_ERROR_MESSAGES = /* @__PURE__ */ new Map([
|
|
1679
|
-
[
|
|
1680
|
-
"Relay login discovery failed. Check the address and retry.",
|
|
1681
|
-
"login.error.discovery"
|
|
1682
|
-
],
|
|
1683
|
-
[
|
|
1684
|
-
"This Relay does not support automatic login. Upgrade it or configure its authentication explicitly.",
|
|
1685
|
-
"login.error.automatic"
|
|
1686
|
-
],
|
|
1687
|
-
[
|
|
1688
|
-
"Cannot reach the Relay securely. Check the Relay address and connection, then try again.",
|
|
1689
|
-
"login.error.secure"
|
|
1690
|
-
],
|
|
1691
|
-
[
|
|
1692
|
-
"The Relay returned an invalid authorization response. Check the Relay configuration.",
|
|
1693
|
-
"login.error.response"
|
|
1694
|
-
],
|
|
1695
|
-
[
|
|
1696
|
-
"This Relay does not support browser sign-in. Ask its administrator to upgrade the Relay, then retry.",
|
|
1697
|
-
"login.error.browser"
|
|
1698
|
-
],
|
|
1699
|
-
[
|
|
1700
|
-
"PC authorization expired. Cancel this request and sign in again.",
|
|
1701
|
-
"login.error.expired"
|
|
1702
|
-
],
|
|
1703
|
-
[
|
|
1704
|
-
"The Relay did not authorize this account. Contact the Relay administrator.",
|
|
1705
|
-
"login.error.unauthorized"
|
|
1706
|
-
],
|
|
1707
|
-
[
|
|
1708
|
-
"Too many authorization attempts. Wait a minute and try again.",
|
|
1709
|
-
"login.error.rateLimit"
|
|
1710
|
-
],
|
|
1711
|
-
[
|
|
1712
|
-
"This authorization was already issued. Cancel this request before signing in again.",
|
|
1713
|
-
"login.error.issued"
|
|
1714
|
-
],
|
|
1715
|
-
[
|
|
1716
|
-
"The credential exchange outcome is uncertain. Cancel this request before signing in again; do not repeat the exchange.",
|
|
1717
|
-
"login.error.exchange"
|
|
1718
|
-
],
|
|
1719
|
-
[
|
|
1720
|
-
"Credential confirmation could not be verified. Restart AgentKnight to recover the saved credential.",
|
|
1721
|
-
"login.error.confirmation"
|
|
1722
|
-
],
|
|
1723
|
-
[
|
|
1724
|
-
"The Relay confirmation service is unavailable. The credential is saved; retry after its administrator restores the service.",
|
|
1725
|
-
"login.error.confirmationService"
|
|
1726
|
-
],
|
|
1727
|
-
[
|
|
1728
|
-
"The saved Relay credential is no longer authorized. Sign in again.",
|
|
1729
|
-
"login.error.revoked"
|
|
1730
|
-
],
|
|
1731
|
-
[
|
|
1732
|
-
"The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification, then retry.",
|
|
1733
|
-
"login.error.verification"
|
|
1734
|
-
],
|
|
1735
|
-
[
|
|
1736
|
-
"Authorization cleanup could not be verified. Retry, or restart AgentKnight after the request expires.",
|
|
1737
|
-
"login.error.cleanup"
|
|
1738
|
-
],
|
|
1739
|
-
["PC authorization was cancelled.", "login.error.cancelled"],
|
|
1740
|
-
[
|
|
1741
|
-
"AgentKnight login is closed. Restart AgentKnight to sign in.",
|
|
1742
|
-
"login.error.closed"
|
|
1743
|
-
],
|
|
1744
|
-
[
|
|
1745
|
-
"The Relay credential belongs to a different PC or account. Check the Relay configuration before signing in again.",
|
|
1746
|
-
"login.error.identity"
|
|
1747
|
-
],
|
|
1748
|
-
[
|
|
1749
|
-
"Unlock your operating system credential store and restart AgentKnight. No file-based credential fallback is available.",
|
|
1750
|
-
"login.error.store"
|
|
1751
|
-
],
|
|
1752
|
-
[
|
|
1753
|
-
"Start or unlock a Secret Service keyring (such as GNOME Keyring) in the same user's D-Bus session, then retry. No file-based or in-memory credential fallback is available.",
|
|
1754
|
-
"login.error.linuxStore"
|
|
1755
|
-
],
|
|
1756
|
-
[
|
|
1757
|
-
"The saved Relay credential is invalid. Recover it in your operating system credential manager before signing in.",
|
|
1758
|
-
"login.error.invalidCredential"
|
|
1759
|
-
],
|
|
1760
|
-
[
|
|
1761
|
-
"A different Relay account or enrollment is already saved for this PC. Resolve it before signing in again.",
|
|
1762
|
-
"login.error.conflict"
|
|
1763
|
-
],
|
|
1764
|
-
[
|
|
1765
|
-
"The operating system credential store did not retain the credential. Unlock it and restart AgentKnight.",
|
|
1766
|
-
"login.error.retention"
|
|
1767
|
-
],
|
|
1768
|
-
[
|
|
1769
|
-
"Use an HTTPS Relay origin without a path, credentials, query, or fragment. HTTP is allowed only for literal loopback addresses.",
|
|
1770
|
-
"login.error.origin"
|
|
1771
|
-
],
|
|
1772
|
-
[
|
|
1773
|
-
"Microsoft sign-in requires Windows Credential Manager, macOS Keychain, or Linux Secret Service. This operating system is not supported.",
|
|
1774
|
-
"login.error.platform"
|
|
1775
|
-
],
|
|
1776
|
-
[
|
|
1777
|
-
"The Relay credential exceeds the operating system credential store capacity. Existing credentials were not changed. Contact your Relay administrator.",
|
|
1778
|
-
"login.error.capacity"
|
|
1779
|
-
]
|
|
1780
|
-
]);
|
|
1781
|
-
function renderRelayLoginPage(input) {
|
|
1782
|
-
const locale = input.locale ?? "zh-CN";
|
|
1783
|
-
const { t, label, mark } = localPageLabels(locale);
|
|
1784
|
-
const login = input.login;
|
|
1785
|
-
const error = LOGIN_ERROR_MESSAGES.get(login.state === "error" ? login.message : input.error ?? "") ?? "login.error";
|
|
1786
|
-
const busy = login.state === "starting" || login.state === "confirming" || login.state === "signed-in";
|
|
1787
|
-
const signInKey = input.method === "aad" ? "login.work" : input.method === "microsoft" ? "login.personal" : input.method === "auto" ? "retry" : "login.signIn";
|
|
1788
|
-
const busyKey = login.state === "starting" ? input.method === "auto" ? "login.discovering" : "login.starting" : login.state === "confirming" ? "login.confirming" : "login.connecting";
|
|
1789
|
-
const startKey = login.state === "error" && input.method !== "auto" ? "login.retry" : signInKey;
|
|
1790
|
-
const token = `<input type="hidden" name="token" value="${escapeHtml(input.token)}">`;
|
|
1791
|
-
const action = login.state === "pending" ? `<a ${mark("login.continue")} class="btn btn-primary button" href="${escapeHtml(login.verificationUri)}" rel="noreferrer">${t("login.continue")}</a>
|
|
1792
|
-
<form method="post" action="/relay-login/cancel">${token}<button ${mark("cancel")} class="btn secondary" type="submit">${t("cancel")}</button></form>` : busy ? `<button ${mark(busyKey)} class="btn btn-primary" type="button" disabled aria-busy="true">${t(busyKey)}</button>` : `<form method="post" action="/relay-login/start">${token}<button ${mark(startKey)} class="btn btn-primary" type="submit">${t(startKey)}</button></form>`;
|
|
1793
|
-
return `<!doctype html>
|
|
1794
|
-
<html lang="${locale}">
|
|
1795
|
-
<head>
|
|
1796
|
-
<meta charset="utf-8">
|
|
1797
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1798
|
-
${localPageAssets}
|
|
1799
|
-
<script src="/relay-login.js" defer></script>
|
|
1800
|
-
<title>AgentKnight</title>
|
|
1801
|
-
</head>
|
|
1802
|
-
<body class="login-page">
|
|
1803
|
-
<main data-relay-login-state="${login.state}"${input.method === void 0 ? "" : ` data-relay-login-method="${input.method}"`}>
|
|
1804
|
-
<header><div class="login-toolbar"><span class="brand"><span class="brand-mark" aria-hidden="true"></span>AgentKnight</span>${renderLanguagePicker(locale)}</div><h1>${escapeHtml(input.machineName)}</h1></header>
|
|
1805
|
-
<section class="login" aria-labelledby="login-heading">
|
|
1806
|
-
<h2 id="login-heading">${label(login.state === "confirming" ? "login.confirm" : login.state === "signed-in" ? "login.launch" : input.method === "auto" ? "login.connect" : "login.title")}</h2>
|
|
1807
|
-
${login.state === "error" || input.error !== void 0 ? `<p class="error" role="alert">${label(error)}</p>` : ""}
|
|
1808
|
-
${action}
|
|
1809
|
-
<p id="login-poll-error" class="error" role="alert" hidden></p>
|
|
1810
|
-
</section>
|
|
1811
|
-
</main>
|
|
1812
|
-
</body>
|
|
1813
|
-
</html>`;
|
|
1814
|
-
}
|
|
1815
|
-
var relayLoginPageScript = `
|
|
1816
|
-
(() => {
|
|
1817
|
-
const { text, apply } = localUI;
|
|
1818
|
-
let main = document.querySelector('main[data-relay-login-state]');
|
|
1819
|
-
if (!main) return;
|
|
1820
|
-
let timer;
|
|
1821
|
-
let stopped = false;
|
|
1822
|
-
let refreshPage = false;
|
|
1823
|
-
let navigationGeneration = 0;
|
|
1824
|
-
const poll = async () => {
|
|
1825
|
-
const generation = navigationGeneration;
|
|
1826
|
-
const isCurrent = () => !stopped && generation === navigationGeneration;
|
|
1827
|
-
if (!isCurrent()) return;
|
|
1828
|
-
try {
|
|
1829
|
-
const response = await fetch('/relay-login/status', { cache: 'no-store' });
|
|
1830
|
-
if (!isCurrent()) return;
|
|
1831
|
-
if (!response.ok && response.status !== 404) throw new Error('Login status unavailable');
|
|
1832
|
-
const state = response.ok ? await response.json() : null;
|
|
1833
|
-
if (!isCurrent()) return;
|
|
1834
|
-
if (refreshPage || response.status === 404 || (state && typeof state.state === 'string' &&
|
|
1835
|
-
(state.state !== main.dataset.relayLoginState || state.method !== main.dataset.relayLoginMethod ||
|
|
1836
|
-
state.state === 'signed-in'))) {
|
|
1837
|
-
const page = await fetch('/', { cache: 'no-store' });
|
|
1838
|
-
if (!isCurrent()) return;
|
|
1839
|
-
if (!page.ok) throw new Error('Login page unavailable');
|
|
1840
|
-
const html = await page.text();
|
|
1841
|
-
if (!isCurrent()) return;
|
|
1842
|
-
const nextPage = new DOMParser().parseFromString(html, 'text/html');
|
|
1843
|
-
const nextMain = nextPage.querySelector('main[data-relay-login-state]');
|
|
1844
|
-
if (nextMain) {
|
|
1845
|
-
main.replaceWith(nextMain);
|
|
1846
|
-
main = nextMain;
|
|
1847
|
-
apply(main);
|
|
1848
|
-
refreshPage = false;
|
|
1849
|
-
} else if (nextPage.querySelector('#pairing-form')) {
|
|
1850
|
-
stopped = true;
|
|
1851
|
-
location.replace('/');
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
const error = document.querySelector('#login-poll-error');
|
|
1855
|
-
if (isCurrent() && error) error.hidden = true;
|
|
1856
|
-
} catch {
|
|
1857
|
-
const error = document.querySelector('#login-poll-error');
|
|
1858
|
-
if (isCurrent() && error) { text(error, 'login.pollError'); error.hidden = false; }
|
|
1859
|
-
} finally {
|
|
1860
|
-
if (isCurrent()) timer = setTimeout(poll, 1500);
|
|
1861
|
-
}
|
|
1862
|
-
};
|
|
1863
|
-
document.addEventListener('submit', event => {
|
|
1864
|
-
const form = event.target;
|
|
1865
|
-
const action = form.getAttribute('action');
|
|
1866
|
-
if (action !== '/relay-login/start' && action !== '/relay-login/cancel') return;
|
|
1867
|
-
const button = form.querySelector('button');
|
|
1868
|
-
if (button.disabled) { event.preventDefault(); return; }
|
|
1869
|
-
button.disabled = true;
|
|
1870
|
-
button.setAttribute('aria-busy', 'true');
|
|
1871
|
-
text(button, action === '/relay-login/start' ? 'login.starting' : 'login.cancelling');
|
|
1872
|
-
});
|
|
1873
|
-
addEventListener('pagehide', () => { stopped = true; navigationGeneration++; clearTimeout(timer); });
|
|
1874
|
-
addEventListener('pageshow', () => {
|
|
1875
|
-
if (stopped) {
|
|
1876
|
-
stopped = false;
|
|
1877
|
-
// Cached form controls may still be busy even when the login state is unchanged.
|
|
1878
|
-
refreshPage = true;
|
|
1879
|
-
timer = setTimeout(poll, 0);
|
|
1880
|
-
}
|
|
1881
|
-
});
|
|
1882
|
-
timer = setTimeout(poll, 1500);
|
|
1883
|
-
})();
|
|
1884
|
-
`;
|
|
1885
|
-
|
|
1886
|
-
// src/local-page-assets.ts
|
|
1887
|
-
import { readFile } from "node:fs/promises";
|
|
1888
|
-
async function readLocalPageAsset(path) {
|
|
1889
|
-
if (path === "/local-ui.css" && true) return '/*! daisyui\nMIT License\n\nCopyright (c) 2020 Pouya Saadeghi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\ntailwindcss\nMIT License\n\nCopyright (c) Tailwind Labs, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n:root { --brand-logo: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22512%22%20height%3D%22512%22%20viewBox%3D%220%200%2048%2048%22%20fill%3D%22none%22%3E%0A%20%20%3Cg%20stroke%3D%22%2355D6A0%22%20stroke-width%3D%221.5%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%20%20%3Cpath%20d%3D%22M24%207L41%2024L24%2041L7%2024Z%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M27.593%2010.593L37.407%2027.593L20.407%2037.407L10.593%2020.407Z%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M29.667%2014.185L33.815%2029.667L18.333%2033.815L14.185%2018.333Z%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M30.543%2017.457V30.543H17.457V17.457Z%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M30.543%2020.222L27.778%2030.543L17.457%2027.778L20.222%2017.457Z%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A"); }\n/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n@layer theme, base, components, utilities;\n@layer theme {\n :root, :host {\n --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",\n "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",\n "Segoe UI Symbol", "Noto Color Emoji";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",\n "Courier New", monospace;\n --default-font-family: var(--font-sans);\n --default-mono-font-family: var(--font-mono);\n }\n}\n@layer base {\n *, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n }\n html, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n }\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n abbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n }\n h1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n b, strong {\n font-weight: bolder;\n }\n code, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n }\n small {\n font-size: 80%;\n }\n sub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n sub {\n bottom: -0.25em;\n }\n sup {\n top: -0.5em;\n }\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n :-moz-focusring:where(:not(iframe)) {\n outline: auto;\n }\n progress {\n vertical-align: baseline;\n }\n summary {\n display: list-item;\n }\n ol, ul, menu {\n list-style: none;\n }\n img, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n }\n img, video {\n max-width: 100%;\n height: auto;\n }\n button, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n }\n :where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n }\n :where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n }\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n ::placeholder {\n opacity: 1;\n }\n @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n }\n textarea {\n resize: vertical;\n }\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n ::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n }\n ::-webkit-datetime-edit {\n display: inline-flex;\n }\n ::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n }\n ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n }\n ::-webkit-calendar-picker-indicator {\n line-height: 1;\n }\n :-moz-ui-invalid {\n box-shadow: none;\n }\n button, input:where([type="button"], [type="reset"], [type="submit"]), ::file-selector-button {\n appearance: button;\n }\n ::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n }\n [hidden]:where(:not([hidden="until-found"])) {\n display: none !important;\n }\n}\n@layer utilities {\n @layer daisyui.l1.l2.l3 {\n .modal {\n pointer-events: none;\n visibility: hidden;\n position: fixed;\n inset: 0px;\n margin: 0px;\n display: grid;\n height: 100%;\n max-height: none;\n width: 100%;\n max-width: none;\n align-items: center;\n justify-items: center;\n background-color: transparent;\n padding: 0px;\n color: inherit;\n transition: overlay 0.3s allow-discrete, visibility 0.3s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n overflow: clip;\n overscroll-behavior: contain;\n z-index: 999;\n scrollbar-gutter: auto;\n }\n .modal::backdrop {\n display: none;\n }\n .modal[popover] {\n inset: 0;\n margin: 0;\n border: 0;\n padding: 0;\n background: transparent;\n color: inherit;\n max-width: none;\n max-height: none;\n }\n .modal[popover]::backdrop {\n background-color: oklch(0% 0 0/ 0.4);\n transition: background-color 0.3s ease-out;\n }\n }\n @layer daisyui.l1.l2 {\n .modal.modal-open {\n pointer-events: auto;\n visibility: visible;\n opacity: 100%;\n transition: visibility 0s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n background-color: oklch(0% 0 0/ 0.4);\n }\n .modal.modal-open > .modal-box {\n translate: 0 0;\n scale: 1;\n opacity: 1;\n }\n :root:has(.modal.modal-open) {\n --page-scroll-lock: ;\n }\n @starting-style {\n .modal.modal-open {\n opacity: 0%;\n }\n }\n .modal[open] {\n pointer-events: auto;\n visibility: visible;\n opacity: 100%;\n transition: visibility 0s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n background-color: oklch(0% 0 0/ 0.4);\n }\n .modal[open] > .modal-box {\n translate: 0 0;\n scale: 1;\n opacity: 1;\n }\n :root:has(.modal[open]) {\n --page-scroll-lock: ;\n }\n @starting-style {\n .modal[open] {\n opacity: 0%;\n }\n }\n .modal:popover-open {\n pointer-events: auto;\n visibility: visible;\n opacity: 100%;\n transition: visibility 0s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n background-color: oklch(0% 0 0/ 0.4);\n }\n .modal:popover-open > .modal-box {\n translate: 0 0;\n scale: 1;\n opacity: 1;\n }\n :root:has(.modal:popover-open) {\n --page-scroll-lock: ;\n }\n @starting-style {\n .modal:popover-open {\n opacity: 0%;\n }\n }\n .modal:target {\n pointer-events: auto;\n visibility: visible;\n opacity: 100%;\n transition: visibility 0s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n background-color: oklch(0% 0 0/ 0.4);\n }\n .modal:target > .modal-box {\n translate: 0 0;\n scale: 1;\n opacity: 1;\n }\n :root:has(.modal:target) {\n --page-scroll-lock: ;\n }\n @starting-style {\n .modal:target {\n opacity: 0%;\n }\n }\n .modal-toggle:checked + .modal {\n pointer-events: auto;\n visibility: visible;\n opacity: 100%;\n transition: visibility 0s allow-discrete, background-color 0.3s ease-out, opacity 0.1s ease-out;\n background-color: oklch(0% 0 0/ 0.4);\n }\n .modal-toggle:checked + .modal > .modal-box {\n translate: 0 0;\n scale: 1;\n opacity: 1;\n }\n :root:has(.modal-toggle:checked + .modal) {\n --page-scroll-lock: ;\n }\n @starting-style {\n .modal-toggle:checked + .modal {\n opacity: 0%;\n }\n }\n }\n @layer daisyui.l1.l2.l3 {\n :where(.btn) {\n width: unset;\n }\n .btn {\n --size: calc(var(--size-field, 0.25rem) * 10);\n --btn-p: 1rem;\n --btn-fg: var(--color-base-content);\n display: inline-flex;\n flex-shrink: 0;\n cursor: pointer;\n flex-wrap: nowrap;\n align-items: center;\n justify-content: center;\n gap: calc(0.25rem * 1.5);\n text-align: center;\n vertical-align: middle;\n outline-offset: 2px;\n webkit-user-select: none;\n user-select: none;\n font-weight: 600;\n border-start-start-radius: var(--join-ss, var(--radius-field));\n border-start-end-radius: var(--join-se, var(--radius-field));\n border-end-start-radius: var(--join-es, var(--radius-field));\n border-end-end-radius: var(--join-ee, var(--radius-field));\n border-width: var(--border);\n touch-action: manipulation;\n transition-property: color, background-color, border-color, box-shadow, transform;\n transition-timing-function: cubic-bezier(0, 0, 0.2, 1);\n transition-duration: 0.2s;\n --btn-bg: var(--btn-color, var(--color-base-200));\n --btn-border: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn {\n --btn-border: color-mix(\n in oklab,\n var(--btn-color, var(--color-base-200)),\n #000 calc(var(--depth) * 5%)\n );\n }\n }\n .btn {\n --btn-soft-bg: initial;\n --btn-shadow: 0 3px 2px -2px var(--btn-bg),\n 0 4px 3px -2px var(--btn-bg);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn {\n --btn-shadow: 0 3px 2px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000),\n 0 4px 3px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000);\n }\n }\n .btn {\n --btn-inset: 0 0.5px 0 0.5px oklch(100% 0 0 / calc(var(--depth) * 6%));\n height: var(--size);\n padding-inline: var(--btn-p);\n font-size: var(--fontsize, 0.875rem);\n background-color: var(--btn-bg);\n color: var(--btn-fg);\n border-color: var(--btn-border);\n border-style: var(--btn-border-style, solid);\n outline-color: var(--btn-color, var(--color-base-content));\n --tw-prose-links: var(--btn-fg);\n background-image: none, var(--fx-noise);\n background-size: auto, calc(var(--noise, 0) * 100%);\n text-shadow: 0 0.5px oklch(100% 0 0 / calc(var(--depth) * 0.15));\n box-shadow: var(--btn-inset) inset, var(--btn-shadow);\n }\n .btn:is([type="checkbox"], [type="radio"]) {\n appearance: none;\n }\n .btn:is([type="checkbox"], [type="radio"])[aria-label]::after {\n --tw-content: attr(aria-label);\n content: var(--tw-content);\n }\n .btn:where(:checked:not(.filter [type="radio"].btn)) {\n --btn-color: var(--color-primary);\n --btn-fg: var(--color-primary-content);\n }\n }\n .prose :where(a.btn:not(.btn-link)):not(:where([class~="not-prose"], [class~="not-prose"] *)) {\n text-decoration-line: none;\n }\n @layer daisyui.l1 {\n @media (hover: hover) {\n .btn:hover {\n --btn-bg: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:hover {\n --btn-bg: color-mix(in oklab, var(--btn-color, var(--color-base-200)), #000 7%);\n }\n }\n .btn:hover {\n color: var(--btn-fg);\n --btn-border: var(--btn-bg);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:hover {\n --btn-border: color-mix(in oklab, var(--btn-bg), #000 calc(var(--depth) * 5%));\n }\n }\n .btn:hover {\n --btn-border-style: solid;\n --btn-inset: 0 0.5px 0 0.5px oklch(100% 0 0 / calc(var(--depth) * 6%));\n --btn-shadow: 0 3px 2px -2px var(--btn-bg),\n 0 4px 3px -2px var(--btn-bg);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:hover {\n --btn-shadow: 0 3px 2px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000),\n 0 4px 3px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000);\n }\n }\n }\n .btn:active:not(.btn-active, [aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n translate: 0 0.5px;\n --btn-bg: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:active:not(.btn-active, [aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-bg: color-mix(in oklab, var(--btn-color, var(--color-base-200)), #000 5%);\n }\n }\n .btn:active:not(.btn-active, [aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n color: var(--btn-fg, var(--color-base-content));\n --btn-border: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:active:not(.btn-active, [aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-border: color-mix(in oklab, var(--btn-color, var(--color-base-200)), #000 7%);\n }\n }\n .btn:active:not(.btn-active, [aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-border-style: solid;\n --btn-inset: 0 0 0 0 oklch(0% 0 0/0);\n --btn-shadow: 0 0 0 0 oklch(0% 0 0/0);\n }\n .btn:where(:checked:not(.filter [type="radio"].btn), :not([type="radio"], [type="checkbox"]):focus-visible ) {\n --btn-bg: var(--btn-color, var(--color-base-200));\n color: var(--btn-fg, var(--color-base-content));\n --btn-border: var(--btn-bg);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:where(:checked:not(.filter [type="radio"].btn), :not([type="radio"], [type="checkbox"]):focus-visible ) {\n --btn-border: color-mix(in oklab, var(--btn-bg), #000 calc(var(--depth) * 5%));\n }\n }\n .btn:where(:checked:not(.filter [type="radio"].btn), :not([type="radio"], [type="checkbox"]):focus-visible ) {\n --btn-border-style: solid;\n --btn-inset: 0 0.5px 0 0.5px oklch(100% 0 0 / calc(var(--depth) * 6%));\n --btn-shadow: 0 3px 2px -2px var(--btn-bg),\n 0 4px 3px -2px var(--btn-bg);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:where(:checked:not(.filter [type="radio"].btn), :not([type="radio"], [type="checkbox"]):focus-visible ) {\n --btn-shadow: 0 3px 2px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000),\n 0 4px 3px -2px color-mix(in oklab, var(--btn-bg) calc(var(--depth) * 30%), #0000);\n }\n }\n .btn:where(:checked:not(.filter [type="radio"].btn), :not([type="radio"], [type="checkbox"]):focus-visible ) {\n isolation: isolate;\n }\n .btn:focus-visible {\n outline-width: 2px;\n outline-style: solid;\n isolation: isolate;\n }\n .btn:has(:focus-visible) {\n outline-width: 2px;\n outline-style: solid;\n isolation: isolate;\n }\n }\n @layer daisyui.l1.l2 {\n .btn:is([aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-bg: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:is([aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-bg: color-mix(in oklab, var(--btn-color, var(--color-base-200)), #000 5%);\n }\n }\n .btn:is([aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n color: var(--btn-fg, var(--color-base-content));\n --btn-border: var(--btn-color, var(--color-base-200));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:is([aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-border: color-mix(in oklab, var(--btn-color, var(--color-base-200)), #000 7%);\n }\n }\n .btn:is([aria-pressed="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"], [aria-current=""]) ) {\n --btn-border-style: solid;\n --btn-inset: 0 0 0 0 oklch(0% 0 0/0);\n --btn-shadow: 0 0 0 0 oklch(0% 0 0/0);\n isolation: isolate;\n }\n }\n @layer daisyui {\n .btn:is(.btn-disabled, :disabled, [disabled], [aria-disabled="true"]) {\n pointer-events: none;\n color: var(--color-base-content);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:is(.btn-disabled, :disabled, [disabled], [aria-disabled="true"]) {\n color: color-mix(in oklch, var(--color-base-content) 20%, #0000);\n }\n }\n .btn:is(.btn-disabled, :disabled, [disabled], [aria-disabled="true"]) {\n --btn-bg: #0000;\n --btn-border: #0000;\n background-image: none;\n --btn-inset: 0 0 0 0 oklch(0% 0 0/0);\n --btn-shadow: 0 0 0 0 oklch(0% 0 0/0);\n }\n .btn:is(.btn-disabled, :disabled, [disabled], [aria-disabled="true"]):not(.btn-link, .btn-ghost) {\n background-color: var(--color-base-content);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .btn:is(.btn-disabled, :disabled, [disabled], [aria-disabled="true"]):not(.btn-link, .btn-ghost) {\n background-color: color-mix(in oklab, var(--color-base-content) 10%, transparent);\n }\n }\n }\n .visible {\n visibility: visible;\n }\n @layer daisyui.l1.l2.l3 {\n .checkbox {\n border: var(--border) solid var(--input-color, var(--color-base-content));\n }\n @supports (color: color-mix(in lab, red, red)) {\n .checkbox {\n border: var(--border) solid var(--input-color, color-mix(in oklab, var(--color-base-content) 20%, #0000));\n }\n }\n .checkbox {\n position: relative;\n display: inline-block;\n flex-shrink: 0;\n cursor: pointer;\n appearance: none;\n border-radius: var(--radius-selector);\n padding: 0.25rem;\n vertical-align: middle;\n color: var(--color-base-content);\n box-shadow: 0 1px oklch(0% 0 0 / calc(var(--depth) * 0.1)) inset, 0 0 #0000 inset, 0 0 #0000;\n transition: background-color 0.2s, box-shadow 0.2s;\n --size: calc(var(--size-selector, 0.25rem) * 6);\n width: var(--size);\n height: var(--size);\n background-size: auto, calc(var(--noise) * 100%);\n background-image: none, var(--fx-noise);\n }\n .checkbox:before {\n --tw-content: "";\n content: var(--tw-content);\n display: block;\n width: 100%;\n height: 100%;\n rotate: 45deg;\n background-color: currentcolor;\n opacity: 0%;\n transition: clip-path 0.3s, opacity 0.1s, rotate 0.3s, translate 0.3s;\n transition-delay: 0.1s;\n clip-path: polygon(20% 100%, 20% 80%, 50% 80%, 50% 80%, 70% 80%, 70% 100%);\n box-shadow: 0px 3px 0 0px oklch(100% 0 0 / calc(var(--depth) * 0.1)) inset;\n font-size: 1rem;\n line-height: 0.75;\n }\n .checkbox:focus-visible {\n outline: 2px solid var(--input-color, currentColor);\n outline-offset: 2px;\n }\n .checkbox:checked {\n background-color: var(--input-color, #0000);\n box-shadow: 0 0 #0000 inset, 0 8px 0 -4px oklch(100% 0 0 / calc(var(--depth) * 0.1)) inset, 0 1px oklch(0% 0 0 / calc(var(--depth) * 0.1));\n }\n .checkbox:checked:before {\n clip-path: polygon(20% 100%, 20% 80%, 50% 80%, 50% 0%, 70% 0%, 70% 100%);\n translate: 3.5% -7%;\n opacity: 100%;\n }\n @media (forced-colors: active) {\n .checkbox:checked:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2714\uFE0E";\n clip-path: none;\n }\n }\n @media print {\n .checkbox:checked:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2714\uFE0E";\n clip-path: none;\n }\n }\n .checkbox[aria-checked="true"] {\n background-color: var(--input-color, #0000);\n box-shadow: 0 0 #0000 inset, 0 8px 0 -4px oklch(100% 0 0 / calc(var(--depth) * 0.1)) inset, 0 1px oklch(0% 0 0 / calc(var(--depth) * 0.1));\n }\n .checkbox[aria-checked="true"]:before {\n clip-path: polygon(20% 100%, 20% 80%, 50% 80%, 50% 0%, 70% 0%, 70% 100%);\n translate: 3.5% -7%;\n opacity: 100%;\n }\n @media (forced-colors: active) {\n .checkbox[aria-checked="true"]:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2714\uFE0E";\n clip-path: none;\n }\n }\n @media print {\n .checkbox[aria-checked="true"]:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2714\uFE0E";\n clip-path: none;\n }\n }\n .checkbox:indeterminate {\n background-color: var( --input-color, var(--color-base-content) );\n }\n @supports (color: color-mix(in lab, red, red)) {\n .checkbox:indeterminate {\n background-color: var( --input-color, color-mix(in oklab, var(--color-base-content) 20%, #0000) );\n }\n }\n .checkbox:indeterminate:before {\n rotate: 0deg;\n opacity: 100%;\n translate: 0 -40%;\n clip-path: polygon(20% 100%, 20% 80%, 50% 80%, 50% 80%, 80% 80%, 80% 100%);\n }\n @media (forced-colors: active) {\n .checkbox:indeterminate:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2212";\n clip-path: none;\n translate: 0;\n }\n }\n .checkbox[aria-checked="mixed"] {\n background-color: var( --input-color, var(--color-base-content) );\n }\n @supports (color: color-mix(in lab, red, red)) {\n .checkbox[aria-checked="mixed"] {\n background-color: var( --input-color, color-mix(in oklab, var(--color-base-content) 20%, #0000) );\n }\n }\n .checkbox[aria-checked="mixed"]:before {\n rotate: 0deg;\n opacity: 100%;\n translate: 0 -40%;\n clip-path: polygon(20% 100%, 20% 80%, 50% 80%, 50% 80%, 80% 80%, 80% 100%);\n }\n @media (forced-colors: active) {\n .checkbox[aria-checked="mixed"]:before {\n rotate: 0deg;\n background-color: transparent;\n --tw-content: "\u2212";\n clip-path: none;\n translate: 0;\n }\n }\n }\n @layer daisyui.l1.l2 {\n .checkbox:disabled {\n cursor: not-allowed;\n opacity: 20%;\n }\n }\n @layer daisyui.l1.l2.l3 {\n .card {\n position: relative;\n display: flex;\n flex-direction: column;\n border-radius: var(--radius-box);\n transition: outline 0.2s ease-in-out;\n outline: 2px solid #0000;\n outline-offset: 2px;\n }\n .card:focus-visible {\n outline-color: currentColor;\n }\n .card[aria-checked="true"] {\n outline-color: currentColor;\n }\n .card:has( > :checked, > :is([type="checkbox"], [type="radio"]):focus-visible) {\n outline-color: currentColor;\n }\n .card:has( > :checked:focus-visible) {\n outline-width: 4px;\n }\n .card[aria-checked="true"]:focus-visible {\n outline-width: 4px;\n }\n .card[aria-checked="true"]:has( > :is([type="checkbox"], [type="radio"]):focus-visible) {\n outline-width: 4px;\n }\n .card:has( > :is([type="checkbox"], [type="radio"])) {\n cursor: pointer;\n user-select: none;\n }\n .card > :is([type="checkbox"], [type="radio"]) {\n appearance: none;\n }\n }\n @layer daisyui.l1.l2.l3.l4 {\n .card figure:first-child {\n overflow: hidden;\n border-start-start-radius: inherit;\n border-start-end-radius: inherit;\n border-end-start-radius: unset;\n border-end-end-radius: unset;\n }\n .card figure:last-child {\n overflow: hidden;\n border-start-start-radius: unset;\n border-start-end-radius: unset;\n border-end-start-radius: inherit;\n border-end-end-radius: inherit;\n }\n .card figure {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n }\n .fixed {\n position: fixed;\n }\n @layer daisyui.l1.l2.l3 {\n .modal-box {\n grid-column-start: 1;\n grid-row-start: 1;\n max-height: 100vh;\n width: calc(11 / 12 * 100%);\n max-width: 32rem;\n background-color: var(--color-base-100);\n padding: calc(0.25rem * 6);\n transition: translate 0.3s ease-out, scale 0.3s ease-out, opacity 0.2s ease-out 0.05s, box-shadow 0.3s ease-out;\n border-top-left-radius: var(--modal-tl, var(--radius-box));\n border-top-right-radius: var(--modal-tr, var(--radius-box));\n border-bottom-left-radius: var(--modal-bl, var(--radius-box));\n border-bottom-right-radius: var(--modal-br, var(--radius-box));\n scale: 95%;\n opacity: 0;\n box-shadow: oklch(0% 0 0/ 0.25) 0px 25px 50px -12px;\n overflow-y: auto;\n overscroll-behavior: contain;\n }\n }\n @layer daisyui.l1.l2 {\n .modal-top > .modal-box {\n height: auto;\n width: 100%;\n max-width: none;\n max-height: calc(100vh - 5em);\n translate: 0 -100%;\n scale: 1;\n --modal-tl: 0;\n --modal-tr: 0;\n --modal-bl: var(--radius-box);\n --modal-br: var(--radius-box);\n }\n .modal-middle > .modal-box {\n height: auto;\n width: calc(11 / 12 * 100%);\n max-width: 32rem;\n max-height: calc(100vh - 5em);\n translate: 0 2%;\n scale: 98%;\n --modal-tl: var(--radius-box);\n --modal-tr: var(--radius-box);\n --modal-bl: var(--radius-box);\n --modal-br: var(--radius-box);\n }\n .modal-bottom > .modal-box {\n height: auto;\n width: 100%;\n max-width: none;\n max-height: calc(100vh - 5em);\n translate: 0 100%;\n scale: 1;\n --modal-tl: var(--radius-box);\n --modal-tr: var(--radius-box);\n --modal-bl: 0;\n --modal-br: 0;\n }\n .modal-start > .modal-box {\n height: 100vh;\n max-height: none;\n width: auto;\n max-width: none;\n translate: -100% 0;\n scale: 1;\n --modal-tl: 0;\n --modal-tr: var(--radius-box);\n --modal-bl: 0;\n --modal-br: var(--radius-box);\n }\n [dir="rtl"] :is(.modal-start > .modal-box) {\n translate: 100% 0;\n --modal-tl: var(--radius-box);\n --modal-tr: 0;\n --modal-bl: var(--radius-box);\n --modal-br: 0;\n }\n .modal-end > .modal-box {\n height: 100vh;\n max-height: none;\n width: auto;\n max-width: none;\n translate: 100% 0;\n scale: 1;\n --modal-tl: var(--radius-box);\n --modal-tr: 0;\n --modal-bl: var(--radius-box);\n --modal-br: 0;\n }\n [dir="rtl"] :is(.modal-end > .modal-box) {\n translate: -100% 0;\n --modal-tl: 0;\n --modal-tr: var(--radius-box);\n --modal-bl: 0;\n --modal-br: var(--radius-box);\n }\n }\n @layer daisyui.l1.l2.l3 {\n .modal-action {\n margin-top: calc(0.25rem * 6);\n display: flex;\n justify-content: flex-end;\n gap: calc(0.25rem * 2);\n }\n .badge {\n display: inline-flex;\n flex-shrink: 0;\n align-items: center;\n justify-content: center;\n gap: calc(0.25rem * 2);\n border-radius: var(--radius-selector);\n vertical-align: middle;\n color: var(--badge-fg);\n border: var(--border) solid var(--badge-color, var(--color-base-200));\n font-size: 0.875rem;\n width: fit-content;\n background-size: auto, calc(var(--noise) * 100%);\n background-image: none, var(--fx-noise);\n background-color: var(--badge-bg);\n --badge-bg: var(--badge-color, var(--color-base-100));\n --badge-fg: var(--color-base-content);\n --size: calc(var(--size-selector, 0.25rem) * 6);\n height: var(--size);\n padding-inline: calc(var(--size) / 2 - var(--border));\n }\n }\n .flex {\n display: flex;\n }\n .hidden {\n display: none;\n }\n .table {\n display: table;\n }\n @layer daisyui.l1.l2 {\n .btn-square {\n padding-inline: 0px;\n width: var(--size);\n height: var(--size);\n }\n }\n .flex-shrink {\n flex-shrink: 1;\n }\n .border-collapse {\n border-collapse: collapse;\n }\n .transform {\n transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,);\n }\n .flex-wrap {\n flex-wrap: wrap;\n }\n .border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n @layer daisyui.l1.l2.l3 {\n .btn-ghost {\n --btn-bg: #0000;\n color: var(--btn-rest-fg, var(--btn-color, var(--color-base-content, currentColor)));\n --btn-border: #0000;\n background-image: none;\n --btn-inset: 0 0 0 0 oklch(0% 0 0/0);\n --btn-shadow: 0 0 0 0 oklch(0% 0 0/0);\n }\n }\n @layer daisyui.l1.l2 {\n .checkbox-sm {\n padding: 0.1875rem;\n --size: calc(var(--size-selector, 0.25rem) * 5);\n }\n .badge-sm {\n --size: calc(var(--size-selector, 0.25rem) * 5);\n font-size: 0.75rem;\n }\n }\n .outline {\n outline-style: var(--tw-outline-style);\n outline-width: 1px;\n }\n @layer daisyui.l1.l2 {\n .btn-primary {\n --btn-color: var(--color-primary);\n --btn-fg: var(--color-primary-content);\n --btn-soft-bg: initial;\n }\n .btn-sm {\n --fontsize: 0.75rem;\n --btn-p: 0.75rem;\n --size: calc(var(--size-field, 0.25rem) * 8);\n }\n }\n}\n:root {\n --color-primary: #087f5b;\n --color-primary-content: #fff;\n --color-secondary: var(--color-primary);\n --color-secondary-content: var(--color-primary-content);\n --color-accent: var(--color-primary);\n --color-accent-content: var(--color-primary-content);\n font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;\n background: var(--color-base-200);\n color: var(--color-base-content);\n --panel: var(--color-base-100);\n --soft: var(--color-base-200);\n --ui-border: var(--color-base-content);\n @supports (color: color-mix(in lab, red, red)) {\n --ui-border: color-mix(in oklab, var(--color-base-content) 12%, transparent);\n }\n --muted: var(--color-base-content);\n @supports (color: color-mix(in lab, red, red)) {\n --muted: color-mix(in oklab, var(--color-base-content) 65%, transparent);\n }\n --accent: var(--color-primary);\n --human: var(--color-primary);\n @supports (color: color-mix(in lab, red, red)) {\n --human: color-mix(in oklab, var(--color-primary) 10%, var(--panel));\n }\n --success: var(--color-success);\n --danger: var(--color-error);\n @supports (color: color-mix(in lab, red, red)) {\n --danger: color-mix(in oklab, var(--color-error) 68%, var(--color-base-content));\n }\n --shadow: 0 16px 48px #1018280d;\n}\n@media (prefers-color-scheme: dark) {\n :root {\n --color-primary: #55d6a0;\n --color-primary-content: #081018;\n }\n}\n* {\n box-sizing: border-box;\n}\nbody {\n margin: 0;\n padding: 40px 32px;\n min-height: 100vh;\n}\nmain {\n max-width: 1200px;\n margin: auto;\n}\nh1 {\n margin: 0;\n font-size: clamp(24px, 3vw, 32px);\n font-weight: 650;\n letter-spacing: -.8px;\n overflow-wrap: anywhere;\n}\nh2 {\n margin: 0;\n font-size: 17px;\n font-weight: 650;\n}\nh3 {\n margin: 0;\n font-size: 15px;\n font-weight: 600;\n overflow-wrap: anywhere;\n}\na:where(:not(.btn)) {\n color: var(--accent);\n text-decoration: none;\n}\na:where(:not(.btn)):hover {\n text-decoration: underline;\n}\nform {\n margin: 0;\n}\n.btn {\n font-weight: 600;\n box-shadow: none;\n text-shadow: none;\n}\n.ui-icon {\n width: 18px;\n height: 18px;\n flex-shrink: 0;\n}\n.icon-heading, .setting-label {\n display: inline-flex;\n align-items: center;\n gap: 10px;\n}\n.setting-label {\n min-width: 0;\n overflow-wrap: anywhere;\n}\n.icon-heading .ui-icon, .setting-label .ui-icon, .relay-action .ui-icon {\n color: var(--accent);\n}\n.relay-action {\n background: transparent;\n border-color: transparent;\n color: var(--color-base-content);\n}\n.relay-action:hover:not(:disabled) {\n background: var(--human);\n}\n.relay-action:disabled {\n background: transparent;\n color: var(--muted);\n}\n.secondary {\n background: var(--panel);\n color: var(--color-base-content);\n border-color: var(--ui-border);\n}\n.brand {\n display: inline-flex;\n align-items: center;\n gap: 9px;\n font-size: 13px;\n font-weight: 650;\n color: var(--muted);\n margin-bottom: 10px;\n}\n.brand-mark {\n width: 36px;\n height: 36px;\n flex-shrink: 0;\n background: var(--brand-logo) center / contain no-repeat;\n}\n.dashboard-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 24px;\n padding-bottom: 30px;\n margin-bottom: 30px;\n border-bottom: 1px solid var(--ui-border);\n}\n.header-actions {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 10px;\n min-width: 0;\n flex-wrap: wrap;\n}\n.language-picker {\n width: auto;\n min-width: 102px;\n background-color: var(--panel);\n border-color: var(--ui-border);\n}\n.account {\n position: relative;\n min-width: 0;\n border: 0;\n}\n.account > summary {\n display: flex;\n gap: 10px;\n align-items: center;\n padding: 8px;\n cursor: pointer;\n list-style: none;\n}\n.account-name {\n font-size: 13px;\n font-weight: 600;\n max-width: 180px;\n overflow-wrap: anywhere;\n}\n.account .badge {\n border: 0;\n color: var(--muted);\n background: var(--soft);\n white-space: nowrap;\n}\n.account[data-state=signed-in] .badge {\n color: var(--color-success);\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, var(--color-success) 70%, var(--color-base-content));\n }\n background: var(--color-success);\n @supports (color: color-mix(in lab, red, red)) {\n background: color-mix(in oklab, var(--color-success) 12%, var(--panel));\n }\n}\n.account-content {\n position: absolute;\n z-index: 4;\n right: 0;\n top: 100%;\n width: 260px;\n padding: 18px;\n border: 1px solid var(--ui-border);\n background: var(--panel);\n border-radius: 14px;\n box-shadow: var(--shadow);\n}\n.account-meta {\n display: flex;\n flex-wrap: wrap;\n gap: 10px;\n font-size: 12px;\n color: var(--muted);\n}\n.account .error:not([hidden]) {\n margin-top: 12px;\n}\n.layout {\n display: grid;\n grid-template-columns: minmax(0, 1fr) 320px;\n gap: 28px;\n align-items: start;\n}\n.sidebar {\n display: grid;\n gap: 18px;\n}\n.section-heading {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 12px;\n margin-bottom: 16px;\n}\nfieldset {\n margin: 0;\n padding: 0;\n border: 0;\n min-width: 0;\n}\n.agent {\n margin-bottom: 16px;\n background: var(--panel);\n border: 1px solid var(--ui-border);\n border-radius: 16px;\n overflow: hidden;\n box-shadow: 0 2px 6px #10182803;\n}\n.agent:has(input:checked) {\n border-color: var(--accent);\n @supports (color: color-mix(in lab, red, red)) {\n border-color: color-mix(in oklab, var(--accent) 32%, var(--ui-border));\n }\n}\n.agent-heading {\n display: flex;\n align-items: center;\n gap: 14px;\n padding: 22px;\n}\n.agent-identity {\n flex: 1;\n min-width: 0;\n}\n.agent-icon {\n display: grid;\n place-items: center;\n width: 42px;\n height: 42px;\n padding: 9px;\n border-radius: 12px;\n background: var(--soft);\n flex-shrink: 0;\n}\n.agent-icon svg {\n width: 100%;\n height: 100%;\n}\n.agent-pi-icon {\n display: block;\n text-align: center;\n font: bold 28px/28px Georgia, serif;\n}\n.connection {\n display: flex;\n align-items: center;\n gap: 6px;\n margin-top: 5px;\n color: var(--muted);\n font-size: 12px;\n}\n.connection::before {\n content: "";\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--muted);\n flex-shrink: 0;\n}\n.connected::before {\n background: var(--color-success);\n}\n.expose {\n display: flex;\n align-items: center;\n gap: 10px;\n font-size: 12px;\n color: var(--muted);\n cursor: pointer;\n}\n.expose .checkbox {\n color: var(--accent);\n}\n.agent > details {\n border-top: 1px solid var(--ui-border);\n}\n.agent summary {\n cursor: pointer;\n padding: 14px 22px;\n color: var(--muted);\n font-size: 12px;\n}\n.count {\n float: right;\n font-variant-numeric: tabular-nums;\n}\n.session-folders {\n list-style: none;\n margin: 0;\n padding: 0 16px 10px;\n max-height: 480px;\n overflow-y: auto;\n}\n.session-folders > li + li {\n border-top: 1px solid var(--ui-border);\n}\n.session-folder > summary {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 14px 6px;\n list-style: none;\n border-radius: 8px;\n}\n.session-folder > summary:hover, .session-link:hover, .session-link:focus-visible {\n background: var(--soft);\n text-decoration: none;\n}\n.folder-icon {\n color: var(--accent);\n flex-shrink: 0;\n}\n.folder-icon svg {\n width: 20px;\n height: 20px;\n}\n.folder-label {\n flex: 1;\n min-width: 0;\n}\n.folder-name {\n display: block;\n font-size: 13px;\n font-weight: 600;\n overflow-wrap: anywhere;\n}\n.folder-path {\n display: block;\n margin-top: 4px;\n font-size: 11px;\n color: var(--muted);\n overflow-wrap: anywhere;\n}\n.folder-count {\n min-width: 22px;\n padding: 2px 6px;\n text-align: center;\n background: var(--soft);\n border-radius: 6px;\n font-size: 11px;\n font-variant-numeric: tabular-nums;\n}\n.folder-chevron svg {\n width: 12px;\n height: 12px;\n}\n.session-folder[open] > summary .folder-chevron {\n transform: rotate(90deg);\n}\n.sessions {\n list-style: none;\n margin: 0 6px 12px 16px;\n padding: 0 0 0 20px;\n border-left: 1px solid var(--ui-border);\n}\n.session + .session {\n border-top: 1px solid var(--ui-border);\n}\n.session-link {\n display: flex;\n align-items: center;\n gap: 12px;\n margin: 0 -10px;\n padding: 14px 10px;\n color: inherit;\n border-radius: 10px;\n}\n.session-symbol {\n display: grid;\n place-items: center;\n width: 30px;\n height: 30px;\n border: 1px solid var(--ui-border);\n border-radius: 8px;\n flex-shrink: 0;\n color: var(--muted);\n}\n.session-link svg {\n width: 16px;\n height: 16px;\n}\n.session-label {\n flex: 1;\n min-width: 0;\n}\n.session-chevron {\n color: var(--muted);\n flex-shrink: 0;\n}\n.session-name {\n display: block;\n font-size: 13px;\n line-height: 1.6;\n overflow-wrap: anywhere;\n white-space: pre-line;\n}\n.chat-settings {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 14px;\n margin-bottom: 28px;\n}\n.chat-settings:where(:has(#image-settings:not([hidden]))) {\n grid-template-columns: repeat(3, minmax(0, 1fr));\n}\n#image-settings .chat-setting {\n height: 100%;\n}\n#image-error {\n grid-column: 1 / -1;\n}\n.chat-setting {\n min-width: 0;\n padding: 18px;\n border-radius: 14px;\n border: 1px solid var(--ui-border);\n background: var(--panel);\n}\n.setting-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 14px;\n font-size: 13px;\n font-weight: 550;\n}\nbutton.toggle {\n width: 40px;\n height: 24px;\n padding: 3px;\n border: 0;\n border-radius: 999px;\n background: var(--muted);\n flex-shrink: 0;\n cursor: pointer;\n}\n.toggle[aria-checked=true] {\n background: var(--accent);\n}\n.toggle span {\n display: block;\n width: 18px;\n height: 18px;\n border-radius: 50%;\n background: #fff;\n transition: transform .15s;\n}\n.toggle[aria-checked=true] span {\n transform: translateX(16px);\n}\n.chat-setting .error:not([hidden]) {\n margin-top: 12px;\n}\n.sync-actions {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n gap: 12px;\n min-width: 0;\n}\n#save-status {\n max-width: 120px;\n font-size: 12px;\n color: var(--muted);\n}\n.pairing {\n padding: 22px;\n border: 1px solid var(--ui-border);\n border-radius: 16px;\n background: var(--panel);\n}\n.qr-area {\n display: grid;\n place-items: center;\n min-height: 252px;\n margin: 20px 0;\n border-radius: 12px;\n background: var(--soft);\n overflow: hidden;\n}\n.qr-placeholder {\n width: 58px;\n height: 58px;\n color: var(--muted);\n opacity: .6;\n}\n.qr {\n width: 100%;\n background: #fff;\n}\n.qr svg {\n display: block;\n width: 100%;\n height: auto;\n}\n.pairing-string {\n display: flex;\n align-items: center;\n gap: 8px;\n min-width: 0;\n margin-bottom: 12px;\n}\n.pairing-string input {\n flex: 1;\n min-width: 0;\n width: 0;\n border: 0;\n background: transparent;\n color: inherit;\n font: inherit;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.pairing-string button {\n flex-shrink: 0;\n}\n.pair-actions {\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n}\n.pair-actions button {\n flex: 1;\n padding-inline: 12px;\n}\n#pair-success {\n text-align: center;\n font-weight: 600;\n}\n.pair-check {\n display: block;\n font-size: 36px;\n margin-bottom: 10px;\n color: var(--color-success);\n}\n.device-row + .device-row {\n margin-top: 16px;\n padding-top: 16px;\n border-top: 1px solid var(--ui-border);\n}\n.device-row h3 {\n font-size: 13px;\n}\n.device-actions {\n display: flex;\n gap: 6px;\n margin-top: 12px;\n flex-wrap: wrap;\n}\n.device-actions .btn {\n font-size: 12px;\n}\n.directory {\n display: block;\n font-size: 11px;\n color: var(--muted);\n margin-top: 8px;\n}\n.deployment-details {\n border: 0;\n padding: 0 8px;\n color: var(--muted);\n font-size: 12px;\n}\n.deployment-details > summary {\n cursor: pointer;\n padding: 8px 0;\n}\n.deployment {\n margin: 8px 0;\n}\n.deployment > div + div {\n margin-top: 14px;\n}\n.deployment dt {\n font-size: 11px;\n color: var(--muted);\n}\n.deployment dd {\n margin: 4px 0 0;\n font-size: 12px;\n overflow-wrap: anywhere;\n}\n.error, .empty {\n margin: 0;\n font-size: 13px;\n line-height: 1.7;\n overflow-wrap: anywhere;\n}\n.error {\n color: var(--danger);\n}\n.empty {\n padding: 12px 0;\n color: var(--muted);\n}\n.agent-error {\n padding: 0 22px 18px;\n}\n#pair-error:not([hidden]), #save-error:not([hidden]), #clients-error:not([hidden]) {\n margin-top: 14px;\n}\n.modal-box {\n width: min(440px, calc(100vw - 32px));\n max-height: calc(100dvh - 32px);\n padding: 32px;\n border: 1px solid var(--ui-border);\n border-radius: 22px;\n background: var(--panel);\n box-shadow: 0 24px 80px #0003;\n}\n.modal::backdrop {\n background: #10182873;\n backdrop-filter: blur(4px);\n}\n.approval-icon {\n display: grid;\n place-items: center;\n width: 52px;\n height: 52px;\n border-radius: 16px;\n color: var(--accent);\n background: var(--human);\n margin-bottom: 22px;\n}\n.approval-icon svg {\n width: 28px;\n height: 28px;\n}\n#client-approval-title {\n font-size: 22px;\n letter-spacing: -.4px;\n}\n#client-approval-device {\n margin: 12px 0 22px;\n color: var(--muted);\n font-size: 14px;\n overflow-wrap: anywhere;\n}\n.verification {\n background: var(--soft);\n border: 1px solid var(--ui-border);\n border-radius: 12px;\n padding: 18px;\n}\n#client-approval-code-label {\n display: block;\n font-size: 12px;\n color: var(--muted);\n margin-bottom: 10px;\n}\n#client-approval-code {\n display: block;\n font-family: "Cascadia Code", Consolas, monospace;\n font-size: 30px;\n font-weight: 600;\n letter-spacing: 5px;\n overflow-wrap: anywhere;\n}\n#client-approval-error:not([hidden]) {\n margin-top: 16px;\n}\n.modal-action {\n gap: 10px;\n margin-top: 26px;\n flex-wrap: wrap;\n}\n.login-page main {\n max-width: 480px;\n margin: 8vh auto;\n}\n.login-page header {\n margin-bottom: 28px;\n}\n.login-toolbar {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 24px;\n}\n.login-toolbar .brand {\n margin: 0;\n}\n.login {\n padding: 30px;\n background: var(--panel);\n border: 1px solid var(--ui-border);\n border-radius: 20px;\n box-shadow: var(--shadow);\n}\n.login h2 {\n margin-bottom: 24px;\n font-size: 20px;\n}\n.login .btn {\n width: 100%;\n height: auto;\n min-height: 44px;\n padding: 12px 18px;\n white-space: normal;\n}\n.login form + form, .login .button + form {\n margin-top: 12px;\n}\n.login .error {\n margin-bottom: 22px;\n}\n#login-poll-error:not([hidden]) {\n margin-top: 18px;\n}\n[hidden] {\n display: none !important;\n}\n:focus-visible {\n outline: 3px solid var(--accent);\n outline-offset: 4px;\n}\nsummary::-webkit-details-marker {\n display: none;\n}\nbutton:disabled {\n cursor: default;\n}\n@media (max-width: 960px) {\n body {\n padding: 28px 20px;\n }\n .dashboard-header {\n align-items: flex-start;\n flex-direction: column;\n gap: 20px;\n }\n .header-actions {\n justify-content: flex-start;\n }\n .layout {\n grid-template-columns: minmax(0, 1fr) 292px;\n gap: 20px;\n }\n .chat-settings {\n grid-template-columns: 1fr;\n }\n}\n@media (max-width: 700px) {\n body {\n padding: 24px 16px;\n }\n .brand-mark {\n width: 32px;\n height: 32px;\n }\n .dashboard-header {\n padding-bottom: 22px;\n margin-bottom: 24px;\n }\n .header-actions {\n gap: 8px;\n width: 100%;\n }\n .account {\n margin-right: auto;\n }\n .account-name {\n max-width: 130px;\n }\n .account-content {\n left: 0;\n right: auto;\n }\n .layout {\n grid-template-columns: minmax(0, 1fr);\n gap: 24px;\n }\n .chat-settings {\n grid-template-columns: 1fr;\n gap: 10px;\n }\n .agent-heading {\n padding: 18px;\n gap: 12px;\n flex-wrap: wrap;\n }\n .agent-icon {\n width: 36px;\n height: 36px;\n padding: 7px;\n }\n .agent-identity {\n min-width: 100px;\n }\n .expose {\n margin-left: auto;\n }\n .qr-area {\n width: 100%;\n max-width: 280px;\n margin-inline: auto;\n }\n .modal-box {\n padding: 26px;\n }\n .modal-action .btn {\n flex: 1;\n }\n .login-page main {\n margin: 3vh auto;\n }\n .login {\n padding: 24px;\n }\n}\n@media (prefers-reduced-motion: reduce) {\n *, *::before, *::after {\n animation-duration: 0s !important;\n transition-duration: 0s !important;\n scroll-behavior: auto !important;\n }\n}\n@layer base {\n :where(:root),:root:has(input.theme-controller[value=light]:checked),[data-theme=light] {\n color-scheme: light;\n --color-base-100: oklch(100% 0 0);\n --color-base-200: oklch(98% 0 0);\n --color-base-300: oklch(95% 0 0);\n --color-base-content: oklch(21% 0.006 285.885);\n --color-primary: oklch(45% 0.24 277.023);\n --color-primary-content: oklch(93% 0.034 272.788);\n --color-secondary: oklch(65% 0.241 354.308);\n --color-secondary-content: oklch(94% 0.028 342.258);\n --color-accent: oklch(77% 0.152 181.912);\n --color-accent-content: oklch(38% 0.063 188.416);\n --color-neutral: oklch(14% 0.005 285.823);\n --color-neutral-content: oklch(92% 0.004 286.32);\n --color-info: oklch(74% 0.16 232.661);\n --color-info-content: oklch(29% 0.066 243.157);\n --color-success: oklch(76% 0.177 163.223);\n --color-success-content: oklch(37% 0.077 168.94);\n --color-warning: oklch(82% 0.189 84.429);\n --color-warning-content: oklch(41% 0.112 45.904);\n --color-error: oklch(71% 0.194 13.428);\n --color-error-content: oklch(27% 0.105 12.094);\n --radius-selector: 0.5rem;\n --radius-field: 0.25rem;\n --radius-box: 0.5rem;\n --size-selector: 0.25rem;\n --size-field: 0.25rem;\n --border: 1px;\n --depth: 1;\n --noise: 0;\n }\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme]) {\n color-scheme: dark;\n --color-base-100: oklch(25.33% 0.016 252.42);\n --color-base-200: oklch(23.26% 0.014 253.1);\n --color-base-300: oklch(21.15% 0.012 254.09);\n --color-base-content: oklch(97.807% 0.029 256.847);\n --color-primary: oklch(58% 0.233 277.117);\n --color-primary-content: oklch(96% 0.018 272.314);\n --color-secondary: oklch(65% 0.241 354.308);\n --color-secondary-content: oklch(94% 0.028 342.258);\n --color-accent: oklch(77% 0.152 181.912);\n --color-accent-content: oklch(38% 0.063 188.416);\n --color-neutral: oklch(14% 0.005 285.823);\n --color-neutral-content: oklch(92% 0.004 286.32);\n --color-info: oklch(74% 0.16 232.661);\n --color-info-content: oklch(29% 0.066 243.157);\n --color-success: oklch(76% 0.177 163.223);\n --color-success-content: oklch(37% 0.077 168.94);\n --color-warning: oklch(82% 0.189 84.429);\n --color-warning-content: oklch(41% 0.112 45.904);\n --color-error: oklch(71% 0.194 13.428);\n --color-error-content: oklch(27% 0.105 12.094);\n --radius-selector: 0.5rem;\n --radius-field: 0.25rem;\n --radius-box: 0.5rem;\n --size-selector: 0.25rem;\n --size-field: 0.25rem;\n --border: 1px;\n --depth: 1;\n --noise: 0;\n }\n }\n :root:has(input.theme-controller[value=light]:checked),[data-theme=light] {\n color-scheme: light;\n --color-base-100: oklch(100% 0 0);\n --color-base-200: oklch(98% 0 0);\n --color-base-300: oklch(95% 0 0);\n --color-base-content: oklch(21% 0.006 285.885);\n --color-primary: oklch(45% 0.24 277.023);\n --color-primary-content: oklch(93% 0.034 272.788);\n --color-secondary: oklch(65% 0.241 354.308);\n --color-secondary-content: oklch(94% 0.028 342.258);\n --color-accent: oklch(77% 0.152 181.912);\n --color-accent-content: oklch(38% 0.063 188.416);\n --color-neutral: oklch(14% 0.005 285.823);\n --color-neutral-content: oklch(92% 0.004 286.32);\n --color-info: oklch(74% 0.16 232.661);\n --color-info-content: oklch(29% 0.066 243.157);\n --color-success: oklch(76% 0.177 163.223);\n --color-success-content: oklch(37% 0.077 168.94);\n --color-warning: oklch(82% 0.189 84.429);\n --color-warning-content: oklch(41% 0.112 45.904);\n --color-error: oklch(71% 0.194 13.428);\n --color-error-content: oklch(27% 0.105 12.094);\n --radius-selector: 0.5rem;\n --radius-field: 0.25rem;\n --radius-box: 0.5rem;\n --size-selector: 0.25rem;\n --size-field: 0.25rem;\n --border: 1px;\n --depth: 1;\n --noise: 0;\n }\n :root:has(input.theme-controller[value=dark]:checked),[data-theme=dark] {\n color-scheme: dark;\n --color-base-100: oklch(25.33% 0.016 252.42);\n --color-base-200: oklch(23.26% 0.014 253.1);\n --color-base-300: oklch(21.15% 0.012 254.09);\n --color-base-content: oklch(97.807% 0.029 256.847);\n --color-primary: oklch(58% 0.233 277.117);\n --color-primary-content: oklch(96% 0.018 272.314);\n --color-secondary: oklch(65% 0.241 354.308);\n --color-secondary-content: oklch(94% 0.028 342.258);\n --color-accent: oklch(77% 0.152 181.912);\n --color-accent-content: oklch(38% 0.063 188.416);\n --color-neutral: oklch(14% 0.005 285.823);\n --color-neutral-content: oklch(92% 0.004 286.32);\n --color-info: oklch(74% 0.16 232.661);\n --color-info-content: oklch(29% 0.066 243.157);\n --color-success: oklch(76% 0.177 163.223);\n --color-success-content: oklch(37% 0.077 168.94);\n --color-warning: oklch(82% 0.189 84.429);\n --color-warning-content: oklch(41% 0.112 45.904);\n --color-error: oklch(71% 0.194 13.428);\n --color-error-content: oklch(27% 0.105 12.094);\n --radius-selector: 0.5rem;\n --radius-field: 0.25rem;\n --radius-box: 0.5rem;\n --size-selector: 0.25rem;\n --size-field: 0.25rem;\n --border: 1px;\n --depth: 1;\n --noise: 0;\n }\n}\n@property --tw-rotate-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-z {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-outline-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@layer properties {\n @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {\n *, ::before, ::after, ::backdrop {\n --tw-rotate-x: initial;\n --tw-rotate-y: initial;\n --tw-rotate-z: initial;\n --tw-skew-x: initial;\n --tw-skew-y: initial;\n --tw-border-style: solid;\n --tw-outline-style: solid;\n }\n }\n}\n';
|
|
1890
|
-
if (path === "/local-ui.js" && true) return '/*! i18next\nThe MIT License (MIT)\n\nCopyright (c) 2011-present i18next\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n"use strict";(()=>{var h=r=>typeof r=="string",z=()=>{let r,e,t=new Promise((s,n)=>{r=s,e=n});return t.resolve=r,t.reject=e,t},q=r=>r==null?"":String(r),Ie=r=>h(r)&&/^[A-Za-z0-9_@.-]{1,128}$/.test(r)&&!r.includes("..")&&!["__proto__","constructor","prototype"].includes(r),re=r=>r?.callbackApi??r?.constructor?.callbackApi,Me=(r,e,t)=>{r.forEach(s=>{e[s]&&(t[s]=e[s])})},Ve=/###/g,xe=r=>r&&r.includes("###")?r.replace(Ve,"."):r,Le=r=>!r||h(r),B=(r,e,t)=>{let s=h(e)?e.split("."):e,n=0;for(;n<s.length-1;){if(Le(r))return{};let i=xe(s[n]);!r[i]&&t&&(r[i]=new t),Object.prototype.hasOwnProperty.call(r,i)?r=r[i]:r={},++n}return Le(r)?{}:{obj:r,k:xe(s[n])}},ve=(r,e,t)=>{let{obj:s,k:n}=B(r,e,Object);if(s!==void 0||e.length===1){s[n]=t;return}let i=e[e.length-1],a=e.slice(0,e.length-1),o=B(r,a,Object);for(;o.obj===void 0&&a.length;)i=`${a[a.length-1]}.${i}`,a=a.slice(0,a.length-1),o=B(r,a,Object),o?.obj&&typeof o.obj[`${o.k}.${i}`]<"u"&&(o.obj=void 0);o.obj[`${o.k}.${i}`]=t},He=(r,e,t,s)=>{let{obj:n,k:i}=B(r,e,Object);n[i]=n[i]||[],n[i].push(t)},Q=(r,e)=>{let{obj:t,k:s}=B(r,e);if(t&&Object.prototype.hasOwnProperty.call(t,s))return t[s]},Ue=(r,e,t)=>{let s=Q(r,t);return s!==void 0?s:Q(e,t)},$e=(r,e,t)=>{for(let s in e)s!=="__proto__"&&s!=="constructor"&&(Object.prototype.hasOwnProperty.call(r,s)?h(r[s])||r[s]instanceof String||h(e[s])||e[s]instanceof String?t&&(r[s]=e[s]):$e(r[s],e[s],t):r[s]=e[s]);return r},N=r=>r.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g,"\\\\$&"),ze={"&":"&","<":"<",">":">",\'"\':""","\'":"'","/":"/"},Se=r=>h(r)?r.replace(/[&<>"\'\\/]/g,e=>ze[e]):r,ae=class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(t!==void 0)return t;let s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}},Be=[" ",",","?","!",";"],_e=new ae(20),qe=(r,e,t)=>{e=e||"",t=t||"";let s=Be.filter(a=>!e.includes(a)&&!t.includes(a));if(s.length===0)return!0;let n=_e.getRegExp(`(${s.map(a=>a==="?"?"\\\\?":a).join("|")})`),i=!n.test(r);if(!i){let a=r.indexOf(t);a>0&&!n.test(r.substring(0,a))&&(i=!0)}return i},oe=(r,e,t=".")=>{if(!r)return;if(r[e])return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0;let s=e.split(t),n=r;for(let i=0;i<s.length;){if(!n||typeof n!="object")return;let a,o="";for(let l=i;l<s.length;++l)if(l!==i&&(o+=t),o+=s[l],a=n[o],(typeof a=="function"||o==="__proto__")&&!Object.prototype.hasOwnProperty.call(n,o)&&(a=void 0),a!==void 0){if(["string","number","boolean"].includes(typeof a)&&l<s.length-1)continue;i+=l-i+1;break}n=a}return n},M=r=>r?.replace(/_/g,"-"),We={type:"logger",log(r){this.output("log",r)},warn(r){this.output("warn",r)},error(r){this.output("error",r)},output(r,e){console?.[r]?.apply?.(console,e)}},le=class r{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||We,this.options=t,this.debug=t.debug,this.seen=new Set}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}once(e,t,...s){return!this.debug||this.seen.has(e)||this.seen.size>=1e3?null:(this.seen.add(e),this[t](...s))}forward(e,t,s,n){return n&&!this.debug?null:(e=e.map(i=>h(i)?i.replace(/[\\r\\n\\x00-\\x1F\\x7F]/g," "):i),h(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new r(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new r(this.logger,e)}},k=new le,V=class{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(s=>{this.observers[s]||(this.observers[s]=new Map);let n=this.observers[s].get(t)||0;this.observers[s].set(t,n+1)}),this}off(e,t){(typeof e=="string"?e.split(" "):[e]).forEach(s=>{if(this.observers[s]){if(!t){delete this.observers[s];return}this.observers[s].delete(t)}})}once(e,t){let s=(...n)=>{t(...n),this.off(e,s)};return this.on(e,s),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([n,i])=>{for(let a=0;a<i;a++)n(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([n,i])=>{for(let a=0;a<i;a++)n(e,...t)})}},Re=new WeakSet,Y=class extends V{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,this.logger=k.create("resourceStore"),this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){let t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}deprecateDottedLng(e){this.logger.once(e,"deprecate",`${e}: a dotted language (\'en.translation.key\') that carries the namespace and key is removed in v27; pass language, namespace and key as separate arguments`)}getResource(e,t,s,n={}){let i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,a=n.ignoreJSONStructure!==void 0?n.ignoreJSONStructure:this.options.ignoreJSONStructure,o;e.includes(".")?(this.deprecateDottedLng("getResource"),o=e.split(".")):(o=[e,t],s&&(Array.isArray(s)?o.push(...s):h(s)&&i?o.push(...s.split(i)):o.push(s)));let l=Q(this.data,o);return l==null&&!t&&!s&&e.includes(".")&&(e=o[0],t=o[1],s=o.slice(2).join(".")),l!=null||!a||!h(s)?l:oe(this.data?.[e]?.[t],s,i)}addResource(e,t,s,n,i={silent:!1}){let a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=[e,t];s&&(o=o.concat(a?s.split(a):s)),e.includes(".")&&(this.deprecateDottedLng("addResource"),o=e.split("."),n=t,t=o[1]),this.addNamespaces(t),ve(this.data,o,n),i.silent||this.emit("added",e,t,s,n)}addResources(e,t,s,n={silent:!1}){for(let i in s)(h(s[i])||Array.isArray(s[i]))&&this.addResource(e,t,i,s[i],{silent:!0});n.silent||this.emit("added",e,t,s)}addResourceBundle(e,t,s,n,i,a={silent:!1,skipCopy:!1}){let o=[e,t];e.includes(".")&&(this.deprecateDottedLng("addResourceBundle"),o=e.split("."),n=s,s=t,t=o[1]),this.addNamespaces(t);let l=Q(this.data,o)||{};a.skipCopy||(s=JSON.parse(JSON.stringify(s))),n?$e(l,s,i):l={...l,...s},ve(this.data,o,l),a.silent||this.emit("added",e,t,s)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(n=>{let i=t[n];return Re.has(i)?!0:!i||Object.keys(i).length===0?!1:(typeof i=="object"&&Re.add(i),!0)})}toJSON(){return this.data}},ce={processors:{},addPostProcessor(r){this.processors[r.name]=r},handle(r,e,t,s,n){return r.forEach(i=>{e=this.processors[i]?.process(e,t,s,n)??e}),e}},Ee=Symbol("i18next/PATH_KEY");function Je(){let r=[],e=Object.create(null),t;return e.get=(s,n)=>(t?.revoke?.(),n===Ee?r:(r.push(n),t=Proxy.revocable(s,e),t.proxy)),Proxy.revocable(Object.create(null),e).proxy}function I(r,e){let{[Ee]:t}=r(Je()),s=e?.keySeparator??".",n=e?.nsSeparator??":",i=e?.enableSelector==="strict";if(t.length>1&&n){let a=e?.ns,o=i?Array.isArray(a)?a:a?[a]:null:Array.isArray(a)?a:null;if(o&&(i?o:o.length>1?o.slice(1):[]).includes(t[0]))return`${t[0]}${n}${t.slice(1).join(s)}`}return t.join(s)}var ne=r=>!h(r)&&typeof r!="boolean"&&typeof r!="number",G=class r extends V{constructor(e,t={}){super(),Me(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils","ownPostProcessors"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=k.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let s={...t};if(e==null)return!1;let n=this.resolve(e,s);if(n?.res===void 0)return!1;let i=ne(n.res);return!(s.returnObjects===!1&&i)}extractFromKey(e,t){let s=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;s===void 0&&(s=":");let n=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator,i=t.ns||this.options.defaultNS||[],a=s&&e.includes(s),o=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!qe(e,s,n);if(a&&!o){let l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:h(i)?[i]:i};let u=e.split(s);(s!==n||s===n&&this.options.ns.includes(u[0]))&&(i=u.shift()),e=u.join(n)}return{key:e,namespaces:h(i)?[i]:i}}translate(e,t,s){let n=typeof t=="object"?{...t}:t;if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),e==null)return"";typeof e=="function"&&(e=I(e,{...this.options,...n})),Array.isArray(e)||(e=[String(e)]),e=e.map(S=>typeof S=="function"?I(S,{...this.options,...n}):String(S));let i=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,a=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:o,namespaces:l}=this.extractFromKey(e[e.length-1],n),u=l[l.length-1],c=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;c===void 0&&(c=":");let g=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(g?.toLowerCase()==="cimode")return d?i?{res:`${u}${c}${o}`,usedKey:o,exactUsedKey:o,usedLng:g,usedNS:u,usedParams:this.getUsedParamsDetails(n)}:`${u}${c}${o}`:i?{res:o,usedKey:o,exactUsedKey:o,usedLng:g,usedNS:u,usedParams:this.getUsedParamsDetails(n)}:o;let p=this.resolve(e,n),f=p?.res,m=p?.usedKey||o,y=p?.exactUsedKey||o,L=["[object Number]","[object Function]","[object RegExp]"],x=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,v=!this.i18nFormat||this.i18nFormat.handleAsObject,b=n.count!==void 0&&!h(n.count),w=r.hasDefaultValue(n),j=b?this.pluralResolver.getSuffix(g,n.count,n):"",K=n.ordinal&&b?this.pluralResolver.getSuffix(g,n.count,{ordinal:!1}):"",pe=b&&!n.ordinal&&n.count===0,F=pe&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${j}`]||n[`defaultValue${K}`]||n.defaultValue,O=f;v&&!f&&w&&(O=F);let De=ne(O),Ke=Object.prototype.toString.apply(O);if(v&&O&&De&&!L.includes(Ke)&&!(h(x)&&Array.isArray(O))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||(this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.logger.once("returnedObject","deprecate","accessing an object without returnObjects returns a sentence about it today; from v27 t() returns the key, as for a missing key (returnedObjectHandler can keep today\'s text)"));let S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,O,{...n,ns:l}):`key \'${o} (${this.language})\' returned an object instead of string.`;return i?(p.res=S,p.usedParams=this.getUsedParamsDetails(n),p):S}if(a){let S=Array.isArray(O),P=S?[]:{},ye=S?y:m;for(let $ in O)if(Object.prototype.hasOwnProperty.call(O,$)){let E=`${ye}${a}${$}`;w&&!f?P[$]=this.translate(E,{...n,defaultValue:ne(F)?F[$]:void 0,joinArrays:!1,ns:l}):P[$]=this.translate(E,{...n,joinArrays:!1,ns:l}),P[$]===E&&(P[$]=O[$])}f=P}}else if(v&&h(x)&&Array.isArray(f))f=f.join(x),f&&(f=this.extendTranslation(f,e,n,p,s));else{let S=!1,P=!1;!this.isValidLookup(f)&&w&&(S=!0,f=F),this.isValidLookup(f)||(P=!0,f=o);let $=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&P?void 0:f,E=w&&F!==f&&this.options.updateMissing;if(P||S||E){if(this.logger.log(E?"updateKey":"missingKey",g,u,b&&!E?`${o}${this.pluralResolver.getSuffix(g,n.count,n)}`:o,E?F:f),a){let C=this.resolve(o,{...n,keySeparator:!1});C&&C.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let H=[],_=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&_&&_[0])for(let C=0;C<_.length;C++)H.push(_[C]);else this.options.saveMissingTo==="all"?H=this.languageUtils.toResolveHierarchy(n.lng||this.language):H.push(n.lng||this.language);let me=(C,D,U)=>{let be=w&&U!==f?U:$;this.options.missingKeyHandler?this.options.missingKeyHandler(C,u,D,be,E,n):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(C,u,D,be,E,n,void 0,this.utils?.hasLoadedNamespace),this.emit("missingKey",C,u,D,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?H.forEach(C=>{let D=this.pluralResolver.getSuffixes(C,n);pe&&n[`defaultValue${this.options.pluralSeparator}zero`]&&!D.includes(`${this.options.pluralSeparator}zero`)&&D.push(`${this.options.pluralSeparator}zero`),D.forEach(U=>{me([C],o+U,n[`defaultValue${U}`]||F)})}):me(H,o,F))}f=this.extendTranslation(f,e,n,p,s),P&&f===o&&this.options.appendNamespaceToMissingKey&&(f=`${u}${c}${o}`),(P||S)&&this.options.parseMissingKeyHandler&&(f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${c}${o}`:o,S?f:void 0,n))}return i?(p.res=f,p.usedParams=this.getUsedParamsDetails(n),p):f}extendTranslation(e,t,s,n,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||n.usedLng,n.usedNS,n.usedKey,{resolved:n});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});let l=h(e)&&(s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables),u;if(l){let g=e.match(this.interpolator.nestingRegexp);u=g&&g.length}let c=s.replace&&!h(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(c={...this.options.interpolation.defaultVariables,...c}),e=this.interpolator.interpolate(e,c,s.lng||this.language||n.usedLng,s),l){let g=e.match(this.interpolator.nestingRegexp),d=g&&g.length;u<d&&(s.nest=!1)}!s.lng&&n&&n.res&&(s.lng=this.language||n.usedLng),s.nest!==!1&&(e=this.interpolator.nest(e,(...g)=>i?.[0]===g[0]&&!s.context?(this.logger.warn(`It seems you are nesting recursively key: ${g[0]} in key: ${t[0]}`),null):this.translate(...g,t),s)),s.interpolation&&this.interpolator.reset()}let a=s.postProcess||this.options.postProcess,o=h(a)?[a]:a;return e!=null&&o?.length&&s.applyPostProcessor!==!1&&(o.forEach(l=>{this.logger.debug&&ce.processors[l]&&this.ownPostProcessors&&!this.ownPostProcessors.has(l)&&this.logger.once(l,"deprecate",`postProcess: \'${l}\' was registered with use() on another i18next instance; from v27 post-processors are per instance, so call use() with it on this instance too`)}),e=ce.handle(o,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...n,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,t={}){let s,n,i,a,o;return h(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?I(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(s))return;let u=this.extractFromKey(l,t),c=u.key;n=c;let g=u.namespaces;this.options.fallbackNS&&(g=g.concat(this.options.fallbackNS));let d=t.count!==void 0&&!h(t.count),p=d&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(h(t.context)||typeof t.context=="number")&&t.context!=="",m=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);g.forEach(y=>{this.isValidLookup(s)||(o=y,!this.checkedLoadedFor[`${m[0]}-${y}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(o)&&(this.checkedLoadedFor[`${m[0]}-${y}`]=!0,this.logger.warn(`key "${n}" for languages "${m.join(", ")}" won\'t get resolved as namespace "${o}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(L=>{if(this.isValidLookup(s))return;a=L;let x=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(x,c,L,y,t);else{let b;d&&(b=this.pluralResolver.getSuffix(L,t.count,t));let w=`${this.options.pluralSeparator}zero`,j=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&b.startsWith(j)&&x.push(c+b.replace(j,this.options.pluralSeparator)),x.push(c+b),p&&x.push(c+w)),f){let K=`${c}${this.options.contextSeparator||"_"}${t.context}`;x.push(K),d&&(t.ordinal&&b.startsWith(j)&&x.push(K+b.replace(j,this.options.pluralSeparator)),x.push(K+b),p&&x.push(K+w))}}let v;for(;v=x.pop();)this.isValidLookup(s)||(i=v,s=this.getResource(L,y,v,t))}))})}),{res:s,usedKey:n,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,s,n={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,s,n):this.resourceStore.getResource(e,t,s,n)}getUsedParamsDetails(e={}){let t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=e.replace&&!h(e.replace),n=s?e.replace:e;if(s&&typeof e.count<"u"&&(n={...n,count:e.count}),this.options.interpolation.defaultVariables&&(n={...this.options.interpolation.defaultVariables,...n}),!s){n={...n};for(let i of t)delete n[i]}return n}static hasDefaultValue(e){let t="defaultValue";for(let s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&s.startsWith(t)&&e[s]!==void 0)return!0;return!1}},Z=class{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=k.create("languageUtils"),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=M(e),!e||!e.includes("-"))return null;let t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=M(e),!e||!e.includes("-"))return e;let t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(h(e)&&e.includes("-")){let s;try{s=Intl.getCanonicalLocales(e)[0]}catch{}return s&&this.options.lowerCaseLng&&(s=s.toLowerCase()),s||(this.options.lowerCaseLng?e.toLowerCase():e)}let t=this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e;return this.logger.debug&&h(e)&&this.deprecateBareCode(e,t),t}deprecateBareCode(e,t){let s;try{s=Intl.getCanonicalLocales(e)[0]}catch{return}this.options.lowerCaseLng&&(s=s.toLowerCase()),s!==t&&this.logger.once(e,"deprecate",`language code \'${e}\' is used as \'${t}\'; i18next v27 canonicalizes it to \'${s}\', use \'${s}\' in lng, fallbackLng, supportedLngs and the resources`)}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(s=>{if(t)return;let n=this.formatLanguageCode(s);(!this.options.supportedLngs||this.isSupportedCode(n))&&(t=n)}),!t&&this.options.supportedLngs&&e.forEach(s=>{if(t)return;let n=this.getScriptPartFromCode(s);if(this.isSupportedCode(n))return t=n;let i=this.getLanguagePartFromCode(s);if(this.isSupportedCode(i))return t=i;t=this.options.supportedLngs.find(a=>a===i?!0:!a.includes("-")&&!i.includes("-")?!1:!!(a.includes("-")&&!i.includes("-")&&a.slice(0,a.indexOf("-"))===i))}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),h(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let s=e[t];return s||(s=e[this.getScriptPartFromCode(t)]),s||(s=e[this.formatLanguageCode(t)]),s||(s=e[this.getLanguagePartFromCode(t)]),s||(s=e.default),s||[]}toResolveHierarchy(e,t){let s=this.options.fallbackLng,n=Array.isArray(s)?s.join("|"):s;n!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=n);let i=t===void 0||t===!1||h(t),a=t===void 0&&typeof this.options.fallbackLng=="function",o=h(e)&&i&&!a,l=null;if(o){let d;t===void 0?d="undefined":t===!1?d="boolean:false":d=`string:${t}`,l=`${e.length}:${e}|${d}`}if(l!==null){let d=this.resolveHierarchyCache[l];if(d!==void 0)return d.slice()}let u=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),c=[],g=d=>{d&&(this.isSupportedCode(d)?c.push(d):this.logger.warn(`rejecting language code not found in supportedLngs: ${d}`))};return h(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&g(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&g(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&g(this.getLanguagePartFromCode(e))):h(e)&&g(this.formatLanguageCode(e)),u.forEach(d=>{let p=this.formatLanguageCode(d);c.includes(p)||g(p)}),l!==null?(this.resolveHierarchyCache[l]=c,c.slice()):c}},we={zero:0,one:1,two:2,few:3,many:4,other:5},Ce={select:r=>r===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})},ue=class{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=k.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let s=M(e==="dev"?"en":e),n=t.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:s,type:n});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(s,{type:n})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Ce;if(!e.match(/-|_/))return Ce;let l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,t)}return this.pluralRulesCache[i]=a,a}needsPlural(e,t={}){let s=this.getRule(e,t);return s||(s=this.getRule("dev",t)),s?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,s={}){return this.getSuffixes(e,s).map(n=>`${t}${n}`)}getSuffixes(e,t={}){let s=this.getRule(e,t);return s||(s=this.getRule("dev",t)),s?s.resolvedOptions().pluralCategories.sort((n,i)=>we[n]-we[i]).map(n=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${n}`):[]}getSuffix(e,t,s={}){let n=this.getRule(e,s);return n?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${n.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,s))}},ke=(r,e,t,s=".",n=!0)=>{let i=Ue(r,e,t);return i==null&&n&&h(t)&&(i=oe(r,t,s),i===void 0&&(i=oe(e,t,s))),i},X=class{constructor(e={}){this.logger=k.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(t=>t),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});let{escape:t,escapeValue:s,useRawValueToEscape:n,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:l,formatSeparator:u,unescapeSuffix:c,unescapePrefix:g,nestingPrefix:d,nestingPrefixEscaped:p,nestingSuffix:f,nestingSuffixEscaped:m,nestingOptionsSeparator:y,maxReplaces:L,alwaysFormat:x}=e.interpolation;if(a||l||p||m){let v=Object.entries({prefixEscaped:a,suffixEscaped:l,nestingPrefixEscaped:p,nestingSuffixEscaped:m}).filter(([,b])=>b).map(([b])=>b);this.logger.once(v.join(),"deprecate",`interpolation.${v.join(", interpolation.")}: the regex-escaped delimiter options are removed in v27; pass the literal delimiters as prefix, suffix, nestingPrefix and nestingSuffix`)}this.escape=t!==void 0?t:Se,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=n!==void 0?n:!1,this.prefix=i?N(i):a||"{{",this.suffix=o?N(o):l||"}}",this.formatSeparator=u||",",this.unescapePrefix=c?"":g?N(g):"-",this.unescapeSuffix=this.unescapePrefix?"":c?N(c):"",this.nestingPrefix=d?N(d):p||N("$t("),this.nestingSuffix=f?N(f):m||N(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=L||1e3,this.alwaysFormat=x!==void 0?x:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(t,s)=>t?.source===s?(t.lastIndex=0,t):new RegExp(s,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"\']|"[^"]*"|\'[^\']*\'|\\\\((?:[^()"\']|"[^"]*"|\'[^\']*\')*\\\\))*?)${this.nestingSuffix}`)}interpolate(e,t,s,n){let i,a,o,l=e,u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=y=>{if(!y.includes(this.formatSeparator)){let b=ke(t,u,y,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,s,{...n,...t,interpolationkey:y}):b}let L=y.split(this.formatSeparator),x=L.shift().trim(),v=L.join(this.formatSeparator).trim();return this.format(ke(t,u,x,this.options.keySeparator,this.options.ignoreJSONStructure),v,s,{...n,...t,interpolationkey:x})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\\$t\\([^)]*\\{[^}]*\\{\\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false \\u2014 if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");let g=n?.missingInterpolationHandler||this.options.missingInterpolationHandler,d=n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables,p=[{regex:this.regexpUnescape,safeValue:y=>y},{regex:this.regexp,safeValue:y=>this.escapeValue?(this.escape===Se&&this.options?.interpolation?.escapeValue!==!1&&h(y)&&y.includes("/")&&this.logger.once("/","deprecate","escapeValue renders \'/\' in a value as \'/\' today; from v27 the default escape leaves \'/\' as it is"),this.escape(y)):y}],f=[],m=0;return p.forEach(y=>{for(o=0;i=y.regex.exec(e);){let L=i.index-m,x=f.find(([w,j])=>L>=w&&L<j);if(x){y.regex.lastIndex=x[1]+m;continue}let v=i[1].trim();if(a=c(v),a===void 0)if(typeof g=="function"){let w=g(e,i,n);a=h(w)?w:""}else if(n&&Object.prototype.hasOwnProperty.call(n,v))a="";else if(d){this.logger.debug&&this.logger.once(`${l}\\0${i[0]}`,"warn",`missed to pass in variable ${v} for interpolating ${l}`),a=i[0];continue}else this.logger.warn(`missed to pass in variable ${v} for interpolating ${e}`),a="";else!h(a)&&!this.useRawValueToEscape&&(a=q(a));let b=q(y.safeValue(a));if(e=e.slice(0,i.index)+b+e.slice(i.index+i[0].length),d?(y.regex===this.regexpUnescape?f.push([i.index,i.index+b.length]):m+=b.length-i[0].length,y.regex.lastIndex+=b.length,y.regex.lastIndex-=i[0].length):y.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,t,s={}){let n,i,a,o=(g,d)=>{let p=this.nestingOptionsSeparator;if(!g.includes(p))return g;let f=g.split(new RegExp(`${N(p)}[ ]*{`)),m=`{${f[1]}`;g=f[0],m=this.interpolate(m,a);let y=m.match(/\'/g),L=m.match(/"/g);((y?.length??0)%2===0&&!L||(L?.length??0)%2!==0)&&(m=m.replace(/\'/g,\'"\'));try{a=JSON.parse(m),d&&(a={...d,...a})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${g}`,x),`${g}${p}${m}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,g},l=new RegExp(this.nestingRegexp),u="",c=0;for(;n=l.exec(e);){let g=[];a={...s},a=a.replace&&!h(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let d=/{.*}/s.test(n[1])?n[1].lastIndexOf("}")+1:n[1].indexOf(this.formatSeparator);if(d!==-1&&(g=n[1].slice(d).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),n[1]=n[1].slice(0,d)),i=t(o.call(this,n[1].trim(),a),a),i&&n[0]===e&&!h(i))return i;h(i)||(i=q(i)),i||(this.logger.warn(`missed to resolve ${n[1]} for nesting ${e}`),i=""),g.length&&(i=g.reduce((p,f)=>this.format(p,f,s.lng,{...s,interpolationkey:n[1].trim()}),i.trim())),u+=e.slice(c,n.index)+q(i),c=l.lastIndex,this.regexp.lastIndex=0}return c?u+e.slice(c):e}},Qe=r=>{let e=r.toLowerCase().trim(),t={};if(r.includes("(")){let s=r.split("(");e=s[0].toLowerCase().trim();let n=s[1].slice(0,-1);e==="currency"&&!n.includes(":")?t.currency||(t.currency=n.trim()):e==="relativetime"&&!n.includes(":")?t.range||(t.range=n.trim()):n.split(";").forEach(a=>{if(a){let[o,...l]=a.split(":"),u=l.join(":").trim().replace(/^\'+|\'+$/g,""),c=o.trim();t[c]||(t[c]=u),u==="false"&&(t[c]=!1),u==="true"&&(t[c]=!0),isNaN(u)||(t[c]=parseInt(u,10))}})}return{formatName:e,formatOptions:t}},Pe=r=>{let e={};return(t,s,n)=>{let i=n;n&&n.interpolationkey&&n.formatParams&&n.formatParams[n.interpolationkey]&&n[n.interpolationkey]&&(i={...i,[n.interpolationkey]:void 0});let a;try{a=s+JSON.stringify(i)}catch{return r(M(s),n)(t)}let o=e[a];return o||(o=r(M(s),n),e[a]=o),o(t)}},Ye=r=>(e,t,s)=>r(M(t),s)(e),ge=class{constructor(e={}){this.logger=k.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";let s=t.cacheInBuiltFormats?Pe:Ye;this.formats={number:s((n,i)=>{let a=new Intl.NumberFormat(n,{...i});return o=>a.format(o)}),currency:s((n,i)=>{let a=new Intl.NumberFormat(n,{...i,style:"currency"});return o=>a.format(o)}),datetime:s((n,i)=>{let a=new Intl.DateTimeFormat(n,{...i});return o=>a.format(o)}),relativetime:s((n,i)=>{let a=new Intl.RelativeTimeFormat(n,{...i});return o=>a.format(o,i.range||"day")}),list:s((n,i)=>{let a=new Intl.ListFormat(n,{...i});return o=>a.format(o)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Pe(t)}format(e,t,s,n={}){if(!t||e==null)return e;let i=t.split(this.formatSeparator),a=[];for(let l=0;l<i.length;l++){let u=i[l];for(;u.indexOf("(")>-1&&!u.includes(")")&&l+1<i.length;)u=`${u}${this.formatSeparator}${i[++l]}`;a.push(u)}return a.reduce((l,u)=>{let{formatName:c,formatOptions:g}=Qe(u);if(this.formats[c]){let d=l;try{let p=n?.formatParams?.[n.interpolationkey]||{},f=p.locale||p.lng||n.locale||n.lng||s;d=this.formats[c](l,f,{...g,...n,...p})}catch(p){this.logger.warn(p)}return d}else this.logger.warn(`there was no format function for ${c}`);return l},e)}},Ge=(r,e)=>{r.pending[e]!==void 0&&(delete r.pending[e],r.pendingCount--)},de=class extends V{constructor(e,t,s,n={}){super(),this.backend=e,this.store=t,this.services=s,this.languageUtils=s.languageUtils,this.options=n,this.logger=k.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=n.maxParallelReads||10,this.readingCalls=0,this.maxRetries=n.maxRetries>=0?n.maxRetries:5,this.retryTimeout=n.retryTimeout>=1?n.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(s,n.backend,n),this.callbackApi=re(this.backend),this.backend&&this.callbackApi===void 0&&(this.backend.read||this.backend.create)&&this.logger.deprecate("backend: set callbackApi to declare the calling convention (true: read(language, namespace, callback) and create(languages, namespace, key, fallbackValue, callback, options); false: both return a promise or a value); guessing it from the number of parameters is deprecated")}queueLoad(e,t,s,n){let i={},a={},o={},l={};return e.forEach(u=>{let c=!0;t.forEach(g=>{let d=`${u}|${g}`;!s.reload&&this.store.hasResourceBundle(u,g)?this.state[d]=2:!s.reload&&this.state[d]<0||(this.state[d]===1?a[d]===void 0&&(a[d]=!0):(this.state[d]=1,c=!1,a[d]===void 0&&(a[d]=!0),i[d]===void 0&&(i[d]=!0),l[g]===void 0&&(l[g]=!0)))}),c||(o[u]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:n}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(l)}}loaded(e,t,s){let n=e.split("|"),i=n[0],a=n[1];t&&this.emit("failedLoading",i,a,t),!t&&s&&this.store.addResourceBundle(i,a,s,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&s&&(this.state[e]=0);let o={};this.queue.forEach(l=>{He(l.loaded,[i],a),Ge(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{o[u]||(o[u]={});let c=l.loaded[u];c.length&&c.forEach(g=>{o[u][g]===void 0&&(o[u][g]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",o),this.queue=this.queue.filter(l=>!l.done)}read(e,t,s,n=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:s,tried:n,wait:i,callback:a});return}this.readingCalls++;let o=(u,c)=>{if(this.readingCalls--,this.waitingReads.length>0){let g=this.waitingReads.shift();this.read(g.lng,g.ns,g.fcName,g.tried,g.wait,g.callback)}if(u&&c&&n<this.maxRetries){setTimeout(()=>{this.read(e,t,s,n+1,i*2,a)},i);return}a(u,c)},l=this.backend[s].bind(this.backend);if(this.callbackApi===!1||this.callbackApi===void 0&&l.length===2){try{let u=l(e,t);u&&typeof u.then=="function"?u.then(c=>o(null,c)).catch(o):o(null,u)}catch(u){o(u)}return}return l(e,t,o)}prepareLoading(e,t,s={},n){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),n&&n();h(e)&&(e=this.languageUtils.toResolveHierarchy(e)),h(t)&&(t=[t]);let i=this.queueLoad(e,t,s,n);if(!i.toLoad.length)return i.pending.length||n(),null;i.toLoad.forEach(a=>{this.loadOne(a)})}load(e,t,s){this.prepareLoading(e,t,{},s)}reload(e,t,s){this.prepareLoading(e,t,{reload:!0},s)}noticeDevFallback(e){e!=="dev"||!this.devIsDefaultFallback||this.logger.once("dev","warn","language \'dev\' is requested because fallbackLng is not set (its default is [\'dev\']); i18next v27 defaults to fallbackLng: false and loads and saves missing keys in the requested language instead. Set fallbackLng to your source language, or to \'dev\' to keep this behavior")}loadOne(e,t=""){let s=e.split("|"),n=s[0],i=s[1];this.noticeDevFallback(n),this.read(n,i,"read",void 0,void 0,(a,o)=>{a&&this.logger.warn(`${t}loading namespace ${i} for language ${n} failed`,a),!a&&o&&this.logger.log(`${t}loaded namespace ${i} for language ${n}`,o),this.loaded(e,a,o)})}saveMissing(e,t,s,n,i,a={},o=()=>{},l=this.newestCloneHasLoadedNamespace||this.services?.utils?.hasLoadedNamespace){if(l&&!l(t)){this.logger.warn(`did not save key "${s}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(s==null||s==="")){if(this.backend?.create){e?.forEach?.(g=>this.noticeDevFallback(g));let u={...a,isUpdate:i},c=this.backend.create.bind(this.backend);if(this.callbackApi===!1||this.callbackApi===void 0&&c.length<6)try{let g;this.callbackApi===!1||c.length===5?g=c(e,t,s,n,u):g=c(e,t,s,n),g&&typeof g.then=="function"?g.then(d=>o(null,d)).catch(o):o(null,g)}catch(g){o(g)}else c(e,t,s,n,o,u)}!e||!e[0]||this.store.addResource(e[0],t,s,n)}}},ie=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:r=>{let e={};if(typeof r[1]=="object"&&(e=r[1]),h(r[1])&&(e.defaultValue=r[1]),h(r[2])&&(e.tDescription=r[2]),typeof r[2]=="object"||typeof r[3]=="object"){let t=r[3]||r[2];Object.keys(t).forEach(s=>{e[s]=t[s]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Oe=r=>(h(r.ns)&&(r.ns=[r.ns]),h(r.fallbackLng)&&(r.fallbackLng=[r.fallbackLng]),h(r.fallbackNS)&&(r.fallbackNS=[r.fallbackNS]),r.supportedLngs&&!r.supportedLngs.includes("cimode")&&(r.supportedLngs=r.supportedLngs.concat(["cimode"])),r),W=()=>{},J,Ze=r=>{Object.getOwnPropertyNames(Object.getPrototypeOf(r)).forEach(t=>{typeof r[t]=="function"&&(r[t]=r[t].bind(r))})},he=class r extends V{constructor(e={},t){if(super(),this.options=Oe(e),this.services={ownPostProcessors:new Set},this.logger=k,this.modules={external:[]},Ze(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e=="function"&&(t=e,e={}),e.defaultNS==null&&e.ns&&(h(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));let s=e.fallbackLng===void 0&&this.options.fallbackLng===void 0,n=ie();this.options={...n,...this.options,...Oe(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);let i=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){J&&J!==this&&J.modules.logger!==this.modules.logger&&k.deprecate("init: this init() replaces the logger another i18next instance set with use(), as the logger is shared in v26; from v27 each instance keeps its own logger"),J=this.modules.logger?this:void 0,this.modules.logger?k.init(i(this.modules.logger),this.options):k.init(null,this.options),this.pendingWarnings?.forEach(p=>this.logger.warn(p)),this.pendingWarnings=void 0;let c;this.modules.formatter?c=this.modules.formatter:c=ge;let g=new Z(this.options);this.store=new Y(this.options.resources,this.options);let d=this.services;d.logger=k,d.resourceStore=this.store,d.languageUtils=g,d.pluralResolver=new ue(g,{prepend:this.options.pluralSeparator}),c&&(d.formatter=i(c),d.formatter.init&&d.formatter.init(d,this.options),this.options.interpolation.format=d.formatter.format.bind(d.formatter)),d.interpolator=new X(this.options),d.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this),reloadResources:this.reloadResources.bind(this)},d.backendConnector=new de(i(this.modules.backend),d.resourceStore,d,this.options),d.backendConnector.devIsDefaultFallback=s,d.backendConnector.on("*",(p,...f)=>{this.emit(p,...f)}),this.modules.languageDetector&&(d.languageDetector=i(this.modules.languageDetector),d.languageDetector.init&&d.languageDetector.init(d,this.options.detection,this.options),d.languageDetector.async&&re(d.languageDetector)===void 0&&this.logger.deprecate("languageDetector: set callbackApi to declare how the async detect() answers (true: detect(callback); false: detect() returns a promise); guessing it from the number of parameters is deprecated")),this.modules.i18nFormat&&(d.i18nFormat=i(this.modules.i18nFormat),d.i18nFormat.init&&d.i18nFormat.init(this)),this.translator=new G(this.services,this.options),this.translator.on("*",(p,...f)=>{this.emit(p,...f)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,t||(t=W),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...g)=>this.store[c](...g)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...g)=>(this.store[c](...g),this)});let l=z(),u=()=>{let c=(g,d)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(d),t(g,d)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),l}loadResources(e,t=W){let s=t,n=h(e)?e:this.language;if(typeof e=="function"&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(n?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return s();let i=[],a=o=>{if(!o||o==="cimode")return;this.services.languageUtils.toResolveHierarchy(o).forEach(u=>{u!=="cimode"&&(i.includes(u)||i.push(u))})};n?a(n):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),this.options.preload?.forEach?.(o=>a(o)),this.services.backendConnector.load(i,this.options.ns,o=>{!o&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),s(o)})}else s(null)}reloadResources(e,t,s){let n=z();if(typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t=void 0),!e){let i=Object.keys(this.services.backendConnector.state).map(a=>a.split("|")[0]);e=[...new Set([...this.languages||[],...i])].filter(a=>a!=="cimode")}return t||(t=this.options.ns),s||(s=W),this.services.backendConnector.reload(e,t,i=>{n.resolve(),s(i)}),n}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");let t=s=>{if(this.modules[s]&&this.modules[s]!==e){let n=`use: this ${s} replaces the ${s} passed to an earlier use() call; only one ${s} is used per instance`;this.isInitializing||this.isInitialized?this.logger.warn(n):(this.pendingWarnings=this.pendingWarnings||[]).push(n)}this.modules[s]=e};return e.type==="backend"&&t("backend"),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&t("languageDetector"),e.type==="i18nFormat"&&t("i18nFormat"),e.type==="postProcessor"&&(ce.addPostProcessor(e),this.services.ownPostProcessors?.add(e.name)),e.type==="formatter"&&t("formatter"),e.type==="3rdParty"&&this.modules.external.push(e),this}hydrate(e,t){return this.options.isClone?this:this.services.resourceStore?(e&&!this.initializedStoreOnce&&(this.services.resourceStore.data=e,Object.values(e).forEach(s=>{Object.keys(s).forEach(n=>{this.options.ns.includes(n)||this.options.ns.push(n)})}),this.initializedStoreOnce=!0,this.isInitialized=!0),t&&!this.initializedLanguageOnce&&(this.changeLanguage(t),this.initializedLanguageOnce=!0),this):(this.logger.warn("hydrate: call init() first, the instance has no resource store yet"),this)}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let t=0;t<this.languages.length;t++){let s=this.languages[t];if(!["cimode","dev"].includes(s)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;let s=z();this.emit("languageChanging",e);let n=o=>{this.language=o,this.languages=this.services.languageUtils.toResolveHierarchy(o),this.resolvedLanguage=void 0,this.setResolvedLanguage(o)},i=(o,l)=>{l?this.isLanguageChangingTo===e&&(n(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,s.resolve((...u)=>this.t(...u)),t&&t(o,(...u)=>this.t(...u))},a=o=>{!e&&!o&&this.services.languageDetector&&(o=[]);let l=h(o)?o:o&&o[0],u=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(h(o)?[o]:o);u&&this.logger.debug&&!Ie(u)&&![].concat(this.options.supportedLngs||[],this.services.languageUtils.getFallbackCodes(this.options.fallbackLng,u),this.options.preload||[]).includes(u)&&!Object.prototype.hasOwnProperty.call(this.store.data,u)&&this.logger.once(`lng:${u}`,"deprecate",`changeLanguage: the language code \'${u.slice(0,64)}\' comes from lng, changeLanguage() or the language detector and is not configured; from v27 such a code is refused unless it has only letters, digits, \'-\', \'_\', \'@\' and \'.\' (no \'..\'), at most 128 characters. Set supportedLngs, or check the code before passing it on`),u&&(this.language||n(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,c=>{i(c,u)})};if(!e&&this.services.languageDetector&&!this.services.languageDetector.async)a(this.services.languageDetector.detect());else if(!e&&this.services.languageDetector&&this.services.languageDetector.async){let o=re(this.services.languageDetector);o===!1||o===void 0&&this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a)}else a(e);return s}getFixedT(e,t,s,n){let i=n?.scopeNs,a=(o,l,...u)=>{let c;typeof l!="object"?c=this.options.overloadTranslationOptionHandler([o,l].concat(u)):c={...l},c.lng=c.lng||a.lng,c.lngs=c.lngs||a.lngs;let g=c.ns!==void 0&&c.ns!==null;c.ns=c.ns||a.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||s||a.keyPrefix);let d={...this.options,...c};Array.isArray(i)&&!g&&(d.ns=i),typeof c.keyPrefix=="function"&&(c.keyPrefix=I(c.keyPrefix,d));let p=this.options.keySeparator||".",f;return c.keyPrefix&&Array.isArray(o)?f=o.map(m=>(typeof m=="function"&&(m=I(m,d)),`${c.keyPrefix}${p}${m}`)):(typeof o=="function"&&(o=I(o,d)),f=c.keyPrefix?`${c.keyPrefix}${p}${o}`:o),this.t(f,c)};return h(e)?a.lng=e:a.lngs=e,a.ns=t,a.keyPrefix=s,a}t(...e){return this.translator?this.translator.translate(...e):(this.logger.warn("t: called before init(); returning an empty string"),"")}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;let s=t.lng||this.resolvedLanguage||this.languages[0],n=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(s.toLowerCase()==="cimode")return!0;let a=(u,c)=>{let g=this.services.backendConnector.state[`${u}|${c}`];return g===-1||g===0||g===2};if(t.precheck){let u=t.precheck(this,a);if(u!==void 0)return u}if(this.hasResourceBundle(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages)return!0;let{languageUtils:o}=this.services,l=t.lng?o.isSupportedCode(s)&&o.toResolveHierarchy(s,!1)[0]:s;return!!((!l||a(l,e))&&(!n||a(i,e)))}loadNamespaces(e,t){let s=z();return this.options.ns?(h(e)&&(e=[e]),e.forEach(n=>{this.options.ns.includes(n)||this.options.ns.push(n)}),this.loadResources(n=>{s.resolve(),t&&t(n)}),s):(t&&t(),Promise.resolve())}loadLanguages(e,t){let s=z();h(e)&&(e=[e]);let n=this.options.preload||[],i=e.filter(a=>!n.includes(a)&&this.services.languageUtils.isSupportedCode(a));return i.length?(this.options.preload=n.concat(i),this.loadResources(a=>{s.resolve(),t&&t(a)}),s):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"ltr";try{let n=new Intl.Locale(e);if(n&&n.getTextInfo){let i=n.getTextInfo();if(i&&i.direction)return i.direction}}catch{}let t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],s=this.services?.languageUtils||new Z(ie());return e.toLowerCase().indexOf("-latn")>1?"ltr":t.includes(s.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){let s=new r(e,t);return s.createInstance=r.createInstance,s}cloneInstance(e={},t=W){let s=e.forkResourceStore;s&&(e={...e},delete e.forkResourceStore);let n={...this.options,preload:!1,...e,isClone:!0},i=new r(n);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(o=>{i[o]=this[o]}),i.services={...this.services},i.services.utils={...i.services.utils,hasLoadedNamespace:i.hasLoadedNamespace.bind(i),reloadResources:i.reloadResources.bind(i)},s){let o=u=>{let c=Array.isArray(u)?[...u]:{...u};return Object.keys(c).forEach(g=>{c[g]&&typeof c[g]=="object"&&(c[g]=o(c[g]))}),c},l=o(this.store.data);i.store=new Y(l,n),i.services.resourceStore=i.store}if(e.interpolation){let l={...ie().interpolation,...this.options.interpolation,...e.interpolation},u={...n,interpolation:l};i.services.interpolator=new X(u)}return i.translator=new G(i.services,n),i.translator.on("*",(o,...l)=>{i.emit(o,...l)}),i.init(n,t),i.translator.options=n,i.translator.backendConnector.newestCloneHasLoadedNamespace=i.hasLoadedNamespace.bind(i),i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}},R=he.createInstance(),Te=R.createInstance,rt=R.dir,at=R.init,ot=R.loadResources,lt=R.reloadResources,ct=R.use,ut=R.changeLanguage,gt=R.getFixedT,dt=R.t,ht=R.exists,ft=R.setDefaultNamespace,pt=R.hasLoadedNamespace,yt=R.loadNamespaces,mt=R.loadLanguages;var fe={"settings.images":"Azure Blob images (not end-to-end encrypted)","settings.imagesError":"Could not save image storage settings. Try again.","settings.imagesUnavailable":"This Relay does not offer image storage. Reconnect and try again.",language:"Language",refresh:"Refresh",retry:"Retry",cancel:"Cancel",details:"Details",account:"Relay account","account.work":"Microsoft work account","account.personal":"Microsoft account","account.fallback":"Account {{id}}","account.legacy":"Legacy account","account.admin":"Administrator","account.user":"User","account.view":"View account","account.signedIn":"Signed in","account.connecting":"Connecting","account.disconnected":"Disconnected","account.error":"Sign-in error","account.unknown":"Status unknown","account.unavailable":"Could not update sign-in status. Refresh the page.","account.failure.disconnected":"The Relay connection was interrupted.","account.failure.invalid":"The Relay returned invalid account information.","account.failure.unsupported":"This Relay does not support account information. Upgrade the Relay.","account.failure.expired":"Your sign-in credential has expired. Sign in again.","account.failure.tls":"Could not read account information securely. Enable HTTPS certificate verification.","account.failure.read":"Could not read account information. Try refreshing later.","account.failure.connection":"Could not read account information. Check the Relay connection and refresh.","relay.connecting":"Connecting\\u2026","relay.reconnect":"Reconnect","relay.disconnect":"Disconnect","relay.disconnecting":"Disconnecting\\u2026","relay.statusError":"Could not update the Relay connection status. Refresh the page.","relay.reconnectError":"Could not reconnect to the Relay. Try again.","relay.disconnectError":"Could not disconnect from the Relay. Try again.",deployment:"Deployment","deployment.version":"Version","deployment.upgraded":"Last upgraded","deployment.noUpgrade":"No record","deployment.config":"Configuration","deployment.environment":"Process environment","deployment.relay":"Relay URL",agents:"Agent sync","agents.sync":"Sync","agents.enable":"Sync","agents.enableName":"Sync {{name}}","agents.connected":"Connected","agents.unavailable":"Unavailable","agents.single":"Single-agent mode","agents.empty":"No configurable agents","agents.dirty":"Unsaved changes","agents.saving":"Syncing\\u2026","agents.saved":"Synced","agents.busy":"Sync is in progress. Try again shortly.","agents.saveError":"Could not sync. Try again.","agents.httpError":"Sync failed (HTTP {{status}}). Try again.","settings.group":"Agent group chat","settings.peer":"Cross-PC agent communication","settings.busy":"Settings are being saved. Try again shortly.","settings.groupError":"Could not save group chat settings. Refresh and try again.","settings.peerError":"Could not save cross-PC settings. Refresh and try again.",pairing:"Pair a phone","pairing.qr":"Pairing QR code","pairing.text":"Pairing string","pairing.copy":"Copy","pairing.copied":"Copied","pairing.copyError":"Could not copy. Select the pairing string and copy it manually.","pairing.show":"Show QR code","pairing.refresh":"Refresh QR code","pairing.hide":"Hide","pairing.success":"Paired","pairing.invalid":"This QR code is no longer valid. Generate a new one.","pairing.expired":"This QR code has expired. Generate a new one.","pairing.statusError":"Could not confirm pairing status. Retrying.","pairing.generateError":"Could not generate a QR code. Try again.","pairing.offline":"The Relay is not connected. Reconnect and try again.",clients:"Devices","clients.empty":"No pending or authorized devices","clients.pending":"Pending approval","clients.online":"Online","clients.offline":"Offline","clients.review":"Review","clients.reject":"Reject","clients.revoke":"Revoke access","clients.revokeConfirm":"Revoke access for {{name}}?","clients.loadError":"Could not update device authorizations. Refresh and try again.","clients.uncertain":"The result is unconfirmed. Refresh the device list before trying again.","clients.unsupported":"Device management requires an upgraded PC and Relay.","clients.allowTitle":"Allow device to connect?","clients.code":"Verification code","clients.allow":"Allow connection","clients.dismiss":"Not now",sessions:"Sessions","sessions.count_one":"{{count}} session","sessions.count_other":"{{count}} sessions","sessions.noDirectory":"No directory","sessions.empty":"No local sessions",session:"Session","session.you":"You","session.subagent":"Subagent","session.assistant":"Assistant","session.activities_one":"{{count}} activity","session.activities_other":"{{count}} activities","session.tasks_one":"{{count}} task","session.tasks_other":"{{count}} tasks","session.running":"Running","session.completed":"Completed","session.failed":"Failed","session.todo.pending":"Pending","session.todo.in_progress":"In progress","session.todo.done":"Done","session.plan":"Plan","session.planDeleted":"Plan deleted","session.navigation":"Session navigation","session.back":"Back to sessions","session.refresh":"Refresh latest","session.info":"View session information","session.machine":"Computer","session.agent":"Agent","session.directory":"Working directory","session.id":"Session ID","session.loadError":"Could not load session","session.reload":"Reload","session.older":"Load earlier messages","session.messages":"Session messages","session.empty":"No messages yet","session.emptyBody":"Messages will appear here when the session starts.","session.end":"Jump to end","session.missing":"This session was not found. Return to the list and refresh.","session.expired":"History has changed. Refresh the latest messages and try again.","session.unavailable":"Could not read this session. Try again or check the agent in the session list.","login.title":"Microsoft sign-in","login.connect":"Connect to Relay","login.confirm":"Confirm computer sign-in","login.launch":"Start AgentKnight","login.work":"Sign in with a work or school account","login.personal":"Sign in with a personal Microsoft account","login.signIn":"Sign in with Microsoft","login.retry":"Retry sign-in","login.continue":"Continue with Microsoft","login.discovering":"Detecting sign-in method\\u2026","login.starting":"Signing in\\u2026","login.confirming":"Confirming credentials\\u2026","login.connecting":"Connecting\\u2026","login.cancelling":"Cancelling\\u2026","login.pollError":"Could not update sign-in status. Retrying.","login.error":"Microsoft sign-in failed. Try again.","login.error.discovery":"Could not detect the Relay sign-in method. Check its address and your connection.","login.error.automatic":"This Relay does not support automatic sign-in. Upgrade it or configure authentication explicitly.","login.error.secure":"Could not connect securely. Check the Relay address and your connection.","login.error.response":"The Relay returned an invalid sign-in response. Check its configuration.","login.error.browser":"This Relay does not support browser sign-in. Ask its administrator to upgrade it.","login.error.expired":"This sign-in request has expired. Sign in again.","login.error.unauthorized":"This account is not authorized. Contact the Relay administrator.","login.error.rateLimit":"Too many sign-in attempts. Try again later.","login.error.issued":"This sign-in request has already been used. Retry sign-in to safely start a new request.","login.error.exchange":"The credential exchange result is unknown. Retry sign-in to safely cancel the previous request.","login.error.confirmation":"Credential confirmation is unverified. Credentials are saved; retry to continue confirmation.","login.error.confirmationService":"The Relay confirmation service is unavailable. Credentials are saved; ask its administrator to restore the service.","login.error.revoked":"The saved Relay credential is no longer authorized. Sign in again.","login.error.verification":"The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification.","login.error.cleanup":"Sign-in cancellation is unverified. Retry, or restart AgentKnight after the request expires.","login.error.cancelled":"Sign-in was cancelled. Sign in again.","login.error.closed":"The sign-in service is closed. Restart AgentKnight.","login.error.identity":"The Relay credential belongs to a different computer or account. Check the configuration before signing in again.","login.error.store":"Could not access system credential storage. Unlock it and restart AgentKnight.","login.error.linuxStore":"Start or unlock a Secret Service keyring (such as GNOME Keyring) in the same user\'s D-Bus session, then retry. Credentials will not fall back to files or an in-memory keyring.","login.error.invalidCredential":"The saved Relay credential is invalid. Recover it in your system credential manager before signing in.","login.error.conflict":"Another Relay account or enrollment is saved on this computer. Resolve the conflict in your system credential manager.","login.error.retention":"The system did not retain the credential. Unlock credential storage and restart AgentKnight.","login.error.origin":"Use an HTTPS Relay origin without a path or credentials. HTTP is allowed only for literal loopback addresses.","login.error.platform":"Microsoft sign-in requires Windows Credential Manager, macOS Keychain, or Linux Secret Service. Use a supported system.","login.error.capacity":"The Relay credential exceeds system storage capacity. Existing credentials were not changed. Contact the Relay administrator."};var Ne={"settings.images":"Azure Blob \\u56FE\\u7247\\uFF08\\u975E\\u7AEF\\u5230\\u7AEF\\u52A0\\u5BC6\\uFF09","settings.imagesError":"\\u65E0\\u6CD5\\u4FDD\\u5B58\\u56FE\\u7247\\u5B58\\u50A8\\u8BBE\\u7F6E\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","settings.imagesUnavailable":"\\u6B64 Relay \\u672A\\u63D0\\u4F9B\\u56FE\\u7247\\u5B58\\u50A8\\uFF0C\\u8BF7\\u91CD\\u8FDE\\u540E\\u91CD\\u8BD5\\u3002",language:"\\u8BED\\u8A00",refresh:"\\u5237\\u65B0",retry:"\\u91CD\\u8BD5",cancel:"\\u53D6\\u6D88",details:"\\u8BE6\\u60C5",account:"Relay \\u8D26\\u6237","account.work":"Microsoft \\u5DE5\\u4F5C\\u8D26\\u6237","account.personal":"Microsoft \\u8D26\\u6237","account.fallback":"\\u8D26\\u6237 {{id}}","account.legacy":"\\u4F20\\u7EDF\\u8D26\\u6237","account.admin":"\\u7BA1\\u7406\\u5458","account.user":"\\u666E\\u901A\\u7528\\u6237","account.view":"\\u67E5\\u770B\\u8D26\\u6237","account.signedIn":"\\u5DF2\\u767B\\u5F55","account.connecting":"\\u8FDE\\u63A5\\u4E2D","account.disconnected":"\\u5DF2\\u65AD\\u5F00","account.error":"\\u767B\\u5F55\\u5F02\\u5E38","account.unknown":"\\u72B6\\u6001\\u672A\\u77E5","account.unavailable":"\\u65E0\\u6CD5\\u66F4\\u65B0\\u767B\\u5F55\\u72B6\\u6001\\uFF0C\\u8BF7\\u5237\\u65B0\\u9875\\u9762\\u3002","account.failure.disconnected":"Relay \\u8FDE\\u63A5\\u5DF2\\u65AD\\u5F00\\u3002","account.failure.invalid":"Relay \\u8FD4\\u56DE\\u4E86\\u65E0\\u6548\\u7684\\u8D26\\u6237\\u4FE1\\u606F\\u3002","account.failure.unsupported":"Relay \\u5C1A\\u4E0D\\u652F\\u6301\\u8D26\\u6237\\u4FE1\\u606F\\uFF0C\\u8BF7\\u5347\\u7EA7 Relay\\u3002","account.failure.expired":"\\u767B\\u5F55\\u51ED\\u636E\\u5DF2\\u5931\\u6548\\uFF0C\\u8BF7\\u91CD\\u65B0\\u767B\\u5F55\\u3002","account.failure.tls":"\\u65E0\\u6CD5\\u5B89\\u5168\\u8BFB\\u53D6\\u8D26\\u6237\\u4FE1\\u606F\\uFF0C\\u8BF7\\u542F\\u7528 HTTPS \\u8BC1\\u4E66\\u9A8C\\u8BC1\\u3002","account.failure.read":"\\u65E0\\u6CD5\\u8BFB\\u53D6\\u8D26\\u6237\\u4FE1\\u606F\\uFF0C\\u8BF7\\u7A0D\\u540E\\u5237\\u65B0\\u3002","account.failure.connection":"\\u65E0\\u6CD5\\u8BFB\\u53D6\\u8D26\\u6237\\u4FE1\\u606F\\uFF0C\\u8BF7\\u68C0\\u67E5 Relay \\u8FDE\\u63A5\\u540E\\u5237\\u65B0\\u3002","relay.connecting":"\\u8FDE\\u63A5\\u4E2D\\u2026","relay.reconnect":"\\u91CD\\u8FDE","relay.disconnect":"\\u65AD\\u5F00\\u8FDE\\u63A5","relay.disconnecting":"\\u6B63\\u5728\\u65AD\\u5F00\\u2026","relay.statusError":"\\u65E0\\u6CD5\\u66F4\\u65B0 Relay \\u8FDE\\u63A5\\u72B6\\u6001\\uFF0C\\u8BF7\\u5237\\u65B0\\u9875\\u9762\\u3002","relay.reconnectError":"\\u65E0\\u6CD5\\u91CD\\u8FDE Relay\\uFF0C\\u8BF7\\u7A0D\\u540E\\u91CD\\u8BD5\\u3002","relay.disconnectError":"\\u65E0\\u6CD5\\u65AD\\u5F00 Relay\\uFF0C\\u8BF7\\u7A0D\\u540E\\u91CD\\u8BD5\\u3002",deployment:"\\u90E8\\u7F72\\u4FE1\\u606F","deployment.version":"\\u5F53\\u524D\\u7248\\u672C","deployment.upgraded":"\\u4E0A\\u6B21\\u5347\\u7EA7","deployment.noUpgrade":"\\u6682\\u65E0\\u8BB0\\u5F55","deployment.config":"\\u7528\\u6237\\u914D\\u7F6E","deployment.environment":"\\u8FDB\\u7A0B\\u73AF\\u5883","deployment.relay":"Relay URL",agents:"Agent \\u540C\\u6B65","agents.sync":"\\u540C\\u6B65","agents.enable":"\\u5F00\\u542F\\u540C\\u6B65","agents.enableName":"\\u5F00\\u542F\\u540C\\u6B65 {{name}}","agents.connected":"\\u5DF2\\u8FDE\\u63A5","agents.unavailable":"\\u4E0D\\u53EF\\u7528","agents.single":"\\u5F53\\u524D\\u4E3A\\u5355 Agent \\u6A21\\u5F0F","agents.empty":"\\u6CA1\\u6709\\u53EF\\u914D\\u7F6E\\u7684 Agent","agents.dirty":"\\u5F85\\u540C\\u6B65","agents.saving":"\\u540C\\u6B65\\u4E2D\\u2026","agents.saved":"\\u5DF2\\u540C\\u6B65","agents.busy":"\\u6B63\\u5728\\u540C\\u6B65\\uFF0C\\u8BF7\\u7A0D\\u540E\\u91CD\\u8BD5\\u3002","agents.saveError":"\\u540C\\u6B65\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","agents.httpError":"\\u540C\\u6B65\\u5931\\u8D25\\uFF08HTTP {{status}}\\uFF09\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","settings.group":"Agent \\u7FA4\\u804A","settings.peer":"Agent \\u7684\\u8DE8 PC \\u901A\\u4FE1","settings.busy":"\\u6B63\\u5728\\u4FDD\\u5B58\\uFF0C\\u8BF7\\u7A0D\\u540E\\u91CD\\u8BD5\\u3002","settings.groupError":"\\u7FA4\\u804A\\u8BBE\\u7F6E\\u4FDD\\u5B58\\u5931\\u8D25\\uFF0C\\u8BF7\\u5237\\u65B0\\u540E\\u91CD\\u8BD5\\u3002","settings.peerError":"\\u8DE8 PC \\u901A\\u4FE1\\u8BBE\\u7F6E\\u4FDD\\u5B58\\u5931\\u8D25\\uFF0C\\u8BF7\\u5237\\u65B0\\u540E\\u91CD\\u8BD5\\u3002",pairing:"\\u624B\\u673A\\u914D\\u5BF9","pairing.qr":"\\u914D\\u5BF9\\u4E8C\\u7EF4\\u7801","pairing.text":"\\u914D\\u5BF9\\u5B57\\u7B26\\u4E32","pairing.copy":"\\u590D\\u5236","pairing.copied":"\\u5DF2\\u590D\\u5236","pairing.copyError":"\\u590D\\u5236\\u5931\\u8D25\\uFF0C\\u8BF7\\u9009\\u4E2D\\u914D\\u5BF9\\u5B57\\u7B26\\u4E32\\u624B\\u52A8\\u590D\\u5236\\u3002","pairing.show":"\\u663E\\u793A\\u4E8C\\u7EF4\\u7801","pairing.refresh":"\\u5237\\u65B0\\u4E8C\\u7EF4\\u7801","pairing.hide":"\\u9690\\u85CF","pairing.success":"\\u914D\\u5BF9\\u6210\\u529F","pairing.invalid":"\\u4E8C\\u7EF4\\u7801\\u5DF2\\u5931\\u6548\\uFF0C\\u8BF7\\u91CD\\u65B0\\u663E\\u793A\\u3002","pairing.expired":"\\u4E8C\\u7EF4\\u7801\\u5DF2\\u8FC7\\u671F\\uFF0C\\u8BF7\\u91CD\\u65B0\\u663E\\u793A\\u3002","pairing.statusError":"\\u65E0\\u6CD5\\u786E\\u8BA4\\u914D\\u5BF9\\u72B6\\u6001\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5\\u3002","pairing.generateError":"\\u65E0\\u6CD5\\u751F\\u6210\\u4E8C\\u7EF4\\u7801\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","pairing.offline":"Relay \\u5C1A\\u672A\\u8FDE\\u63A5\\uFF0C\\u8BF7\\u91CD\\u8FDE\\u540E\\u91CD\\u8BD5\\u3002",clients:"\\u8BBE\\u5907","clients.empty":"\\u6CA1\\u6709\\u5F85\\u6279\\u51C6\\u6216\\u5DF2\\u6388\\u6743\\u7684\\u5BA2\\u6237\\u7AEF","clients.pending":"\\u5F85\\u6279\\u51C6","clients.online":"\\u5728\\u7EBF","clients.offline":"\\u79BB\\u7EBF","clients.review":"\\u67E5\\u770B\\u8BF7\\u6C42","clients.reject":"\\u62D2\\u7EDD","clients.revoke":"\\u64A4\\u9500\\u6388\\u6743","clients.revokeConfirm":"\\u64A4\\u9500 {{name}} \\u7684\\u8BBF\\u95EE\\u6388\\u6743\\uFF1F","clients.loadError":"\\u65E0\\u6CD5\\u66F4\\u65B0\\u5BA2\\u6237\\u7AEF\\u6388\\u6743\\uFF0C\\u8BF7\\u5237\\u65B0\\u91CD\\u8BD5\\u3002","clients.uncertain":"\\u64CD\\u4F5C\\u7ED3\\u679C\\u5F85\\u786E\\u8BA4\\uFF0C\\u8BF7\\u5237\\u65B0\\u5BA2\\u6237\\u7AEF\\u5217\\u8868\\u3002","clients.unsupported":"\\u5BA2\\u6237\\u7AEF\\u7BA1\\u7406\\u9700\\u8981\\u5347\\u7EA7 PC \\u548C Relay\\u3002","clients.allowTitle":"\\u5141\\u8BB8\\u8BBE\\u5907\\u8FDE\\u63A5\\uFF1F","clients.code":"\\u6838\\u5BF9\\u7801","clients.allow":"\\u5141\\u8BB8\\u8FDE\\u63A5","clients.dismiss":"\\u6682\\u4E0D\\u5904\\u7406",sessions:"\\u4F1A\\u8BDD","sessions.count_one":"{{count}} \\u4E2A\\u4F1A\\u8BDD","sessions.count_other":"{{count}} \\u4E2A\\u4F1A\\u8BDD","sessions.noDirectory":"\\u672A\\u63D0\\u4F9B\\u76EE\\u5F55","sessions.empty":"\\u6CA1\\u6709\\u672C\\u5730\\u4F1A\\u8BDD",session:"\\u4F1A\\u8BDD","session.you":"\\u4F60","session.subagent":"\\u5B50 Agent","session.assistant":"\\u52A9\\u624B","session.activities_one":"{{count}} \\u9879\\u6D3B\\u52A8","session.activities_other":"{{count}} \\u9879\\u6D3B\\u52A8","session.tasks_one":"{{count}} \\u9879\\u4EFB\\u52A1","session.tasks_other":"{{count}} \\u9879\\u4EFB\\u52A1","session.running":"\\u8FDB\\u884C\\u4E2D","session.completed":"\\u5DF2\\u5B8C\\u6210","session.failed":"\\u5931\\u8D25","session.todo.pending":"\\u5F85\\u5904\\u7406","session.todo.in_progress":"\\u8FDB\\u884C\\u4E2D","session.todo.done":"\\u5DF2\\u5B8C\\u6210","session.plan":"\\u8BA1\\u5212","session.planDeleted":"\\u8BA1\\u5212\\u5DF2\\u5220\\u9664","session.navigation":"\\u4F1A\\u8BDD\\u5BFC\\u822A","session.back":"\\u8FD4\\u56DE\\u4F1A\\u8BDD\\u5217\\u8868","session.refresh":"\\u5237\\u65B0\\u6700\\u65B0","session.info":"\\u67E5\\u770B\\u4F1A\\u8BDD\\u4FE1\\u606F","session.machine":"\\u7535\\u8111","session.agent":"Agent","session.directory":"\\u5DE5\\u4F5C\\u76EE\\u5F55","session.id":"Session ID","session.loadError":"\\u672A\\u80FD\\u52A0\\u8F7D\\u4F1A\\u8BDD","session.reload":"\\u91CD\\u65B0\\u52A0\\u8F7D","session.older":"\\u67E5\\u770B\\u66F4\\u65E9\\u6D88\\u606F","session.messages":"\\u4F1A\\u8BDD\\u6D88\\u606F","session.empty":"\\u8FD8\\u6CA1\\u6709\\u6D88\\u606F","session.emptyBody":"\\u4F1A\\u8BDD\\u5F00\\u59CB\\u540E\\uFF0C\\u6D88\\u606F\\u4F1A\\u663E\\u793A\\u5728\\u8FD9\\u91CC\\u3002","session.end":"\\u8DF3\\u5230\\u672B\\u5C3E","session.missing":"\\u627E\\u4E0D\\u5230\\u8FD9\\u4E2A\\u4F1A\\u8BDD\\uFF0C\\u8BF7\\u8FD4\\u56DE\\u5217\\u8868\\u5237\\u65B0\\u3002","session.expired":"\\u5386\\u53F2\\u8BB0\\u5F55\\u5DF2\\u53D8\\u5316\\uFF0C\\u8BF7\\u5237\\u65B0\\u6700\\u65B0\\u6D88\\u606F\\u540E\\u91CD\\u8BD5\\u3002","session.unavailable":"\\u6682\\u65F6\\u65E0\\u6CD5\\u8BFB\\u53D6\\u4F1A\\u8BDD\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u6216\\u8FD4\\u56DE\\u5217\\u8868\\u68C0\\u67E5 Agent \\u72B6\\u6001\\u3002","login.title":"Microsoft \\u767B\\u5F55","login.connect":"\\u8FDE\\u63A5 Relay","login.confirm":"\\u786E\\u8BA4\\u7535\\u8111\\u767B\\u5F55","login.launch":"\\u542F\\u52A8 AgentKnight","login.work":"\\u4F7F\\u7528\\u5DE5\\u4F5C\\u6216\\u5B66\\u6821\\u8D26\\u6237\\u767B\\u5F55","login.personal":"\\u4F7F\\u7528 Microsoft \\u4E2A\\u4EBA\\u8D26\\u6237\\u767B\\u5F55","login.signIn":"\\u4F7F\\u7528 Microsoft \\u767B\\u5F55","login.retry":"\\u91CD\\u8BD5\\u767B\\u5F55","login.continue":"\\u7EE7\\u7EED Microsoft \\u767B\\u5F55","login.discovering":"\\u6B63\\u5728\\u8BC6\\u522B\\u767B\\u5F55\\u65B9\\u5F0F\\u2026","login.starting":"\\u6B63\\u5728\\u767B\\u5F55\\u2026","login.confirming":"\\u6B63\\u5728\\u786E\\u8BA4\\u767B\\u5F55\\u51ED\\u636E\\u2026","login.connecting":"\\u6B63\\u5728\\u8FDE\\u63A5\\u2026","login.cancelling":"\\u6B63\\u5728\\u53D6\\u6D88\\u2026","login.pollError":"\\u65E0\\u6CD5\\u66F4\\u65B0\\u767B\\u5F55\\u72B6\\u6001\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5\\u3002","login.error":"Microsoft \\u767B\\u5F55\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","login.error.discovery":"\\u65E0\\u6CD5\\u8BC6\\u522B Relay \\u767B\\u5F55\\u65B9\\u5F0F\\uFF0C\\u8BF7\\u68C0\\u67E5\\u5730\\u5740\\u548C\\u7F51\\u7EDC\\u8FDE\\u63A5\\u540E\\u91CD\\u8BD5\\u3002","login.error.automatic":"\\u6B64 Relay \\u4E0D\\u652F\\u6301\\u81EA\\u52A8\\u767B\\u5F55\\uFF0C\\u8BF7\\u5347\\u7EA7 Relay \\u6216\\u5728\\u914D\\u7F6E\\u6587\\u4EF6\\u4E2D\\u6307\\u5B9A\\u767B\\u5F55\\u65B9\\u5F0F\\u3002","login.error.secure":"\\u65E0\\u6CD5\\u5B89\\u5168\\u8FDE\\u63A5 Relay\\uFF0C\\u8BF7\\u68C0\\u67E5 Relay \\u5730\\u5740\\u548C\\u7F51\\u7EDC\\u8FDE\\u63A5\\u540E\\u91CD\\u8BD5\\u3002","login.error.response":"Relay \\u8FD4\\u56DE\\u7684\\u767B\\u5F55\\u54CD\\u5E94\\u65E0\\u6548\\uFF0C\\u8BF7\\u68C0\\u67E5 Relay \\u914D\\u7F6E\\u3002","login.error.browser":"\\u6B64 Relay \\u4E0D\\u652F\\u6301\\u6D4F\\u89C8\\u5668\\u767B\\u5F55\\uFF0C\\u8BF7\\u8054\\u7CFB\\u7BA1\\u7406\\u5458\\u5347\\u7EA7 Relay \\u540E\\u91CD\\u8BD5\\u3002","login.error.expired":"\\u767B\\u5F55\\u8BF7\\u6C42\\u5DF2\\u8FC7\\u671F\\uFF0C\\u8BF7\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.unauthorized":"\\u6B64\\u8D26\\u6237\\u672A\\u83B7 Relay \\u6388\\u6743\\uFF0C\\u8BF7\\u8054\\u7CFB Relay \\u7BA1\\u7406\\u5458\\u3002","login.error.rateLimit":"\\u767B\\u5F55\\u5C1D\\u8BD5\\u8FC7\\u4E8E\\u9891\\u7E41\\uFF0C\\u8BF7\\u7A0D\\u540E\\u91CD\\u8BD5\\u3002","login.error.issued":"\\u6B64\\u767B\\u5F55\\u8BF7\\u6C42\\u5DF2\\u88AB\\u4F7F\\u7528\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u767B\\u5F55\\u4EE5\\u5B89\\u5168\\u53D1\\u8D77\\u65B0\\u8BF7\\u6C42\\u3002","login.error.exchange":"\\u51ED\\u636E\\u4EA4\\u6362\\u7ED3\\u679C\\u672A\\u77E5\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u767B\\u5F55\\u4EE5\\u5B89\\u5168\\u53D6\\u6D88\\u539F\\u8BF7\\u6C42\\u5E76\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.confirmation":"\\u51ED\\u636E\\u786E\\u8BA4\\u7ED3\\u679C\\u672A\\u77E5\\u3002\\u51ED\\u636E\\u5DF2\\u4FDD\\u5B58\\uFF0C\\u91CD\\u8BD5\\u5C06\\u7EE7\\u7EED\\u786E\\u8BA4\\u3002","login.error.confirmationService":"Relay \\u786E\\u8BA4\\u670D\\u52A1\\u5F02\\u5E38\\u3002\\u51ED\\u636E\\u5DF2\\u4FDD\\u5B58\\uFF0C\\u8BF7\\u8054\\u7CFB\\u7BA1\\u7406\\u5458\\u6062\\u590D\\u670D\\u52A1\\u540E\\u91CD\\u8BD5\\u3002","login.error.revoked":"\\u5DF2\\u4FDD\\u5B58\\u7684 Relay \\u51ED\\u636E\\u5DF2\\u5931\\u6548\\uFF0C\\u8BF7\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.verification":"Relay \\u65E0\\u6CD5\\u9A8C\\u8BC1\\u5DF2\\u4FDD\\u5B58\\u7684\\u51ED\\u636E\\uFF0C\\u8BF7\\u8054\\u7CFB\\u7BA1\\u7406\\u5458\\u542F\\u7528 Microsoft \\u51ED\\u636E\\u9A8C\\u8BC1\\u540E\\u91CD\\u8BD5\\u3002","login.error.cleanup":"\\u65E0\\u6CD5\\u786E\\u8BA4\\u767B\\u5F55\\u8BF7\\u6C42\\u662F\\u5426\\u5DF2\\u53D6\\u6D88\\uFF0C\\u8BF7\\u91CD\\u8BD5\\uFF0C\\u6216\\u7B49\\u5F85\\u8BF7\\u6C42\\u8FC7\\u671F\\u540E\\u91CD\\u542F AgentKnight\\u3002","login.error.cancelled":"\\u767B\\u5F55\\u5DF2\\u53D6\\u6D88\\uFF0C\\u8BF7\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.closed":"\\u767B\\u5F55\\u670D\\u52A1\\u5DF2\\u5173\\u95ED\\uFF0C\\u8BF7\\u91CD\\u542F AgentKnight \\u540E\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.identity":"Relay \\u51ED\\u636E\\u4E0E\\u6B64\\u7535\\u8111\\u6216\\u8D26\\u6237\\u4E0D\\u5339\\u914D\\uFF0C\\u8BF7\\u68C0\\u67E5 Relay \\u914D\\u7F6E\\u540E\\u91CD\\u65B0\\u767B\\u5F55\\u3002","login.error.store":"\\u65E0\\u6CD5\\u8BBF\\u95EE\\u7CFB\\u7EDF\\u51ED\\u636E\\u5B58\\u50A8\\uFF0C\\u8BF7\\u89E3\\u9501\\u51ED\\u636E\\u5B58\\u50A8\\u5E76\\u91CD\\u542F AgentKnight\\u3002","login.error.linuxStore":"\\u8BF7\\u5728\\u540C\\u4E00\\u7528\\u6237\\u7684 D-Bus \\u4F1A\\u8BDD\\u4E2D\\u542F\\u52A8\\u6216\\u89E3\\u9501 Secret Service \\u5BC6\\u94A5\\u73AF\\uFF08\\u5982 GNOME Keyring\\uFF09\\u540E\\u91CD\\u8BD5\\u3002\\u51ED\\u636E\\u4E0D\\u4F1A\\u964D\\u7EA7\\u4FDD\\u5B58\\u5230\\u6587\\u4EF6\\u6216\\u5185\\u5B58\\u5BC6\\u94A5\\u73AF\\u3002","login.error.invalidCredential":"\\u5DF2\\u4FDD\\u5B58\\u7684 Relay \\u51ED\\u636E\\u65E0\\u6548\\uFF0C\\u8BF7\\u5148\\u5728\\u7CFB\\u7EDF\\u51ED\\u636E\\u7BA1\\u7406\\u5668\\u4E2D\\u6062\\u590D\\u51ED\\u636E\\u518D\\u767B\\u5F55\\u3002","login.error.conflict":"\\u6B64\\u7535\\u8111\\u5DF2\\u4FDD\\u5B58\\u5176\\u4ED6 Relay \\u8D26\\u6237\\u6216\\u767B\\u5F55\\u8BF7\\u6C42\\uFF0C\\u8BF7\\u5148\\u5728\\u7CFB\\u7EDF\\u51ED\\u636E\\u7BA1\\u7406\\u5668\\u4E2D\\u5904\\u7406\\u51B2\\u7A81\\u3002","login.error.retention":"\\u7CFB\\u7EDF\\u672A\\u80FD\\u4FDD\\u5B58\\u767B\\u5F55\\u51ED\\u636E\\uFF0C\\u8BF7\\u89E3\\u9501\\u51ED\\u636E\\u5B58\\u50A8\\u5E76\\u91CD\\u542F AgentKnight\\u3002","login.error.origin":"\\u8BF7\\u4F7F\\u7528\\u4E0D\\u542B\\u8DEF\\u5F84\\u6216\\u51ED\\u636E\\u7684 HTTPS Relay \\u5730\\u5740\\uFF1BHTTP \\u4EC5\\u5141\\u8BB8\\u672C\\u673A\\u56DE\\u73AF IP \\u5730\\u5740\\u3002","login.error.platform":"Microsoft \\u767B\\u5F55\\u9700\\u8981 Windows \\u51ED\\u636E\\u7BA1\\u7406\\u5668\\u3001macOS \\u94A5\\u5319\\u4E32\\u6216 Linux Secret Service\\uFF0C\\u8BF7\\u4F7F\\u7528\\u53D7\\u652F\\u6301\\u7684\\u7CFB\\u7EDF\\u3002","login.error.capacity":"Relay \\u51ED\\u636E\\u8D85\\u51FA\\u7CFB\\u7EDF\\u5B58\\u50A8\\u5BB9\\u91CF\\uFF0C\\u539F\\u51ED\\u636E\\u672A\\u66F4\\u6539\\u3002\\u8BF7\\u8054\\u7CFB Relay \\u7BA1\\u7406\\u5458\\u3002"};var tt={en:{translation:fe},"zh-CN":{translation:Ne}},Ae=Te();Ae.init({resources:tt,lng:"zh-CN",fallbackLng:"en",initAsync:!1,keySeparator:!1,interpolation:{escapeValue:!1}});function ee(r="zh-CN"){return(e,t={})=>Ae.t(e,{...t,lng:r})}function te(r){return r==="zh-CN"||r==="en"}var A=class extends Error{constructor(t,s,n={}){super(s);this.key=t;this.values=n}key;values};function je(r,e,t={}){if(typeof r=="object"&&r!==null){if("errorKey"in r&&typeof r.errorKey=="string"&&Object.hasOwn(fe,r.errorKey))return new A(r.errorKey,"");if("error"in r&&typeof r.error=="string"&&r.error)return new A(void 0,r.error)}return new A(e,"",t)}var T=te(document.documentElement.lang)?document.documentElement.lang:"zh-CN";function Fe(r,e,t={}){let s=r.querySelector("[data-action-label]")??r;s.dataset.i18n=e,s.dataset.i18nValues=JSON.stringify(t),s.textContent=ee(T)(e,t)}function se(r=document){for(let t of r.querySelectorAll("[data-i18n], [data-i18n-aria-label], [data-i18n-title]")){let s=JSON.parse(t.dataset.i18nValues??"{}"),n=ee(T);t.dataset.i18n&&(t.textContent=n(t.dataset.i18n,s));for(let i of["aria-label","title"]){let a=t.getAttribute(`data-i18n-${i}`);a&&t.setAttribute(i,n(a,s))}}for(let t of r.querySelectorAll("time[data-date-format]")){let s=new Date(t.dateTime);if(!Number.isFinite(s.getTime()))continue;let n=t.dataset.dateFormat;t.textContent=n==="day"?s.toLocaleDateString(T,{year:"numeric",month:"long",day:"numeric"}):n==="time"?s.toLocaleTimeString(T,{hour:"2-digit",minute:"2-digit",hour12:!1}):s.toLocaleString(T,{hour12:!1}),n==="time"&&(t.title=s.toLocaleString(T,{hour12:!1}))}let e=document.querySelector("#language-picker");e&&(e.value=T)}function st(r){T=r,document.documentElement.lang=r,document.cookie=`ak-language=${r}; Path=/; Max-Age=31536000; SameSite=Strict`,se()}function nt(r,e,t){e instanceof A&&e.key===void 0?(delete r.dataset.i18n,delete r.dataset.i18nValues,r.textContent=e.message):Fe(r,e instanceof A?e.key??t:t,e instanceof A?e.values:{})}var it={t:(r,e)=>ee(T)(r,e),text:Fe,apply:se,report:nt,failure:je};window.localUI=it;document.addEventListener("change",r=>{r.target instanceof HTMLSelectElement&&r.target.id==="language-picker"&&te(r.target.value)&&st(r.target.value)});addEventListener("pageshow",()=>{let r=/(?:^|;\\s*)ak-language=(zh-CN|en)(?:;|$)/.exec(document.cookie)?.[1];te(r)&&(T=r,document.documentElement.lang=r),se()});se();})();\n';
|
|
1891
|
-
return readFile(new URL(`../dist/${path.slice(1)}`, import.meta.url), "utf8");
|
|
1892
|
-
}
|
|
1893
|
-
|
|
1894
|
-
// src/pairing-page.ts
|
|
1895
|
-
var PAIRING_PAGE_HOST = "127.0.0.1";
|
|
1896
|
-
var MAX_FORM_BODY_BYTES = 1024;
|
|
1897
|
-
var FormBodyTooLargeError = class extends Error {
|
|
1898
|
-
};
|
|
1899
|
-
var PairingPageServer = class {
|
|
1900
|
-
#options;
|
|
1901
|
-
#refreshToken = randomBytes(24).toString("base64url");
|
|
1902
|
-
#server;
|
|
1903
|
-
#saving = false;
|
|
1904
|
-
#loginMutating = false;
|
|
1905
|
-
#loginFailureMessage;
|
|
1906
|
-
constructor(options) {
|
|
1907
|
-
this.#options = options;
|
|
1908
|
-
this.#server = createServer((request, response) => {
|
|
1909
|
-
void this.#handleRequest(request, response).catch((error) => {
|
|
1910
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "mobile.pairing-page.request.failed");
|
|
1911
|
-
if (!response.headersSent) {
|
|
1912
|
-
this.#writeHeaders(response, error instanceof FormBodyTooLargeError ? 413 : 503, "text/plain; charset=utf-8");
|
|
1913
|
-
}
|
|
1914
|
-
if (!response.writableEnded) {
|
|
1915
|
-
response.end(error instanceof FormBodyTooLargeError ? "Form body exceeds the size limit." : "Local page is temporarily unavailable.");
|
|
1916
|
-
}
|
|
1917
|
-
});
|
|
1918
|
-
});
|
|
1919
|
-
}
|
|
1920
|
-
get url() {
|
|
1921
|
-
const address = this.#server.address();
|
|
1922
|
-
if (address === null || typeof address === "string") throw new Error("Pairing page server is not listening");
|
|
1923
|
-
return `http://${PAIRING_PAGE_HOST}:${address.port}`;
|
|
1924
|
-
}
|
|
1925
|
-
async start() {
|
|
1926
|
-
if (this.#server.listening) return;
|
|
1927
|
-
await new Promise((resolve2, reject) => {
|
|
1928
|
-
const onError = (error) => {
|
|
1929
|
-
this.#server.off("listening", onListening);
|
|
1930
|
-
reject(error);
|
|
1931
|
-
};
|
|
1932
|
-
const onListening = () => {
|
|
1933
|
-
this.#server.off("error", onError);
|
|
1934
|
-
resolve2();
|
|
1935
|
-
};
|
|
1936
|
-
this.#server.once("error", onError);
|
|
1937
|
-
this.#server.once("listening", onListening);
|
|
1938
|
-
this.#server.listen(this.#options.port, PAIRING_PAGE_HOST);
|
|
1939
|
-
});
|
|
1940
|
-
}
|
|
1941
|
-
async stop() {
|
|
1942
|
-
if (!this.#server.listening) return;
|
|
1943
|
-
await new Promise((resolve2, reject) => {
|
|
1944
|
-
this.#server.close((error) => error === void 0 ? resolve2() : reject(error));
|
|
1945
|
-
this.#server.closeAllConnections();
|
|
1946
|
-
});
|
|
1947
|
-
}
|
|
1948
|
-
useRuntime(options) {
|
|
1949
|
-
if (this.#options.relayLogin?.getState().state !== "signed-in") {
|
|
1950
|
-
throw new Error("Microsoft sign-in must finish before starting the local runtime page.");
|
|
1951
|
-
}
|
|
1952
|
-
this.#options = { ...options, port: Number(new URL(this.url).port) };
|
|
1953
|
-
this.#loginFailureMessage = void 0;
|
|
1954
|
-
return this;
|
|
1955
|
-
}
|
|
1956
|
-
async #handleRequest(request, response) {
|
|
1957
|
-
if (request.headers.host !== new URL(this.url).host) {
|
|
1958
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8", "no-referrer");
|
|
1959
|
-
response.end("Invalid Host header.");
|
|
1960
|
-
return;
|
|
1961
|
-
}
|
|
1962
|
-
const requestUrl = new URL(request.url ?? "/", "http://localhost");
|
|
1963
|
-
const locale = resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]);
|
|
1964
|
-
response.setHeader("content-language", locale);
|
|
1965
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login/callback") {
|
|
1966
|
-
const params = requestUrl.searchParams;
|
|
1967
|
-
if ((request.url ?? "").startsWith("/relay-login/callback?") && !requestUrl.hash && [...params.keys()].every((key) => params.getAll(key).length === 1)) {
|
|
1968
|
-
try {
|
|
1969
|
-
const release = this.#options.relayLogin?.acceptCallback(
|
|
1970
|
-
Object.fromEntries(params),
|
|
1971
|
-
`${this.url}/relay-login/callback`
|
|
1972
|
-
);
|
|
1973
|
-
if (release) {
|
|
1974
|
-
this.#loginFailureMessage = void 0;
|
|
1975
|
-
response.once("finish", release);
|
|
1976
|
-
}
|
|
1977
|
-
} catch {
|
|
1978
|
-
this.#options.logger?.error({ operation: "callback" }, "relay.login.operation.failed");
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
this.#redirectLogin(response, "/");
|
|
1982
|
-
return;
|
|
1983
|
-
}
|
|
1984
|
-
if (request.method === "GET" && requestUrl.pathname === "/health") {
|
|
1985
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1986
|
-
response.end('{"ok":true}');
|
|
1987
|
-
return;
|
|
1988
|
-
}
|
|
1989
|
-
if (request.method === "GET" && (requestUrl.pathname === "/local-ui.css" || requestUrl.pathname === "/local-ui.js")) {
|
|
1990
|
-
const asset = await readLocalPageAsset(requestUrl.pathname);
|
|
1991
|
-
this.#writeHeaders(response, 200, requestUrl.pathname.endsWith(".css") ? "text/css; charset=utf-8" : "text/javascript; charset=utf-8");
|
|
1992
|
-
response.end(asset);
|
|
1993
|
-
return;
|
|
1994
|
-
}
|
|
1995
|
-
if (request.method === "GET" && requestUrl.pathname === "/local-page.js") {
|
|
1996
|
-
this.#writeHeaders(response, 200, "text/javascript; charset=utf-8");
|
|
1997
|
-
response.end(localPageScript);
|
|
1998
|
-
return;
|
|
1999
|
-
}
|
|
2000
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login.js") {
|
|
2001
|
-
this.#writeHeaders(response, 200, "text/javascript; charset=utf-8");
|
|
2002
|
-
response.end(relayLoginPageScript);
|
|
2003
|
-
return;
|
|
2004
|
-
}
|
|
2005
|
-
if (request.method === "GET" && (requestUrl.pathname === "/" || requestUrl.pathname === "/pair")) {
|
|
2006
|
-
await this.#renderPage(request, response, 200, { saved: requestUrl.searchParams.get("saved") === "1" });
|
|
2007
|
-
return;
|
|
2008
|
-
}
|
|
2009
|
-
const relayLogin = this.#options.relayLogin;
|
|
2010
|
-
if (requestUrl.pathname === "/session" && relayLogin === void 0 && this.#options.sessions !== void 0) {
|
|
2011
|
-
if (request.method !== "GET") {
|
|
2012
|
-
response.setHeader("allow", "GET");
|
|
2013
|
-
this.#writeHeaders(response, 405, "text/plain; charset=utf-8");
|
|
2014
|
-
response.end("Method not allowed.");
|
|
2015
|
-
return;
|
|
2016
|
-
}
|
|
2017
|
-
if (request.headers.origin !== void 0 && request.headers.origin !== this.url || request.headers["sec-fetch-site"] === "cross-site") {
|
|
2018
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
2019
|
-
response.end("Invalid request origin.");
|
|
2020
|
-
return;
|
|
2021
|
-
}
|
|
2022
|
-
const params = requestUrl.searchParams;
|
|
2023
|
-
const parsed = SessionTimelinePageRequestSchema.pick({ sessionId: true, cursor: true }).strict().safeParse(Object.fromEntries(params));
|
|
2024
|
-
if (!parsed.success || [...params.keys()].some((key) => params.getAll(key).length !== 1)) {
|
|
2025
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
2026
|
-
response.end("Invalid session request.");
|
|
2027
|
-
return;
|
|
2028
|
-
}
|
|
2029
|
-
let session;
|
|
2030
|
-
try {
|
|
2031
|
-
session = (await this.#options.sessions.list()).find((entry) => entry.id === parsed.data.sessionId);
|
|
2032
|
-
if (session === void 0) {
|
|
2033
|
-
this.#writeHeaders(response, 404, "text/html; charset=utf-8");
|
|
2034
|
-
response.end(renderSessionPage({ locale, machineName: this.#options.machineName, error: { key: "session.missing" } }));
|
|
2035
|
-
return;
|
|
2036
|
-
}
|
|
2037
|
-
const page = SessionTimelinePageSchema.parse(await this.#options.sessions.readPage(session.id, parsed.data.cursor));
|
|
2038
|
-
const expired = page.cursorStatus === "expired" || page.hasMore && (!page.cursor || page.cursor === parsed.data.cursor);
|
|
2039
|
-
this.#writeHeaders(response, expired ? 409 : 200, "text/html; charset=utf-8");
|
|
2040
|
-
response.end(renderSessionPage({
|
|
2041
|
-
locale,
|
|
2042
|
-
machineName: this.#options.machineName,
|
|
2043
|
-
session,
|
|
2044
|
-
...expired ? { error: { key: "session.expired" } } : { page }
|
|
2045
|
-
}));
|
|
2046
|
-
} catch (error) {
|
|
2047
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "local.session-page.read.failed");
|
|
2048
|
-
this.#writeHeaders(response, 503, "text/html; charset=utf-8");
|
|
2049
|
-
response.end(renderSessionPage({
|
|
2050
|
-
locale,
|
|
2051
|
-
machineName: this.#options.machineName,
|
|
2052
|
-
...session === void 0 ? {} : { session },
|
|
2053
|
-
error: { key: "session.unavailable" }
|
|
2054
|
-
}));
|
|
2055
|
-
}
|
|
2056
|
-
return;
|
|
2057
|
-
}
|
|
2058
|
-
if (relayLogin === void 0 && this.#options.reconnectRelay !== void 0 && request.method === "GET" && requestUrl.pathname === "/relay-status") {
|
|
2059
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2060
|
-
response.end(JSON.stringify({
|
|
2061
|
-
state: this.#options.getRegistrationStatus().state,
|
|
2062
|
-
...this.#options.imageSettings === void 0 ? {} : {
|
|
2063
|
-
imageStorage: { available: this.#options.imageSettings.available, enabled: this.#options.imageSettings.enabled }
|
|
2064
|
-
}
|
|
2065
|
-
}));
|
|
2066
|
-
return;
|
|
2067
|
-
}
|
|
2068
|
-
if (relayLogin === void 0 && this.#options.getAccount !== void 0 && request.method === "GET" && requestUrl.pathname === "/relay-account") {
|
|
2069
|
-
const account = await this.#options.getAccount();
|
|
2070
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2071
|
-
response.end(JSON.stringify(account));
|
|
2072
|
-
return;
|
|
2073
|
-
}
|
|
2074
|
-
if (relayLogin !== void 0) {
|
|
2075
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login/status") {
|
|
2076
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2077
|
-
response.end(JSON.stringify({ state: this.#loginState(relayLogin).state, method: relayLogin.method }));
|
|
2078
|
-
return;
|
|
2079
|
-
}
|
|
2080
|
-
if (request.method === "POST" && (requestUrl.pathname === "/relay-login/start" || requestUrl.pathname === "/relay-login/cancel")) {
|
|
2081
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2082
|
-
if (form === void 0) return;
|
|
2083
|
-
if (form.getAll("token").length !== 1 || [...form.keys()].some((key) => key !== "token")) {
|
|
2084
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
2085
|
-
response.end("\u767B\u5F55\u8BF7\u6C42\u65E0\u6548\u3002");
|
|
2086
|
-
return;
|
|
2087
|
-
}
|
|
2088
|
-
const operation = requestUrl.pathname === "/relay-login/start" ? "start" : "cancel";
|
|
2089
|
-
const login = this.#loginState(relayLogin);
|
|
2090
|
-
if (this.#loginMutating || (operation === "start" ? login.state !== "signed-out" && login.state !== "error" : login.state !== "pending" && login.state !== "starting" && login.state !== "confirming")) {
|
|
2091
|
-
this.#renderLogin(request, response, 409, login);
|
|
2092
|
-
return;
|
|
2093
|
-
}
|
|
2094
|
-
this.#loginMutating = true;
|
|
2095
|
-
this.#loginFailureMessage = void 0;
|
|
2096
|
-
try {
|
|
2097
|
-
if (operation === "start") await relayLogin.start();
|
|
2098
|
-
else await relayLogin.cancel();
|
|
2099
|
-
} catch (error) {
|
|
2100
|
-
this.#loginFailureMessage = error instanceof Error ? error.message : RELAY_LOGIN_ERROR;
|
|
2101
|
-
this.#options.logger?.error({ operation }, "relay.login.operation.failed");
|
|
2102
|
-
this.#renderLogin(request, response, 503, this.#loginState(relayLogin));
|
|
2103
|
-
return;
|
|
2104
|
-
} finally {
|
|
2105
|
-
this.#loginMutating = false;
|
|
2106
|
-
}
|
|
2107
|
-
const next = relayLogin.getState();
|
|
2108
|
-
this.#redirectLogin(response, operation === "start" && next.state === "pending" ? next.verificationUri : "/");
|
|
2109
|
-
return;
|
|
2110
|
-
}
|
|
2111
|
-
if (request.method === "POST" && ["/pair", "/pair/status", "/refresh", "/selection", "/group-chat-settings", "/peer-chat-settings", "/image-settings", "/relay-reconnect", "/relay-disconnect", "/clients", "/clients/decide"].includes(requestUrl.pathname)) {
|
|
2112
|
-
if (await this.#readAuthorizedForm(request, response) === void 0) return;
|
|
2113
|
-
this.#renderLogin(request, response, 409, this.#loginState(relayLogin));
|
|
2114
|
-
return;
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
const relayOperation = requestUrl.pathname === "/relay-reconnect" ? this.#options.reconnectRelay : requestUrl.pathname === "/relay-disconnect" ? this.#options.disconnectRelay : void 0;
|
|
2118
|
-
if (request.method === "POST" && relayOperation !== void 0) {
|
|
2119
|
-
const disconnecting = requestUrl.pathname === "/relay-disconnect";
|
|
2120
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2121
|
-
if (form === void 0) return;
|
|
2122
|
-
if (form.getAll("token").length !== 1 || [...form.keys()].some((key) => key !== "token")) {
|
|
2123
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
2124
|
-
response.end(disconnecting ? "Invalid Relay disconnect request." : "Invalid Relay reconnect request.");
|
|
2125
|
-
return;
|
|
2126
|
-
}
|
|
2127
|
-
try {
|
|
2128
|
-
relayOperation();
|
|
2129
|
-
} catch (error) {
|
|
2130
|
-
const message = { key: disconnecting ? "relay.disconnectError" : "relay.reconnectError" };
|
|
2131
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, disconnecting ? "relay.disconnect.failed" : "relay.reconnect.failed");
|
|
2132
|
-
if (wantsJson(request)) {
|
|
2133
|
-
this.#writeHeaders(response, 503, "application/json; charset=utf-8");
|
|
2134
|
-
response.end(JSON.stringify(localPageErrorPayload(message, locale)));
|
|
2135
|
-
} else {
|
|
2136
|
-
await this.#renderPage(request, response, 503, { reconnectError: message });
|
|
2137
|
-
}
|
|
2138
|
-
return;
|
|
2139
|
-
}
|
|
2140
|
-
if (wantsJson(request)) {
|
|
2141
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2142
|
-
response.end(JSON.stringify({ state: this.#options.getRegistrationStatus().state }));
|
|
2143
|
-
} else {
|
|
2144
|
-
response.writeHead(303, { location: "/", "cache-control": "no-store" });
|
|
2145
|
-
response.end();
|
|
2146
|
-
}
|
|
2147
|
-
return;
|
|
2148
|
-
}
|
|
2149
|
-
const chatKind = requestUrl.pathname === "/group-chat-settings" ? "group" : requestUrl.pathname === "/peer-chat-settings" ? "peer" : requestUrl.pathname === "/image-settings" ? "image" : void 0;
|
|
2150
|
-
const chatSettings = chatKind === "group" ? this.#options.groupChatSettings : chatKind === "peer" ? this.#options.peerChatSettings : this.#options.imageSettings;
|
|
2151
|
-
if (request.method === "POST" && chatKind !== void 0 && chatSettings !== void 0) {
|
|
2152
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2153
|
-
if (form === void 0) return;
|
|
2154
|
-
if (chatKind === "image" && !this.#options.imageSettings?.available) {
|
|
2155
|
-
await this.#chatSettingsError(request, response, chatKind, { key: "settings.imagesUnavailable" });
|
|
2156
|
-
return;
|
|
2157
|
-
}
|
|
2158
|
-
const values = form.getAll("enabled");
|
|
2159
|
-
if (form.getAll("token").length !== 1 || values.length !== 1 || values[0] !== "true" && values[0] !== "false" || [...form.keys()].some((key) => key !== "token" && key !== "enabled")) {
|
|
2160
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
2161
|
-
response.end(`Invalid ${chatKind} chat setting.`);
|
|
2162
|
-
return;
|
|
2163
|
-
}
|
|
2164
|
-
if (this.#saving) {
|
|
2165
|
-
await this.#chatSettingsError(request, response, chatKind, { key: "settings.busy" });
|
|
2166
|
-
return;
|
|
2167
|
-
}
|
|
2168
|
-
this.#saving = true;
|
|
2169
|
-
try {
|
|
2170
|
-
await chatSettings.save(values[0] === "true");
|
|
2171
|
-
} catch (error) {
|
|
2172
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, `${chatKind}-chat.settings.save.failed`);
|
|
2173
|
-
await this.#chatSettingsError(
|
|
2174
|
-
request,
|
|
2175
|
-
response,
|
|
2176
|
-
chatKind,
|
|
2177
|
-
{ key: chatKind === "group" ? "settings.groupError" : chatKind === "peer" ? "settings.peerError" : "settings.imagesError" }
|
|
2178
|
-
);
|
|
2179
|
-
return;
|
|
2180
|
-
} finally {
|
|
2181
|
-
this.#saving = false;
|
|
2182
|
-
}
|
|
2183
|
-
if (wantsJson(request)) {
|
|
2184
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2185
|
-
response.end(JSON.stringify({ ok: true, enabled: chatSettings.enabled }));
|
|
2186
|
-
} else {
|
|
2187
|
-
response.writeHead(303, { location: "/", "cache-control": "no-store" });
|
|
2188
|
-
response.end();
|
|
2189
|
-
}
|
|
2190
|
-
return;
|
|
2191
|
-
}
|
|
2192
|
-
const selection = this.#options.agentSelection;
|
|
2193
|
-
if (request.method === "POST" && requestUrl.pathname === "/selection" && selection !== void 0) {
|
|
2194
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2195
|
-
if (form === void 0) return;
|
|
2196
|
-
const parsed = AgentSelectionSchema2.safeParse({ agents: form.getAll("agents") });
|
|
2197
|
-
if (!parsed.success) {
|
|
2198
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
2199
|
-
response.end("Invalid agent selection.");
|
|
2200
|
-
return;
|
|
2201
|
-
}
|
|
2202
|
-
if (this.#saving) {
|
|
2203
|
-
await this.#selectionError(request, response, { key: "agents.busy" }, parsed.data.agents);
|
|
2204
|
-
return;
|
|
2205
|
-
}
|
|
2206
|
-
this.#saving = true;
|
|
2207
|
-
try {
|
|
2208
|
-
await selection.saveSelection(parsed.data);
|
|
2209
|
-
} catch (error) {
|
|
2210
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "coding-agent.selection.failed");
|
|
2211
|
-
await this.#selectionError(request, response, toErrorDetails(error).message, parsed.data.agents);
|
|
2212
|
-
return;
|
|
2213
|
-
} finally {
|
|
2214
|
-
this.#saving = false;
|
|
2215
|
-
}
|
|
2216
|
-
if (wantsJson(request)) {
|
|
2217
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2218
|
-
response.end('{"ok":true}');
|
|
2219
|
-
} else {
|
|
2220
|
-
response.writeHead(303, { location: "/?saved=1", "cache-control": "no-store" });
|
|
2221
|
-
response.end();
|
|
2222
|
-
}
|
|
2223
|
-
return;
|
|
2224
|
-
}
|
|
2225
|
-
if (request.method === "POST" && ["/clients", "/clients/decide"].includes(requestUrl.pathname)) {
|
|
2226
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2227
|
-
if (form === void 0) return;
|
|
2228
|
-
const provider = this.#options.pairingProvider;
|
|
2229
|
-
if (provider.listClients === void 0 || provider.decideClient === void 0) {
|
|
2230
|
-
this.#writeHeaders(response, 409, "application/json; charset=utf-8");
|
|
2231
|
-
response.end(JSON.stringify(localPageErrorPayload({ key: "clients.unsupported" }, locale)));
|
|
2232
|
-
return;
|
|
2233
|
-
}
|
|
2234
|
-
try {
|
|
2235
|
-
if (requestUrl.pathname === "/clients/decide") {
|
|
2236
|
-
const id = MobileAuthorizationIdSchema.safeParse(form.get("requestId"));
|
|
2237
|
-
const key = MobileIdentityPublicKeySchema.safeParse(form.get("publicKey"));
|
|
2238
|
-
const action = form.get("action");
|
|
2239
|
-
if (!id.success || !key.success || action !== "approve" && action !== "reject" && action !== "revoke" || [...form.keys()].some((field) => !["token", "requestId", "publicKey", "action"].includes(field) || form.getAll(field).length !== 1)) {
|
|
2240
|
-
this.#writeHeaders(response, 400, "application/json; charset=utf-8");
|
|
2241
|
-
response.end(JSON.stringify({ error: "Invalid client decision." }));
|
|
2242
|
-
return;
|
|
2243
|
-
}
|
|
2244
|
-
await provider.decideClient(id.data, action, key.data);
|
|
2245
|
-
}
|
|
2246
|
-
const clients = await provider.listClients();
|
|
2247
|
-
const result = MobileAuthorizationListResultSchema.parse({ clients });
|
|
2248
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2249
|
-
response.end(JSON.stringify(result));
|
|
2250
|
-
} catch (error) {
|
|
2251
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "mobile.clients.request.failed");
|
|
2252
|
-
this.#writeHeaders(response, 503, "application/json; charset=utf-8");
|
|
2253
|
-
response.end(JSON.stringify(localPageErrorPayload({ key: "clients.uncertain" }, locale)));
|
|
2254
|
-
}
|
|
2255
|
-
return;
|
|
2256
|
-
}
|
|
2257
|
-
if (request.method === "POST" && requestUrl.pathname === "/pair/status") {
|
|
2258
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
2259
|
-
if (form === void 0) return;
|
|
2260
|
-
const statusId = PairingStatusRequestSchema.shape.statusId.safeParse(form.get("statusId"));
|
|
2261
|
-
if (!statusId.success || form.getAll("statusId").length !== 1) {
|
|
2262
|
-
this.#writeHeaders(response, 400, "application/json; charset=utf-8");
|
|
2263
|
-
response.end(JSON.stringify({ error: "Invalid pairing status identity." }));
|
|
2264
|
-
return;
|
|
2265
|
-
}
|
|
2266
|
-
const state = await this.#options.pairingProvider.getPairingStatus?.(statusId.data) ?? "unavailable";
|
|
2267
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2268
|
-
response.end(JSON.stringify({ state }));
|
|
2269
|
-
return;
|
|
2270
|
-
}
|
|
2271
|
-
if (request.method === "POST" && (requestUrl.pathname === "/pair" || requestUrl.pathname === "/refresh")) {
|
|
2272
|
-
if (await this.#readAuthorizedForm(request, response) === void 0) return;
|
|
2273
|
-
const registration = this.#options.getRegistrationStatus();
|
|
2274
|
-
if (registration.state !== "registered") {
|
|
2275
|
-
await this.#pairingError(request, response, registration.state === "error" ? registration.message : { key: registration.state === "connecting" ? "relay.connecting" : "pairing.offline" });
|
|
2276
|
-
return;
|
|
2277
|
-
}
|
|
2278
|
-
try {
|
|
2279
|
-
const pairing = await this.#options.pairingProvider.getPairing({ force: requestUrl.pathname === "/refresh" });
|
|
2280
|
-
const svg = await QRCode.toString(pairing.uri, {
|
|
2281
|
-
type: "svg",
|
|
2282
|
-
errorCorrectionLevel: "M",
|
|
2283
|
-
margin: 3,
|
|
2284
|
-
width: 420,
|
|
2285
|
-
color: { dark: "#101820", light: "#ffffff" }
|
|
2286
|
-
});
|
|
2287
|
-
const rendered = {
|
|
2288
|
-
svg,
|
|
2289
|
-
uri: pairing.uri,
|
|
2290
|
-
expiresAt: pairing.expiresAt,
|
|
2291
|
-
...pairing.statusId === void 0 ? {} : { statusId: pairing.statusId }
|
|
2292
|
-
};
|
|
2293
|
-
if (wantsJson(request)) {
|
|
2294
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
2295
|
-
response.end(JSON.stringify(rendered));
|
|
2296
|
-
} else {
|
|
2297
|
-
await this.#renderPage(request, response, 200, { pairing: rendered });
|
|
2298
|
-
}
|
|
2299
|
-
} catch (error) {
|
|
2300
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "mobile.pairing-page.generate.failed");
|
|
2301
|
-
await this.#pairingError(request, response, toErrorDetails(error).message);
|
|
2302
|
-
}
|
|
2303
|
-
return;
|
|
2304
|
-
}
|
|
2305
|
-
if ([
|
|
2306
|
-
"/",
|
|
2307
|
-
"/pair",
|
|
2308
|
-
"/pair/status",
|
|
2309
|
-
"/selection",
|
|
2310
|
-
"/group-chat-settings",
|
|
2311
|
-
"/peer-chat-settings",
|
|
2312
|
-
"/image-settings",
|
|
2313
|
-
"/refresh",
|
|
2314
|
-
"/local-page.js",
|
|
2315
|
-
"/relay-login.js",
|
|
2316
|
-
"/local-ui.css",
|
|
2317
|
-
"/local-ui.js",
|
|
2318
|
-
"/relay-login/start",
|
|
2319
|
-
"/relay-login/cancel",
|
|
2320
|
-
"/relay-login/callback",
|
|
2321
|
-
"/relay-reconnect",
|
|
2322
|
-
"/relay-disconnect",
|
|
2323
|
-
...this.#options.reconnectRelay === void 0 || relayLogin !== void 0 ? [] : ["/relay-status"],
|
|
2324
|
-
...relayLogin === void 0 ? [] : ["/relay-login/status"]
|
|
2325
|
-
].includes(requestUrl.pathname)) {
|
|
2326
|
-
response.setHeader("allow", requestUrl.pathname === "/pair" ? "GET, POST" : ["/", "/local-page.js", "/relay-login.js", "/local-ui.css", "/local-ui.js", "/relay-login/status", "/relay-login/callback", "/relay-status"].includes(requestUrl.pathname) ? "GET" : "POST");
|
|
2327
|
-
this.#writeHeaders(response, 405, "text/plain; charset=utf-8");
|
|
2328
|
-
response.end("Method not allowed.");
|
|
2329
|
-
return;
|
|
2330
|
-
}
|
|
2331
|
-
this.#writeHeaders(response, 404, "text/plain; charset=utf-8");
|
|
2332
|
-
response.end("Not found.");
|
|
2333
|
-
}
|
|
2334
|
-
async #readAuthorizedForm(request, response) {
|
|
2335
|
-
if (request.headers.origin !== void 0 && request.headers.origin !== this.url || request.headers["sec-fetch-site"] === "cross-site") {
|
|
2336
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
2337
|
-
response.end("Invalid request origin.");
|
|
2338
|
-
return void 0;
|
|
2339
|
-
}
|
|
2340
|
-
if (!request.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) {
|
|
2341
|
-
this.#writeHeaders(response, 415, "text/plain; charset=utf-8");
|
|
2342
|
-
response.end("Expected form data.");
|
|
2343
|
-
return void 0;
|
|
2344
|
-
}
|
|
2345
|
-
const form = new URLSearchParams(await readFormBody(request));
|
|
2346
|
-
if (!secureEqual(form.get("token"), this.#refreshToken)) {
|
|
2347
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
2348
|
-
response.end("Invalid local page token.");
|
|
2349
|
-
return void 0;
|
|
2350
|
-
}
|
|
2351
|
-
return form;
|
|
2352
|
-
}
|
|
2353
|
-
async #renderPage(request, response, status, state = {}) {
|
|
2354
|
-
if (this.#options.relayLogin !== void 0) {
|
|
2355
|
-
this.#renderLogin(request, response, status, this.#loginState(this.#options.relayLogin));
|
|
2356
|
-
return;
|
|
2357
|
-
}
|
|
2358
|
-
const agents = state.agents ?? await this.#options.agentSelection?.listAgents();
|
|
2359
|
-
const sessions = agents === void 0 ? await this.#options.sessions?.list() : void 0;
|
|
2360
|
-
const deploymentInfo = await this.#options.getDeploymentInfo?.();
|
|
2361
|
-
const account = await this.#options.getAccount?.();
|
|
2362
|
-
const registration = this.#options.getRegistrationStatus();
|
|
2363
|
-
this.#writeHeaders(response, status, "text/html; charset=utf-8");
|
|
2364
|
-
response.end(renderAgentSelectionPage({
|
|
2365
|
-
locale: resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]),
|
|
2366
|
-
machineName: this.#options.machineName,
|
|
2367
|
-
token: this.#refreshToken,
|
|
2368
|
-
manageClients: this.#options.pairingProvider.listClients !== void 0,
|
|
2369
|
-
...this.#options.reconnectRelay === void 0 ? {} : { relayState: registration.state },
|
|
2370
|
-
...this.#options.disconnectRelay === void 0 ? {} : { canDisconnectRelay: true },
|
|
2371
|
-
...deploymentInfo === void 0 ? {} : { deploymentInfo },
|
|
2372
|
-
...account === void 0 ? {} : { account },
|
|
2373
|
-
...agents === void 0 ? {} : { agents },
|
|
2374
|
-
...sessions === void 0 ? {} : { sessions },
|
|
2375
|
-
canReadSessions: this.#options.sessions !== void 0,
|
|
2376
|
-
...this.#options.groupChatSettings === void 0 ? {} : { groupChatEnabled: this.#options.groupChatSettings.enabled },
|
|
2377
|
-
...this.#options.peerChatSettings === void 0 ? {} : { peerChatEnabled: this.#options.peerChatSettings.enabled },
|
|
2378
|
-
...this.#options.imageSettings === void 0 ? {} : {
|
|
2379
|
-
imageSettings: { available: this.#options.imageSettings.available, enabled: this.#options.imageSettings.enabled }
|
|
2380
|
-
},
|
|
2381
|
-
...registration.state === "registered" ? {} : {
|
|
2382
|
-
pairingError: registration.state === "error" ? registration.message : { key: registration.state === "connecting" ? "relay.connecting" : "pairing.offline" }
|
|
2383
|
-
},
|
|
2384
|
-
...state
|
|
2385
|
-
}));
|
|
2386
|
-
}
|
|
2387
|
-
#renderLogin(request, response, status, login) {
|
|
2388
|
-
this.#writeHeaders(response, status, "text/html; charset=utf-8");
|
|
2389
|
-
response.end(renderRelayLoginPage({
|
|
2390
|
-
locale: resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]),
|
|
2391
|
-
machineName: this.#options.machineName,
|
|
2392
|
-
token: this.#refreshToken,
|
|
2393
|
-
login,
|
|
2394
|
-
...this.#options.relayLogin?.method === void 0 ? {} : { method: this.#options.relayLogin.method },
|
|
2395
|
-
...this.#loginFailureMessage === void 0 ? {} : { error: this.#loginFailureMessage }
|
|
2396
|
-
}));
|
|
2397
|
-
}
|
|
2398
|
-
#loginState(provider) {
|
|
2399
|
-
const login = provider.getState();
|
|
2400
|
-
return this.#loginFailureMessage !== void 0 && login.state === "signed-out" ? { state: "error", message: this.#loginFailureMessage } : login;
|
|
2401
|
-
}
|
|
2402
|
-
async #chatSettingsError(request, response, kind, error) {
|
|
2403
|
-
if (wantsJson(request)) {
|
|
2404
|
-
this.#writeHeaders(response, 409, "application/json; charset=utf-8");
|
|
2405
|
-
response.end(JSON.stringify(localPageErrorPayload(error, resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]))));
|
|
2406
|
-
} else {
|
|
2407
|
-
await this.#renderPage(request, response, 409, kind === "group" ? { groupChatError: error } : kind === "peer" ? { peerChatError: error } : { imageError: error });
|
|
2408
|
-
}
|
|
2409
|
-
}
|
|
2410
|
-
async #selectionError(request, response, error, selected) {
|
|
2411
|
-
if (wantsJson(request)) {
|
|
2412
|
-
this.#writeHeaders(response, 409, "application/json; charset=utf-8");
|
|
2413
|
-
response.end(JSON.stringify(localPageErrorPayload(error, resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]))));
|
|
2414
|
-
} else {
|
|
2415
|
-
const agents = (await this.#options.agentSelection?.listAgents())?.map((agent) => ({
|
|
2416
|
-
...agent,
|
|
2417
|
-
selected: selected.includes(agent.id)
|
|
2418
|
-
}));
|
|
2419
|
-
await this.#renderPage(request, response, 409, { error, ...agents === void 0 ? {} : { agents } });
|
|
2420
|
-
}
|
|
2421
|
-
}
|
|
2422
|
-
async #pairingError(request, response, error) {
|
|
2423
|
-
if (wantsJson(request)) {
|
|
2424
|
-
this.#writeHeaders(response, 503, "application/json; charset=utf-8");
|
|
2425
|
-
response.end(JSON.stringify(localPageErrorPayload(error, resolveLocalPageLocale(request.headers.cookie, request.headers["accept-language"]))));
|
|
2426
|
-
} else {
|
|
2427
|
-
await this.#renderPage(request, response, 503, { pairingError: error });
|
|
2428
|
-
}
|
|
2429
|
-
}
|
|
2430
|
-
#writeHeaders(response, status, contentType, referrerPolicy = "same-origin") {
|
|
2431
|
-
const formOrigins = this.#options.relayLogin === void 0 ? "'self'" : `'self' ${this.#options.relayLogin.relayOrigin} https://login.microsoftonline.com https://login.live.com`;
|
|
2432
|
-
response.writeHead(status, {
|
|
2433
|
-
"cache-control": "no-store, max-age=0",
|
|
2434
|
-
"content-security-policy": `default-src 'none'; img-src data:; script-src 'self'; connect-src 'self'; style-src 'self' 'unsafe-inline'; form-action ${formOrigins}; base-uri 'none'; frame-ancestors 'none'`,
|
|
2435
|
-
"content-type": contentType,
|
|
2436
|
-
// no-referrer turns native browser POST origins into "null".
|
|
2437
|
-
"referrer-policy": referrerPolicy,
|
|
2438
|
-
"x-content-type-options": "nosniff"
|
|
2439
|
-
});
|
|
2440
|
-
}
|
|
2441
|
-
#redirectLogin(response, location) {
|
|
2442
|
-
response.writeHead(303, {
|
|
2443
|
-
location,
|
|
2444
|
-
"cache-control": "no-store, max-age=0",
|
|
2445
|
-
"referrer-policy": "no-referrer",
|
|
2446
|
-
"x-content-type-options": "nosniff"
|
|
2447
|
-
});
|
|
2448
|
-
response.end();
|
|
2449
|
-
}
|
|
2450
|
-
};
|
|
2451
|
-
function wantsJson(request) {
|
|
2452
|
-
return request.headers.accept?.includes("application/json") === true;
|
|
2453
|
-
}
|
|
2454
|
-
async function readFormBody(request, maxBytes = MAX_FORM_BODY_BYTES) {
|
|
2455
|
-
const chunks = [];
|
|
2456
|
-
let size = 0;
|
|
2457
|
-
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
2458
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
2459
|
-
size += buffer.length;
|
|
2460
|
-
if (size > maxBytes) {
|
|
2461
|
-
request.resume();
|
|
2462
|
-
throw new FormBodyTooLargeError("Pairing page form body exceeds the size limit");
|
|
2463
|
-
}
|
|
2464
|
-
chunks.push(buffer);
|
|
2465
|
-
}
|
|
2466
|
-
return Buffer.concat(chunks).toString("utf8");
|
|
2467
|
-
}
|
|
2468
|
-
function secureEqual(value, expected) {
|
|
2469
|
-
if (value === null) return false;
|
|
2470
|
-
const actualBuffer = Buffer.from(value);
|
|
2471
|
-
const expectedBuffer = Buffer.from(expected);
|
|
2472
|
-
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
|
2473
|
-
}
|
|
2474
|
-
|
|
2475
|
-
// src/relay-login.ts
|
|
2476
|
-
import { createHash, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
2477
|
-
var MESSAGES = {
|
|
2478
|
-
network: "Cannot reach the Relay securely. Check the Relay address and connection, then try again.",
|
|
2479
|
-
response: "The Relay returned an invalid authorization response. Check the Relay configuration.",
|
|
2480
|
-
upgrade: "This Relay does not support browser sign-in. Ask its administrator to upgrade the Relay, then retry.",
|
|
2481
|
-
expired: "PC authorization expired. Cancel this request and sign in again.",
|
|
2482
|
-
denied: "The Relay did not authorize this account. Contact the Relay administrator.",
|
|
2483
|
-
limited: "Too many authorization attempts. Wait a minute and try again.",
|
|
2484
|
-
issued: "This authorization was already issued. Cancel this request before signing in again.",
|
|
2485
|
-
exchange: "The credential exchange outcome is uncertain. Cancel this request before signing in again; do not repeat the exchange.",
|
|
2486
|
-
confirmation: "Credential confirmation could not be verified. Restart AgentKnight to recover the saved credential.",
|
|
2487
|
-
confirmationService: "The Relay confirmation service is unavailable. The credential is saved; retry after its administrator restores the service.",
|
|
2488
|
-
credential: "The saved Relay credential is no longer authorized. Sign in again.",
|
|
2489
|
-
verification: "The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification, then retry.",
|
|
2490
|
-
cleanup: "Authorization cleanup could not be verified. Retry, or restart AgentKnight after the request expires.",
|
|
2491
|
-
cancelled: "PC authorization was cancelled.",
|
|
2492
|
-
closed: "AgentKnight login is closed. Restart AgentKnight to sign in.",
|
|
2493
|
-
identity: "The Relay credential belongs to a different PC or account. Check the Relay configuration before signing in again."
|
|
2494
|
-
};
|
|
2495
|
-
var LoginError = class extends Error {
|
|
2496
|
-
constructor(code, retryAfterMs, responseStatus, rejectionEvidence) {
|
|
2497
|
-
super(MESSAGES[code]);
|
|
2498
|
-
this.code = code;
|
|
2499
|
-
this.retryAfterMs = retryAfterMs;
|
|
2500
|
-
this.responseStatus = responseStatus;
|
|
2501
|
-
this.rejectionEvidence = rejectionEvidence;
|
|
2502
|
-
this.name = "RelayLoginError";
|
|
2503
|
-
}
|
|
2504
|
-
code;
|
|
2505
|
-
retryAfterMs;
|
|
2506
|
-
responseStatus;
|
|
2507
|
-
rejectionEvidence;
|
|
2508
|
-
};
|
|
2509
|
-
function safeError(error) {
|
|
2510
|
-
if (error instanceof LoginError) {
|
|
2511
|
-
return new LoginError(error.code, error.retryAfterMs, error.responseStatus, error.rejectionEvidence);
|
|
2512
|
-
}
|
|
2513
|
-
if (error instanceof RelayCredentialStoreError) return new RelayCredentialStoreError(error.code);
|
|
2514
|
-
return new LoginError("network");
|
|
2515
|
-
}
|
|
2516
|
-
function failure(code, status, retryAfterMs) {
|
|
2517
|
-
if (status === 401 && code === "DEVICE_GRANT_INVALID") {
|
|
2518
|
-
return new LoginError("denied", void 0, status, "credential-invalid");
|
|
2519
|
-
}
|
|
2520
|
-
if (status === 404 && (code === "ENROLLMENT_NOT_FOUND" || code === "PC_ENROLLMENT_NOT_FOUND")) {
|
|
2521
|
-
return new LoginError("response", void 0, status, "enrollment-missing");
|
|
2522
|
-
}
|
|
2523
|
-
if (status === 429) return new LoginError("limited", retryAfterMs, status);
|
|
2524
|
-
if (status === 410 && (code === "ENROLLMENT_EXPIRED" || code === "PC_ENROLLMENT_EXPIRED")) {
|
|
2525
|
-
return new LoginError("expired", void 0, status, "enrollment-expired");
|
|
2526
|
-
}
|
|
2527
|
-
if (code === "ENROLLMENT_CONFLICT" || code === "PC_ENROLLMENT_INVALID_STATE") {
|
|
2528
|
-
return new LoginError("issued", void 0, status);
|
|
2529
|
-
}
|
|
2530
|
-
if (status === 401 || status === 403) return new LoginError("denied", void 0, status);
|
|
2531
|
-
return new LoginError(status >= 500 ? "network" : "response", void 0, status);
|
|
2532
|
-
}
|
|
2533
|
-
function aborted(signal) {
|
|
2534
|
-
if (signal.aborted) throw new LoginError("cancelled");
|
|
2535
|
-
}
|
|
2536
|
-
async function abortable(work, signal) {
|
|
2537
|
-
if (signal.aborted) {
|
|
2538
|
-
void work.catch(() => void 0);
|
|
2539
|
-
throw new LoginError("cancelled");
|
|
2540
|
-
}
|
|
2541
|
-
let onAbort = () => {
|
|
2542
|
-
};
|
|
2543
|
-
const cancellation = new Promise((_resolve, reject) => {
|
|
2544
|
-
onAbort = () => reject(new LoginError("cancelled"));
|
|
2545
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2546
|
-
});
|
|
2547
|
-
try {
|
|
2548
|
-
return await Promise.race([work, cancellation]);
|
|
2549
|
-
} finally {
|
|
2550
|
-
signal.removeEventListener("abort", onAbort);
|
|
2551
|
-
}
|
|
2552
|
-
}
|
|
2553
|
-
var MicrosoftRelayLogin = class {
|
|
2554
|
-
method = "microsoft";
|
|
2555
|
-
#relayUrl;
|
|
2556
|
-
#identity;
|
|
2557
|
-
#fetch;
|
|
2558
|
-
#getRedirectUri;
|
|
2559
|
-
#store;
|
|
2560
|
-
#state = { state: "signed-out" };
|
|
2561
|
-
#credential;
|
|
2562
|
-
#active;
|
|
2563
|
-
#cancelling;
|
|
2564
|
-
#closed = false;
|
|
2565
|
-
#reauthorize;
|
|
2566
|
-
#waiters = /* @__PURE__ */ new Set();
|
|
2567
|
-
constructor(options) {
|
|
2568
|
-
this.#relayUrl = normalizeRelayOrigin(options.relayUrl);
|
|
2569
|
-
this.#identity = { ...options.identity };
|
|
2570
|
-
this.#store = options.store;
|
|
2571
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
2572
|
-
this.#reauthorize = options.reauthorize ?? false;
|
|
2573
|
-
this.#getRedirectUri = options.getRedirectUri;
|
|
2574
|
-
}
|
|
2575
|
-
getState() {
|
|
2576
|
-
return { ...this.#state };
|
|
2577
|
-
}
|
|
2578
|
-
get relayOrigin() {
|
|
2579
|
-
return this.#relayUrl;
|
|
2580
|
-
}
|
|
2581
|
-
async restore() {
|
|
2582
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2583
|
-
if (this.#cancelling) await this.#cancelling;
|
|
2584
|
-
if (this.#credential) return structuredClone(this.#credential);
|
|
2585
|
-
const operation = this.#active ?? this.#launch(true);
|
|
2586
|
-
await operation.done;
|
|
2587
|
-
if (operation.error) return void 0;
|
|
2588
|
-
return this.#credential === void 0 ? void 0 : structuredClone(this.#credential);
|
|
2589
|
-
}
|
|
2590
|
-
async start() {
|
|
2591
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2592
|
-
if (this.#cancelling) await this.#cancelling;
|
|
2593
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2594
|
-
if (this.#credential) return;
|
|
2595
|
-
const previous = this.#active;
|
|
2596
|
-
if (previous?.error) {
|
|
2597
|
-
await previous.done;
|
|
2598
|
-
if (previous.confirmAttempted) {
|
|
2599
|
-
if (this.#active === previous) this.#active = void 0;
|
|
2600
|
-
} else {
|
|
2601
|
-
await this.cancel();
|
|
2602
|
-
}
|
|
2603
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2604
|
-
}
|
|
2605
|
-
const operation = this.#active ?? this.#launch(false);
|
|
2606
|
-
await operation.ready;
|
|
2607
|
-
if (operation.restoreOnly) {
|
|
2608
|
-
await operation.done;
|
|
2609
|
-
if (!this.#credential) await this.start();
|
|
2610
|
-
}
|
|
2611
|
-
}
|
|
2612
|
-
acceptCallback(input, redirectUri) {
|
|
2613
|
-
const parsed = PcBrowserAuthorizationCallbackSchema.safeParse(input);
|
|
2614
|
-
const operation = this.#active;
|
|
2615
|
-
const browser = operation?.browser;
|
|
2616
|
-
if (!parsed.success || !operation || !browser || this.#closed || operation.controller.signal.aborted || operation.error || browser.received || this.#state.state !== "pending" || !operation.enrollment || Date.now() >= operation.enrollment.expiresAt || browser.redirectUri !== redirectUri) return void 0;
|
|
2617
|
-
const receivedState = Buffer.from(parsed.data.state);
|
|
2618
|
-
const expectedState = Buffer.from(browser.state);
|
|
2619
|
-
if (receivedState.length !== expectedState.length || !timingSafeEqual2(receivedState, expectedState)) return void 0;
|
|
2620
|
-
browser.received = true;
|
|
2621
|
-
let delivered = false;
|
|
2622
|
-
return () => {
|
|
2623
|
-
if (delivered) return;
|
|
2624
|
-
delivered = true;
|
|
2625
|
-
if (!operation.controller.signal.aborted && this.#active === operation && operation.enrollment && Date.now() < operation.enrollment.expiresAt) browser.deliver(parsed.data);
|
|
2626
|
-
};
|
|
2627
|
-
}
|
|
2628
|
-
async cancel() {
|
|
2629
|
-
if (this.#cancelling) return this.#cancelling;
|
|
2630
|
-
const cancellation = this.#cancel();
|
|
2631
|
-
this.#cancelling = cancellation;
|
|
2632
|
-
try {
|
|
2633
|
-
await cancellation;
|
|
2634
|
-
} finally {
|
|
2635
|
-
if (this.#cancelling === cancellation) this.#cancelling = void 0;
|
|
2636
|
-
}
|
|
2637
|
-
}
|
|
2638
|
-
async close() {
|
|
2639
|
-
this.#closed = true;
|
|
2640
|
-
for (const waiter of this.#waiters) waiter.reject(new LoginError("closed"));
|
|
2641
|
-
this.#waiters.clear();
|
|
2642
|
-
await this.cancel();
|
|
2643
|
-
}
|
|
2644
|
-
waitForCredential(signal) {
|
|
2645
|
-
if (this.#closed) return Promise.reject(new LoginError("closed"));
|
|
2646
|
-
if (signal?.aborted) return Promise.reject(new LoginError("cancelled"));
|
|
2647
|
-
if (this.#credential) return Promise.resolve(structuredClone(this.#credential));
|
|
2648
|
-
return new Promise((resolve2, reject) => {
|
|
2649
|
-
const cleanup = () => {
|
|
2650
|
-
this.#waiters.delete(waiter);
|
|
2651
|
-
signal?.removeEventListener("abort", onAbort);
|
|
2652
|
-
};
|
|
2653
|
-
const waiter = {
|
|
2654
|
-
resolve: (credential) => {
|
|
2655
|
-
cleanup();
|
|
2656
|
-
resolve2(structuredClone(credential));
|
|
2657
|
-
},
|
|
2658
|
-
reject: (error) => {
|
|
2659
|
-
cleanup();
|
|
2660
|
-
reject(error);
|
|
2661
|
-
}
|
|
2662
|
-
};
|
|
2663
|
-
const onAbort = () => waiter.reject(new LoginError("cancelled"));
|
|
2664
|
-
this.#waiters.add(waiter);
|
|
2665
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2666
|
-
});
|
|
2667
|
-
}
|
|
2668
|
-
#launch(restoreOnly) {
|
|
2669
|
-
let resolveReady = () => {
|
|
2670
|
-
};
|
|
2671
|
-
let rejectReady = (_error) => {
|
|
2672
|
-
};
|
|
2673
|
-
const ready = new Promise((resolve2, reject) => {
|
|
2674
|
-
resolveReady = resolve2;
|
|
2675
|
-
rejectReady = reject;
|
|
2676
|
-
});
|
|
2677
|
-
void ready.catch(() => void 0);
|
|
2678
|
-
const operation = {
|
|
2679
|
-
controller: new AbortController(),
|
|
2680
|
-
ready,
|
|
2681
|
-
resolveReady,
|
|
2682
|
-
rejectReady,
|
|
2683
|
-
done: Promise.resolve(),
|
|
2684
|
-
createAttempted: false,
|
|
2685
|
-
confirmAttempted: false,
|
|
2686
|
-
pendingRejected: false,
|
|
2687
|
-
restoreOnly
|
|
2688
|
-
};
|
|
2689
|
-
this.#active = operation;
|
|
2690
|
-
this.#state = { state: "starting" };
|
|
2691
|
-
operation.done = this.#execute(operation, restoreOnly).catch((error) => {
|
|
2692
|
-
const safe = safeError(error);
|
|
2693
|
-
operation.error = safe;
|
|
2694
|
-
if (!operation.controller.signal.aborted) this.#state = { state: "error", message: safe.message };
|
|
2695
|
-
operation.rejectReady(safe);
|
|
2696
|
-
}).finally(() => {
|
|
2697
|
-
if (this.#active === operation && (this.#credential !== void 0 || !operation.createAttempted && !operation.enrollment)) this.#active = void 0;
|
|
2698
|
-
});
|
|
2699
|
-
return operation;
|
|
2700
|
-
}
|
|
2701
|
-
async #readStore() {
|
|
2702
|
-
try {
|
|
2703
|
-
this.#store ??= await createRelayCredentialStore(this.#relayUrl, this.#identity.machineId);
|
|
2704
|
-
return validateRelayCredentialSlots(await this.#store.read(), this.#relayUrl, this.#identity.machineId);
|
|
2705
|
-
} catch (error) {
|
|
2706
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2707
|
-
}
|
|
2708
|
-
}
|
|
2709
|
-
async #execute(operation, restoreOnly) {
|
|
2710
|
-
let slots = await this.#readStore();
|
|
2711
|
-
aborted(operation.controller.signal);
|
|
2712
|
-
if (restoreOnly && this.#reauthorize) {
|
|
2713
|
-
this.#state = { state: "signed-out" };
|
|
2714
|
-
operation.resolveReady();
|
|
2715
|
-
return;
|
|
2716
|
-
}
|
|
2717
|
-
if (slots.pending) {
|
|
2718
|
-
const pending = slots.pending;
|
|
2719
|
-
if (pending.confirmation.status !== "pending") throw new RelayCredentialStoreError("invalid");
|
|
2720
|
-
operation.pending = pending;
|
|
2721
|
-
operation.confirmAttempted = true;
|
|
2722
|
-
operation.enrollment = {
|
|
2723
|
-
id: pending.confirmation.enrollmentId,
|
|
2724
|
-
verifier: pending.confirmation.verifier,
|
|
2725
|
-
expiresAt: pending.confirmation.confirmBy
|
|
2726
|
-
};
|
|
2727
|
-
if (!this.#reauthorize) {
|
|
2728
|
-
await this.#confirm(operation, pending);
|
|
2729
|
-
operation.resolveReady();
|
|
2730
|
-
return;
|
|
2731
|
-
}
|
|
2732
|
-
await this.#confirm(operation, pending, false);
|
|
2733
|
-
delete operation.pending;
|
|
2734
|
-
delete operation.enrollment;
|
|
2735
|
-
operation.confirmAttempted = false;
|
|
2736
|
-
slots = await this.#readStore();
|
|
2737
|
-
aborted(operation.controller.signal);
|
|
2738
|
-
}
|
|
2739
|
-
if (slots.confirmed && !this.#reauthorize) {
|
|
2740
|
-
await this.#verifyConfirmed(slots.confirmed);
|
|
2741
|
-
aborted(operation.controller.signal);
|
|
2742
|
-
this.#signedIn(slots.confirmed);
|
|
2743
|
-
operation.resolveReady();
|
|
2744
|
-
return;
|
|
2745
|
-
}
|
|
2746
|
-
if (restoreOnly) {
|
|
2747
|
-
this.#state = { state: "signed-out" };
|
|
2748
|
-
operation.resolveReady();
|
|
2749
|
-
return;
|
|
2750
|
-
}
|
|
2751
|
-
const redirectUri = this.#getRedirectUri();
|
|
2752
|
-
if (!PcBrowserRedirectUriSchema.safeParse(redirectUri).success) throw new LoginError("response");
|
|
2753
|
-
const verifier = randomBytes2(32).toString("base64url");
|
|
2754
|
-
const state = randomBytes2(32).toString("base64url");
|
|
2755
|
-
const input = PcBrowserAuthorizationStartRequestSchema.safeParse({
|
|
2756
|
-
machineId: this.#identity.machineId,
|
|
2757
|
-
deviceName: this.#identity.machineName,
|
|
2758
|
-
codeChallenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
2759
|
-
redirectUri,
|
|
2760
|
-
state
|
|
2761
|
-
});
|
|
2762
|
-
if (!input.success) throw new LoginError("identity");
|
|
2763
|
-
operation.createAttempted = true;
|
|
2764
|
-
let started;
|
|
2765
|
-
try {
|
|
2766
|
-
started = await this.#post("/pc-enrollments/browser", input.data, PcBrowserAuthorizationStartResultSchema);
|
|
2767
|
-
} catch (error) {
|
|
2768
|
-
if (error instanceof LoginError && error.responseStatus !== void 0 && error.responseStatus >= 400 && error.responseStatus < 500) {
|
|
2769
|
-
operation.createAttempted = false;
|
|
2770
|
-
}
|
|
2771
|
-
if (error instanceof LoginError && (error.responseStatus === 404 || error.responseStatus === 405)) {
|
|
2772
|
-
throw new LoginError("upgrade");
|
|
2773
|
-
}
|
|
2774
|
-
throw error;
|
|
2775
|
-
}
|
|
2776
|
-
if (!started.ok) throw new LoginError("response");
|
|
2777
|
-
operation.enrollment = {
|
|
2778
|
-
id: started.enrollmentId,
|
|
2779
|
-
verifier,
|
|
2780
|
-
expiresAt: started.expiresAt
|
|
2781
|
-
};
|
|
2782
|
-
aborted(operation.controller.signal);
|
|
2783
|
-
if (started.verificationUri !== `${this.#relayUrl}/pc-enrollments/browser/${started.enrollmentId}` || !Number.isSafeInteger(started.expiresAt) || started.expiresAt - Date.now() > 2147483647) throw new LoginError("response");
|
|
2784
|
-
if (started.expiresAt <= Date.now()) throw new LoginError("expired");
|
|
2785
|
-
let deliver = (_callback) => {
|
|
2786
|
-
};
|
|
2787
|
-
const callback = new Promise((resolve2) => {
|
|
2788
|
-
deliver = resolve2;
|
|
2789
|
-
});
|
|
2790
|
-
const browser = {
|
|
2791
|
-
state,
|
|
2792
|
-
redirectUri: input.data.redirectUri,
|
|
2793
|
-
received: false,
|
|
2794
|
-
callback,
|
|
2795
|
-
deliver
|
|
2796
|
-
};
|
|
2797
|
-
operation.browser = browser;
|
|
2798
|
-
this.#state = {
|
|
2799
|
-
state: "pending",
|
|
2800
|
-
verificationUri: started.verificationUri,
|
|
2801
|
-
expiresAt: started.expiresAt
|
|
2802
|
-
};
|
|
2803
|
-
operation.resolveReady();
|
|
2804
|
-
await this.#authorizeBrowser(operation, operation.enrollment, browser);
|
|
2805
|
-
}
|
|
2806
|
-
async #authorizeBrowser(operation, enrollment, browser) {
|
|
2807
|
-
let timer;
|
|
2808
|
-
let callback;
|
|
2809
|
-
try {
|
|
2810
|
-
callback = await abortable(Promise.race([
|
|
2811
|
-
browser.callback,
|
|
2812
|
-
new Promise((_resolve, reject) => {
|
|
2813
|
-
timer = setTimeout(() => reject(new LoginError("expired")), enrollment.expiresAt - Date.now());
|
|
2814
|
-
})
|
|
2815
|
-
]), operation.controller.signal);
|
|
2816
|
-
} finally {
|
|
2817
|
-
clearTimeout(timer);
|
|
2818
|
-
}
|
|
2819
|
-
aborted(operation.controller.signal);
|
|
2820
|
-
if (Date.now() >= enrollment.expiresAt) throw new LoginError("expired");
|
|
2821
|
-
if ("error" in callback) {
|
|
2822
|
-
throw new LoginError(callback.error === "access_denied" ? "denied" : callback.error);
|
|
2823
|
-
}
|
|
2824
|
-
this.#state = { state: "confirming" };
|
|
2825
|
-
let result;
|
|
2826
|
-
try {
|
|
2827
|
-
result = await this.#post(
|
|
2828
|
-
`/pc-enrollments/browser/${enrollment.id}/exchange`,
|
|
2829
|
-
{ verifier: enrollment.verifier, code: callback.code, redirectUri: browser.redirectUri },
|
|
2830
|
-
PcEnrollmentExchangeResultSchema,
|
|
2831
|
-
{ deadline: enrollment.expiresAt }
|
|
2832
|
-
);
|
|
2833
|
-
} catch {
|
|
2834
|
-
throw new LoginError("exchange");
|
|
2835
|
-
}
|
|
2836
|
-
aborted(operation.controller.signal);
|
|
2837
|
-
if (!result.ok) throw new LoginError("exchange");
|
|
2838
|
-
if (result.machineId !== this.#identity.machineId) throw new LoginError("identity");
|
|
2839
|
-
const pending = {
|
|
2840
|
-
version: 1,
|
|
2841
|
-
relayUrl: this.#relayUrl,
|
|
2842
|
-
machineId: result.machineId,
|
|
2843
|
-
token: result.token,
|
|
2844
|
-
tokenId: result.tokenId,
|
|
2845
|
-
grantId: result.grantId,
|
|
2846
|
-
user: result.user,
|
|
2847
|
-
confirmation: {
|
|
2848
|
-
status: "pending",
|
|
2849
|
-
confirmBy: result.confirmBy,
|
|
2850
|
-
enrollmentId: enrollment.id,
|
|
2851
|
-
verifier: enrollment.verifier
|
|
2852
|
-
}
|
|
2853
|
-
};
|
|
2854
|
-
operation.pending = pending;
|
|
2855
|
-
try {
|
|
2856
|
-
const store = this.#store;
|
|
2857
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2858
|
-
await store.savePending(pending);
|
|
2859
|
-
} catch (error) {
|
|
2860
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2861
|
-
}
|
|
2862
|
-
aborted(operation.controller.signal);
|
|
2863
|
-
await this.#confirm(operation, pending);
|
|
2864
|
-
}
|
|
2865
|
-
async #verifyConfirmed(credential) {
|
|
2866
|
-
this.#state = { state: "confirming" };
|
|
2867
|
-
try {
|
|
2868
|
-
await this.#post("/pc-enrollments/confirm", {}, MicrosoftMutationResultSchema, { token: credential.token });
|
|
2869
|
-
} catch (error) {
|
|
2870
|
-
if (error instanceof LoginError && error.rejectionEvidence === "credential-invalid") {
|
|
2871
|
-
this.#reauthorize = true;
|
|
2872
|
-
throw new LoginError("credential");
|
|
2873
|
-
}
|
|
2874
|
-
if (error instanceof LoginError && error.responseStatus === 404) throw new LoginError("verification");
|
|
2875
|
-
throw safeError(error);
|
|
2876
|
-
}
|
|
2877
|
-
}
|
|
2878
|
-
async #confirm(operation, credential, publish = true) {
|
|
2879
|
-
this.#state = { state: "confirming" };
|
|
2880
|
-
const saved = await this.#readStore();
|
|
2881
|
-
if (!saved.pending || !sameRelayCredential(saved.pending, credential)) {
|
|
2882
|
-
throw new RelayCredentialStoreError("verification");
|
|
2883
|
-
}
|
|
2884
|
-
aborted(operation.controller.signal);
|
|
2885
|
-
if (publish) this.#reauthorize = false;
|
|
2886
|
-
operation.confirmAttempted = true;
|
|
2887
|
-
try {
|
|
2888
|
-
await this.#post("/pc-enrollments/confirm", {}, MicrosoftMutationResultSchema, { token: credential.token });
|
|
2889
|
-
} catch (error) {
|
|
2890
|
-
if (error instanceof LoginError && error.rejectionEvidence === "credential-invalid") {
|
|
2891
|
-
this.#reauthorize = true;
|
|
2892
|
-
operation.confirmAttempted = false;
|
|
2893
|
-
operation.pendingRejected = true;
|
|
2894
|
-
throw new LoginError("credential");
|
|
2895
|
-
}
|
|
2896
|
-
if (error instanceof LoginError && error.responseStatus !== void 0 && error.responseStatus >= 500) {
|
|
2897
|
-
throw new LoginError("confirmationService", void 0, error.responseStatus);
|
|
2898
|
-
}
|
|
2899
|
-
throw new LoginError("confirmation");
|
|
2900
|
-
}
|
|
2901
|
-
try {
|
|
2902
|
-
const store = this.#store;
|
|
2903
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2904
|
-
await store.confirmPending(credential.tokenId);
|
|
2905
|
-
const confirmed = (await this.#readStore()).confirmed;
|
|
2906
|
-
const expected = {
|
|
2907
|
-
...credential,
|
|
2908
|
-
confirmation: { status: "confirmed", confirmBy: credential.confirmation.confirmBy }
|
|
2909
|
-
};
|
|
2910
|
-
if (!confirmed || !sameRelayCredential(confirmed, expected)) {
|
|
2911
|
-
throw new RelayCredentialStoreError("verification");
|
|
2912
|
-
}
|
|
2913
|
-
if (publish) this.#signedIn(confirmed);
|
|
2914
|
-
} catch (error) {
|
|
2915
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2916
|
-
}
|
|
2917
|
-
}
|
|
2918
|
-
#signedIn(credential) {
|
|
2919
|
-
this.#credential = structuredClone(credential);
|
|
2920
|
-
this.#state = { state: "signed-in", userId: credential.user.userId };
|
|
2921
|
-
for (const waiter of this.#waiters) waiter.resolve(credential);
|
|
2922
|
-
this.#waiters.clear();
|
|
2923
|
-
}
|
|
2924
|
-
async #cancel() {
|
|
2925
|
-
const operation = this.#active;
|
|
2926
|
-
if (!operation) return;
|
|
2927
|
-
operation.controller.abort();
|
|
2928
|
-
await operation.done;
|
|
2929
|
-
if (this.#credential) return;
|
|
2930
|
-
try {
|
|
2931
|
-
if (operation.confirmAttempted) throw new LoginError("confirmation");
|
|
2932
|
-
if (!operation.enrollment && operation.createAttempted) throw new LoginError("cleanup");
|
|
2933
|
-
if (operation.enrollment) {
|
|
2934
|
-
try {
|
|
2935
|
-
await this.#post(
|
|
2936
|
-
`/pc-enrollments/${operation.enrollment.id}/cancel`,
|
|
2937
|
-
{ verifier: operation.enrollment.verifier },
|
|
2938
|
-
MicrosoftMutationResultSchema
|
|
2939
|
-
);
|
|
2940
|
-
} catch (error) {
|
|
2941
|
-
if (!(error instanceof LoginError && (error.rejectionEvidence === "enrollment-expired" || operation.pending !== void 0 && operation.pendingRejected && error.rejectionEvidence === "enrollment-missing"))) throw error;
|
|
2942
|
-
}
|
|
2943
|
-
}
|
|
2944
|
-
if (operation.pending) {
|
|
2945
|
-
const store = this.#store;
|
|
2946
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2947
|
-
await store.clearPending(operation.pending.tokenId);
|
|
2948
|
-
}
|
|
2949
|
-
if (this.#active === operation) this.#active = void 0;
|
|
2950
|
-
this.#state = { state: "signed-out" };
|
|
2951
|
-
} catch (error) {
|
|
2952
|
-
const safe = error instanceof LoginError && error.code === "confirmation" ? new LoginError("confirmation") : new LoginError("cleanup");
|
|
2953
|
-
this.#state = { state: "error", message: safe.message };
|
|
2954
|
-
throw safe;
|
|
2955
|
-
}
|
|
2956
|
-
}
|
|
2957
|
-
async #post(path, body, schema, options = {}) {
|
|
2958
|
-
if (this.#relayUrl.startsWith("https:") && process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
2959
|
-
throw new LoginError("network");
|
|
2960
|
-
}
|
|
2961
|
-
const controller = new AbortController();
|
|
2962
|
-
const signal = options.signal === void 0 ? controller.signal : AbortSignal.any([controller.signal, options.signal]);
|
|
2963
|
-
const timeout = Math.min(15e3, (options.deadline ?? Infinity) - Date.now());
|
|
2964
|
-
if (timeout <= 0) throw new LoginError("expired");
|
|
2965
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
2966
|
-
try {
|
|
2967
|
-
const work = (async () => {
|
|
2968
|
-
const response = await this.#fetch(`${this.#relayUrl}${path}`, {
|
|
2969
|
-
method: "POST",
|
|
2970
|
-
redirect: "error",
|
|
2971
|
-
credentials: "omit",
|
|
2972
|
-
cache: "no-store",
|
|
2973
|
-
headers: {
|
|
2974
|
-
"content-type": "application/json",
|
|
2975
|
-
accept: "application/json",
|
|
2976
|
-
...options.token === void 0 ? {} : { authorization: `Bearer ${options.token}` }
|
|
2977
|
-
},
|
|
2978
|
-
body: JSON.stringify(body),
|
|
2979
|
-
signal
|
|
2980
|
-
});
|
|
2981
|
-
if (signal.aborted || response.redirected || response.url && response.url !== `${this.#relayUrl}${path}`) {
|
|
2982
|
-
await response.body?.cancel();
|
|
2983
|
-
throw new LoginError("response");
|
|
2984
|
-
}
|
|
2985
|
-
const reader = response.body?.getReader();
|
|
2986
|
-
if (!reader) throw new LoginError("response", void 0, response.status);
|
|
2987
|
-
const chunks = [];
|
|
2988
|
-
let size = 0;
|
|
2989
|
-
try {
|
|
2990
|
-
while (true) {
|
|
2991
|
-
const chunk = await abortable(reader.read(), signal);
|
|
2992
|
-
if (chunk.done) break;
|
|
2993
|
-
size += chunk.value.byteLength;
|
|
2994
|
-
if (size > 16 * 1024) throw new LoginError("response");
|
|
2995
|
-
chunks.push(chunk.value);
|
|
2996
|
-
}
|
|
2997
|
-
} finally {
|
|
2998
|
-
void reader.cancel().catch(() => void 0);
|
|
2999
|
-
reader.releaseLock();
|
|
3000
|
-
}
|
|
3001
|
-
let value;
|
|
3002
|
-
try {
|
|
3003
|
-
value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
3004
|
-
} catch {
|
|
3005
|
-
throw new LoginError("response", void 0, response.status);
|
|
3006
|
-
}
|
|
3007
|
-
const rejected = MicrosoftEnrollmentFailureSchema.safeParse(value);
|
|
3008
|
-
if (!response.ok || rejected.success) {
|
|
3009
|
-
const retry = response.headers.get("retry-after");
|
|
3010
|
-
const seconds = retry !== null && /^\d+$/.test(retry) ? Number(retry) : NaN;
|
|
3011
|
-
const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : retry === null ? 6e4 : Math.max(0, Date.parse(retry) - Date.now());
|
|
3012
|
-
throw failure(
|
|
3013
|
-
rejected.success ? rejected.data.error.code : "",
|
|
3014
|
-
response.status,
|
|
3015
|
-
Number.isFinite(retryAfterMs) ? retryAfterMs : 6e4
|
|
3016
|
-
);
|
|
3017
|
-
}
|
|
3018
|
-
const parsed = schema.safeParse(value);
|
|
3019
|
-
if (!parsed.success) throw new LoginError("response");
|
|
3020
|
-
return parsed.data;
|
|
3021
|
-
})();
|
|
3022
|
-
return await abortable(work, signal);
|
|
3023
|
-
} catch (error) {
|
|
3024
|
-
if (options.signal?.aborted) throw new LoginError("cancelled");
|
|
3025
|
-
if (controller.signal.aborted) throw new LoginError("network");
|
|
3026
|
-
throw safeError(error);
|
|
3027
|
-
} finally {
|
|
3028
|
-
clearTimeout(timer);
|
|
3029
|
-
}
|
|
3030
|
-
}
|
|
3031
|
-
};
|
|
3032
|
-
|
|
3033
|
-
// src/relay-auth-discovery.ts
|
|
3034
|
-
var DISCOVERY_ERROR = "Relay login discovery failed. Check the address and retry.";
|
|
3035
|
-
var UNSUPPORTED_ERROR = "This Relay does not support automatic login. Upgrade it or configure its authentication explicitly.";
|
|
3036
|
-
var AutoRelayLogin = class {
|
|
3037
|
-
constructor(options) {
|
|
3038
|
-
this.options = options;
|
|
3039
|
-
this.#signal = AbortSignal.any([this.#closed.signal, ...options.signal === void 0 ? [] : [options.signal]]);
|
|
3040
|
-
this.relayOrigin = normalizeRelayOrigin(options.relayUrl);
|
|
3041
|
-
if (!this.relayOrigin.startsWith("https:") || process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
3042
|
-
throw new Error("Automatic Relay login requires HTTPS with certificate verification.");
|
|
3043
|
-
}
|
|
3044
|
-
}
|
|
3045
|
-
options;
|
|
3046
|
-
relayOrigin;
|
|
3047
|
-
#closed = new AbortController();
|
|
3048
|
-
#readyWaiters = /* @__PURE__ */ new Set();
|
|
3049
|
-
#signal;
|
|
3050
|
-
#discovery;
|
|
3051
|
-
#pending;
|
|
3052
|
-
#provider;
|
|
3053
|
-
#authentication;
|
|
3054
|
-
#state = { state: "signed-out" };
|
|
3055
|
-
get method() {
|
|
3056
|
-
return this.#authentication?.mode ?? "auto";
|
|
3057
|
-
}
|
|
3058
|
-
getState() {
|
|
3059
|
-
return this.#provider?.getState() ?? { ...this.#state };
|
|
3060
|
-
}
|
|
3061
|
-
acceptCallback(input, redirectUri) {
|
|
3062
|
-
return this.#provider?.acceptCallback(input, redirectUri);
|
|
3063
|
-
}
|
|
3064
|
-
prepare() {
|
|
3065
|
-
if (this.#signal.aborted) return Promise.reject(new Error("Relay login cancelled."));
|
|
3066
|
-
if (this.#provider !== void 0) return Promise.resolve();
|
|
3067
|
-
this.#pending ??= this.#discover().finally(() => {
|
|
3068
|
-
this.#pending = void 0;
|
|
3069
|
-
});
|
|
3070
|
-
return this.#pending;
|
|
3071
|
-
}
|
|
3072
|
-
async #discover() {
|
|
3073
|
-
const controller = new AbortController();
|
|
3074
|
-
this.#discovery = controller;
|
|
3075
|
-
const signal = AbortSignal.any([controller.signal, this.#signal, AbortSignal.timeout(1e4)]);
|
|
3076
|
-
this.#state = { state: "starting" };
|
|
3077
|
-
let unsupported = false;
|
|
3078
|
-
try {
|
|
3079
|
-
const response = await (this.options.fetch ?? globalThis.fetch)(`${this.relayOrigin}${RELAY_AUTH_DISCOVERY_PATH}`, {
|
|
3080
|
-
headers: { accept: "application/json" },
|
|
3081
|
-
redirect: "error",
|
|
3082
|
-
credentials: "omit",
|
|
3083
|
-
cache: "no-store",
|
|
3084
|
-
signal
|
|
3085
|
-
});
|
|
3086
|
-
const reader = response.body?.getReader();
|
|
3087
|
-
let metadata;
|
|
3088
|
-
try {
|
|
3089
|
-
unsupported = response.status === 404;
|
|
3090
|
-
if (!response.ok || response.redirected || reader === void 0 || response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== "application/json") {
|
|
3091
|
-
throw new Error(DISCOVERY_ERROR);
|
|
3092
|
-
}
|
|
3093
|
-
const chunks = [];
|
|
3094
|
-
let bytes = 0;
|
|
3095
|
-
for (; ; ) {
|
|
3096
|
-
const next = await reader.read();
|
|
3097
|
-
if (next.done) break;
|
|
3098
|
-
bytes += next.value.byteLength;
|
|
3099
|
-
if (bytes > 16384) throw new Error(DISCOVERY_ERROR);
|
|
3100
|
-
chunks.push(next.value);
|
|
3101
|
-
}
|
|
3102
|
-
metadata = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
3103
|
-
} finally {
|
|
3104
|
-
await reader?.cancel();
|
|
3105
|
-
reader?.releaseLock();
|
|
3106
|
-
}
|
|
3107
|
-
signal.throwIfAborted();
|
|
3108
|
-
const authentication = RelayAuthDiscoverySchema.parse(metadata).authentication;
|
|
3109
|
-
if (authentication.mode === "token") {
|
|
3110
|
-
unsupported = true;
|
|
3111
|
-
throw new Error(UNSUPPORTED_ERROR);
|
|
3112
|
-
}
|
|
3113
|
-
if (authentication.mode === "aad" && authentication.clientId.toLowerCase() === authentication.apiClientId.toLowerCase()) {
|
|
3114
|
-
throw new Error(DISCOVERY_ERROR);
|
|
3115
|
-
}
|
|
3116
|
-
const normalized = authentication.mode === "aad" ? {
|
|
3117
|
-
mode: "aad",
|
|
3118
|
-
tenantId: authentication.tenantId.toLowerCase(),
|
|
3119
|
-
clientId: authentication.clientId.toLowerCase(),
|
|
3120
|
-
apiClientId: authentication.apiClientId.toLowerCase()
|
|
3121
|
-
} : authentication;
|
|
3122
|
-
const provider = await this.options.createLogin(normalized);
|
|
3123
|
-
if (signal.aborted) {
|
|
3124
|
-
await provider.close();
|
|
3125
|
-
signal.throwIfAborted();
|
|
3126
|
-
}
|
|
3127
|
-
this.#authentication = normalized;
|
|
3128
|
-
this.#provider = provider;
|
|
3129
|
-
for (const ready of this.#readyWaiters) ready(provider);
|
|
3130
|
-
this.#readyWaiters.clear();
|
|
3131
|
-
} catch {
|
|
3132
|
-
if (!this.#signal.aborted && !controller.signal.aborted) {
|
|
3133
|
-
this.#state = { state: "error", message: unsupported ? UNSUPPORTED_ERROR : DISCOVERY_ERROR };
|
|
3134
|
-
}
|
|
3135
|
-
}
|
|
3136
|
-
}
|
|
3137
|
-
#withAuthentication(credential) {
|
|
3138
|
-
if (this.#authentication === void 0) throw new Error(DISCOVERY_ERROR);
|
|
3139
|
-
this.#signal.throwIfAborted();
|
|
3140
|
-
return {
|
|
3141
|
-
...credential,
|
|
3142
|
-
authentication: this.#authentication,
|
|
3143
|
-
...this.#authentication.mode === "aad" ? { close: () => this.close() } : {}
|
|
3144
|
-
};
|
|
3145
|
-
}
|
|
3146
|
-
async restore() {
|
|
3147
|
-
await this.prepare();
|
|
3148
|
-
const credential = await this.#provider?.restore();
|
|
3149
|
-
return credential === void 0 ? void 0 : this.#withAuthentication(credential);
|
|
3150
|
-
}
|
|
3151
|
-
async start() {
|
|
3152
|
-
if (this.#provider === void 0) {
|
|
3153
|
-
if (this.options.reauthorize) await this.prepare();
|
|
3154
|
-
else await this.restore();
|
|
3155
|
-
return;
|
|
3156
|
-
}
|
|
3157
|
-
await this.#provider.start();
|
|
3158
|
-
}
|
|
3159
|
-
async cancel() {
|
|
3160
|
-
this.#discovery?.abort();
|
|
3161
|
-
this.#state = { state: "signed-out" };
|
|
3162
|
-
await this.#provider?.cancel();
|
|
3163
|
-
}
|
|
3164
|
-
async close() {
|
|
3165
|
-
this.#closed.abort(new Error("Relay login cancelled."));
|
|
3166
|
-
this.#discovery?.abort();
|
|
3167
|
-
await this.#provider?.close();
|
|
3168
|
-
}
|
|
3169
|
-
async waitForCredential(signal) {
|
|
3170
|
-
const combined = AbortSignal.any([this.#signal, ...signal === void 0 ? [] : [signal]]);
|
|
3171
|
-
combined.throwIfAborted();
|
|
3172
|
-
const provider = this.#provider ?? await new Promise((resolve2, reject) => {
|
|
3173
|
-
const abort = () => {
|
|
3174
|
-
this.#readyWaiters.delete(ready);
|
|
3175
|
-
combined.removeEventListener("abort", abort);
|
|
3176
|
-
reject(combined.reason);
|
|
3177
|
-
};
|
|
3178
|
-
const ready = (value) => {
|
|
3179
|
-
this.#readyWaiters.delete(ready);
|
|
3180
|
-
combined.removeEventListener("abort", abort);
|
|
3181
|
-
if (combined.aborted) reject(combined.reason);
|
|
3182
|
-
else resolve2(value);
|
|
3183
|
-
};
|
|
3184
|
-
combined.addEventListener("abort", abort, { once: true });
|
|
3185
|
-
this.#readyWaiters.add(ready);
|
|
3186
|
-
});
|
|
3187
|
-
return this.#withAuthentication(await provider.waitForCredential(combined));
|
|
3188
|
-
}
|
|
3189
|
-
};
|
|
3190
|
-
|
|
3191
|
-
// src/relay-login-startup.ts
|
|
3192
|
-
async function completeRelayLogin(options) {
|
|
3193
|
-
const { settings: settings2, identity, force, signal, report } = options;
|
|
3194
|
-
if (settings2.relayAuthentication.mode === "token") {
|
|
3195
|
-
if (force) {
|
|
3196
|
-
throw new Error("Set RELAY_AUTH=microsoft in the selected environment file to sign in. The existing token has not been changed.");
|
|
3197
|
-
}
|
|
3198
|
-
return void 0;
|
|
3199
|
-
}
|
|
3200
|
-
let page;
|
|
3201
|
-
let pageTransferred = false;
|
|
3202
|
-
let authorized = false;
|
|
3203
|
-
const createLogin = async (authentication) => authentication.mode === "aad" ? await (await import("./aad-relay-login-PN2MTPBR.js")).createAadRelayLogin({
|
|
3204
|
-
...authentication,
|
|
3205
|
-
relayUrl: settings2.relayUrl,
|
|
3206
|
-
machineId: identity.machineId
|
|
3207
|
-
}) : new MicrosoftRelayLogin({
|
|
3208
|
-
relayUrl: settings2.relayUrl,
|
|
3209
|
-
identity,
|
|
3210
|
-
reauthorize: force,
|
|
3211
|
-
getRedirectUri: () => {
|
|
3212
|
-
if (!page) throw new Error("Microsoft login page is not listening.");
|
|
3213
|
-
return `${page.url}/relay-login/callback`;
|
|
3214
|
-
}
|
|
3215
|
-
});
|
|
3216
|
-
const login = settings2.relayAuthentication.mode === "auto" ? new AutoRelayLogin({ relayUrl: settings2.relayUrl, signal, reauthorize: force, createLogin }) : await createLogin(settings2.relayAuthentication);
|
|
3217
|
-
try {
|
|
3218
|
-
if (force && login instanceof AutoRelayLogin) await login.prepare();
|
|
3219
|
-
if (!force) {
|
|
3220
|
-
const credential2 = await login.restore();
|
|
3221
|
-
signal.throwIfAborted();
|
|
3222
|
-
if (credential2 !== void 0) {
|
|
3223
|
-
authorized = true;
|
|
3224
|
-
return credential2;
|
|
3225
|
-
}
|
|
3226
|
-
}
|
|
3227
|
-
if (!settings2.pairingPageEnabled && !force) {
|
|
3228
|
-
const state = login.getState();
|
|
3229
|
-
if (state.state === "error") throw new Error(state.message);
|
|
3230
|
-
throw new Error("Microsoft sign-in is required. Run agentknight login with the same --env file and OS user before starting the headless Agent.");
|
|
3231
|
-
}
|
|
3232
|
-
signal.throwIfAborted();
|
|
3233
|
-
page = new PairingPageServer({
|
|
3234
|
-
machineName: identity.machineName,
|
|
3235
|
-
port: settings2.pairingPagePort,
|
|
3236
|
-
relayLogin: login,
|
|
3237
|
-
getRegistrationStatus: () => ({ state: "connecting", message: "Sign in with Microsoft." }),
|
|
3238
|
-
pairingProvider: { getPairing: async () => {
|
|
3239
|
-
throw new Error("Sign in before pairing.");
|
|
3240
|
-
} }
|
|
3241
|
-
});
|
|
3242
|
-
await page.start();
|
|
3243
|
-
options.onListening?.(Number(new URL(page.url).port));
|
|
3244
|
-
report(`Microsoft sign-in: ${page.url}`);
|
|
3245
|
-
const credential = await login.waitForCredential(signal);
|
|
3246
|
-
signal.throwIfAborted();
|
|
3247
|
-
if (!force) {
|
|
3248
|
-
options.onAuthorizedPage(page);
|
|
3249
|
-
pageTransferred = true;
|
|
3250
|
-
}
|
|
3251
|
-
authorized = true;
|
|
3252
|
-
return credential;
|
|
3253
|
-
} finally {
|
|
3254
|
-
try {
|
|
3255
|
-
if (!pageTransferred) await page?.stop();
|
|
3256
|
-
} finally {
|
|
3257
|
-
if (!authorized || (settings2.relayAuthentication.mode === "auto" ? login.method : settings2.relayAuthentication.mode) !== "aad") {
|
|
3258
|
-
await login.close();
|
|
3259
|
-
}
|
|
3260
|
-
}
|
|
3261
|
-
}
|
|
3262
|
-
}
|
|
3263
|
-
|
|
3264
|
-
// src/relay-account.ts
|
|
3265
|
-
import { relayRequestToken } from "@agentknight/sdk/configuration";
|
|
3266
|
-
var AccountReadError = class extends Error {
|
|
3267
|
-
constructor(key, state = "unavailable") {
|
|
3268
|
-
super(localPageTranslator()(key));
|
|
3269
|
-
this.key = key;
|
|
3270
|
-
this.state = state;
|
|
3271
|
-
}
|
|
3272
|
-
key;
|
|
3273
|
-
state;
|
|
3274
|
-
};
|
|
3275
|
-
var RelayAccount = class {
|
|
3276
|
-
constructor(options) {
|
|
3277
|
-
this.options = options;
|
|
3278
|
-
this.#lastUser = options.user;
|
|
3279
|
-
this.#method = options.method;
|
|
3280
|
-
}
|
|
3281
|
-
options;
|
|
3282
|
-
#cached;
|
|
3283
|
-
#expiresAt = 0;
|
|
3284
|
-
#pending;
|
|
3285
|
-
#lastUser;
|
|
3286
|
-
#method;
|
|
3287
|
-
async read(registration) {
|
|
3288
|
-
if (registration.state !== "registered") {
|
|
3289
|
-
this.#expiresAt = 0;
|
|
3290
|
-
this.#pending = void 0;
|
|
3291
|
-
return this.#view(
|
|
3292
|
-
registration.state === "connecting" ? "connecting" : "disconnected",
|
|
3293
|
-
registration.state === "error" ? "account.failure.disconnected" : void 0
|
|
3294
|
-
);
|
|
3295
|
-
}
|
|
3296
|
-
if (this.#cached !== void 0 && Date.now() < this.#expiresAt) return this.#cached;
|
|
3297
|
-
if (this.#pending !== void 0) return this.#pending;
|
|
3298
|
-
const pending = this.#load();
|
|
3299
|
-
this.#pending = pending;
|
|
3300
|
-
try {
|
|
3301
|
-
const account = await pending;
|
|
3302
|
-
if (this.#pending === pending) {
|
|
3303
|
-
this.#cached = account;
|
|
3304
|
-
this.#lastUser = account.user;
|
|
3305
|
-
this.#method = account.method;
|
|
3306
|
-
this.#expiresAt = Date.now() + (account.state === "signed-in" ? 3e4 : 5e3);
|
|
3307
|
-
}
|
|
3308
|
-
return account;
|
|
3309
|
-
} finally {
|
|
3310
|
-
if (this.#pending === pending) this.#pending = void 0;
|
|
3311
|
-
}
|
|
3312
|
-
}
|
|
3313
|
-
#view(state, errorKey) {
|
|
3314
|
-
return {
|
|
3315
|
-
state,
|
|
3316
|
-
method: this.#method,
|
|
3317
|
-
userId: this.options.config.userId,
|
|
3318
|
-
...this.#lastUser === void 0 ? {} : { user: { ...this.#lastUser } },
|
|
3319
|
-
...errorKey === void 0 ? {} : { error: localPageTranslator()(errorKey), errorKey }
|
|
3320
|
-
};
|
|
3321
|
-
}
|
|
3322
|
-
async #load() {
|
|
3323
|
-
try {
|
|
3324
|
-
const { config, machineId } = this.options;
|
|
3325
|
-
if (this.options.method === "aad") {
|
|
3326
|
-
const user = await readAadAccount(config.relayUrl, await relayRequestToken(config), this.options.fetch);
|
|
3327
|
-
if (user.userId !== config.userId) throw new AccountReadError("account.failure.invalid", "error");
|
|
3328
|
-
return { state: "signed-in", method: "aad", userId: config.userId, user };
|
|
3329
|
-
}
|
|
3330
|
-
const url = `${normalizeRelayOrigin(config.relayUrl)}/auth/pc/account`;
|
|
3331
|
-
if (url.startsWith("https:") && process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
3332
|
-
throw new AccountReadError("account.failure.tls");
|
|
3333
|
-
}
|
|
3334
|
-
const response = await (this.options.fetch ?? globalThis.fetch)(url, {
|
|
3335
|
-
method: "POST",
|
|
3336
|
-
redirect: "error",
|
|
3337
|
-
credentials: "omit",
|
|
3338
|
-
cache: "no-store",
|
|
3339
|
-
signal: AbortSignal.timeout(3e3),
|
|
3340
|
-
headers: { authorization: `Bearer ${config.relayToken}`, "content-type": "application/json", accept: "application/json" },
|
|
3341
|
-
body: JSON.stringify(PcAccountRequestSchema.parse({ userId: config.userId, machineId }))
|
|
3342
|
-
});
|
|
3343
|
-
const reader = response.body?.getReader();
|
|
3344
|
-
try {
|
|
3345
|
-
if (response.redirected || response.url && response.url !== url) throw new AccountReadError("account.failure.invalid");
|
|
3346
|
-
if (response.status === 404) throw new AccountReadError("account.failure.unsupported");
|
|
3347
|
-
if (response.status === 401 || response.status === 403) throw new AccountReadError("account.failure.expired", "error");
|
|
3348
|
-
if (!response.ok || reader === void 0) throw new AccountReadError("account.failure.read");
|
|
3349
|
-
const chunks = [];
|
|
3350
|
-
let size = 0;
|
|
3351
|
-
while (true) {
|
|
3352
|
-
const chunk = await reader.read();
|
|
3353
|
-
if (chunk.done) break;
|
|
3354
|
-
size += chunk.value.byteLength;
|
|
3355
|
-
if (size > 16 * 1024) throw new AccountReadError("account.failure.invalid");
|
|
3356
|
-
chunks.push(chunk.value);
|
|
3357
|
-
}
|
|
3358
|
-
const parsed = PcAccountResultSchema.safeParse(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
3359
|
-
if (!parsed.success || !parsed.data.ok || parsed.data.user.userId !== config.userId || this.options.method === "microsoft" && parsed.data.method !== "microsoft") {
|
|
3360
|
-
throw new AccountReadError("account.failure.invalid");
|
|
3361
|
-
}
|
|
3362
|
-
return { state: "signed-in", method: parsed.data.method, userId: config.userId, user: parsed.data.user };
|
|
3363
|
-
} finally {
|
|
3364
|
-
await reader?.cancel();
|
|
3365
|
-
reader?.releaseLock();
|
|
3366
|
-
}
|
|
3367
|
-
} catch (error) {
|
|
3368
|
-
return this.#view(
|
|
3369
|
-
error instanceof AccountReadError ? error.state : "unavailable",
|
|
3370
|
-
error instanceof AccountReadError ? error.key : "account.failure.connection"
|
|
3371
|
-
);
|
|
3372
|
-
}
|
|
3373
|
-
}
|
|
3374
|
-
};
|
|
3375
|
-
|
|
3376
|
-
// src/diagnostic-logger.ts
|
|
3377
|
-
import {
|
|
3378
|
-
appendFileSync,
|
|
3379
|
-
existsSync,
|
|
3380
|
-
mkdirSync,
|
|
3381
|
-
renameSync,
|
|
3382
|
-
statSync,
|
|
3383
|
-
unlinkSync
|
|
3384
|
-
} from "node:fs";
|
|
3385
|
-
import { join } from "node:path";
|
|
3386
|
-
import pino from "pino";
|
|
3387
|
-
var MAX_LOG_BYTES = 1024 * 1024;
|
|
3388
|
-
var MAX_LOG_ARCHIVES = 9;
|
|
3389
|
-
var REDACTED = "[REDACTED]";
|
|
3390
|
-
var SENSITIVE_FIELD = /password|token|secret|credential|authorization|cookie|message|stack|reason|prompt|content|payload|body/i;
|
|
3391
|
-
var BEARER_TOKEN = /bearer\s+[A-Za-z0-9._~+/=-]+/gi;
|
|
3392
|
-
var SENSITIVE_ASSIGNMENT = /(password|token|secret|credential|authorization)\s*(?:=|:|is)?\s*[^\s,;]+/gi;
|
|
3393
|
-
var SENSITIVE_QUERY = /([?&](?:password|token|secret|credential|authorization)=)[^&#\s]+/gi;
|
|
3394
|
-
var LONG_ENCODED_VALUE = /(?<![A-Za-z0-9_-])[A-Za-z0-9_+/=-]{40,}(?![A-Za-z0-9_-])/g;
|
|
3395
|
-
function createDiagnosticLogger(dataDirectory, level, options = {}) {
|
|
3396
|
-
const version = options.version ?? readAppVersion();
|
|
3397
|
-
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(version) || version.length > 128 || version !== version.trim()) {
|
|
3398
|
-
throw new Error("Diagnostic log version must be a safe application version");
|
|
3399
|
-
}
|
|
3400
|
-
const logDirectory = join(dataDirectory, "logs", version);
|
|
3401
|
-
const logPath = join(logDirectory, "pc-agent.jsonl");
|
|
3402
|
-
mkdirSync(logDirectory, { recursive: true });
|
|
3403
|
-
const fileDestination = new RotatingFileDestination(
|
|
3404
|
-
logPath,
|
|
3405
|
-
options.maxLogBytes ?? MAX_LOG_BYTES,
|
|
3406
|
-
version
|
|
3407
|
-
);
|
|
3408
|
-
const logger = pino(
|
|
3409
|
-
{
|
|
3410
|
-
level,
|
|
3411
|
-
base: { component: "pc-agent", appVersion: version },
|
|
3412
|
-
redact: {
|
|
3413
|
-
paths: [
|
|
3414
|
-
"token",
|
|
3415
|
-
"relayToken",
|
|
3416
|
-
"password",
|
|
3417
|
-
"secret",
|
|
3418
|
-
"mobileCredential",
|
|
3419
|
-
"contentKey",
|
|
3420
|
-
"authorization",
|
|
3421
|
-
"*.token",
|
|
3422
|
-
"*.relayToken",
|
|
3423
|
-
"*.password",
|
|
3424
|
-
"*.secret",
|
|
3425
|
-
"*.mobileCredential",
|
|
3426
|
-
"*.contentKey",
|
|
3427
|
-
"*.authorization",
|
|
3428
|
-
"req.headers.authorization"
|
|
3429
|
-
],
|
|
3430
|
-
censor: REDACTED
|
|
3431
|
-
}
|
|
3432
|
-
},
|
|
3433
|
-
pino.multistream([
|
|
3434
|
-
{
|
|
3435
|
-
level: "trace",
|
|
3436
|
-
stream: new SanitizingDestination(
|
|
3437
|
-
options.terminalStream ?? process.stdout,
|
|
3438
|
-
(message) => fileDestination.sanitize(message)
|
|
3439
|
-
)
|
|
3440
|
-
},
|
|
3441
|
-
{ level: "trace", stream: fileDestination }
|
|
3442
|
-
])
|
|
3443
|
-
);
|
|
3444
|
-
return {
|
|
3445
|
-
logger,
|
|
3446
|
-
logPath,
|
|
3447
|
-
async close() {
|
|
3448
|
-
logger.flush();
|
|
3449
|
-
}
|
|
3450
|
-
};
|
|
3451
|
-
}
|
|
3452
|
-
var RotatingFileDestination = class {
|
|
3453
|
-
constructor(logPath, maxBytes, appVersion) {
|
|
3454
|
-
this.logPath = logPath;
|
|
3455
|
-
this.maxBytes = maxBytes;
|
|
3456
|
-
this.appVersion = appVersion;
|
|
3457
|
-
try {
|
|
3458
|
-
this.#currentBytes = existsSync(logPath) ? statSync(logPath).size : 0;
|
|
3459
|
-
if (this.#currentBytes >= maxBytes) {
|
|
3460
|
-
this.#rotate();
|
|
3461
|
-
}
|
|
3462
|
-
} catch (error) {
|
|
3463
|
-
this.#disable(error);
|
|
3464
|
-
}
|
|
3465
|
-
}
|
|
3466
|
-
logPath;
|
|
3467
|
-
maxBytes;
|
|
3468
|
-
appVersion;
|
|
3469
|
-
#currentBytes = 0;
|
|
3470
|
-
#disabled = false;
|
|
3471
|
-
write(message) {
|
|
3472
|
-
if (this.#disabled) {
|
|
3473
|
-
return;
|
|
3474
|
-
}
|
|
3475
|
-
try {
|
|
3476
|
-
let safeMessage = this.#sanitizePersistedLogLine(message);
|
|
3477
|
-
let messageBytes = Buffer.byteLength(safeMessage);
|
|
3478
|
-
if (messageBytes > this.maxBytes) {
|
|
3479
|
-
safeMessage = `${JSON.stringify({
|
|
3480
|
-
level: 40,
|
|
3481
|
-
time: Date.now(),
|
|
3482
|
-
component: "pc-agent",
|
|
3483
|
-
appVersion: this.appVersion,
|
|
3484
|
-
droppedBytes: messageBytes,
|
|
3485
|
-
msg: "pc-agent.diagnostics.oversized-entry-dropped"
|
|
3486
|
-
})}
|
|
3487
|
-
`;
|
|
3488
|
-
messageBytes = Buffer.byteLength(safeMessage);
|
|
3489
|
-
if (messageBytes > this.maxBytes) {
|
|
3490
|
-
throw new Error("Diagnostic log byte limit cannot fit a failure record");
|
|
3491
|
-
}
|
|
3492
|
-
}
|
|
3493
|
-
if (this.#currentBytes > 0 && this.#currentBytes + messageBytes > this.maxBytes) {
|
|
3494
|
-
this.#rotate();
|
|
3495
|
-
}
|
|
3496
|
-
appendFileSync(this.logPath, safeMessage, "utf8");
|
|
3497
|
-
this.#currentBytes += messageBytes;
|
|
3498
|
-
} catch (error) {
|
|
3499
|
-
this.#disable(error);
|
|
3500
|
-
}
|
|
3501
|
-
}
|
|
3502
|
-
sanitize(message) {
|
|
3503
|
-
return this.#sanitizePersistedLogLine(message);
|
|
3504
|
-
}
|
|
3505
|
-
#disable(error) {
|
|
3506
|
-
this.#disabled = true;
|
|
3507
|
-
const details = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
3508
|
-
process.stderr.write(
|
|
3509
|
-
`PC diagnostic file logging disabled after a write failure: ${details}
|
|
3510
|
-
`
|
|
3511
|
-
);
|
|
3512
|
-
}
|
|
3513
|
-
#sanitizePersistedLogLine(message) {
|
|
3514
|
-
let parsed;
|
|
3515
|
-
try {
|
|
3516
|
-
parsed = JSON.parse(message);
|
|
3517
|
-
} catch {
|
|
3518
|
-
return `${JSON.stringify({
|
|
3519
|
-
level: 40,
|
|
3520
|
-
time: Date.now(),
|
|
3521
|
-
component: "pc-agent",
|
|
3522
|
-
appVersion: this.appVersion,
|
|
3523
|
-
msg: "pc-agent.diagnostics.unstructured-entry-dropped"
|
|
3524
|
-
})}
|
|
3525
|
-
`;
|
|
3526
|
-
}
|
|
3527
|
-
const sanitized = this.#sanitizePersistedValue(parsed);
|
|
3528
|
-
return `${JSON.stringify(
|
|
3529
|
-
sanitized !== null && typeof sanitized === "object" && !Array.isArray(sanitized) ? { ...sanitized, appVersion: this.appVersion } : sanitized
|
|
3530
|
-
)}
|
|
3531
|
-
`;
|
|
3532
|
-
}
|
|
3533
|
-
#sanitizePersistedValue(value, key) {
|
|
3534
|
-
if (key !== void 0 && key !== "msg" && SENSITIVE_FIELD.test(key)) {
|
|
3535
|
-
return REDACTED;
|
|
3536
|
-
}
|
|
3537
|
-
if (typeof value === "string") {
|
|
3538
|
-
return this.#sanitizePersistedText(value);
|
|
3539
|
-
}
|
|
3540
|
-
if (Array.isArray(value)) {
|
|
3541
|
-
return value.map((item) => this.#sanitizePersistedValue(item));
|
|
3542
|
-
}
|
|
3543
|
-
if (value !== null && typeof value === "object") {
|
|
3544
|
-
return Object.fromEntries(
|
|
3545
|
-
Object.entries(value).map(([childKey, childValue]) => [
|
|
3546
|
-
childKey,
|
|
3547
|
-
this.#sanitizePersistedValue(childValue, childKey)
|
|
3548
|
-
])
|
|
3549
|
-
);
|
|
3550
|
-
}
|
|
3551
|
-
return value;
|
|
3552
|
-
}
|
|
3553
|
-
#sanitizePersistedText(value) {
|
|
3554
|
-
return value.replace(BEARER_TOKEN, "Bearer [REDACTED]").replace(SENSITIVE_ASSIGNMENT, "$1=[REDACTED]").replace(SENSITIVE_QUERY, "$1[REDACTED]").replace(LONG_ENCODED_VALUE, REDACTED).slice(0, 500);
|
|
3555
|
-
}
|
|
3556
|
-
#path(index) {
|
|
3557
|
-
return index === 0 ? this.logPath : `${this.logPath}.${index}`;
|
|
3558
|
-
}
|
|
3559
|
-
#rotate() {
|
|
3560
|
-
const oldestPath = this.#path(MAX_LOG_ARCHIVES);
|
|
3561
|
-
if (existsSync(oldestPath)) {
|
|
3562
|
-
unlinkSync(oldestPath);
|
|
3563
|
-
}
|
|
3564
|
-
for (let index = MAX_LOG_ARCHIVES - 1; index >= 0; index -= 1) {
|
|
3565
|
-
const path = this.#path(index);
|
|
3566
|
-
if (existsSync(path)) {
|
|
3567
|
-
renameSync(path, this.#path(index + 1));
|
|
3568
|
-
}
|
|
3569
|
-
}
|
|
3570
|
-
this.#currentBytes = 0;
|
|
3571
|
-
}
|
|
3572
|
-
};
|
|
3573
|
-
var SanitizingDestination = class {
|
|
3574
|
-
constructor(destination, sanitize) {
|
|
3575
|
-
this.destination = destination;
|
|
3576
|
-
this.sanitize = sanitize;
|
|
3577
|
-
}
|
|
3578
|
-
destination;
|
|
3579
|
-
sanitize;
|
|
3580
|
-
write(message) {
|
|
3581
|
-
this.destination.write(this.sanitize(message));
|
|
3582
|
-
}
|
|
3583
|
-
};
|
|
3584
|
-
|
|
3585
|
-
// src/chat-settings.ts
|
|
3586
|
-
import { join as join2 } from "node:path";
|
|
3587
|
-
import { z as z2 } from "zod";
|
|
3588
|
-
var settings = {
|
|
3589
|
-
groupChatEnabled: {
|
|
3590
|
-
file: "group-chat-settings.json",
|
|
3591
|
-
label: "Group chat",
|
|
3592
|
-
schema: z2.object({ groupChatEnabled: z2.boolean() }).strict().transform((value) => value.groupChatEnabled)
|
|
3593
|
-
},
|
|
3594
|
-
peerChatEnabled: {
|
|
3595
|
-
file: "peer-chat-settings.json",
|
|
3596
|
-
label: "Peer chat",
|
|
3597
|
-
schema: z2.object({ peerChatEnabled: z2.boolean() }).strict().transform((value) => value.peerChatEnabled)
|
|
3598
|
-
}
|
|
3599
|
-
};
|
|
3600
|
-
var ChatSettings = class _ChatSettings {
|
|
3601
|
-
constructor(path, key, enabled) {
|
|
3602
|
-
this.path = path;
|
|
3603
|
-
this.key = key;
|
|
3604
|
-
this.#enabled = enabled;
|
|
3605
|
-
}
|
|
3606
|
-
path;
|
|
3607
|
-
key;
|
|
3608
|
-
#enabled;
|
|
3609
|
-
#saving = false;
|
|
3610
|
-
static async load(directory, defaultEnabled, key = "groupChatEnabled") {
|
|
3611
|
-
const path = join2(directory, settings[key].file);
|
|
3612
|
-
const stored = await readOptionalJson(path);
|
|
3613
|
-
return new _ChatSettings(path, key, stored === void 0 ? defaultEnabled : settings[key].schema.parse(stored));
|
|
3614
|
-
}
|
|
3615
|
-
get enabled() {
|
|
3616
|
-
return this.#enabled;
|
|
3617
|
-
}
|
|
3618
|
-
async save(enabled, apply) {
|
|
3619
|
-
const label = settings[this.key].label;
|
|
3620
|
-
if (this.#saving) throw new Error(`${label} settings are being saved; try again.`);
|
|
3621
|
-
this.#saving = true;
|
|
3622
|
-
const previous = this.#enabled;
|
|
3623
|
-
try {
|
|
3624
|
-
await apply(enabled);
|
|
3625
|
-
await writePrivateJson(this.path, { [this.key]: enabled });
|
|
3626
|
-
this.#enabled = enabled;
|
|
3627
|
-
} catch (error) {
|
|
3628
|
-
try {
|
|
3629
|
-
await apply(previous);
|
|
3630
|
-
} catch (rollbackError) {
|
|
3631
|
-
throw new AggregateError([error, rollbackError], `${label} settings could not be saved or restored.`);
|
|
3632
|
-
}
|
|
3633
|
-
throw error;
|
|
3634
|
-
} finally {
|
|
3635
|
-
this.#saving = false;
|
|
3636
|
-
}
|
|
3637
|
-
}
|
|
3638
|
-
};
|
|
3639
|
-
|
|
3640
|
-
// src/image-settings.ts
|
|
3641
|
-
import { join as join3 } from "node:path";
|
|
3642
|
-
import { z as z3 } from "zod";
|
|
3643
|
-
var ImageSettingsSchema = z3.object({
|
|
3644
|
-
relayUrl: z3.url(),
|
|
3645
|
-
enabled: z3.boolean()
|
|
3646
|
-
}).strict();
|
|
3647
|
-
var ImageSettings = class _ImageSettings {
|
|
3648
|
-
constructor(path, relayUrl, enabled) {
|
|
3649
|
-
this.path = path;
|
|
3650
|
-
this.relayUrl = relayUrl;
|
|
3651
|
-
this.#enabled = enabled;
|
|
3652
|
-
}
|
|
3653
|
-
path;
|
|
3654
|
-
relayUrl;
|
|
3655
|
-
#enabled;
|
|
3656
|
-
#saving = false;
|
|
3657
|
-
static async load(directory, relayUrl, defaultEnabled = false) {
|
|
3658
|
-
const path = join3(directory, "image-settings.json");
|
|
3659
|
-
const value = await readOptionalJson(path);
|
|
3660
|
-
const saved = value === void 0 ? void 0 : ImageSettingsSchema.parse(value);
|
|
3661
|
-
const origin = new URL(relayUrl).origin;
|
|
3662
|
-
return new _ImageSettings(path, origin, saved?.relayUrl === origin ? saved.enabled : defaultEnabled);
|
|
3663
|
-
}
|
|
3664
|
-
get enabled() {
|
|
3665
|
-
return this.#enabled;
|
|
3666
|
-
}
|
|
3667
|
-
async save(enabled, apply) {
|
|
3668
|
-
if (this.#saving) throw new Error("Image settings are being saved; try again.");
|
|
3669
|
-
this.#saving = true;
|
|
3670
|
-
const previous = this.#enabled;
|
|
3671
|
-
try {
|
|
3672
|
-
await apply(enabled);
|
|
3673
|
-
await writePrivateJson(this.path, { relayUrl: this.relayUrl, enabled });
|
|
3674
|
-
this.#enabled = enabled;
|
|
3675
|
-
} catch (error) {
|
|
3676
|
-
try {
|
|
3677
|
-
await apply(previous);
|
|
3678
|
-
} catch (rollbackError) {
|
|
3679
|
-
throw new AggregateError([error, rollbackError], "Image settings could not be saved or restored.");
|
|
3680
|
-
}
|
|
3681
|
-
throw error;
|
|
3682
|
-
} finally {
|
|
3683
|
-
this.#saving = false;
|
|
3684
|
-
}
|
|
3685
|
-
}
|
|
3686
|
-
};
|
|
3687
|
-
|
|
3688
|
-
// src/device-identity.ts
|
|
3689
|
-
import { randomUUID } from "node:crypto";
|
|
3690
|
-
import { link, lstat, mkdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
|
|
3691
|
-
import { hostname } from "node:os";
|
|
3692
|
-
import { join as join4 } from "node:path";
|
|
3693
|
-
import { z as z4 } from "zod";
|
|
3694
|
-
import { DeviceIdentitySchema } from "@agentknight/sdk/configuration";
|
|
3695
|
-
import { DeviceIdentitySchema as DeviceIdentitySchema2 } from "@agentknight/sdk/configuration";
|
|
3696
|
-
var V1DeviceIdentitySchema = z4.object({
|
|
3697
|
-
schemaVersion: z4.literal(1),
|
|
3698
|
-
machineId: z4.uuid(),
|
|
3699
|
-
machineName: z4.string().trim().min(1).max(120),
|
|
3700
|
-
createdAt: z4.iso.datetime({ offset: true })
|
|
3701
|
-
});
|
|
3702
|
-
function resolveMachineName(environment = process.env, fallback = hostname()) {
|
|
3703
|
-
const computerName = environment.COMPUTERNAME?.trim();
|
|
3704
|
-
return computerName === void 0 || computerName.length === 0 ? fallback : computerName;
|
|
3705
|
-
}
|
|
3706
|
-
function isMissing(error) {
|
|
3707
|
-
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
3708
|
-
}
|
|
3709
|
-
async function optionalStat(path) {
|
|
3710
|
-
try {
|
|
3711
|
-
return await lstat(path);
|
|
3712
|
-
} catch (error) {
|
|
3713
|
-
if (isMissing(error)) return void 0;
|
|
3714
|
-
throw error;
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
async function readStableDeviceId(path) {
|
|
3718
|
-
const info = await optionalStat(path);
|
|
3719
|
-
if (info === void 0) return void 0;
|
|
3720
|
-
if (!info.isFile()) throw new Error(`Device ID must be a regular file, not a link: ${path}`);
|
|
3721
|
-
const parsed = z4.uuid().safeParse((await readFile2(path, "utf8")).trim());
|
|
3722
|
-
if (!parsed.success) throw new Error(`Invalid device ID in ${path}`, { cause: parsed.error });
|
|
3723
|
-
return parsed.data;
|
|
3724
|
-
}
|
|
3725
|
-
async function requireDirectory(path) {
|
|
3726
|
-
const info = await optionalStat(path);
|
|
3727
|
-
if (info === void 0) return;
|
|
3728
|
-
if (!info.isDirectory()) throw new Error(`Identity directory must not be linked or a special file: ${path}`);
|
|
3729
|
-
}
|
|
3730
|
-
async function writePrivateFile(path, contents, replace) {
|
|
3731
|
-
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
3732
|
-
try {
|
|
3733
|
-
await writeFile(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
3734
|
-
if (replace) {
|
|
3735
|
-
await rename(temporaryPath, path);
|
|
3736
|
-
} else {
|
|
3737
|
-
await link(temporaryPath, path);
|
|
3738
|
-
}
|
|
3739
|
-
} finally {
|
|
3740
|
-
await rm(temporaryPath, { force: true });
|
|
3741
|
-
}
|
|
3742
|
-
}
|
|
3743
|
-
async function loadOrCreateDeviceIdentity(dataDirectory, currentMachineName = resolveMachineName()) {
|
|
3744
|
-
const path = join4(dataDirectory, "device.json");
|
|
3745
|
-
const stablePath = join4(dataDirectory, "device-id");
|
|
3746
|
-
await requireDirectory(dataDirectory);
|
|
3747
|
-
let existing;
|
|
3748
|
-
try {
|
|
3749
|
-
existing = z4.union([DeviceIdentitySchema, V1DeviceIdentitySchema]).parse(
|
|
3750
|
-
JSON.parse(await readFile2(path, "utf8"))
|
|
3751
|
-
);
|
|
3752
|
-
} catch (error) {
|
|
3753
|
-
if (!isMissing(error)) throw error;
|
|
3754
|
-
}
|
|
3755
|
-
const canonicalId = await readStableDeviceId(stablePath);
|
|
3756
|
-
const existingStableId = existing?.schemaVersion === 2 ? existing.stableDeviceId : void 0;
|
|
3757
|
-
if (canonicalId !== void 0 && existingStableId !== void 0 && canonicalId !== existingStableId) {
|
|
3758
|
-
throw new Error(`Conflicting device IDs in ${stablePath} and ${path}; reconcile them before starting.`);
|
|
3759
|
-
}
|
|
3760
|
-
const identity = DeviceIdentitySchema.parse({
|
|
3761
|
-
schemaVersion: 2,
|
|
3762
|
-
machineId: existing?.machineId ?? randomUUID(),
|
|
3763
|
-
stableDeviceId: canonicalId ?? existingStableId ?? existing?.machineId ?? randomUUID(),
|
|
3764
|
-
machineName: currentMachineName,
|
|
3765
|
-
createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3766
|
-
});
|
|
3767
|
-
await mkdir(dataDirectory, { recursive: true, mode: 448 });
|
|
3768
|
-
if (canonicalId === void 0) {
|
|
3769
|
-
await writePrivateFile(stablePath, `${identity.stableDeviceId}
|
|
3770
|
-
`, false);
|
|
3771
|
-
}
|
|
3772
|
-
if (existing === void 0 || existing.schemaVersion !== 2 || existing.machineName !== identity.machineName || existing.stableDeviceId !== identity.stableDeviceId) {
|
|
3773
|
-
await writePrivateFile(path, `${JSON.stringify(identity, null, 2)}
|
|
3774
|
-
`, existing !== void 0);
|
|
3775
|
-
}
|
|
3776
|
-
return identity;
|
|
3777
|
-
}
|
|
3778
|
-
|
|
3779
|
-
// src/pairing-qr.ts
|
|
3780
|
-
import qrcode from "qrcode-terminal";
|
|
3781
|
-
function printPairingQr(uri, expiresAt) {
|
|
3782
|
-
qrcode.generate(uri, { small: true }, (image) => {
|
|
3783
|
-
const expires = new Date(expiresAt).toLocaleTimeString();
|
|
3784
|
-
process.stdout.write(
|
|
3785
|
-
`
|
|
3786
|
-
Pair this PC with AgentKnight Android (expires ${expires}):
|
|
3787
|
-
${image}
|
|
3788
|
-
`
|
|
3789
|
-
);
|
|
3790
|
-
});
|
|
3791
|
-
}
|
|
3792
|
-
|
|
3793
|
-
// src/start-client.ts
|
|
3794
|
-
async function startClient(appVersion, cliOptions, resolved, cliPath) {
|
|
3795
|
-
clearClientConfiguration(process.env);
|
|
3796
|
-
Object.assign(process.env, resolved.environment);
|
|
3797
|
-
const settings2 = loadStartupConfig(resolved.environment, cliOptions);
|
|
3798
|
-
const upgradeId = cliOptions.command === "login" ? void 0 : await claimUpgradeStartup(settings2.dataDirectory, appVersion, cliPath);
|
|
3799
|
-
let diagnostics;
|
|
3800
|
-
let logger;
|
|
3801
|
-
try {
|
|
3802
|
-
diagnostics = createDiagnosticLogger(settings2.dataDirectory, settings2.logLevel, { version: appVersion });
|
|
3803
|
-
logger = diagnostics.logger;
|
|
3804
|
-
} catch (error) {
|
|
3805
|
-
logger = pino2({
|
|
3806
|
-
level: settings2.logLevel,
|
|
3807
|
-
base: { component: "pc-agent" }
|
|
3808
|
-
});
|
|
3809
|
-
logger.warn(
|
|
3810
|
-
{ error: toErrorDetails(error) },
|
|
3811
|
-
"pc-agent.diagnostics.file-disabled"
|
|
3812
|
-
);
|
|
3813
|
-
}
|
|
3814
|
-
logger.info(
|
|
3815
|
-
{
|
|
3816
|
-
diagnosticLogPath: diagnostics?.logPath,
|
|
3817
|
-
node: process.version,
|
|
3818
|
-
platform: process.platform,
|
|
3819
|
-
architecture: process.arch
|
|
3820
|
-
},
|
|
3821
|
-
"pc-agent.diagnostics.ready"
|
|
3822
|
-
);
|
|
3823
|
-
let agent;
|
|
3824
|
-
let identityHash = "initializing";
|
|
3825
|
-
const configHash = resolved.envFile === void 0 ? void 0 : await fileHash(resolved.envFile);
|
|
3826
|
-
const restart = restartEnvironment(
|
|
3827
|
-
resolved.environment,
|
|
3828
|
-
resolved.envFile === void 0 ? {} : parseEnv(readFileSync(resolved.envFile, "utf8")),
|
|
3829
|
-
settings2.dataDirectory
|
|
3830
|
-
);
|
|
3831
|
-
const restartArgs = [
|
|
3832
|
-
...cliOptions.noEnv ? ["--no-env"] : [],
|
|
3833
|
-
...resolved.envFile === void 0 ? [] : ["--env", resolved.envFile],
|
|
3834
|
-
...cliOptions.agents === void 0 ? [] : ["--agents", cliOptions.agents.length === 0 ? "none" : cliOptions.agents.join(",")]
|
|
3835
|
-
];
|
|
3836
|
-
const relayDisplay = new URL(settings2.relayUrl);
|
|
3837
|
-
relayDisplay.username = "";
|
|
3838
|
-
relayDisplay.password = "";
|
|
3839
|
-
relayDisplay.search = "";
|
|
3840
|
-
relayDisplay.hash = "";
|
|
3841
|
-
const control = await startRuntimeControl({
|
|
3842
|
-
directory: settings2.dataDirectory,
|
|
3843
|
-
...upgradeId === void 0 ? {} : { upgradeId },
|
|
3844
|
-
getStatus: async () => ({
|
|
3845
|
-
version: appVersion,
|
|
3846
|
-
...agent === void 0 ? { ready: false, busy: true } : await agent.getUpgradeStatus(),
|
|
3847
|
-
relayUrl: relayDisplay.toString(),
|
|
3848
|
-
identityHash,
|
|
3849
|
-
...resolved.envFile === void 0 ? {} : { configPath: resolved.envFile },
|
|
3850
|
-
...configHash === void 0 ? {} : { configHash },
|
|
3851
|
-
executable: process.execPath,
|
|
3852
|
-
cliPath,
|
|
3853
|
-
cwd: process.cwd(),
|
|
3854
|
-
args: restartArgs,
|
|
3855
|
-
canRestart: restart.canRestart,
|
|
3856
|
-
restartEnvironment: restart.environment,
|
|
3857
|
-
stopping: agent?.isStopping ?? false,
|
|
3858
|
-
...upgradeId === void 0 ? {} : { upgradeId }
|
|
3859
|
-
}),
|
|
3860
|
-
prepare: async () => {
|
|
3861
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3862
|
-
await agent.prepareForUpgrade();
|
|
3863
|
-
},
|
|
3864
|
-
cancel: () => agent?.cancelUpgrade(),
|
|
3865
|
-
stop: async () => {
|
|
3866
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3867
|
-
await agent.stopForUpgrade();
|
|
3868
|
-
},
|
|
3869
|
-
runPeerChat: async (request, signal) => {
|
|
3870
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3871
|
-
return agent.runPeerChat(request, signal);
|
|
3872
|
-
},
|
|
3873
|
-
onError: (error) => logger.warn({ error: toErrorDetails(error) }, "pc-agent.control.failed")
|
|
3874
|
-
});
|
|
3875
|
-
let retainedPairingPage;
|
|
3876
|
-
let relayCredential;
|
|
3877
|
-
try {
|
|
3878
|
-
const identity = settings2.machineName === void 0 ? await loadOrCreateDeviceIdentity(settings2.dataDirectory) : await loadOrCreateDeviceIdentity(
|
|
3879
|
-
settings2.dataDirectory,
|
|
3880
|
-
settings2.machineName
|
|
3881
|
-
);
|
|
3882
|
-
const loginAbort = new AbortController();
|
|
3883
|
-
const abortLogin = () => loginAbort.abort(new Error("Microsoft sign-in cancelled."));
|
|
3884
|
-
process.once("SIGINT", abortLogin);
|
|
3885
|
-
process.once("SIGTERM", abortLogin);
|
|
3886
|
-
try {
|
|
3887
|
-
relayCredential = await completeRelayLogin({
|
|
3888
|
-
settings: settings2,
|
|
3889
|
-
identity,
|
|
3890
|
-
force: cliOptions.command === "login",
|
|
3891
|
-
signal: loginAbort.signal,
|
|
3892
|
-
report: (message) => process.stdout.write(`${message}
|
|
3893
|
-
`),
|
|
3894
|
-
onAuthorizedPage: (page) => {
|
|
3895
|
-
retainedPairingPage = page;
|
|
3896
|
-
}
|
|
3897
|
-
});
|
|
3898
|
-
} finally {
|
|
3899
|
-
process.off("SIGINT", abortLogin);
|
|
3900
|
-
process.off("SIGTERM", abortLogin);
|
|
3901
|
-
}
|
|
3902
|
-
if (cliOptions.command === "login") {
|
|
3903
|
-
process.stdout.write("Microsoft sign-in saved. Start AgentKnight to connect and pair.\n");
|
|
3904
|
-
return;
|
|
3905
|
-
}
|
|
3906
|
-
const config = loadConfig(resolved.environment, {
|
|
3907
|
-
...cliOptions,
|
|
3908
|
-
...relayCredential === void 0 ? {} : { relayCredential }
|
|
3909
|
-
});
|
|
3910
|
-
config.dataDirectory = resolve(config.dataDirectory);
|
|
3911
|
-
if (retainedPairingPage !== void 0) config.pairingPagePort = Number(new URL(retainedPairingPage.url).port);
|
|
3912
|
-
const groupChatSettings = await ChatSettings.load(config.dataDirectory, config.groupChatEnabled !== false);
|
|
3913
|
-
config.groupChatEnabled = groupChatSettings.enabled;
|
|
3914
|
-
const peerChatSettings = await ChatSettings.load(config.dataDirectory, config.peerChatEnabled !== false, "peerChatEnabled");
|
|
3915
|
-
config.peerChatEnabled = peerChatSettings.enabled;
|
|
3916
|
-
const imageSettings = await ImageSettings.load(config.dataDirectory, config.relayUrl, config.sessionImagesEnabled);
|
|
3917
|
-
config.sessionImagesEnabled = imageSettings.enabled;
|
|
3918
|
-
const { initialize, supportsAgentSelection } = await import("@agentknight/sdk");
|
|
3919
|
-
const runningAgent = await initialize({
|
|
3920
|
-
...config,
|
|
3921
|
-
identity,
|
|
3922
|
-
appVersion,
|
|
3923
|
-
logger,
|
|
3924
|
-
directoryLease: control.directoryLease,
|
|
3925
|
-
...config.showPairingQr && process.stdout.isTTY ? {
|
|
3926
|
-
onPairing: (ticket) => printPairingQr(ticket.uri, ticket.expiresAt)
|
|
3927
|
-
} : {}
|
|
3928
|
-
});
|
|
3929
|
-
const { adapter, pairingProvider } = runningAgent;
|
|
3930
|
-
agent = runningAgent;
|
|
3931
|
-
identityHash = runningAgent.identityHash;
|
|
3932
|
-
if (upgradeId !== void 0) runningAgent.holdUpgradeStartup();
|
|
3933
|
-
const setGroupChatEnabled = adapter.setGroupChatEnabled?.bind(adapter);
|
|
3934
|
-
const relayAuthMethod = relayCredential?.authentication?.mode ?? settings2.relayAuthentication.mode;
|
|
3935
|
-
if (relayAuthMethod === "auto") throw new Error("Relay authentication discovery must finish before connecting.");
|
|
3936
|
-
const relayAccount = new RelayAccount({
|
|
3937
|
-
config,
|
|
3938
|
-
machineId: identity.machineId,
|
|
3939
|
-
method: relayAuthMethod,
|
|
3940
|
-
...relayCredential === void 0 ? {} : { user: relayCredential.user }
|
|
3941
|
-
});
|
|
3942
|
-
let pairingPage;
|
|
3943
|
-
if (config.pairingPageEnabled) {
|
|
3944
|
-
const { createLocalSessions } = await import("./local-sessions-T4LOKU66.js");
|
|
3945
|
-
const pageOptions = {
|
|
3946
|
-
machineName: identity.machineName,
|
|
3947
|
-
port: config.pairingPagePort,
|
|
3948
|
-
pairingProvider,
|
|
3949
|
-
sessions: createLocalSessions(adapter, { userId: config.userId, machineId: identity.machineId }),
|
|
3950
|
-
getRegistrationStatus: () => runningAgent.relayRegistrationStatus,
|
|
3951
|
-
imageSettings: {
|
|
3952
|
-
get available() {
|
|
3953
|
-
return runningAgent.sessionImageStorage !== void 0;
|
|
3954
|
-
},
|
|
3955
|
-
get enabled() {
|
|
3956
|
-
return imageSettings.enabled;
|
|
3957
|
-
},
|
|
3958
|
-
save: (enabled) => runningAgent.runLocalMutation(() => imageSettings.save(enabled, (value) => runningAgent.setSessionImagesEnabled(value)))
|
|
3959
|
-
},
|
|
3960
|
-
reconnectRelay: () => runningAgent.reconnectRelay(),
|
|
3961
|
-
disconnectRelay: () => runningAgent.disconnectRelay(),
|
|
3962
|
-
getAccount: () => relayAccount.read(runningAgent.relayRegistrationStatus),
|
|
3963
|
-
getDeploymentInfo: async () => {
|
|
3964
|
-
const lastUpgrade = await readLastUpgrade(config.dataDirectory);
|
|
3965
|
-
return {
|
|
3966
|
-
version: appVersion,
|
|
3967
|
-
relayUrl: config.relayUrl,
|
|
3968
|
-
...resolved.envFile === void 0 ? {} : { configPath: resolved.envFile },
|
|
3969
|
-
...lastUpgrade === void 0 ? {} : { upgradedAt: lastUpgrade.upgradedAt }
|
|
3970
|
-
};
|
|
3971
|
-
},
|
|
3972
|
-
...supportsAgentSelection(adapter) ? {
|
|
3973
|
-
agentSelection: {
|
|
3974
|
-
listAgents: () => adapter.listAgents(),
|
|
3975
|
-
saveSelection: (selection) => runningAgent.runLocalMutation(() => adapter.saveSelection(selection))
|
|
3976
|
-
}
|
|
3977
|
-
} : {},
|
|
3978
|
-
...setGroupChatEnabled === void 0 ? {} : {
|
|
3979
|
-
groupChatSettings: {
|
|
3980
|
-
get enabled() {
|
|
3981
|
-
return groupChatSettings.enabled;
|
|
3982
|
-
},
|
|
3983
|
-
save: (enabled) => runningAgent.runLocalMutation(() => groupChatSettings.save(enabled, setGroupChatEnabled))
|
|
3984
|
-
}
|
|
3985
|
-
},
|
|
3986
|
-
...adapter.setPeerChatEnabled === void 0 ? {} : {
|
|
3987
|
-
peerChatSettings: {
|
|
3988
|
-
get enabled() {
|
|
3989
|
-
return peerChatSettings.enabled;
|
|
3990
|
-
},
|
|
3991
|
-
save: (enabled) => runningAgent.runLocalMutation(() => peerChatSettings.save(enabled, (value) => runningAgent.setPeerChatEnabled(value)))
|
|
3992
|
-
}
|
|
3993
|
-
},
|
|
3994
|
-
logger
|
|
3995
|
-
};
|
|
3996
|
-
pairingPage = retainedPairingPage === void 0 ? new PairingPageServer(pageOptions) : retainedPairingPage.useRuntime(pageOptions);
|
|
3997
|
-
}
|
|
3998
|
-
let stopping = false;
|
|
3999
|
-
async function stop(reason) {
|
|
4000
|
-
if (stopping) {
|
|
4001
|
-
return;
|
|
4002
|
-
}
|
|
4003
|
-
stopping = true;
|
|
4004
|
-
logger.info({ reason }, "pc-agent.stopping");
|
|
4005
|
-
const results = await Promise.allSettled([runningAgent.stop(), pairingPage?.stop()]);
|
|
4006
|
-
const errors = results.filter(
|
|
4007
|
-
(result) => result.status === "rejected"
|
|
4008
|
-
).map((result) => result.reason);
|
|
4009
|
-
if (errors.length > 0) {
|
|
4010
|
-
throw new AggregateError(errors, "Failed to stop PC Agent resources");
|
|
4011
|
-
}
|
|
4012
|
-
}
|
|
4013
|
-
process.once("SIGINT", () => {
|
|
4014
|
-
void stop("SIGINT").catch((error) => {
|
|
4015
|
-
logger.error({ error: toErrorDetails(error) }, "pc-agent.stop.failed");
|
|
4016
|
-
});
|
|
4017
|
-
});
|
|
4018
|
-
process.once("SIGTERM", () => {
|
|
4019
|
-
void stop("SIGTERM").catch((error) => {
|
|
4020
|
-
logger.error({ error: toErrorDetails(error) }, "pc-agent.stop.failed");
|
|
4021
|
-
});
|
|
4022
|
-
});
|
|
4023
|
-
try {
|
|
4024
|
-
await pairingPage?.start();
|
|
4025
|
-
if (pairingPage !== void 0) {
|
|
4026
|
-
logger.info({ url: pairingPage.url }, "mobile.pairing-page.listening");
|
|
4027
|
-
}
|
|
4028
|
-
await runningAgent.start();
|
|
4029
|
-
await runningAgent.waitUntilStopped();
|
|
4030
|
-
await stop("normal-completion");
|
|
4031
|
-
} catch (error) {
|
|
4032
|
-
logger.fatal({ error: toErrorDetails(error) }, "pc-agent.failed");
|
|
4033
|
-
process.exitCode = 1;
|
|
4034
|
-
await stop("startup-failure").catch((stopError) => {
|
|
4035
|
-
logger.error(
|
|
4036
|
-
{ error: toErrorDetails(stopError) },
|
|
4037
|
-
"pc-agent.stop.failed"
|
|
4038
|
-
);
|
|
4039
|
-
});
|
|
4040
|
-
}
|
|
4041
|
-
} finally {
|
|
4042
|
-
try {
|
|
4043
|
-
try {
|
|
4044
|
-
await agent?.stop();
|
|
4045
|
-
} finally {
|
|
4046
|
-
try {
|
|
4047
|
-
await retainedPairingPage?.stop();
|
|
4048
|
-
} finally {
|
|
4049
|
-
await relayCredential?.close?.();
|
|
4050
|
-
}
|
|
4051
|
-
}
|
|
4052
|
-
} finally {
|
|
4053
|
-
await control.close();
|
|
4054
|
-
if (diagnostics !== void 0) {
|
|
4055
|
-
try {
|
|
4056
|
-
await diagnostics.close();
|
|
4057
|
-
} catch (error) {
|
|
4058
|
-
process.stderr.write(
|
|
4059
|
-
`Unable to close PC diagnostic log: ${toErrorDetails(error).message}
|
|
4060
|
-
`
|
|
4061
|
-
);
|
|
4062
|
-
}
|
|
4063
|
-
}
|
|
4064
|
-
}
|
|
4065
|
-
}
|
|
4066
|
-
}
|
|
4067
|
-
export {
|
|
4068
|
-
startClient
|
|
4069
|
-
};
|