@agentknight/client 0.9.49 → 0.9.51
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/LICENSE +201 -201
- package/README.md +356 -341
- package/dist/chunks/aad-relay-login-NABH6HML.js +14 -0
- package/dist/chunks/{chunk-OZKXJ6L4.js → chunk-HWCSV7QP.js} +1305 -1087
- package/dist/chunks/{chunk-NHA7HI6P.js → chunk-WS6ISEXX.js} +1 -1
- package/dist/chunks/chunk-XODJ7TIT.js +475 -0
- package/dist/chunks/{local-sessions-EZUANCR4.js → local-sessions-CLY45IWB.js} +1 -1
- package/dist/chunks/start-client-XMBDUDJZ.js +3971 -0
- package/dist/cli.js +12 -5
- package/dist/upgrade-worker.js +200 -4
- package/package.json +14 -6
- package/dist/chunks/start-client-C3PK6POG.js +0 -3428
|
@@ -1,3428 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
readAppVersion,
|
|
4
|
-
toErrorDetails
|
|
5
|
-
} from "./chunk-NHA7HI6P.js";
|
|
6
|
-
import {
|
|
7
|
-
claimUpgradeStartup,
|
|
8
|
-
fileHash,
|
|
9
|
-
restartEnvironment
|
|
10
|
-
} from "./chunk-KYTI7A5R.js";
|
|
11
|
-
import {
|
|
12
|
-
clearClientConfiguration,
|
|
13
|
-
defaultClientHome,
|
|
14
|
-
defaultPairingPagePort,
|
|
15
|
-
normalizeClientEnvironment,
|
|
16
|
-
sameClientPath
|
|
17
|
-
} from "./chunk-YNKNHR5K.js";
|
|
18
|
-
import {
|
|
19
|
-
startRuntimeControl
|
|
20
|
-
} from "./chunk-WZIU4HVH.js";
|
|
21
|
-
import {
|
|
22
|
-
readLastUpgrade,
|
|
23
|
-
readOptionalJson,
|
|
24
|
-
writePrivateJson
|
|
25
|
-
} from "./chunk-SPZWIFFP.js";
|
|
26
|
-
import {
|
|
27
|
-
AuthUserSchema,
|
|
28
|
-
MicrosoftEnrollmentFailureSchema,
|
|
29
|
-
MicrosoftMutationResultSchema,
|
|
30
|
-
PairingStatusRequestSchema,
|
|
31
|
-
PcAccountRequestSchema,
|
|
32
|
-
PcAccountResultSchema,
|
|
33
|
-
PcBrowserAuthorizationCallbackSchema,
|
|
34
|
-
PcBrowserAuthorizationStartRequestSchema,
|
|
35
|
-
PcBrowserAuthorizationStartResultSchema,
|
|
36
|
-
PcBrowserRedirectUriSchema,
|
|
37
|
-
PcEnrollmentExchangeResultSchema,
|
|
38
|
-
PcEnrollmentIdSchema,
|
|
39
|
-
PcEnrollmentStartRequestSchema,
|
|
40
|
-
PcEnrollmentVerifierRequestSchema,
|
|
41
|
-
SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH,
|
|
42
|
-
SessionTimelinePageRequestSchema,
|
|
43
|
-
SessionTimelinePageSchema
|
|
44
|
-
} from "./chunk-OZKXJ6L4.js";
|
|
45
|
-
|
|
46
|
-
// src/start-client.ts
|
|
47
|
-
import { readFileSync } from "node:fs";
|
|
48
|
-
import { resolve as resolve2 } from "node:path";
|
|
49
|
-
import { parseEnv } from "node:util";
|
|
50
|
-
import pino2 from "pino";
|
|
51
|
-
|
|
52
|
-
// src/config.ts
|
|
53
|
-
import { z } from "zod";
|
|
54
|
-
import {
|
|
55
|
-
AgentSelectionSchema,
|
|
56
|
-
CODING_AGENT_IDS,
|
|
57
|
-
SessionImageRelayUrlSchema,
|
|
58
|
-
SessionImagesConfigSchema
|
|
59
|
-
} from "@agentknight/sdk/configuration";
|
|
60
|
-
var BooleanStringSchema = z.enum(["true", "false"]).default("false").transform((value) => value === "true");
|
|
61
|
-
var EnabledBooleanStringSchema = z.enum(["true", "false"]).default("true").transform((value) => value === "true");
|
|
62
|
-
var OptionalPathSchema = z.preprocess(
|
|
63
|
-
(value) => typeof value === "string" && value.trim() === "" ? void 0 : value,
|
|
64
|
-
z.string().trim().min(1).optional()
|
|
65
|
-
);
|
|
66
|
-
var AcpArgumentsSchema = z.string().default("[]").transform((value, context) => {
|
|
67
|
-
let decoded;
|
|
68
|
-
try {
|
|
69
|
-
decoded = JSON.parse(value);
|
|
70
|
-
} catch (error) {
|
|
71
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
72
|
-
context.addIssue({ code: "custom", message: "AGENTKNIGHT_ACP_ARGS must be a JSON array of strings" });
|
|
73
|
-
return z.NEVER;
|
|
74
|
-
}
|
|
75
|
-
const parsed = z.array(z.string()).max(128).safeParse(decoded);
|
|
76
|
-
if (!parsed.success) {
|
|
77
|
-
context.addIssue({ code: "custom", message: "AGENTKNIGHT_ACP_ARGS must be a JSON array of strings" });
|
|
78
|
-
return z.NEVER;
|
|
79
|
-
}
|
|
80
|
-
return parsed.data;
|
|
81
|
-
});
|
|
82
|
-
var EnvironmentSchema = z.object({
|
|
83
|
-
RELAY_URL: z.url(),
|
|
84
|
-
RELAY_TOKEN: z.string().min(24).optional(),
|
|
85
|
-
RELAY_AUTH: z.enum(["token", "microsoft"]).optional(),
|
|
86
|
-
USER_ID: z.string().trim().min(1).max(256).default("admin"),
|
|
87
|
-
AGENTKNIGHT_MACHINE_NAME: z.string().trim().min(1).max(120).optional(),
|
|
88
|
-
AGENTKNIGHT_HOME: z.string().trim().min(1).optional(),
|
|
89
|
-
AGENTKNIGHT_WORKSPACE_ROOT: z.string().trim().min(1).optional(),
|
|
90
|
-
AGENTKNIGHT_CODING_AGENT: z.enum(["managed", ...CODING_AGENT_IDS]).default("managed"),
|
|
91
|
-
AGENTKNIGHT_GROUP_CHAT_ENABLED: EnabledBooleanStringSchema,
|
|
92
|
-
AGENTKNIGHT_PEER_CHAT_ENABLED: EnabledBooleanStringSchema,
|
|
93
|
-
PI_CODING_AGENT_DIR: OptionalPathSchema,
|
|
94
|
-
AGENTKNIGHT_CODEX_COMMAND: OptionalPathSchema,
|
|
95
|
-
AGENTKNIGHT_ACP_COMMAND: OptionalPathSchema,
|
|
96
|
-
AGENTKNIGHT_ACP_ARGS: AcpArgumentsSchema,
|
|
97
|
-
SESSION_REFRESH_INTERVAL_MS: z.coerce.number().int().min(5e3).max(36e5).default(3e4),
|
|
98
|
-
HEARTBEAT_INTERVAL_MS: z.coerce.number().int().min(5e3).max(12e4).default(15e3),
|
|
99
|
-
LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
|
|
100
|
-
SHOW_PAIRING_QR: BooleanStringSchema,
|
|
101
|
-
PAIRING_PAGE_ENABLED: EnabledBooleanStringSchema,
|
|
102
|
-
PAIRING_PAGE_PORT: z.coerce.number().int().min(1024).max(65535).default(defaultPairingPagePort),
|
|
103
|
-
PC_AGENT_EXIT_AFTER_SNAPSHOT: BooleanStringSchema,
|
|
104
|
-
SNAPSHOT_SUPPRESSION_ENABLED: EnabledBooleanStringSchema,
|
|
105
|
-
TIMELINE_COMPRESSION_ENABLED: BooleanStringSchema,
|
|
106
|
-
TIMELINE_INCREMENTAL_ENABLED: EnabledBooleanStringSchema,
|
|
107
|
-
SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE: EnabledBooleanStringSchema,
|
|
108
|
-
SESSION_IMAGES_STORAGE_ACCOUNT: SessionImagesConfigSchema.shape.storageAccount.default("agentknightimagesbsp09"),
|
|
109
|
-
SESSION_IMAGES_STORAGE_CONTAINER: SessionImagesConfigSchema.shape.storageContainer.optional(),
|
|
110
|
-
SECURE_MESSAGE_PACKET_BUDGET: z.coerce.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).default(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH)
|
|
111
|
-
}).superRefine((value, context) => {
|
|
112
|
-
if (value.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE) {
|
|
113
|
-
if (!SessionImageRelayUrlSchema.safeParse(value.RELAY_URL).success) {
|
|
114
|
-
context.addIssue({
|
|
115
|
-
code: "custom",
|
|
116
|
-
path: ["RELAY_URL"],
|
|
117
|
-
message: "Session images require an HTTPS Relay origin without a path, credentials, query or fragment"
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
if (value.RELAY_AUTH === "token" && value.RELAY_TOKEN === void 0) {
|
|
122
|
-
context.addIssue({ code: "custom", path: ["RELAY_TOKEN"], message: "Token authentication requires RELAY_TOKEN" });
|
|
123
|
-
}
|
|
124
|
-
if (value.AGENTKNIGHT_CODING_AGENT === "acp" && value.AGENTKNIGHT_ACP_COMMAND === void 0) {
|
|
125
|
-
context.addIssue({
|
|
126
|
-
code: "custom",
|
|
127
|
-
path: ["AGENTKNIGHT_ACP_COMMAND"],
|
|
128
|
-
message: "ACP requires an installed agent executable in AGENTKNIGHT_ACP_COMMAND"
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
function codingAgentConfig(environment) {
|
|
133
|
-
switch (environment.AGENTKNIGHT_CODING_AGENT) {
|
|
134
|
-
case "managed":
|
|
135
|
-
return {
|
|
136
|
-
kind: "managed",
|
|
137
|
-
...environment.AGENTKNIGHT_CODEX_COMMAND === void 0 ? {} : { codexCommand: environment.AGENTKNIGHT_CODEX_COMMAND },
|
|
138
|
-
...environment.PI_CODING_AGENT_DIR === void 0 ? {} : { piDirectory: environment.PI_CODING_AGENT_DIR },
|
|
139
|
-
...environment.AGENTKNIGHT_ACP_COMMAND === void 0 ? {} : {
|
|
140
|
-
acp: { command: environment.AGENTKNIGHT_ACP_COMMAND, args: environment.AGENTKNIGHT_ACP_ARGS }
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
case "copilot":
|
|
144
|
-
return { kind: "copilot" };
|
|
145
|
-
case "pi":
|
|
146
|
-
return {
|
|
147
|
-
kind: "pi",
|
|
148
|
-
...environment.PI_CODING_AGENT_DIR === void 0 ? {} : { agentDirectory: environment.PI_CODING_AGENT_DIR }
|
|
149
|
-
};
|
|
150
|
-
case "codex":
|
|
151
|
-
return {
|
|
152
|
-
kind: "codex",
|
|
153
|
-
...environment.AGENTKNIGHT_CODEX_COMMAND === void 0 ? {} : { command: environment.AGENTKNIGHT_CODEX_COMMAND }
|
|
154
|
-
};
|
|
155
|
-
case "claude":
|
|
156
|
-
return { kind: "claude" };
|
|
157
|
-
case "acp":
|
|
158
|
-
if (environment.AGENTKNIGHT_ACP_COMMAND === void 0) {
|
|
159
|
-
throw new Error("AGENTKNIGHT_ACP_COMMAND is required");
|
|
160
|
-
}
|
|
161
|
-
return {
|
|
162
|
-
kind: "acp",
|
|
163
|
-
command: environment.AGENTKNIGHT_ACP_COMMAND,
|
|
164
|
-
args: environment.AGENTKNIGHT_ACP_ARGS
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
function loadConfig(environment = process.env, options = {}) {
|
|
169
|
-
const { relayAuthentication, ...settings2 } = loadStartupConfig(environment, options);
|
|
170
|
-
if (relayAuthentication.mode === "token") {
|
|
171
|
-
return { ...settings2, relayToken: relayAuthentication.token, userId: relayAuthentication.userId };
|
|
172
|
-
}
|
|
173
|
-
if (options.relayCredential === void 0) {
|
|
174
|
-
throw new Error("Sign in with Microsoft on the local AgentKnight page before connecting to Relay.");
|
|
175
|
-
}
|
|
176
|
-
return {
|
|
177
|
-
...settings2,
|
|
178
|
-
relayToken: z.string().min(32).max(4096).parse(options.relayCredential.token),
|
|
179
|
-
userId: z.string().min(1).max(256).parse(options.relayCredential.user.userId)
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
function loadStartupConfig(environment = process.env, options = {}) {
|
|
183
|
-
const normalizedEnvironment = normalizeClientEnvironment(environment);
|
|
184
|
-
if (normalizedEnvironment.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE === void 0 && !SessionImageRelayUrlSchema.safeParse(normalizedEnvironment.RELAY_URL).success) {
|
|
185
|
-
normalizedEnvironment.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE = "false";
|
|
186
|
-
}
|
|
187
|
-
const initialSelection = options.agents === void 0 ? void 0 : AgentSelectionSchema.parse({ agents: options.agents });
|
|
188
|
-
const startupEnvironment = normalizedEnvironment.RELAY_AUTH === "microsoft" ? { ...normalizedEnvironment, RELAY_TOKEN: void 0, USER_ID: void 0 } : normalizedEnvironment;
|
|
189
|
-
const parsed = EnvironmentSchema.parse(initialSelection === void 0 ? startupEnvironment : { ...startupEnvironment, AGENTKNIGHT_CODING_AGENT: "managed" });
|
|
190
|
-
const engine = codingAgentConfig(parsed);
|
|
191
|
-
return {
|
|
192
|
-
relayUrl: parsed.RELAY_URL,
|
|
193
|
-
relayAuthentication: parsed.RELAY_AUTH === "microsoft" || parsed.RELAY_TOKEN === void 0 ? { mode: "microsoft" } : { mode: "token", token: parsed.RELAY_TOKEN, userId: parsed.USER_ID },
|
|
194
|
-
...parsed.AGENTKNIGHT_MACHINE_NAME === void 0 ? {} : { machineName: parsed.AGENTKNIGHT_MACHINE_NAME },
|
|
195
|
-
...parsed.AGENTKNIGHT_WORKSPACE_ROOT === void 0 ? {} : { workspaceRoot: parsed.AGENTKNIGHT_WORKSPACE_ROOT },
|
|
196
|
-
dataDirectory: parsed.AGENTKNIGHT_HOME ?? defaultClientHome(),
|
|
197
|
-
refreshIntervalMs: parsed.SESSION_REFRESH_INTERVAL_MS,
|
|
198
|
-
heartbeatIntervalMs: parsed.HEARTBEAT_INTERVAL_MS,
|
|
199
|
-
logLevel: parsed.LOG_LEVEL,
|
|
200
|
-
showPairingQr: parsed.SHOW_PAIRING_QR,
|
|
201
|
-
pairingPageEnabled: parsed.PAIRING_PAGE_ENABLED,
|
|
202
|
-
pairingPagePort: parsed.PAIRING_PAGE_PORT,
|
|
203
|
-
exitAfterSnapshot: parsed.PC_AGENT_EXIT_AFTER_SNAPSHOT,
|
|
204
|
-
codingAgent: engine.kind === "managed" && initialSelection !== void 0 ? { ...engine, initialSelection } : engine,
|
|
205
|
-
groupChatEnabled: parsed.AGENTKNIGHT_GROUP_CHAT_ENABLED,
|
|
206
|
-
peerChatEnabled: parsed.AGENTKNIGHT_PEER_CHAT_ENABLED,
|
|
207
|
-
snapshotSuppressionEnabled: parsed.SNAPSHOT_SUPPRESSION_ENABLED,
|
|
208
|
-
timelineCompressionEnabled: parsed.TIMELINE_COMPRESSION_ENABLED,
|
|
209
|
-
timelineIncrementalEnabled: parsed.TIMELINE_INCREMENTAL_ENABLED,
|
|
210
|
-
secureMessagePacketBudget: parsed.SECURE_MESSAGE_PACKET_BUDGET,
|
|
211
|
-
...parsed.SESSION_IMAGES_ALLOW_UNENCRYPTED_STORAGE ? {
|
|
212
|
-
sessionImages: SessionImagesConfigSchema.parse({
|
|
213
|
-
allowUnencryptedStorage: true,
|
|
214
|
-
storageAccount: parsed.SESSION_IMAGES_STORAGE_ACCOUNT,
|
|
215
|
-
storageContainer: parsed.SESSION_IMAGES_STORAGE_CONTAINER ?? "session-images"
|
|
216
|
-
})
|
|
217
|
-
} : {}
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// src/pairing-page.ts
|
|
222
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
223
|
-
import { createServer } from "node:http";
|
|
224
|
-
import QRCode from "qrcode";
|
|
225
|
-
import { AgentSelectionSchema as AgentSelectionSchema2 } from "@agentknight/sdk/configuration";
|
|
226
|
-
|
|
227
|
-
// src/agent-selection-page.ts
|
|
228
|
-
import { codingAgentPresentation } from "@agentknight/sdk/configuration";
|
|
229
|
-
|
|
230
|
-
// src/local-page-html.ts
|
|
231
|
-
function escapeHtml(value) {
|
|
232
|
-
return value.replace(/[&<>"']/g, (character) => {
|
|
233
|
-
switch (character) {
|
|
234
|
-
case "&":
|
|
235
|
-
return "&";
|
|
236
|
-
case "<":
|
|
237
|
-
return "<";
|
|
238
|
-
case ">":
|
|
239
|
-
return ">";
|
|
240
|
-
case '"':
|
|
241
|
-
return """;
|
|
242
|
-
case "'":
|
|
243
|
-
return "'";
|
|
244
|
-
default:
|
|
245
|
-
return character;
|
|
246
|
-
}
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
function relayDisplayUrl(value) {
|
|
250
|
-
let url;
|
|
251
|
-
try {
|
|
252
|
-
url = new URL(value);
|
|
253
|
-
} catch {
|
|
254
|
-
return "\u2014";
|
|
255
|
-
}
|
|
256
|
-
if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) return "\u2014";
|
|
257
|
-
url.username = "";
|
|
258
|
-
url.password = "";
|
|
259
|
-
url.search = "";
|
|
260
|
-
url.hash = "";
|
|
261
|
-
return url.href;
|
|
262
|
-
}
|
|
263
|
-
function relayAccountUrl(value) {
|
|
264
|
-
let url;
|
|
265
|
-
try {
|
|
266
|
-
url = new URL(relayDisplayUrl(value));
|
|
267
|
-
} catch {
|
|
268
|
-
return void 0;
|
|
269
|
-
}
|
|
270
|
-
if (url.protocol === "wss:") url.protocol = "https:";
|
|
271
|
-
if (url.protocol === "ws:") url.protocol = "http:";
|
|
272
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname))) {
|
|
273
|
-
return void 0;
|
|
274
|
-
}
|
|
275
|
-
return new URL("/account", url).href;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// src/session-markdown.ts
|
|
279
|
-
import MarkdownIt from "markdown-it";
|
|
280
|
-
var markdown = new MarkdownIt({ html: false, breaks: true });
|
|
281
|
-
markdown.validateLink = (value) => {
|
|
282
|
-
try {
|
|
283
|
-
const url = new URL(value);
|
|
284
|
-
return ["https:", "http:"].includes(url.protocol) && !url.username && !url.password;
|
|
285
|
-
} catch {
|
|
286
|
-
return false;
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => {
|
|
290
|
-
const token = tokens[index];
|
|
291
|
-
if (token === void 0) throw new Error("Missing Markdown link token");
|
|
292
|
-
token.attrSet("target", "_blank");
|
|
293
|
-
token.attrSet("rel", "noopener noreferrer");
|
|
294
|
-
return renderer.renderToken(tokens, index, options);
|
|
295
|
-
};
|
|
296
|
-
markdown.renderer.rules.image = (tokens, index) => {
|
|
297
|
-
const token = tokens[index];
|
|
298
|
-
if (token === void 0) throw new Error("Missing Markdown image token");
|
|
299
|
-
const source = String(token.attrGet("src") ?? "");
|
|
300
|
-
const label = escapeHtml(token.content || "\u56FE\u7247");
|
|
301
|
-
return markdown.validateLink(source) ? `<a class="image-link" href="${escapeHtml(source)}" target="_blank" rel="noopener noreferrer">${label} \u2197</a>` : label;
|
|
302
|
-
};
|
|
303
|
-
markdown.renderer.rules.table_open = () => '<div class="table-scroll" tabindex="0" role="region" aria-label="\u8868\u683C"><table>';
|
|
304
|
-
markdown.renderer.rules.table_close = () => "</table></div>";
|
|
305
|
-
function renderSessionMarkdown(content) {
|
|
306
|
-
return markdown.render(content);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// src/session-page.ts
|
|
310
|
-
var icons = {
|
|
311
|
-
back: '<path d="m12 5-7 7 7 7M5 12h14"/>',
|
|
312
|
-
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"/>',
|
|
313
|
-
folder: '<path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v10H3Z"/>',
|
|
314
|
-
info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7v1"/>',
|
|
315
|
-
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"/>',
|
|
316
|
-
agent: '<path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5Z"/>',
|
|
317
|
-
chevron: '<path d="m9 5 7 7-7 7"/>',
|
|
318
|
-
down: '<path d="M12 4v16m-6-6 6 6 6-6"/>',
|
|
319
|
-
file: '<path d="M14 2H5v20h14V7l-5-5Zm0 0v6h5M8 13h8M8 17h6"/>',
|
|
320
|
-
check: '<path d="m5 12 4 4L19 6"/>',
|
|
321
|
-
warning: '<path d="m12 3 10 18H2L12 3Zm0 6v5m0 3v1"/>',
|
|
322
|
-
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'
|
|
323
|
-
};
|
|
324
|
-
function icon(name) {
|
|
325
|
-
return `<svg 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>`;
|
|
326
|
-
}
|
|
327
|
-
function sessionPageUrl(sessionId, cursor) {
|
|
328
|
-
return `/session?${new URLSearchParams({ sessionId, ...cursor === void 0 ? {} : { cursor } })}`;
|
|
329
|
-
}
|
|
330
|
-
function renderSessionLink(session) {
|
|
331
|
-
return `<a class="session-link" href="${escapeHtml(sessionPageUrl(session.id))}">
|
|
332
|
-
<span class="session-symbol">${icon("chat")}</span><span class="session-label">
|
|
333
|
-
<span class="session-name">${escapeHtml(session.name || session.id)}</span></span>
|
|
334
|
-
<span class="session-chevron">${icon("chevron")}</span></a>`;
|
|
335
|
-
}
|
|
336
|
-
function renderSessionGroups(sessions, canRead) {
|
|
337
|
-
const groups = /* @__PURE__ */ new Map();
|
|
338
|
-
for (const session of sessions) {
|
|
339
|
-
const directory = session.workingDirectory || "";
|
|
340
|
-
const group = groups.get(directory);
|
|
341
|
-
if (group === void 0) groups.set(directory, [session]);
|
|
342
|
-
else group.push(session);
|
|
343
|
-
}
|
|
344
|
-
return `<ul class="session-folders">${[...groups].map(([directory, entries]) => {
|
|
345
|
-
const name = directory.split(/[\\/]/).filter(Boolean).at(-1) || directory || "\u672A\u63D0\u4F9B\u76EE\u5F55";
|
|
346
|
-
return `<li><details class="session-folder"><summary>
|
|
347
|
-
<span class="folder-icon">${icon("folder")}</span><span class="folder-label">
|
|
348
|
-
<span class="folder-name">${escapeHtml(name)}</span>${directory && directory !== name ? `<span class="folder-path">${escapeHtml(directory)}</span>` : ""}</span>
|
|
349
|
-
<span class="folder-count" aria-label="${entries.length} \u4E2A\u4F1A\u8BDD">${entries.length}</span>
|
|
350
|
-
<span class="folder-chevron">${icon("chevron")}</span></summary>
|
|
351
|
-
<ul class="sessions" aria-label="${escapeHtml(directory || name)}">${entries.map((session) => `<li class="session">${canRead ? renderSessionLink(session) : `<span class="session-name">${escapeHtml(session.name || session.id)}</span>`}</li>`).join("")}</ul>
|
|
352
|
-
</details></li>`;
|
|
353
|
-
}).join("") || '<li class="empty">\u6CA1\u6709\u672C\u5730\u4F1A\u8BDD</li>'}</ul>`;
|
|
354
|
-
}
|
|
355
|
-
var statusLabels = { running: "\u8FDB\u884C\u4E2D", completed: "\u5DF2\u5B8C\u6210", failed: "\u5931\u8D25" };
|
|
356
|
-
function renderAttachments(attachments = []) {
|
|
357
|
-
return attachments.map((attachment) => {
|
|
358
|
-
const image = attachment.kind === "image" && attachment.data !== void 0 && /^(image\/(png|jpeg|gif|webp))$/.test(attachment.mimeType ?? "");
|
|
359
|
-
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)}">` : icon("file")}<figcaption>${escapeHtml(attachment.name)}${!image && attachment.uri ? `<span class="attachment-path">${escapeHtml(attachment.uri)}</span>` : ""}</figcaption></figure>`;
|
|
360
|
-
}).join("");
|
|
361
|
-
}
|
|
362
|
-
function renderItem(item, agentName) {
|
|
363
|
-
const date = new Date(item.timestamp);
|
|
364
|
-
const time = `<time datetime="${escapeHtml(item.timestamp)}" title="${escapeHtml(
|
|
365
|
-
date.toLocaleString("zh-CN", { hour12: false })
|
|
366
|
-
)}">${date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit", hour12: false })}</time>`;
|
|
367
|
-
let content;
|
|
368
|
-
switch (item.kind) {
|
|
369
|
-
case "human-message":
|
|
370
|
-
content = `<header class="message-heading"><h2>\u4F60</h2>${time}</header>
|
|
371
|
-
<div class="human-bubble"><div class="message-content plain-text">${escapeHtml(item.content)}</div>${renderAttachments(item.attachments)}</div>`;
|
|
372
|
-
break;
|
|
373
|
-
case "assistant-message": {
|
|
374
|
-
const name = item.actor === "subagent" ? "\u5B50 Agent" : agentName;
|
|
375
|
-
content = `<header class="message-heading"><span class="avatar">${icon("agent")}</span><h2>${escapeHtml(name)}</h2>${item.model ? `<span class="model">${escapeHtml(item.model)}</span>` : ""}${time}</header>
|
|
376
|
-
<div class="assistant-body"><div class="message-content markdown">${renderSessionMarkdown(item.content)}</div>${renderAttachments(item.attachments)}</div>`;
|
|
377
|
-
break;
|
|
378
|
-
}
|
|
379
|
-
case "activity-group":
|
|
380
|
-
content = `<details class="activity-details"><summary><span class="status-icon ${item.status}">${icon(
|
|
381
|
-
item.status === "completed" ? "check" : item.status === "failed" ? "warning" : "clock"
|
|
382
|
-
)}</span><span>${item.steps.length} \u9879\u6D3B\u52A8</span><span class="activity-status">${statusLabels[item.status]}</span>
|
|
383
|
-
<span class="disclosure">${icon("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}">${statusLabels[step.status]}</span></div>${[
|
|
384
|
-
"description" in step ? step.description : void 0,
|
|
385
|
-
"resultSummary" in step ? step.resultSummary : void 0,
|
|
386
|
-
"error" in step ? step.error : void 0
|
|
387
|
-
].map((value) => value ? `<div class="message-content plain-text">${escapeHtml(value)}</div>` : "").join("")}</li>`).join("")}</ul><div class="activity-time">${time}</div></details>`;
|
|
388
|
-
break;
|
|
389
|
-
case "notice":
|
|
390
|
-
content = `<div class="notice-content ${item.severity}">${icon(
|
|
391
|
-
item.severity === "success" ? "check" : item.severity === "error" || item.severity === "warning" ? "warning" : "info"
|
|
392
|
-
)}<div><header class="message-heading"><h2>${escapeHtml(item.title)}</h2>${time}</header>
|
|
393
|
-
<div class="message-content plain-text">${escapeHtml(item.content)}</div></div></div>`;
|
|
394
|
-
break;
|
|
395
|
-
case "plan-update":
|
|
396
|
-
content = `<details class="plan-details"><summary>${icon("file")}<span>${item.operation === "deleted" ? "\u8BA1\u5212\u5DF2\u5220\u9664" : "\u8BA1\u5212"}</span>${item.todos.length ? `<span class="activity-status">${item.todos.length} \u9879\u4EFB\u52A1</span>` : ""}<span class="disclosure">${icon("chevron")}</span></summary>
|
|
397
|
-
<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>${escapeHtml(todo.status)}</span></div>${todo.description ? `<div class="message-content plain-text">${escapeHtml(todo.description)}</div>` : ""}</li>`).join("")}</ul>${time}</div></details>`;
|
|
398
|
-
break;
|
|
399
|
-
}
|
|
400
|
-
return `<li class="message ${item.kind}" id="item-${escapeHtml(item.id)}"><article>${content}</article></li>`;
|
|
401
|
-
}
|
|
402
|
-
function renderMessages(items, agentName) {
|
|
403
|
-
let previousDate = "";
|
|
404
|
-
return items.map((item) => {
|
|
405
|
-
const date = new Date(item.timestamp).toLocaleDateString("zh-CN", { year: "numeric", month: "long", day: "numeric" });
|
|
406
|
-
const divider = date === previousDate ? "" : `<li class="day-divider"><span>${escapeHtml(date)}</span></li>`;
|
|
407
|
-
previousDate = date;
|
|
408
|
-
return divider + renderItem(item, agentName);
|
|
409
|
-
}).join("");
|
|
410
|
-
}
|
|
411
|
-
function renderSessionPage(input) {
|
|
412
|
-
const { session, page, error } = input;
|
|
413
|
-
const title = session?.name || "\u4F1A\u8BDD";
|
|
414
|
-
const latest = session === void 0 ? "/" : sessionPageUrl(session.id);
|
|
415
|
-
const project = session?.workingDirectory?.split(/[\\/]/).filter(Boolean).at(-1);
|
|
416
|
-
const hasMessages = page !== void 0 && page.items.length > 0;
|
|
417
|
-
return `<!doctype html>
|
|
418
|
-
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
419
|
-
<title>${escapeHtml(title)} \xB7 AgentKnight</title>
|
|
420
|
-
<style>
|
|
421
|
-
:root { color-scheme: light dark; font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; background: #fcfcfd; color: #202735; --panel: #fff; --soft: #f3f5f8; --border: #e5e8ee; --muted: #667085; --accent: #435bc0; --human: #eef1fc; --success: #298063; --danger: #b54738; --shadow: 0 8px 30px #1826400c; }
|
|
422
|
-
* { box-sizing: border-box; } body { margin: 0; } svg { display: block; width: 20px; height: 20px; flex-shrink: 0; }
|
|
423
|
-
a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }
|
|
424
|
-
:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; border-radius: 4px; }
|
|
425
|
-
.topbar { position: sticky; top: 0; z-index: 3; background: var(--panel); border-bottom: 1px solid var(--border); }
|
|
426
|
-
nav { min-height: 64px; max-width: 1280px; margin: auto; padding: 12px 32px; display: flex; align-items: center; gap: 20px; }
|
|
427
|
-
.back { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); font-size: 14px; min-height: 36px; }
|
|
428
|
-
.nav-divider { height: 20px; width: 1px; background: var(--border); }
|
|
429
|
-
.brand { display: inline-flex; align-items: center; gap: 9px; font-size: 14px; font-weight: 650; color: inherit; letter-spacing: -.3px; }
|
|
430
|
-
.brand-mark { width: 15px; height: 15px; background: var(--accent); border-radius: 5px; transform: rotate(-12deg); }
|
|
431
|
-
.machine { margin-left: auto; color: var(--muted); font-size: 12px; max-width: 30%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
432
|
-
.refresh { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px; padding: 8px 12px; border: 1px solid var(--border); border-radius: 8px; color: inherit; font-size: 13px; }
|
|
433
|
-
.refresh:hover { background: var(--soft); text-decoration: none; } .refresh svg { width: 16px; height: 16px; }
|
|
434
|
-
main { max-width: 900px; margin: auto; padding: 38px 28px 80px; }
|
|
435
|
-
.session-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; padding-bottom: 28px; border-bottom: 1px solid var(--border); }
|
|
436
|
-
.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; }
|
|
437
|
-
.context { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; color: var(--muted); font-size: 12px; }
|
|
438
|
-
.context > span { display: inline-flex; align-items: center; gap: 6px; min-width: 0; overflow-wrap: anywhere; }
|
|
439
|
-
.context svg { width: 14px; height: 14px; } .context .agent-chip { padding: 4px 8px; background: var(--soft); border-radius: 6px; }
|
|
440
|
-
details > summary { cursor: pointer; list-style: none; } summary::-webkit-details-marker { display: none; }
|
|
441
|
-
.session-info { position: relative; flex-shrink: 0; }
|
|
442
|
-
.session-info > summary { width: 36px; height: 36px; display: grid; place-items: center; color: var(--muted); border-radius: 8px; }
|
|
443
|
-
.session-info > summary:hover, .session-info[open] > summary { background: var(--soft); color: var(--accent); }
|
|
444
|
-
.session-info:not([open]) .meta { display: none; }
|
|
445
|
-
.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(--border); border-radius: 12px; box-shadow: var(--shadow); font-size: 13px; }
|
|
446
|
-
.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; }
|
|
447
|
-
.meta code { font-size: 12px; } .messages { list-style: none; padding: 0; margin: 0; }
|
|
448
|
-
.day-divider { display: flex; align-items: center; justify-content: center; gap: 16px; color: var(--muted); font-size: 11px; margin: 26px 0 32px; }
|
|
449
|
-
.day-divider::before, .day-divider::after { content: ""; height: 1px; width: 42px; background: var(--border); }
|
|
450
|
-
.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; }
|
|
451
|
-
.message-heading h2 { font-size: 13px; font-weight: 650; margin: 0; overflow-wrap: anywhere; }
|
|
452
|
-
time, .model { color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
|
453
|
-
.model { overflow-wrap: anywhere; } .message-heading time { margin-left: auto; } .avatar { width: 30px; height: 30px; border: 1px solid var(--border); border-radius: 9px; display: grid; place-items: center; background: var(--panel); color: var(--accent); }
|
|
454
|
-
.avatar svg { width: 17px; height: 17px; } .assistant-body { padding-left: 40px; }
|
|
455
|
-
.message-content { overflow-wrap: anywhere; font-size: 14px; line-height: 1.85; } .plain-text { white-space: pre-wrap; }
|
|
456
|
-
.human-message { margin-left: auto; width: fit-content; max-width: 85%; }
|
|
457
|
-
.human-message .message-heading { justify-content: flex-end; gap: 10px; margin: 0 4px 8px; }
|
|
458
|
-
.human-message .message-heading h2 { color: var(--muted); font-weight: 500; font-size: 12px; }
|
|
459
|
-
.human-message .message-heading time { margin-left: 0; }
|
|
460
|
-
.human-bubble { background: var(--human); padding: 16px 20px; border-radius: 16px 4px 16px 16px; }
|
|
461
|
-
.markdown > :first-child { margin-top: 0; } .markdown > :last-child { margin-bottom: 0; }
|
|
462
|
-
.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; }
|
|
463
|
-
.markdown h1 { font-size: 22px; } .markdown h2 { font-size: 19px; } .markdown h3 { font-size: 16px; } .markdown h4, .markdown h5, .markdown h6 { font-size: 14px; }
|
|
464
|
-
.markdown ul, .markdown ol { padding-left: 24px; margin: 12px 0 18px; } .markdown li { margin: 5px 0; }
|
|
465
|
-
.markdown blockquote { margin: 16px 0; padding: 2px 0 2px 16px; border-left: 3px solid var(--border); color: var(--muted); } .markdown blockquote p:last-child { margin-bottom: 0; }
|
|
466
|
-
code, pre { font-family: "Cascadia Code", Consolas, monospace; font-size: 12px; }
|
|
467
|
-
.markdown :not(pre) > code { background: var(--soft); border: 1px solid var(--border); padding: 2px 5px; border-radius: 5px; }
|
|
468
|
-
.markdown pre { overflow-x: auto; background: var(--soft); border: 1px solid var(--border); padding: 18px 20px; border-radius: 10px; line-height: 1.7; margin: 18px 0; }
|
|
469
|
-
.markdown pre code { white-space: pre; overflow-wrap: normal; } .markdown a { text-decoration: underline; text-underline-offset: 3px; }
|
|
470
|
-
.markdown hr { border: 0; border-top: 1px solid var(--border); margin: 24px 0; }
|
|
471
|
-
.table-scroll { overflow-x: auto; margin: 18px 0; border: 1px solid var(--border); border-radius: 10px; }
|
|
472
|
-
table { border-collapse: collapse; width: 100%; font-size: 13px; } th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--border); min-width: 100px; } th { background: var(--soft); font-weight: 600; } tr:last-child td { border-bottom: 0; }
|
|
473
|
-
.activity-group, .plan-update { margin: 16px 0 16px 40px; }
|
|
474
|
-
.activity-details, .plan-details { border: 1px solid var(--border); border-radius: 10px; background: var(--panel); }
|
|
475
|
-
.activity-details > summary, .plan-details > summary { display: flex; align-items: center; gap: 9px; padding: 12px 14px; font-size: 12px; }
|
|
476
|
-
.activity-details summary:hover, .plan-details summary:hover { background: var(--soft); border-radius: 10px; }
|
|
477
|
-
summary svg { width: 16px; height: 16px; } .activity-status { color: var(--muted); margin-left: auto; }
|
|
478
|
-
.disclosure { color: var(--muted); } details[open] > summary .disclosure { transform: rotate(90deg); }
|
|
479
|
-
.completed { color: var(--success); } .failed { color: var(--danger); } .running { color: var(--accent); }
|
|
480
|
-
.steps { list-style: none; margin: 0; padding: 0 16px; } .steps li { padding: 12px 0; border-top: 1px solid var(--border); }
|
|
481
|
-
.step-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; font-size: 12px; overflow-wrap: anywhere; }
|
|
482
|
-
.step-heading strong { font-family: "Cascadia Code", Consolas, monospace; font-weight: 500; }
|
|
483
|
-
.step-status { flex-shrink: 0; font-size: 11px; } .steps .message-content { font-size: 12px; color: var(--muted); margin-top: 8px; }
|
|
484
|
-
.activity-time { padding: 0 16px 12px; text-align: right; } .plan-body { padding: 8px 16px 16px; } .plan-body .steps { padding: 0; }
|
|
485
|
-
.notice { margin: 20px 0 20px 40px; } .notice-content { display: flex; gap: 10px; border-left: 2px solid var(--border); padding: 2px 0 2px 14px; color: var(--muted); }
|
|
486
|
-
.notice-content > svg { width: 16px; height: 16px; margin-top: 2px; } .notice-content > div { flex: 1; min-width: 0; }
|
|
487
|
-
.notice .message-heading { margin-bottom: 4px; } .notice .message-heading h2 { font-size: 12px; } .notice .message-content { font-size: 12px; }
|
|
488
|
-
.notice-content.success > svg { color: var(--success); } .notice-content.warning > svg, .notice-content.error > svg { color: var(--danger); }
|
|
489
|
-
figure { margin: 16px 0 0; } img { display: block; max-width: 100%; max-height: 520px; object-fit: contain; border-radius: 10px; }
|
|
490
|
-
figcaption { font-size: 12px; overflow-wrap: anywhere; } .image-attachment figcaption { margin-top: 8px; color: var(--muted); }
|
|
491
|
-
.file-attachment { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid var(--border); background: var(--panel); border-radius: 10px; }
|
|
492
|
-
.file-attachment > svg { color: var(--accent); } .file-attachment figcaption { min-width: 0; }
|
|
493
|
-
.attachment-path { display: block; color: var(--muted); font-size: 11px; margin-top: 4px; white-space: pre-wrap; }
|
|
494
|
-
.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(--border); font-size: 12px; color: var(--muted); background: var(--panel); }
|
|
495
|
-
.pager a:hover { background: var(--soft); color: var(--accent); text-decoration: none; } .pager svg { width: 14px; height: 14px; }
|
|
496
|
-
.state { display: flex; flex-direction: column; align-items: center; text-align: center; padding: 70px 20px; color: var(--muted); }
|
|
497
|
-
.state > svg { width: 36px; height: 36px; margin-bottom: 20px; } .state h2 { font-size: 16px; color: #202735; margin: 0 0 8px; font-weight: 600; }
|
|
498
|
-
.state p { margin: 0; font-size: 13px; line-height: 1.8; max-width: 380px; } .state.error > svg { color: var(--danger); }
|
|
499
|
-
.state a { margin-top: 20px; font-size: 13px; border: 1px solid var(--border); background: var(--panel); border-radius: 8px; padding: 9px 18px; }
|
|
500
|
-
.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(--border); border-radius: 50%; box-shadow: var(--shadow); }
|
|
501
|
-
.jump-latest:hover { color: var(--accent); background: var(--soft); } #conversation-end { scroll-margin-bottom: 24px; }
|
|
502
|
-
@media (max-width: 600px) {
|
|
503
|
-
nav { padding: 10px 16px; gap: 12px; min-height: 58px; } .brand { font-size: 12px; } .brand-mark { width: 12px; height: 12px; }
|
|
504
|
-
.machine, .nav-divider { display: none; } .refresh { margin-left: auto; padding: 8px; } .refresh span { display: none; }
|
|
505
|
-
main { padding: 26px 18px 70px; } .session-heading { gap: 10px; padding-bottom: 22px; }
|
|
506
|
-
.assistant-body { padding-left: 0; } .human-message { max-width: 94%; } .human-bubble { padding: 14px 16px; }
|
|
507
|
-
.activity-group, .plan-update, .notice { margin-left: 0; } .message-content { font-size: 14px; }
|
|
508
|
-
.model { max-width: 45%; } .jump-latest { right: 16px; bottom: 16px; }
|
|
509
|
-
}
|
|
510
|
-
@media (prefers-color-scheme: dark) {
|
|
511
|
-
:root { background: #14171c; color: #e2e5ec; --panel: #191d24; --soft: #20252e; --border: #2d333e; --muted: #a1a9b9; --accent: #a5b4fc; --human: #262e46; --success: #83c9ad; --danger: #f3a99a; --shadow: 0 8px 30px #0002; }
|
|
512
|
-
.state h2 { color: #e2e5ec; }
|
|
513
|
-
}
|
|
514
|
-
</style></head><body>
|
|
515
|
-
<div class="topbar"><nav aria-label="\u4F1A\u8BDD\u5BFC\u822A">
|
|
516
|
-
<a class="back" href="/" aria-label="\u8FD4\u56DE\u4F1A\u8BDD\u5217\u8868">${icon("back")}<span>\u4F1A\u8BDD</span></a><span class="nav-divider" aria-hidden="true"></span>
|
|
517
|
-
<a class="brand" href="/"><span class="brand-mark" aria-hidden="true"></span>AgentKnight</a>
|
|
518
|
-
<span class="machine" title="${escapeHtml(input.machineName)}">${escapeHtml(input.machineName)}</span>
|
|
519
|
-
${session === void 0 ? "" : `<a class="refresh" href="${escapeHtml(latest)}" aria-label="\u5237\u65B0\u6700\u65B0" title="\u5237\u65B0\u6700\u65B0">${icon("refresh")}<span>\u5237\u65B0</span></a>`}
|
|
520
|
-
</nav></div><main>
|
|
521
|
-
<div class="session-heading"><div class="session-identity"><h1>${escapeHtml(title)}</h1>
|
|
522
|
-
${session === void 0 ? "" : `<div class="context"><span class="agent-chip">${icon("agent")}${escapeHtml(session.agentName)}</span>${project ? `<span title="${escapeHtml(session.workingDirectory ?? "")}">${icon("folder")}${escapeHtml(project)}</span>` : ""}</div>`}</div>
|
|
523
|
-
${session === void 0 ? "" : `<details class="session-info"><summary aria-label="\u67E5\u770B\u4F1A\u8BDD\u4FE1\u606F" title="\u67E5\u770B\u4F1A\u8BDD\u4FE1\u606F">${icon("info")}</summary><dl class="meta">
|
|
524
|
-
<div><dt>\u7535\u8111</dt><dd>${escapeHtml(input.machineName)}</dd></div><div><dt>Agent</dt><dd>${escapeHtml(session.agentName)}</dd></div>${session.workingDirectory ? `<div><dt>\u5DE5\u4F5C\u76EE\u5F55</dt><dd>${escapeHtml(session.workingDirectory)}</dd></div>` : ""}<div><dt>Session ID</dt><dd><code>${escapeHtml(session.id)}</code></dd></div></dl></details>`}</div>
|
|
525
|
-
${error ? `<div class="state error" role="alert">${icon("warning")}<h2>\u672A\u80FD\u52A0\u8F7D\u4F1A\u8BDD</h2><p>${escapeHtml(error)}</p><a href="${escapeHtml(latest)}">${session ? "\u91CD\u65B0\u52A0\u8F7D" : "\u8FD4\u56DE\u4F1A\u8BDD\u5217\u8868"}</a></div>` : ""}
|
|
526
|
-
${page === void 0 ? "" : `${page.hasMore && session && page.cursor ? `<div class="pager"><a href="${escapeHtml(sessionPageUrl(session.id, page.cursor))}">${icon("clock")}\u67E5\u770B\u66F4\u65E9\u6D88\u606F</a></div>` : ""}
|
|
527
|
-
${hasMessages ? `<ol class="messages" aria-label="\u4F1A\u8BDD\u6D88\u606F">${renderMessages(page.items, session?.agentName || "Assistant")}</ol>` : `<div class="state empty">${icon("chat")}<h2>\u8FD8\u6CA1\u6709\u6D88\u606F</h2><p>\u4F1A\u8BDD\u5F00\u59CB\u540E\uFF0C\u6D88\u606F\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002</p></div>`}`}
|
|
528
|
-
<div id="conversation-end"></div></main>
|
|
529
|
-
${hasMessages ? `<a class="jump-latest" href="#conversation-end" aria-label="\u8DF3\u5230\u672B\u5C3E" title="\u8DF3\u5230\u672B\u5C3E">${icon("down")}</a>` : ""}
|
|
530
|
-
</body></html>`;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// src/agent-selection-page.ts
|
|
534
|
-
function relayAccountLabel(account) {
|
|
535
|
-
if (account.method === "microsoft" && (account.user === void 0 || account.user.username === `msa-${account.userId}`)) {
|
|
536
|
-
return "Microsoft \u8D26\u6237";
|
|
537
|
-
}
|
|
538
|
-
return account.user?.username ?? `\u8D26\u6237 ${account.userId}`;
|
|
539
|
-
}
|
|
540
|
-
function renderChatToggle(id, label, enabled, error, token) {
|
|
541
|
-
if (enabled === void 0) return "";
|
|
542
|
-
return `
|
|
543
|
-
<form id="${id}-form" class="chat-setting" method="post" action="/${id}-settings">
|
|
544
|
-
<input type="hidden" name="token" value="${escapeHtml(token)}">
|
|
545
|
-
<input id="${id}-value" type="hidden" name="enabled" value="${!enabled}">
|
|
546
|
-
<div class="setting-row">
|
|
547
|
-
<span id="${id}-label">${escapeHtml(label)}</span>
|
|
548
|
-
<button id="${id}-toggle" class="toggle" type="submit" role="switch" aria-labelledby="${id}-label" aria-checked="${enabled}"><span aria-hidden="true"></span></button>
|
|
549
|
-
</div>
|
|
550
|
-
<p id="${id}-error" class="error" role="alert"${error ? "" : " hidden"}>${escapeHtml(error ?? "")}</p>
|
|
551
|
-
</form>`;
|
|
552
|
-
}
|
|
553
|
-
function renderAgentSelectionPage(input) {
|
|
554
|
-
const account = input.account;
|
|
555
|
-
const accountUrl = input.deploymentInfo === void 0 ? void 0 : relayAccountUrl(input.deploymentInfo.relayUrl);
|
|
556
|
-
const accountPanel = account === void 0 ? "" : `
|
|
557
|
-
<div id="relay-account" class="account" data-state="${account.state}" role="status" aria-label="Relay \u8D26\u6237">
|
|
558
|
-
<span id="relay-account-name" class="account-name">${escapeHtml(relayAccountLabel(account))}</span>
|
|
559
|
-
<div class="account-meta"><span id="relay-account-method">${account.method === "microsoft" ? "Microsoft" : "\u4F20\u7EDF\u8D26\u6237"}</span><span id="relay-account-role"${account.user === void 0 ? " hidden" : ""}>${account.user?.role === "admin" ? "\u7BA1\u7406\u5458" : "\u666E\u901A\u7528\u6237"}</span><span id="relay-account-state">${account.state === "signed-in" ? "\u5DF2\u767B\u5F55" : account.state === "connecting" ? "\u8FDE\u63A5\u4E2D" : account.state === "disconnected" ? "\u5DF2\u65AD\u5F00" : account.state === "error" ? "\u767B\u5F55\u5F02\u5E38" : "\u72B6\u6001\u672A\u77E5"}</span>${accountUrl === void 0 ? "" : `<a id="relay-account-link" href="${escapeHtml(accountUrl)}" target="_blank" rel="noopener noreferrer"${account.method === "microsoft" ? "" : " hidden"}>\u67E5\u770B\u8D26\u6237</a>`}</div>
|
|
560
|
-
<p id="relay-account-error" class="error"${account.error === void 0 ? " hidden" : ""}>${escapeHtml(account.error ?? "")}</p>
|
|
561
|
-
</div>`;
|
|
562
|
-
const reconnect = input.relayState === void 0 ? "" : `
|
|
563
|
-
<form id="relay-reconnect-form" method="post" action="/relay-reconnect" data-state="${input.relayState}">
|
|
564
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
565
|
-
<button id="relay-reconnect" class="secondary" type="submit"${input.relayState === "registered" ? " hidden" : ""}${input.relayState === "connecting" ? " disabled" : ""}>${input.relayState === "connecting" ? "\u8FDE\u63A5\u4E2D\u2026" : "\u91CD\u8FDE"}</button>
|
|
566
|
-
<p id="relay-reconnect-error" class="error" role="alert"${input.reconnectError ? "" : " hidden"}>${escapeHtml(input.reconnectError ?? "")}</p>
|
|
567
|
-
</form>`;
|
|
568
|
-
const disconnect = !input.canDisconnectRelay || input.relayState === void 0 ? "" : `
|
|
569
|
-
<form id="relay-disconnect-form" method="post" action="/relay-disconnect">
|
|
570
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
571
|
-
<button id="relay-disconnect" class="secondary" type="submit"${input.relayState === "disconnected" ? " hidden" : ""}>\u65AD\u5F00\u8FDE\u63A5</button>
|
|
572
|
-
</form>`;
|
|
573
|
-
const deployment = input.deploymentInfo;
|
|
574
|
-
const upgradedAt = deployment?.upgradedAt;
|
|
575
|
-
const upgradeTime = upgradedAt === void 0 ? void 0 : new Date(upgradedAt);
|
|
576
|
-
const upgradeLabel = upgradeTime !== void 0 && Number.isFinite(upgradeTime.getTime()) ? upgradeTime.toLocaleString("zh-CN", { hour12: false }) : upgradedAt;
|
|
577
|
-
const deploymentPanel = deployment === void 0 ? "" : `
|
|
578
|
-
<dl class="deployment" aria-label="\u90E8\u7F72\u4FE1\u606F">
|
|
579
|
-
<div><dt>\u5F53\u524D\u7248\u672C</dt><dd>${escapeHtml(deployment.version)}</dd></div>
|
|
580
|
-
<div><dt>\u4E0A\u6B21\u5347\u7EA7</dt><dd>${deployment.upgradedAt ? `<time datetime="${escapeHtml(deployment.upgradedAt)}">${escapeHtml(upgradeLabel ?? deployment.upgradedAt)}</time>` : "\u6682\u65E0\u8BB0\u5F55"}</dd></div>
|
|
581
|
-
<div><dt>\u7528\u6237\u914D\u7F6E</dt><dd>${escapeHtml(deployment.configPath || "\u8FDB\u7A0B\u73AF\u5883")}</dd></div>
|
|
582
|
-
<div><dt>Relay URL</dt><dd>${escapeHtml(relayDisplayUrl(deployment.relayUrl))}</dd></div>
|
|
583
|
-
</dl>`;
|
|
584
|
-
const cards = input.agents?.map((agent) => {
|
|
585
|
-
const presentation = codingAgentPresentation(agent.id);
|
|
586
|
-
const name = agent.name.trim() || presentation.name;
|
|
587
|
-
return `<section class="agent">
|
|
588
|
-
<div class="agent-heading">
|
|
589
|
-
<span class="agent-icon">${presentation.icon}</span>
|
|
590
|
-
<div class="agent-identity"><h3>${escapeHtml(name)}</h3>
|
|
591
|
-
<span class="connection${agent.available ? " connected" : ""}">${agent.available ? "\u5DF2\u8FDE\u63A5" : "\u4E0D\u53EF\u7528"}</span>
|
|
592
|
-
</div>
|
|
593
|
-
<label class="expose"><span>\u5F00\u542F\u540C\u6B65</span>
|
|
594
|
-
<input type="checkbox" name="agents" value="${escapeHtml(agent.id)}" aria-label="\u5F00\u542F\u540C\u6B65 ${escapeHtml(name)}"${agent.selected ? " checked" : ""}${!agent.available && !agent.selected ? " disabled" : ""}>
|
|
595
|
-
</label>
|
|
596
|
-
</div>
|
|
597
|
-
${agent.error ? `<p class="error agent-error">${escapeHtml(agent.error)}</p>` : ""}
|
|
598
|
-
<details${agent.selected ? " open" : ""}>
|
|
599
|
-
<summary>\u4F1A\u8BDD <span class="count">${agent.sessions.length}</span></summary>
|
|
600
|
-
${renderSessionGroups(agent.sessions, input.canReadSessions === true)}
|
|
601
|
-
</details>
|
|
602
|
-
</section>`;
|
|
603
|
-
}).join("");
|
|
604
|
-
const chatSettings = renderChatToggle("group-chat", "Agent \u7FA4\u804A", input.groupChatEnabled, input.groupChatError, input.token) + renderChatToggle("peer-chat", "Agent \u7684\u8DE8 PC \u901A\u4FE1", input.peerChatEnabled, input.peerChatError, input.token);
|
|
605
|
-
return `<!doctype html>
|
|
606
|
-
<html lang="zh-CN">
|
|
607
|
-
<head>
|
|
608
|
-
<meta charset="utf-8">
|
|
609
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
610
|
-
<title>AgentKnight</title>
|
|
611
|
-
<script src="/local-page.js" defer></script>
|
|
612
|
-
<style>
|
|
613
|
-
:root { color-scheme: light dark; font-family: "Segoe UI", system-ui, sans-serif; background: #f5f7fb; color: #172338; --panel: #fff; --border: #dfe6ef; --muted: #63728a; --accent: #275cd5; }
|
|
614
|
-
* { box-sizing: border-box; }
|
|
615
|
-
body { margin: 0; padding: 48px 28px; }
|
|
616
|
-
main { max-width: 1120px; margin: auto; }
|
|
617
|
-
header { display: flex; gap: 24px; align-items: center; justify-content: space-between; margin-bottom: 38px; }
|
|
618
|
-
.header-actions { display: flex; align-items: center; gap: 24px; min-width: 0; }
|
|
619
|
-
.header-actions > a { flex-shrink: 0; }
|
|
620
|
-
#relay-reconnect, #relay-disconnect { white-space: nowrap; }
|
|
621
|
-
.account { min-width: 0; max-width: 360px; text-align: right; }
|
|
622
|
-
.account-name { display: block; font-size: 15px; font-weight: 650; overflow-wrap: anywhere; }
|
|
623
|
-
.account-meta { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 6px 12px; margin-top: 6px; font-size: 12px; color: var(--muted); }
|
|
624
|
-
#relay-account-state { color: var(--muted); }
|
|
625
|
-
.account[data-state=signed-in] #relay-account-state { color: #268561; }
|
|
626
|
-
#relay-account-error { margin-top: 8px; text-align: left; }
|
|
627
|
-
h1 { margin: 0; font-size: clamp(24px, 4vw, 32px); letter-spacing: -.7px; overflow-wrap: anywhere; }
|
|
628
|
-
h2 { margin: 0; font-size: 19px; font-weight: 650; }
|
|
629
|
-
h3 { margin: 0; font-size: 17px; font-weight: 650; overflow-wrap: anywhere; }
|
|
630
|
-
a { color: var(--accent); text-decoration: none; }
|
|
631
|
-
a:hover { text-decoration: underline; }
|
|
632
|
-
.brand { display: inline-flex; align-items: center; gap: 9px; font-weight: 650; font-size: 14px; color: var(--muted); margin-bottom: 12px; }
|
|
633
|
-
.brand-mark { width: 12px; height: 12px; border-radius: 4px; background: var(--accent); transform: rotate(-12deg); }
|
|
634
|
-
.deployment { display: grid; grid-template-columns: minmax(0, .7fr) minmax(0, 1.2fr) minmax(0, 1.5fr) minmax(0, 1.2fr); gap: 22px; margin: 0 0 28px; padding: 18px 22px; background: var(--panel); border: 1px solid var(--border); border-radius: 14px; }
|
|
635
|
-
.deployment dt { margin-bottom: 7px; font-size: 12px; color: var(--muted); }
|
|
636
|
-
.deployment dd { margin: 0; font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
|
|
637
|
-
.layout { display: grid; grid-template-columns: minmax(0, 1fr) 344px; gap: 28px; align-items: start; }
|
|
638
|
-
.section-heading { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; }
|
|
639
|
-
fieldset { margin: 0; padding: 0; border: 0; min-width: 0; }
|
|
640
|
-
.agent { background: var(--panel); border: 1px solid var(--border); border-radius: 16px; margin-bottom: 14px; overflow: hidden; }
|
|
641
|
-
.agent:has(input:checked) { border-color: #a6bce9; }
|
|
642
|
-
.agent-heading { display: flex; align-items: center; gap: 14px; padding: 22px; }
|
|
643
|
-
.agent-identity { min-width: 0; flex: 1; }
|
|
644
|
-
.agent-icon { display: grid; place-items: center; width: 44px; height: 44px; padding: 9px; border-radius: 12px; background: #eef2fa; flex-shrink: 0; }
|
|
645
|
-
.agent-icon svg { width: 100%; height: 100%; }
|
|
646
|
-
.agent-pi-icon { display: block; text-align: center; font: bold 28px/28px Georgia, serif; }
|
|
647
|
-
.connection { display: inline-flex; gap: 6px; align-items: center; margin-top: 6px; font-size: 12px; color: var(--muted); }
|
|
648
|
-
.connection::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: #a2adbd; }
|
|
649
|
-
.connected::before { background: #268561; }
|
|
650
|
-
.expose { display: flex; gap: 10px; align-items: center; font-size: 13px; cursor: pointer; }
|
|
651
|
-
input[type=checkbox] { width: 20px; height: 20px; accent-color: var(--accent); margin: 0; }
|
|
652
|
-
input:disabled { cursor: not-allowed; }
|
|
653
|
-
details { border-top: 1px solid var(--border); }
|
|
654
|
-
summary { cursor: pointer; padding: 13px 22px; font-size: 13px; color: var(--muted); }
|
|
655
|
-
.count { float: right; font-variant-numeric: tabular-nums; }
|
|
656
|
-
.session-folders { list-style: none; margin: 0; padding: 0 16px 10px; max-height: 480px; overflow-y: auto; }
|
|
657
|
-
.session-folder { border: 0; }
|
|
658
|
-
.session-folders > li + li { border-top: 1px solid var(--border); }
|
|
659
|
-
.session-folder > summary { display: flex; align-items: center; gap: 12px; padding: 14px 6px; list-style: none; border-radius: 8px; }
|
|
660
|
-
.session-folder > summary::-webkit-details-marker { display: none; }
|
|
661
|
-
.session-folder > summary:hover { background: #275cd50a; }
|
|
662
|
-
.folder-icon { color: var(--accent); flex-shrink: 0; } .folder-icon svg { width: 22px; height: 22px; display: block; }
|
|
663
|
-
.folder-label { flex: 1; min-width: 0; } .folder-name { display: block; color: var(--accent); font-size: 14px; font-weight: 600; overflow-wrap: anywhere; }
|
|
664
|
-
.folder-path { display: block; margin-top: 4px; font-size: 11px; line-height: 1.5; color: var(--muted); overflow-wrap: anywhere; }
|
|
665
|
-
.folder-count { min-width: 24px; padding: 3px 6px; text-align: center; border: 1px solid var(--border); border-radius: 6px; font-size: 11px; font-variant-numeric: tabular-nums; }
|
|
666
|
-
.folder-chevron svg { display: block; width: 14px; height: 14px; } .session-folder[open] > summary .folder-chevron { transform: rotate(90deg); }
|
|
667
|
-
.sessions { list-style: none; margin: 0 6px 12px 16px; padding: 0 0 0 20px; border-left: 1px solid var(--border); }
|
|
668
|
-
.session { padding: 4px 0; }
|
|
669
|
-
.session + .session { border-top: 1px solid var(--border); }
|
|
670
|
-
.session-link { display: flex; align-items: center; gap: 12px; margin: 0 -10px; padding: 14px 10px; color: inherit; border-radius: 10px; }
|
|
671
|
-
.session-link:hover, .session-link:focus-visible { background: #275cd50a; color: var(--accent); text-decoration: none; }
|
|
672
|
-
.session-symbol { display: grid; place-items: center; width: 32px; height: 32px; border: 1px solid var(--border); border-radius: 9px; flex-shrink: 0; color: var(--muted); }
|
|
673
|
-
.session-link svg { display: block; width: 16px; height: 16px; } .session-label { flex: 1; min-width: 0; }
|
|
674
|
-
.session-chevron { color: var(--muted); flex-shrink: 0; }
|
|
675
|
-
.session-name { display: block; font-size: 14px; line-height: 1.55; overflow-wrap: anywhere; white-space: pre-line; }
|
|
676
|
-
.error, .empty { margin: 0; overflow-wrap: anywhere; font-size: 14px; line-height: 1.6; }
|
|
677
|
-
.empty { padding: 14px 0; color: var(--muted); }
|
|
678
|
-
.error { color: #b42318; }
|
|
679
|
-
.agent-error { padding: 0 22px 18px; }
|
|
680
|
-
.save-bar { display: flex; align-items: center; justify-content: flex-end; gap: 16px; position: sticky; bottom: 0; padding: 16px 0; background: #f5f7fbf5; }
|
|
681
|
-
#save-status { font-size: 13px; color: var(--muted); }
|
|
682
|
-
#save-error { padding: 10px 0; }
|
|
683
|
-
button { padding: 11px 24px; border: 1px solid transparent; border-radius: 10px; background: var(--accent); color: #fff; font: inherit; font-size: 14px; font-weight: 650; cursor: pointer; }
|
|
684
|
-
button:disabled { opacity: .5; cursor: default; }
|
|
685
|
-
.secondary { background: var(--panel); color: var(--accent); border-color: var(--border); }
|
|
686
|
-
.chat-settings { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 24px; }
|
|
687
|
-
.chat-setting { flex: 1 1 240px; min-width: 0; margin: 0; padding: 18px 22px; background: var(--panel); border: 1px solid var(--border); border-radius: 16px; }
|
|
688
|
-
.setting-row { display: flex; justify-content: space-between; align-items: center; gap: 16px; font-size: 15px; font-weight: 600; }
|
|
689
|
-
button.toggle { width: 48px; height: 28px; padding: 3px; border-radius: 999px; flex-shrink: 0; background: var(--muted); }
|
|
690
|
-
button.toggle[aria-checked=false] { background: var(--muted); }
|
|
691
|
-
button.toggle[aria-checked=true] { background: var(--accent); }
|
|
692
|
-
.toggle span { display: block; width: 20px; height: 20px; border-radius: 50%; background: #fff; transition: transform .15s; }
|
|
693
|
-
.toggle[aria-checked=true] span { transform: translateX(20px); }
|
|
694
|
-
.chat-setting .error:not([hidden]) { margin-top: 12px; }
|
|
695
|
-
.pairing { padding: 24px; background: var(--panel); border: 1px solid var(--border); border-radius: 20px; }
|
|
696
|
-
.qr-area { display: grid; place-items: center; min-height: 280px; margin: 24px 0; background: #f5f7fb; border-radius: 14px; overflow: hidden; }
|
|
697
|
-
.qr-placeholder { color: #91a1ba; width: 70px; height: 70px; }
|
|
698
|
-
.qr { width: 100%; background: #fff; }
|
|
699
|
-
.qr svg { display: block; width: 100%; height: auto; }
|
|
700
|
-
.pair-actions { display: flex; gap: 10px; }
|
|
701
|
-
.pair-actions button { flex: 1; }
|
|
702
|
-
#pair-error { padding-top: 16px; }
|
|
703
|
-
[hidden] { display: none !important; }
|
|
704
|
-
:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; }
|
|
705
|
-
@media (max-width: 800px) {
|
|
706
|
-
body { padding: 24px 16px; } header { margin-bottom: 28px; }
|
|
707
|
-
header { flex-wrap: wrap; gap: 18px; } .header-actions { width: 100%; justify-content: space-between; }
|
|
708
|
-
.account { text-align: left; max-width: 100%; } .account-meta { justify-content: flex-start; }
|
|
709
|
-
.deployment { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; padding: 18px; }
|
|
710
|
-
.layout { grid-template-columns: minmax(0, 1fr); gap: 22px; }
|
|
711
|
-
.pairing { width: 100%; } .qr-area { max-width: 300px; margin: 24px auto; }
|
|
712
|
-
.agent-heading { padding: 18px; gap: 12px; } .agent-icon { width: 38px; height: 38px; padding: 7px; }
|
|
713
|
-
h3 { font-size: 15px; } .expose { gap: 7px; } .save-bar { z-index: 1; }
|
|
714
|
-
}
|
|
715
|
-
@media (prefers-color-scheme: dark) {
|
|
716
|
-
:root { background: #111925; color: #e6edf6; --panel: #192435; --border: #33435b; --muted: #a0aec4; --accent: #8cabff; }
|
|
717
|
-
.agent:has(input:checked) { border-color: #5777af; }
|
|
718
|
-
.agent-icon, .qr-area { background: #233147; }
|
|
719
|
-
.save-bar { background: #111925f5; } button:not(.secondary) { background: #416fe0; color: #fff; }
|
|
720
|
-
.error { color: #ffb4ab; }
|
|
721
|
-
.account[data-state=signed-in] #relay-account-state { color: #7dd6b1; }
|
|
722
|
-
}
|
|
723
|
-
</style>
|
|
724
|
-
</head>
|
|
725
|
-
<body>
|
|
726
|
-
<main>
|
|
727
|
-
<header><div><span class="brand"><span class="brand-mark" aria-hidden="true"></span>AgentKnight</span><h1>${escapeHtml(input.machineName)}</h1></div><div class="header-actions">${accountPanel}${reconnect}${disconnect}<a href="/">\u5237\u65B0</a></div></header>
|
|
728
|
-
${deploymentPanel}
|
|
729
|
-
<div class="layout">
|
|
730
|
-
<section aria-labelledby="agents-heading">
|
|
731
|
-
${chatSettings ? `<div class="chat-settings">${chatSettings}</div>` : ""}
|
|
732
|
-
<div class="section-heading"><h2 id="agents-heading">Agent \u540C\u6B65</h2></div>
|
|
733
|
-
${input.agents === void 0 ? input.sessions === void 0 ? '<p class="empty">\u5F53\u524D\u4E3A\u5355 Agent \u6A21\u5F0F</p>' : renderSessionGroups(input.sessions, true) : `<form id="selection-form" method="post" action="/selection">
|
|
734
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
735
|
-
<fieldset>${cards || '<p class="empty">\u6CA1\u6709\u53EF\u914D\u7F6E\u7684 Agent</p>'}</fieldset>
|
|
736
|
-
<p id="save-error" class="error" role="alert"${input.error ? "" : " hidden"}>${escapeHtml(input.error ?? "")}</p>
|
|
737
|
-
<div class="save-bar"><span id="save-status" role="status" aria-live="polite">${input.saved ? "\u5DF2\u540C\u6B65" : ""}</span><button id="save-button" type="submit">${input.error ? "\u91CD\u8BD5" : "\u540C\u6B65"}</button></div>
|
|
738
|
-
</form>`}
|
|
739
|
-
</section>
|
|
740
|
-
<aside class="pairing" aria-labelledby="pairing-heading">
|
|
741
|
-
<h2 id="pairing-heading">\u624B\u673A\u914D\u5BF9</h2>
|
|
742
|
-
<div class="qr-area">
|
|
743
|
-
<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>
|
|
744
|
-
<div id="pairing-qr" class="qr" role="img" aria-label="\u914D\u5BF9\u4E8C\u7EF4\u7801"${input.pairing ? ` data-expires-at="${input.pairing.expiresAt}"${input.pairing.statusId ? ` data-status-id="${escapeHtml(input.pairing.statusId)}"` : ""}` : " hidden"}>${input.pairing?.svg ?? ""}</div>
|
|
745
|
-
<div id="pair-success" role="status" hidden>\u2713 \u914D\u5BF9\u6210\u529F</div>
|
|
746
|
-
</div>
|
|
747
|
-
<form id="pairing-form" method="post" action="/pair">
|
|
748
|
-
<input type="hidden" name="token" value="${escapeHtml(input.token)}">
|
|
749
|
-
<div class="pair-actions"><button id="show-qr" class="secondary" type="submit"${input.pairing ? " hidden" : ""}>\u663E\u793A\u4E8C\u7EF4\u7801</button><button id="refresh-qr" class="secondary" type="submit" formaction="/refresh"${input.pairing ? "" : " hidden"}>\u5237\u65B0\u4E8C\u7EF4\u7801</button><button id="hide-qr" class="secondary" type="button"${input.pairing ? "" : " hidden"}>\u9690\u85CF</button></div>
|
|
750
|
-
</form>
|
|
751
|
-
<p id="pair-error" class="error" role="alert"${input.pairingError ? "" : " hidden"}${input.pairingError && input.relayState !== void 0 && input.relayState !== "registered" ? ' data-relay-offline="true"' : ""}>${escapeHtml(input.pairingError ?? "")}</p>
|
|
752
|
-
</aside>
|
|
753
|
-
</div>
|
|
754
|
-
</main>
|
|
755
|
-
</body>
|
|
756
|
-
</html>`;
|
|
757
|
-
}
|
|
758
|
-
var localPageScript = `
|
|
759
|
-
(() => {
|
|
760
|
-
const reconnectForm = document.querySelector('#relay-reconnect-form');
|
|
761
|
-
if (reconnectForm) {
|
|
762
|
-
const button = document.querySelector('#relay-reconnect');
|
|
763
|
-
const disconnectForm = document.querySelector('#relay-disconnect-form');
|
|
764
|
-
const disconnectButton = document.querySelector('#relay-disconnect');
|
|
765
|
-
const error = document.querySelector('#relay-reconnect-error');
|
|
766
|
-
let stopped = false;
|
|
767
|
-
let timer;
|
|
768
|
-
let generation = 0;
|
|
769
|
-
let submitting = false;
|
|
770
|
-
let state = reconnectForm.dataset.state;
|
|
771
|
-
let failureState;
|
|
772
|
-
const update = next => {
|
|
773
|
-
if (!next || !['connecting', 'registered', 'disconnected', 'error'].includes(next.state)) throw new Error('Invalid Relay status');
|
|
774
|
-
state = next.state;
|
|
775
|
-
button.hidden = next.state === 'registered';
|
|
776
|
-
button.disabled = next.state === 'connecting';
|
|
777
|
-
button.textContent = next.state === 'connecting' ? '\u8FDE\u63A5\u4E2D\u2026' : '\u91CD\u8FDE';
|
|
778
|
-
if (disconnectButton) {
|
|
779
|
-
disconnectButton.hidden = next.state === 'disconnected';
|
|
780
|
-
disconnectButton.disabled = false;
|
|
781
|
-
disconnectButton.textContent = '\u65AD\u5F00\u8FDE\u63A5';
|
|
782
|
-
}
|
|
783
|
-
if (next.state === 'disconnected') conceal();
|
|
784
|
-
const pairingError = document.querySelector('#pair-error');
|
|
785
|
-
if (next.state === 'registered' && pairingError?.dataset.relayOffline === 'true') {
|
|
786
|
-
pairingError.hidden = true;
|
|
787
|
-
pairingError.textContent = '';
|
|
788
|
-
delete pairingError.dataset.relayOffline;
|
|
789
|
-
}
|
|
790
|
-
};
|
|
791
|
-
const poll = async () => {
|
|
792
|
-
const current = generation;
|
|
793
|
-
try {
|
|
794
|
-
const response = await fetch('/relay-status', { cache: 'no-store', signal: AbortSignal.timeout(5000) });
|
|
795
|
-
if (!response.ok) throw new Error('Relay status unavailable');
|
|
796
|
-
const next = await response.json();
|
|
797
|
-
if (!stopped && current === generation && !submitting) {
|
|
798
|
-
update(next);
|
|
799
|
-
if (next.state !== failureState) error.hidden = true;
|
|
800
|
-
}
|
|
801
|
-
} catch {
|
|
802
|
-
if (!stopped && current === generation && !submitting) {
|
|
803
|
-
error.textContent = '\u65E0\u6CD5\u66F4\u65B0 Relay \u8FDE\u63A5\u72B6\u6001\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u3002';
|
|
804
|
-
error.hidden = false;
|
|
805
|
-
}
|
|
806
|
-
} finally {
|
|
807
|
-
if (!stopped && current === generation) timer = setTimeout(poll, 3000);
|
|
808
|
-
}
|
|
809
|
-
};
|
|
810
|
-
const submit = async (event, form, actionButton, disconnecting) => {
|
|
811
|
-
event.preventDefault();
|
|
812
|
-
if (actionButton.disabled || submitting) return;
|
|
813
|
-
const current = ++generation;
|
|
814
|
-
clearTimeout(timer);
|
|
815
|
-
submitting = true;
|
|
816
|
-
button.disabled = true;
|
|
817
|
-
if (disconnectButton) disconnectButton.disabled = true;
|
|
818
|
-
actionButton.textContent = disconnecting ? '\u6B63\u5728\u65AD\u5F00\u2026' : '\u8FDE\u63A5\u4E2D\u2026';
|
|
819
|
-
error.hidden = true;
|
|
820
|
-
failureState = undefined;
|
|
821
|
-
try {
|
|
822
|
-
const response = await fetch(form.action, {
|
|
823
|
-
method: 'POST', headers: { Accept: 'application/json' },
|
|
824
|
-
body: new URLSearchParams(new FormData(form)), signal: AbortSignal.timeout(5000),
|
|
825
|
-
});
|
|
826
|
-
if (!response.ok) throw new Error('Relay reconnect failed');
|
|
827
|
-
const next = await response.json();
|
|
828
|
-
if (!stopped && current === generation) {
|
|
829
|
-
update(next);
|
|
830
|
-
if (actionButton.hidden) (button.hidden ? disconnectButton : button)?.focus();
|
|
831
|
-
}
|
|
832
|
-
} catch {
|
|
833
|
-
if (!stopped && current === generation) {
|
|
834
|
-
update({ state: disconnecting ? state : 'error' });
|
|
835
|
-
failureState = state;
|
|
836
|
-
error.textContent = disconnecting ? '\u65E0\u6CD5\u65AD\u5F00 Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002' : '\u65E0\u6CD5\u91CD\u8FDE Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002';
|
|
837
|
-
error.hidden = false;
|
|
838
|
-
}
|
|
839
|
-
} finally {
|
|
840
|
-
submitting = false;
|
|
841
|
-
if (!stopped && current === generation) timer = setTimeout(poll, 1000);
|
|
842
|
-
}
|
|
843
|
-
};
|
|
844
|
-
reconnectForm.addEventListener('submit', event => submit(event, reconnectForm, button, false));
|
|
845
|
-
if (disconnectForm && disconnectButton) {
|
|
846
|
-
disconnectForm.addEventListener('submit', event => submit(event, disconnectForm, disconnectButton, true));
|
|
847
|
-
}
|
|
848
|
-
addEventListener('pagehide', () => { stopped = true; generation++; clearTimeout(timer); });
|
|
849
|
-
addEventListener('pageshow', () => { if (stopped) { stopped = false; timer = setTimeout(poll, 0); } });
|
|
850
|
-
timer = setTimeout(poll, 1000);
|
|
851
|
-
}
|
|
852
|
-
const account = document.querySelector('#relay-account');
|
|
853
|
-
if (account) {
|
|
854
|
-
const accountLabel = ${relayAccountLabel.toString()};
|
|
855
|
-
const name = document.querySelector('#relay-account-name');
|
|
856
|
-
const accountLink = document.querySelector('#relay-account-link');
|
|
857
|
-
const method = document.querySelector('#relay-account-method');
|
|
858
|
-
const role = document.querySelector('#relay-account-role');
|
|
859
|
-
const state = document.querySelector('#relay-account-state');
|
|
860
|
-
const error = document.querySelector('#relay-account-error');
|
|
861
|
-
let stopped = false;
|
|
862
|
-
let timer;
|
|
863
|
-
let navigationGeneration = 0;
|
|
864
|
-
const poll = async () => {
|
|
865
|
-
const generation = navigationGeneration;
|
|
866
|
-
const isCurrent = () => !stopped && generation === navigationGeneration;
|
|
867
|
-
try {
|
|
868
|
-
const response = await fetch('/relay-account', { cache: 'no-store', signal: AbortSignal.timeout(5000) });
|
|
869
|
-
if (!response.ok) throw new Error('Account unavailable');
|
|
870
|
-
const next = await response.json();
|
|
871
|
-
if (!isCurrent()) return;
|
|
872
|
-
name.textContent = accountLabel(next);
|
|
873
|
-
if (accountLink) accountLink.hidden = next.method !== 'microsoft';
|
|
874
|
-
method.textContent = next.method === 'microsoft' ? 'Microsoft' : '\u4F20\u7EDF\u8D26\u6237';
|
|
875
|
-
role.hidden = !next.user;
|
|
876
|
-
role.textContent = next.user?.role === 'admin' ? '\u7BA1\u7406\u5458' : '\u666E\u901A\u7528\u6237';
|
|
877
|
-
account.dataset.state = next.state;
|
|
878
|
-
state.textContent = next.state === 'signed-in' ? '\u5DF2\u767B\u5F55' : next.state === 'connecting' ? '\u8FDE\u63A5\u4E2D' : next.state === 'disconnected' ? '\u5DF2\u65AD\u5F00' : next.state === 'error' ? '\u767B\u5F55\u5F02\u5E38' : '\u72B6\u6001\u672A\u77E5';
|
|
879
|
-
error.textContent = next.error ?? '';
|
|
880
|
-
error.hidden = !next.error;
|
|
881
|
-
} catch {
|
|
882
|
-
if (!isCurrent()) return;
|
|
883
|
-
account.dataset.state = 'error';
|
|
884
|
-
state.textContent = '\u72B6\u6001\u672A\u77E5';
|
|
885
|
-
error.textContent = '\u65E0\u6CD5\u66F4\u65B0\u767B\u5F55\u72B6\u6001\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u3002';
|
|
886
|
-
error.hidden = false;
|
|
887
|
-
} finally {
|
|
888
|
-
if (isCurrent()) timer = setTimeout(poll, 10000);
|
|
889
|
-
}
|
|
890
|
-
};
|
|
891
|
-
addEventListener('pagehide', () => { stopped = true; navigationGeneration++; clearTimeout(timer); });
|
|
892
|
-
addEventListener('pageshow', () => { if (stopped) { stopped = false; timer = setTimeout(poll, 0); } });
|
|
893
|
-
timer = setTimeout(poll, 1000);
|
|
894
|
-
}
|
|
895
|
-
for (const [id, failureMessage] of [
|
|
896
|
-
['group-chat', '\u7FA4\u804A\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002'],
|
|
897
|
-
['peer-chat', '\u8DE8 PC \u901A\u4FE1\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002'],
|
|
898
|
-
]) {
|
|
899
|
-
const chatSettings = document.querySelector('#' + id + '-form');
|
|
900
|
-
if (!chatSettings) continue;
|
|
901
|
-
const toggle = document.querySelector('#' + id + '-toggle');
|
|
902
|
-
const value = document.querySelector('#' + id + '-value');
|
|
903
|
-
const error = document.querySelector('#' + id + '-error');
|
|
904
|
-
chatSettings.addEventListener('submit', async event => {
|
|
905
|
-
event.preventDefault();
|
|
906
|
-
if (toggle.disabled) return;
|
|
907
|
-
toggle.disabled = true;
|
|
908
|
-
toggle.setAttribute('aria-busy', 'true');
|
|
909
|
-
error.hidden = true;
|
|
910
|
-
try {
|
|
911
|
-
const response = await fetch(chatSettings.action, {
|
|
912
|
-
method: 'POST', headers: { Accept: 'application/json' }, body: new URLSearchParams(new FormData(chatSettings)),
|
|
913
|
-
});
|
|
914
|
-
const result = await response.json();
|
|
915
|
-
if (!response.ok || result?.ok !== true || typeof result.enabled !== 'boolean') {
|
|
916
|
-
throw new Error(result?.error || failureMessage);
|
|
917
|
-
}
|
|
918
|
-
toggle.setAttribute('aria-checked', String(result.enabled));
|
|
919
|
-
value.value = String(!result.enabled);
|
|
920
|
-
} catch (reason) {
|
|
921
|
-
error.textContent = reason instanceof Error ? reason.message : '\u4FDD\u5B58\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002';
|
|
922
|
-
error.hidden = false;
|
|
923
|
-
} finally {
|
|
924
|
-
toggle.disabled = false;
|
|
925
|
-
toggle.removeAttribute('aria-busy');
|
|
926
|
-
}
|
|
927
|
-
});
|
|
928
|
-
}
|
|
929
|
-
const form = document.querySelector('#selection-form');
|
|
930
|
-
if (form) {
|
|
931
|
-
const button = document.querySelector('#save-button');
|
|
932
|
-
const status = document.querySelector('#save-status');
|
|
933
|
-
const error = document.querySelector('#save-error');
|
|
934
|
-
const fields = form.querySelector('fieldset');
|
|
935
|
-
const selection = () => JSON.stringify([...form.querySelectorAll('[name=agents]:checked')].map(input => input.value).sort());
|
|
936
|
-
let saved = selection();
|
|
937
|
-
let saving = false;
|
|
938
|
-
let acknowledged = status.textContent === '\u5DF2\u540C\u6B65';
|
|
939
|
-
const update = () => {
|
|
940
|
-
const dirty = selection() !== saved;
|
|
941
|
-
button.disabled = saving || (acknowledged && !dirty && error.hidden);
|
|
942
|
-
if (!saving) status.textContent = dirty ? '\u5F85\u540C\u6B65' : status.textContent === '\u5DF2\u540C\u6B65' ? '\u5DF2\u540C\u6B65' : '';
|
|
943
|
-
};
|
|
944
|
-
form.addEventListener('change', update);
|
|
945
|
-
update();
|
|
946
|
-
form.addEventListener('submit', async event => {
|
|
947
|
-
event.preventDefault();
|
|
948
|
-
if (button.disabled || saving) return;
|
|
949
|
-
const body = new URLSearchParams(new FormData(form));
|
|
950
|
-
const submitted = selection();
|
|
951
|
-
saving = true;
|
|
952
|
-
fields.disabled = true;
|
|
953
|
-
button.disabled = true;
|
|
954
|
-
status.textContent = '\u540C\u6B65\u4E2D\u2026';
|
|
955
|
-
error.hidden = true;
|
|
956
|
-
try {
|
|
957
|
-
const response = await fetch(form.action, { method: 'POST', headers: { Accept: 'application/json' }, body });
|
|
958
|
-
const result = await response.json().catch(() => null);
|
|
959
|
-
if (!response.ok || result?.ok !== true) throw new Error(result?.error || '\u540C\u6B65\u5931\u8D25\uFF08HTTP ' + response.status + '\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u3002');
|
|
960
|
-
saved = submitted;
|
|
961
|
-
acknowledged = true;
|
|
962
|
-
button.textContent = '\u540C\u6B65';
|
|
963
|
-
status.textContent = '\u5DF2\u540C\u6B65';
|
|
964
|
-
} catch (reason) {
|
|
965
|
-
error.textContent = reason instanceof Error ? reason.message : '\u540C\u6B65\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002';
|
|
966
|
-
error.hidden = false;
|
|
967
|
-
button.textContent = '\u91CD\u8BD5';
|
|
968
|
-
status.textContent = '';
|
|
969
|
-
} finally {
|
|
970
|
-
saving = false;
|
|
971
|
-
fields.disabled = false;
|
|
972
|
-
update();
|
|
973
|
-
}
|
|
974
|
-
});
|
|
975
|
-
}
|
|
976
|
-
const pairing = document.querySelector('#pairing-form');
|
|
977
|
-
const qr = document.querySelector('#pairing-qr');
|
|
978
|
-
const placeholder = document.querySelector('#qr-placeholder');
|
|
979
|
-
const show = document.querySelector('#show-qr');
|
|
980
|
-
const refresh = document.querySelector('#refresh-qr');
|
|
981
|
-
const hide = document.querySelector('#hide-qr');
|
|
982
|
-
const pairError = document.querySelector('#pair-error');
|
|
983
|
-
const pairSuccess = document.querySelector('#pair-success');
|
|
984
|
-
let expiry;
|
|
985
|
-
let statusTimer;
|
|
986
|
-
let statusGeneration = 0;
|
|
987
|
-
let loading = false;
|
|
988
|
-
const stopStatus = () => {
|
|
989
|
-
clearTimeout(statusTimer);
|
|
990
|
-
statusGeneration++;
|
|
991
|
-
};
|
|
992
|
-
const conceal = () => {
|
|
993
|
-
clearTimeout(expiry);
|
|
994
|
-
stopStatus();
|
|
995
|
-
qr.replaceChildren();
|
|
996
|
-
qr.hidden = true;
|
|
997
|
-
delete qr.dataset.statusId;
|
|
998
|
-
delete qr.dataset.expiresAt;
|
|
999
|
-
placeholder.removeAttribute('hidden');
|
|
1000
|
-
pairSuccess.hidden = true;
|
|
1001
|
-
show.hidden = false;
|
|
1002
|
-
refresh.hidden = true;
|
|
1003
|
-
hide.hidden = true;
|
|
1004
|
-
};
|
|
1005
|
-
const watchStatus = statusId => {
|
|
1006
|
-
stopStatus();
|
|
1007
|
-
if (typeof statusId !== 'string') return;
|
|
1008
|
-
const generation = statusGeneration;
|
|
1009
|
-
const poll = async () => {
|
|
1010
|
-
try {
|
|
1011
|
-
const body = new URLSearchParams(new FormData(pairing));
|
|
1012
|
-
body.set('statusId', statusId);
|
|
1013
|
-
const response = await fetch('/pair/status', { method: 'POST', headers: { Accept: 'application/json' }, body });
|
|
1014
|
-
const result = await response.json();
|
|
1015
|
-
if (generation !== statusGeneration) return;
|
|
1016
|
-
if (!response.ok || !['pending', 'paired', 'unavailable'].includes(result?.state)) throw new Error('Pairing status unavailable');
|
|
1017
|
-
if (result.state === 'paired') {
|
|
1018
|
-
conceal();
|
|
1019
|
-
placeholder.setAttribute('hidden', '');
|
|
1020
|
-
pairSuccess.hidden = false;
|
|
1021
|
-
pairError.hidden = true;
|
|
1022
|
-
return;
|
|
1023
|
-
}
|
|
1024
|
-
if (result.state === 'unavailable') {
|
|
1025
|
-
conceal();
|
|
1026
|
-
pairError.textContent = '\u4E8C\u7EF4\u7801\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u663E\u793A\u3002';
|
|
1027
|
-
pairError.hidden = false;
|
|
1028
|
-
return;
|
|
1029
|
-
}
|
|
1030
|
-
pairError.hidden = true;
|
|
1031
|
-
} catch {
|
|
1032
|
-
// A lost status response is not pairing success. Retry until this QR expires.
|
|
1033
|
-
if (generation !== statusGeneration) return;
|
|
1034
|
-
pairError.textContent = '\u65E0\u6CD5\u786E\u8BA4\u914D\u5BF9\u72B6\u6001\uFF0C\u6B63\u5728\u91CD\u8BD5\u3002';
|
|
1035
|
-
pairError.hidden = false;
|
|
1036
|
-
}
|
|
1037
|
-
if (generation === statusGeneration) statusTimer = setTimeout(poll, 1000);
|
|
1038
|
-
};
|
|
1039
|
-
statusTimer = setTimeout(poll, 1000);
|
|
1040
|
-
};
|
|
1041
|
-
const expire = expiresAt => {
|
|
1042
|
-
clearTimeout(expiry);
|
|
1043
|
-
expiry = setTimeout(() => {
|
|
1044
|
-
conceal();
|
|
1045
|
-
pairError.textContent = '\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u663E\u793A\u3002';
|
|
1046
|
-
pairError.hidden = false;
|
|
1047
|
-
}, Math.max(0, expiresAt - Date.now()));
|
|
1048
|
-
};
|
|
1049
|
-
if (qr.dataset.expiresAt) expire(Number(qr.dataset.expiresAt));
|
|
1050
|
-
if (qr.dataset.statusId) watchStatus(qr.dataset.statusId);
|
|
1051
|
-
if (typeof window !== 'undefined') window.addEventListener('pagehide', conceal);
|
|
1052
|
-
hide.addEventListener('click', conceal);
|
|
1053
|
-
pairing.addEventListener('submit', async event => {
|
|
1054
|
-
event.preventDefault();
|
|
1055
|
-
if (loading) return;
|
|
1056
|
-
loading = true;
|
|
1057
|
-
show.disabled = refresh.disabled = hide.disabled = true;
|
|
1058
|
-
pairError.hidden = true;
|
|
1059
|
-
delete pairError.dataset.relayOffline;
|
|
1060
|
-
conceal();
|
|
1061
|
-
const generation = statusGeneration;
|
|
1062
|
-
const endpoint = event.submitter?.getAttribute('formaction') || pairing.action;
|
|
1063
|
-
try {
|
|
1064
|
-
const response = await fetch(endpoint, { method: 'POST', headers: { Accept: 'application/json' }, body: new URLSearchParams(new FormData(pairing)) });
|
|
1065
|
-
const result = await response.json().catch(() => null);
|
|
1066
|
-
if (generation !== statusGeneration) return;
|
|
1067
|
-
if (!response.ok || typeof result?.svg !== 'string' || typeof result?.expiresAt !== 'number') throw new Error(result?.error || '\u65E0\u6CD5\u751F\u6210\u4E8C\u7EF4\u7801\uFF08HTTP ' + response.status + '\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u3002');
|
|
1068
|
-
qr.innerHTML = result.svg;
|
|
1069
|
-
qr.hidden = false;
|
|
1070
|
-
placeholder.setAttribute('hidden', '');
|
|
1071
|
-
show.hidden = true;
|
|
1072
|
-
refresh.hidden = hide.hidden = false;
|
|
1073
|
-
expire(result.expiresAt);
|
|
1074
|
-
watchStatus(result.statusId);
|
|
1075
|
-
} catch (reason) {
|
|
1076
|
-
if (generation !== statusGeneration) return;
|
|
1077
|
-
conceal();
|
|
1078
|
-
pairError.textContent = reason instanceof Error ? reason.message : '\u65E0\u6CD5\u751F\u6210\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u91CD\u8BD5\u3002';
|
|
1079
|
-
pairError.hidden = false;
|
|
1080
|
-
} finally {
|
|
1081
|
-
loading = false;
|
|
1082
|
-
show.disabled = refresh.disabled = hide.disabled = false;
|
|
1083
|
-
}
|
|
1084
|
-
});
|
|
1085
|
-
})();
|
|
1086
|
-
`;
|
|
1087
|
-
|
|
1088
|
-
// src/relay-login-page.ts
|
|
1089
|
-
var RELAY_LOGIN_ERROR = "Microsoft \u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002";
|
|
1090
|
-
var LOGIN_ERROR_MESSAGES = /* @__PURE__ */ new Map([
|
|
1091
|
-
[
|
|
1092
|
-
"Cannot reach the Relay securely. Check the Relay address and connection, then try again.",
|
|
1093
|
-
"\u65E0\u6CD5\u5B89\u5168\u8FDE\u63A5 Relay\uFF0C\u8BF7\u68C0\u67E5 Relay \u5730\u5740\u548C\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002"
|
|
1094
|
-
],
|
|
1095
|
-
[
|
|
1096
|
-
"The Relay returned an invalid authorization response. Check the Relay configuration.",
|
|
1097
|
-
"Relay \u8FD4\u56DE\u7684\u767B\u5F55\u54CD\u5E94\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 Relay \u914D\u7F6E\u3002"
|
|
1098
|
-
],
|
|
1099
|
-
[
|
|
1100
|
-
"This Relay does not support browser sign-in. Ask its administrator to upgrade the Relay, then retry.",
|
|
1101
|
-
"\u6B64 Relay \u4E0D\u652F\u6301\u6D4F\u89C8\u5668\u767B\u5F55\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u5347\u7EA7 Relay \u540E\u91CD\u8BD5\u3002"
|
|
1102
|
-
],
|
|
1103
|
-
[
|
|
1104
|
-
"PC authorization expired. Cancel this request and sign in again.",
|
|
1105
|
-
"\u767B\u5F55\u8BF7\u6C42\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"
|
|
1106
|
-
],
|
|
1107
|
-
[
|
|
1108
|
-
"The Relay did not authorize this account. Contact the Relay administrator.",
|
|
1109
|
-
"\u6B64\u8D26\u6237\u672A\u83B7 Relay \u6388\u6743\uFF0C\u8BF7\u8054\u7CFB Relay \u7BA1\u7406\u5458\u3002"
|
|
1110
|
-
],
|
|
1111
|
-
[
|
|
1112
|
-
"Too many authorization attempts. Wait a minute and try again.",
|
|
1113
|
-
"\u767B\u5F55\u5C1D\u8BD5\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"
|
|
1114
|
-
],
|
|
1115
|
-
[
|
|
1116
|
-
"This authorization was already issued. Cancel this request before signing in again.",
|
|
1117
|
-
"\u6B64\u767B\u5F55\u8BF7\u6C42\u5DF2\u88AB\u4F7F\u7528\uFF0C\u8BF7\u91CD\u8BD5\u767B\u5F55\u4EE5\u5B89\u5168\u53D1\u8D77\u65B0\u8BF7\u6C42\u3002"
|
|
1118
|
-
],
|
|
1119
|
-
[
|
|
1120
|
-
"The credential exchange outcome is uncertain. Cancel this request before signing in again; do not repeat the exchange.",
|
|
1121
|
-
"\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"
|
|
1122
|
-
],
|
|
1123
|
-
[
|
|
1124
|
-
"Credential confirmation could not be verified. Restart AgentKnight to recover the saved credential.",
|
|
1125
|
-
"\u51ED\u636E\u786E\u8BA4\u7ED3\u679C\u672A\u77E5\u3002\u51ED\u636E\u5DF2\u4FDD\u5B58\uFF0C\u91CD\u8BD5\u5C06\u7EE7\u7EED\u786E\u8BA4\u3002"
|
|
1126
|
-
],
|
|
1127
|
-
[
|
|
1128
|
-
"The Relay confirmation service is unavailable. The credential is saved; retry after its administrator restores the service.",
|
|
1129
|
-
"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"
|
|
1130
|
-
],
|
|
1131
|
-
[
|
|
1132
|
-
"The saved Relay credential is no longer authorized. Sign in again.",
|
|
1133
|
-
"\u5DF2\u4FDD\u5B58\u7684 Relay \u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"
|
|
1134
|
-
],
|
|
1135
|
-
[
|
|
1136
|
-
"The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification, then retry.",
|
|
1137
|
-
"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"
|
|
1138
|
-
],
|
|
1139
|
-
[
|
|
1140
|
-
"Authorization cleanup could not be verified. Retry, or restart AgentKnight after the request expires.",
|
|
1141
|
-
"\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"
|
|
1142
|
-
],
|
|
1143
|
-
["PC authorization was cancelled.", "\u767B\u5F55\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"],
|
|
1144
|
-
[
|
|
1145
|
-
"AgentKnight login is closed. Restart AgentKnight to sign in.",
|
|
1146
|
-
"\u767B\u5F55\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u91CD\u542F AgentKnight \u540E\u91CD\u65B0\u767B\u5F55\u3002"
|
|
1147
|
-
],
|
|
1148
|
-
[
|
|
1149
|
-
"The Relay credential belongs to a different PC or account. Check the Relay configuration before signing in again.",
|
|
1150
|
-
"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"
|
|
1151
|
-
],
|
|
1152
|
-
[
|
|
1153
|
-
"Unlock your operating system credential store and restart AgentKnight. No file-based credential fallback is available.",
|
|
1154
|
-
"\u65E0\u6CD5\u8BBF\u95EE\u7CFB\u7EDF\u51ED\u636E\u5B58\u50A8\uFF0C\u8BF7\u89E3\u9501\u51ED\u636E\u5B58\u50A8\u5E76\u91CD\u542F AgentKnight\u3002"
|
|
1155
|
-
],
|
|
1156
|
-
[
|
|
1157
|
-
"The saved Relay credential is invalid. Recover it in your operating system credential manager before signing in.",
|
|
1158
|
-
"\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"
|
|
1159
|
-
],
|
|
1160
|
-
[
|
|
1161
|
-
"A different Relay account or enrollment is already saved for this PC. Resolve it before signing in again.",
|
|
1162
|
-
"\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"
|
|
1163
|
-
],
|
|
1164
|
-
[
|
|
1165
|
-
"The operating system credential store did not retain the credential. Unlock it and restart AgentKnight.",
|
|
1166
|
-
"\u7CFB\u7EDF\u672A\u80FD\u4FDD\u5B58\u767B\u5F55\u51ED\u636E\uFF0C\u8BF7\u89E3\u9501\u51ED\u636E\u5B58\u50A8\u5E76\u91CD\u542F AgentKnight\u3002"
|
|
1167
|
-
],
|
|
1168
|
-
[
|
|
1169
|
-
"Use an HTTPS Relay origin without a path, credentials, query, or fragment. HTTP is allowed only for literal loopback addresses.",
|
|
1170
|
-
"\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"
|
|
1171
|
-
],
|
|
1172
|
-
[
|
|
1173
|
-
"Microsoft sign-in requires Windows Credential Manager or macOS Keychain. This operating system is not supported.",
|
|
1174
|
-
"Microsoft \u767B\u5F55\u4EC5\u652F\u6301 Windows \u548C macOS\uFF0C\u8BF7\u4F7F\u7528\u53D7\u652F\u6301\u7684\u7CFB\u7EDF\u3002"
|
|
1175
|
-
],
|
|
1176
|
-
[
|
|
1177
|
-
"The Relay credential exceeds the operating system credential store capacity. Existing credentials were not changed. Contact your Relay administrator.",
|
|
1178
|
-
"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"
|
|
1179
|
-
]
|
|
1180
|
-
]);
|
|
1181
|
-
function renderRelayLoginPage(input) {
|
|
1182
|
-
const login = input.login;
|
|
1183
|
-
const error = LOGIN_ERROR_MESSAGES.get(login.state === "error" ? login.message : input.error ?? "") ?? RELAY_LOGIN_ERROR;
|
|
1184
|
-
const busy = login.state === "starting" || login.state === "confirming" || login.state === "signed-in";
|
|
1185
|
-
const token = `<input type="hidden" name="token" value="${escapeHtml(input.token)}">`;
|
|
1186
|
-
const action = login.state === "pending" ? `<a class="button" href="${escapeHtml(login.verificationUri)}" rel="noreferrer">\u7EE7\u7EED Microsoft \u767B\u5F55</a>
|
|
1187
|
-
<form method="post" action="/relay-login/cancel">${token}<button class="secondary" type="submit">\u53D6\u6D88</button></form>` : busy ? `<button type="button" disabled aria-busy="true">${login.state === "starting" ? "\u6B63\u5728\u767B\u5F55\u2026" : login.state === "confirming" ? "\u6B63\u5728\u786E\u8BA4\u767B\u5F55\u51ED\u636E\u2026" : "\u6B63\u5728\u8FDE\u63A5\u2026"}</button>` : `<form method="post" action="/relay-login/start">${token}<button type="submit">${login.state === "error" ? "\u91CD\u8BD5\u767B\u5F55" : "\u4F7F\u7528 Microsoft \u767B\u5F55"}</button></form>`;
|
|
1188
|
-
return `<!doctype html>
|
|
1189
|
-
<html lang="zh-CN">
|
|
1190
|
-
<head>
|
|
1191
|
-
<meta charset="utf-8">
|
|
1192
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1193
|
-
<script src="/relay-login.js" defer></script>
|
|
1194
|
-
<title>AgentKnight</title>
|
|
1195
|
-
<style>
|
|
1196
|
-
:root { color-scheme: light dark; font-family: "Segoe UI", system-ui, sans-serif; background: #f5f7fb; color: #172338; --panel: #fff; --border: #dfe6ef; --muted: #63728a; --accent: #275cd5; }
|
|
1197
|
-
* { box-sizing: border-box; }
|
|
1198
|
-
body { margin: 0; padding: 48px 28px; }
|
|
1199
|
-
main { max-width: 480px; margin: 8vh auto; }
|
|
1200
|
-
header { margin-bottom: 28px; }
|
|
1201
|
-
h1 { margin: 0; font-size: clamp(24px, 4vw, 32px); letter-spacing: -.7px; overflow-wrap: anywhere; }
|
|
1202
|
-
h2 { margin: 0 0 24px; font-size: 19px; font-weight: 650; }
|
|
1203
|
-
.brand { display: inline-flex; align-items: center; gap: 9px; font-weight: 650; font-size: 14px; color: var(--muted); margin-bottom: 12px; }
|
|
1204
|
-
.brand-mark { width: 12px; height: 12px; border-radius: 4px; background: var(--accent); transform: rotate(-12deg); }
|
|
1205
|
-
.login { padding: 28px; background: var(--panel); border: 1px solid var(--border); border-radius: 20px; }
|
|
1206
|
-
form { margin: 0; }
|
|
1207
|
-
form + form, .button + form { margin-top: 12px; }
|
|
1208
|
-
button, .button { display: block; width: 100%; padding: 12px 20px; border: 1px solid transparent; border-radius: 10px; background: var(--accent); color: #fff; font: inherit; font-size: 14px; font-weight: 650; cursor: pointer; text-align: center; text-decoration: none; }
|
|
1209
|
-
button:disabled { opacity: .6; cursor: default; }
|
|
1210
|
-
.secondary { background: var(--panel); color: var(--accent); border-color: var(--border); }
|
|
1211
|
-
.error { margin: 0 0 24px; color: #b42318; font-size: 14px; line-height: 1.6; overflow-wrap: anywhere; }
|
|
1212
|
-
:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; }
|
|
1213
|
-
@media (max-width: 600px) { body { padding: 24px 16px; } main { margin: 4vh auto; } .login { padding: 24px; } }
|
|
1214
|
-
@media (prefers-color-scheme: dark) {
|
|
1215
|
-
:root { background: #111925; color: #e6edf6; --panel: #192435; --border: #33435b; --muted: #a0aec4; --accent: #8cabff; }
|
|
1216
|
-
button:not(.secondary), .button { background: #416fe0; color: #fff; }
|
|
1217
|
-
.error { color: #ffb4ab; }
|
|
1218
|
-
}
|
|
1219
|
-
</style>
|
|
1220
|
-
</head>
|
|
1221
|
-
<body>
|
|
1222
|
-
<main data-relay-login-state="${login.state}">
|
|
1223
|
-
<header><span class="brand"><span class="brand-mark" aria-hidden="true"></span>AgentKnight</span><h1>${escapeHtml(input.machineName)}</h1></header>
|
|
1224
|
-
<section class="login" aria-labelledby="login-heading">
|
|
1225
|
-
<h2 id="login-heading">${login.state === "confirming" ? "\u786E\u8BA4\u7535\u8111\u767B\u5F55" : login.state === "signed-in" ? "\u542F\u52A8 AgentKnight" : "Microsoft \u767B\u5F55"}</h2>
|
|
1226
|
-
${login.state === "error" || input.error !== void 0 ? `<p class="error" role="alert">${escapeHtml(error)}</p>` : ""}
|
|
1227
|
-
${action}
|
|
1228
|
-
</section>
|
|
1229
|
-
</main>
|
|
1230
|
-
</body>
|
|
1231
|
-
</html>`;
|
|
1232
|
-
}
|
|
1233
|
-
var relayLoginPageScript = `
|
|
1234
|
-
(() => {
|
|
1235
|
-
let main = document.querySelector('main[data-relay-login-state]');
|
|
1236
|
-
if (!main) return;
|
|
1237
|
-
let timer;
|
|
1238
|
-
let stopped = false;
|
|
1239
|
-
let refreshPage = false;
|
|
1240
|
-
let navigationGeneration = 0;
|
|
1241
|
-
const poll = async () => {
|
|
1242
|
-
const generation = navigationGeneration;
|
|
1243
|
-
const isCurrent = () => !stopped && generation === navigationGeneration;
|
|
1244
|
-
if (!isCurrent()) return;
|
|
1245
|
-
try {
|
|
1246
|
-
const response = await fetch('/relay-login/status', { cache: 'no-store' });
|
|
1247
|
-
if (!isCurrent()) return;
|
|
1248
|
-
const state = response.ok ? await response.json() : null;
|
|
1249
|
-
if (!isCurrent()) return;
|
|
1250
|
-
if (refreshPage || response.status === 404 || (state && typeof state.state === 'string' &&
|
|
1251
|
-
(state.state !== main.dataset.relayLoginState || state.state === 'signed-in'))) {
|
|
1252
|
-
const page = await fetch('/', { cache: 'no-store' });
|
|
1253
|
-
if (!isCurrent()) return;
|
|
1254
|
-
if (page.ok) {
|
|
1255
|
-
const html = await page.text();
|
|
1256
|
-
if (!isCurrent()) return;
|
|
1257
|
-
const nextPage = new DOMParser().parseFromString(html, 'text/html');
|
|
1258
|
-
const nextMain = nextPage.querySelector('main[data-relay-login-state]');
|
|
1259
|
-
if (nextMain) {
|
|
1260
|
-
main.replaceWith(nextMain);
|
|
1261
|
-
main = nextMain;
|
|
1262
|
-
refreshPage = false;
|
|
1263
|
-
} else if (nextPage.querySelector('#pairing-form')) {
|
|
1264
|
-
stopped = true;
|
|
1265
|
-
location.replace('/');
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
}
|
|
1269
|
-
} catch {
|
|
1270
|
-
// Keep the page recoverable after transient local request failures.
|
|
1271
|
-
} finally {
|
|
1272
|
-
if (isCurrent()) timer = setTimeout(poll, 1500);
|
|
1273
|
-
}
|
|
1274
|
-
};
|
|
1275
|
-
document.addEventListener('submit', event => {
|
|
1276
|
-
const form = event.target;
|
|
1277
|
-
const action = form.getAttribute('action');
|
|
1278
|
-
if (action !== '/relay-login/start' && action !== '/relay-login/cancel') return;
|
|
1279
|
-
const button = form.querySelector('button');
|
|
1280
|
-
if (button.disabled) { event.preventDefault(); return; }
|
|
1281
|
-
button.disabled = true;
|
|
1282
|
-
button.setAttribute('aria-busy', 'true');
|
|
1283
|
-
button.textContent = action === '/relay-login/start' ? '\u6B63\u5728\u767B\u5F55\u2026' : '\u6B63\u5728\u53D6\u6D88\u2026';
|
|
1284
|
-
});
|
|
1285
|
-
addEventListener('pagehide', () => { stopped = true; navigationGeneration++; clearTimeout(timer); });
|
|
1286
|
-
addEventListener('pageshow', () => {
|
|
1287
|
-
if (stopped) {
|
|
1288
|
-
stopped = false;
|
|
1289
|
-
// Cached form controls may still be busy even when the login state is unchanged.
|
|
1290
|
-
refreshPage = true;
|
|
1291
|
-
timer = setTimeout(poll, 0);
|
|
1292
|
-
}
|
|
1293
|
-
});
|
|
1294
|
-
timer = setTimeout(poll, 1500);
|
|
1295
|
-
})();
|
|
1296
|
-
`;
|
|
1297
|
-
|
|
1298
|
-
// src/pairing-page.ts
|
|
1299
|
-
var PAIRING_PAGE_HOST = "127.0.0.1";
|
|
1300
|
-
var MAX_FORM_BODY_BYTES = 1024;
|
|
1301
|
-
var FormBodyTooLargeError = class extends Error {
|
|
1302
|
-
};
|
|
1303
|
-
var PairingPageServer = class {
|
|
1304
|
-
#options;
|
|
1305
|
-
#refreshToken = randomBytes(24).toString("base64url");
|
|
1306
|
-
#server;
|
|
1307
|
-
#saving = false;
|
|
1308
|
-
#loginMutating = false;
|
|
1309
|
-
#loginFailureMessage;
|
|
1310
|
-
constructor(options) {
|
|
1311
|
-
this.#options = options;
|
|
1312
|
-
this.#server = createServer((request, response) => {
|
|
1313
|
-
void this.#handleRequest(request, response).catch((error) => {
|
|
1314
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "mobile.pairing-page.request.failed");
|
|
1315
|
-
if (!response.headersSent) {
|
|
1316
|
-
this.#writeHeaders(response, error instanceof FormBodyTooLargeError ? 413 : 503, "text/plain; charset=utf-8");
|
|
1317
|
-
}
|
|
1318
|
-
if (!response.writableEnded) {
|
|
1319
|
-
response.end(error instanceof FormBodyTooLargeError ? "Form body exceeds the size limit." : "Local page is temporarily unavailable.");
|
|
1320
|
-
}
|
|
1321
|
-
});
|
|
1322
|
-
});
|
|
1323
|
-
}
|
|
1324
|
-
get url() {
|
|
1325
|
-
const address = this.#server.address();
|
|
1326
|
-
if (address === null || typeof address === "string") throw new Error("Pairing page server is not listening");
|
|
1327
|
-
return `http://${PAIRING_PAGE_HOST}:${address.port}`;
|
|
1328
|
-
}
|
|
1329
|
-
async start() {
|
|
1330
|
-
if (this.#server.listening) return;
|
|
1331
|
-
await new Promise((resolve3, reject) => {
|
|
1332
|
-
const onError = (error) => {
|
|
1333
|
-
this.#server.off("listening", onListening);
|
|
1334
|
-
reject(error);
|
|
1335
|
-
};
|
|
1336
|
-
const onListening = () => {
|
|
1337
|
-
this.#server.off("error", onError);
|
|
1338
|
-
resolve3();
|
|
1339
|
-
};
|
|
1340
|
-
this.#server.once("error", onError);
|
|
1341
|
-
this.#server.once("listening", onListening);
|
|
1342
|
-
this.#server.listen(this.#options.port, PAIRING_PAGE_HOST);
|
|
1343
|
-
});
|
|
1344
|
-
}
|
|
1345
|
-
async stop() {
|
|
1346
|
-
if (!this.#server.listening) return;
|
|
1347
|
-
await new Promise((resolve3, reject) => {
|
|
1348
|
-
this.#server.close((error) => error === void 0 ? resolve3() : reject(error));
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
useRuntime(options) {
|
|
1352
|
-
if (this.#options.relayLogin?.getState().state !== "signed-in") {
|
|
1353
|
-
throw new Error("Microsoft sign-in must finish before starting the local runtime page.");
|
|
1354
|
-
}
|
|
1355
|
-
this.#options = { ...options, port: Number(new URL(this.url).port) };
|
|
1356
|
-
this.#loginFailureMessage = void 0;
|
|
1357
|
-
return this;
|
|
1358
|
-
}
|
|
1359
|
-
async #handleRequest(request, response) {
|
|
1360
|
-
if (request.headers.host !== new URL(this.url).host) {
|
|
1361
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8", "no-referrer");
|
|
1362
|
-
response.end("Invalid Host header.");
|
|
1363
|
-
return;
|
|
1364
|
-
}
|
|
1365
|
-
const requestUrl = new URL(request.url ?? "/", "http://localhost");
|
|
1366
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login/callback") {
|
|
1367
|
-
const params = requestUrl.searchParams;
|
|
1368
|
-
if ((request.url ?? "").startsWith("/relay-login/callback?") && !requestUrl.hash && [...params.keys()].every((key) => params.getAll(key).length === 1)) {
|
|
1369
|
-
try {
|
|
1370
|
-
const release = this.#options.relayLogin?.acceptCallback(
|
|
1371
|
-
Object.fromEntries(params),
|
|
1372
|
-
`${this.url}/relay-login/callback`
|
|
1373
|
-
);
|
|
1374
|
-
if (release) {
|
|
1375
|
-
this.#loginFailureMessage = void 0;
|
|
1376
|
-
response.once("finish", release);
|
|
1377
|
-
}
|
|
1378
|
-
} catch {
|
|
1379
|
-
this.#options.logger?.error({ operation: "callback" }, "relay.login.operation.failed");
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
this.#redirectLogin(response, "/");
|
|
1383
|
-
return;
|
|
1384
|
-
}
|
|
1385
|
-
if (request.method === "GET" && requestUrl.pathname === "/health") {
|
|
1386
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1387
|
-
response.end('{"ok":true}');
|
|
1388
|
-
return;
|
|
1389
|
-
}
|
|
1390
|
-
if (request.method === "GET" && requestUrl.pathname === "/local-page.js") {
|
|
1391
|
-
this.#writeHeaders(response, 200, "text/javascript; charset=utf-8");
|
|
1392
|
-
response.end(localPageScript);
|
|
1393
|
-
return;
|
|
1394
|
-
}
|
|
1395
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login.js") {
|
|
1396
|
-
this.#writeHeaders(response, 200, "text/javascript; charset=utf-8");
|
|
1397
|
-
response.end(relayLoginPageScript);
|
|
1398
|
-
return;
|
|
1399
|
-
}
|
|
1400
|
-
if (request.method === "GET" && (requestUrl.pathname === "/" || requestUrl.pathname === "/pair")) {
|
|
1401
|
-
await this.#renderPage(response, 200, { saved: requestUrl.searchParams.get("saved") === "1" });
|
|
1402
|
-
return;
|
|
1403
|
-
}
|
|
1404
|
-
const relayLogin = this.#options.relayLogin;
|
|
1405
|
-
if (requestUrl.pathname === "/session" && relayLogin === void 0 && this.#options.sessions !== void 0) {
|
|
1406
|
-
if (request.method !== "GET") {
|
|
1407
|
-
response.setHeader("allow", "GET");
|
|
1408
|
-
this.#writeHeaders(response, 405, "text/plain; charset=utf-8");
|
|
1409
|
-
response.end("Method not allowed.");
|
|
1410
|
-
return;
|
|
1411
|
-
}
|
|
1412
|
-
if (request.headers.origin !== void 0 && request.headers.origin !== this.url || request.headers["sec-fetch-site"] === "cross-site") {
|
|
1413
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
1414
|
-
response.end("Invalid request origin.");
|
|
1415
|
-
return;
|
|
1416
|
-
}
|
|
1417
|
-
const params = requestUrl.searchParams;
|
|
1418
|
-
const parsed = SessionTimelinePageRequestSchema.pick({ sessionId: true, cursor: true }).strict().safeParse(Object.fromEntries(params));
|
|
1419
|
-
if (!parsed.success || [...params.keys()].some((key) => params.getAll(key).length !== 1)) {
|
|
1420
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
1421
|
-
response.end("Invalid session request.");
|
|
1422
|
-
return;
|
|
1423
|
-
}
|
|
1424
|
-
let session;
|
|
1425
|
-
try {
|
|
1426
|
-
session = (await this.#options.sessions.list()).find((entry) => entry.id === parsed.data.sessionId);
|
|
1427
|
-
if (session === void 0) {
|
|
1428
|
-
this.#writeHeaders(response, 404, "text/html; charset=utf-8");
|
|
1429
|
-
response.end(renderSessionPage({ machineName: this.#options.machineName, error: "\u627E\u4E0D\u5230\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u8BF7\u8FD4\u56DE\u5217\u8868\u5237\u65B0\u3002" }));
|
|
1430
|
-
return;
|
|
1431
|
-
}
|
|
1432
|
-
const page = SessionTimelinePageSchema.parse(await this.#options.sessions.readPage(session.id, parsed.data.cursor));
|
|
1433
|
-
const expired = page.cursorStatus === "expired" || page.hasMore && (!page.cursor || page.cursor === parsed.data.cursor);
|
|
1434
|
-
this.#writeHeaders(response, expired ? 409 : 200, "text/html; charset=utf-8");
|
|
1435
|
-
response.end(renderSessionPage({
|
|
1436
|
-
machineName: this.#options.machineName,
|
|
1437
|
-
session,
|
|
1438
|
-
...expired ? { error: "\u5386\u53F2\u8BB0\u5F55\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u6700\u65B0\u6D88\u606F\u540E\u91CD\u8BD5\u3002" } : { page }
|
|
1439
|
-
}));
|
|
1440
|
-
} catch (error) {
|
|
1441
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "local.session-page.read.failed");
|
|
1442
|
-
this.#writeHeaders(response, 503, "text/html; charset=utf-8");
|
|
1443
|
-
response.end(renderSessionPage({
|
|
1444
|
-
machineName: this.#options.machineName,
|
|
1445
|
-
...session === void 0 ? {} : { session },
|
|
1446
|
-
error: "\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u8BD5\u6216\u8FD4\u56DE\u5217\u8868\u68C0\u67E5 Agent \u72B6\u6001\u3002"
|
|
1447
|
-
}));
|
|
1448
|
-
}
|
|
1449
|
-
return;
|
|
1450
|
-
}
|
|
1451
|
-
if (relayLogin === void 0 && this.#options.reconnectRelay !== void 0 && request.method === "GET" && requestUrl.pathname === "/relay-status") {
|
|
1452
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1453
|
-
response.end(JSON.stringify({ state: this.#options.getRegistrationStatus().state }));
|
|
1454
|
-
return;
|
|
1455
|
-
}
|
|
1456
|
-
if (relayLogin === void 0 && this.#options.getAccount !== void 0 && request.method === "GET" && requestUrl.pathname === "/relay-account") {
|
|
1457
|
-
const account = await this.#options.getAccount();
|
|
1458
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1459
|
-
response.end(JSON.stringify(account));
|
|
1460
|
-
return;
|
|
1461
|
-
}
|
|
1462
|
-
if (relayLogin !== void 0) {
|
|
1463
|
-
if (request.method === "GET" && requestUrl.pathname === "/relay-login/status") {
|
|
1464
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1465
|
-
response.end(JSON.stringify({ state: this.#loginState(relayLogin).state }));
|
|
1466
|
-
return;
|
|
1467
|
-
}
|
|
1468
|
-
if (request.method === "POST" && (requestUrl.pathname === "/relay-login/start" || requestUrl.pathname === "/relay-login/cancel")) {
|
|
1469
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
1470
|
-
if (form === void 0) return;
|
|
1471
|
-
if (form.getAll("token").length !== 1 || [...form.keys()].some((key) => key !== "token")) {
|
|
1472
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
1473
|
-
response.end("\u767B\u5F55\u8BF7\u6C42\u65E0\u6548\u3002");
|
|
1474
|
-
return;
|
|
1475
|
-
}
|
|
1476
|
-
const operation = requestUrl.pathname === "/relay-login/start" ? "start" : "cancel";
|
|
1477
|
-
const login = this.#loginState(relayLogin);
|
|
1478
|
-
if (this.#loginMutating || (operation === "start" ? login.state !== "signed-out" && login.state !== "error" : login.state !== "pending" && login.state !== "starting" && login.state !== "confirming")) {
|
|
1479
|
-
this.#renderLogin(response, 409, login);
|
|
1480
|
-
return;
|
|
1481
|
-
}
|
|
1482
|
-
this.#loginMutating = true;
|
|
1483
|
-
this.#loginFailureMessage = void 0;
|
|
1484
|
-
try {
|
|
1485
|
-
if (operation === "start") await relayLogin.start();
|
|
1486
|
-
else await relayLogin.cancel();
|
|
1487
|
-
} catch (error) {
|
|
1488
|
-
this.#loginFailureMessage = error instanceof Error ? error.message : RELAY_LOGIN_ERROR;
|
|
1489
|
-
this.#options.logger?.error({ operation }, "relay.login.operation.failed");
|
|
1490
|
-
this.#renderLogin(response, 503, this.#loginState(relayLogin));
|
|
1491
|
-
return;
|
|
1492
|
-
} finally {
|
|
1493
|
-
this.#loginMutating = false;
|
|
1494
|
-
}
|
|
1495
|
-
const next = relayLogin.getState();
|
|
1496
|
-
this.#redirectLogin(response, operation === "start" && next.state === "pending" ? next.verificationUri : "/");
|
|
1497
|
-
return;
|
|
1498
|
-
}
|
|
1499
|
-
if (request.method === "POST" && ["/pair", "/pair/status", "/refresh", "/selection", "/group-chat-settings", "/peer-chat-settings", "/relay-reconnect", "/relay-disconnect"].includes(requestUrl.pathname)) {
|
|
1500
|
-
if (await this.#readAuthorizedForm(request, response) === void 0) return;
|
|
1501
|
-
this.#renderLogin(response, 409, this.#loginState(relayLogin));
|
|
1502
|
-
return;
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
const relayOperation = requestUrl.pathname === "/relay-reconnect" ? this.#options.reconnectRelay : requestUrl.pathname === "/relay-disconnect" ? this.#options.disconnectRelay : void 0;
|
|
1506
|
-
if (request.method === "POST" && relayOperation !== void 0) {
|
|
1507
|
-
const disconnecting = requestUrl.pathname === "/relay-disconnect";
|
|
1508
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
1509
|
-
if (form === void 0) return;
|
|
1510
|
-
if (form.getAll("token").length !== 1 || [...form.keys()].some((key) => key !== "token")) {
|
|
1511
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
1512
|
-
response.end(disconnecting ? "Invalid Relay disconnect request." : "Invalid Relay reconnect request.");
|
|
1513
|
-
return;
|
|
1514
|
-
}
|
|
1515
|
-
try {
|
|
1516
|
-
relayOperation();
|
|
1517
|
-
} catch (error) {
|
|
1518
|
-
const message = disconnecting ? "\u65E0\u6CD5\u65AD\u5F00 Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002" : "\u65E0\u6CD5\u91CD\u8FDE Relay\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";
|
|
1519
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, disconnecting ? "relay.disconnect.failed" : "relay.reconnect.failed");
|
|
1520
|
-
if (wantsJson(request)) {
|
|
1521
|
-
this.#writeHeaders(response, 503, "application/json; charset=utf-8");
|
|
1522
|
-
response.end(JSON.stringify({ error: message }));
|
|
1523
|
-
} else {
|
|
1524
|
-
await this.#renderPage(response, 503, { reconnectError: message });
|
|
1525
|
-
}
|
|
1526
|
-
return;
|
|
1527
|
-
}
|
|
1528
|
-
if (wantsJson(request)) {
|
|
1529
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1530
|
-
response.end(JSON.stringify({ state: this.#options.getRegistrationStatus().state }));
|
|
1531
|
-
} else {
|
|
1532
|
-
response.writeHead(303, { location: "/", "cache-control": "no-store" });
|
|
1533
|
-
response.end();
|
|
1534
|
-
}
|
|
1535
|
-
return;
|
|
1536
|
-
}
|
|
1537
|
-
const chatKind = requestUrl.pathname === "/group-chat-settings" ? "group" : requestUrl.pathname === "/peer-chat-settings" ? "peer" : void 0;
|
|
1538
|
-
const chatSettings = chatKind === "group" ? this.#options.groupChatSettings : this.#options.peerChatSettings;
|
|
1539
|
-
if (request.method === "POST" && chatKind !== void 0 && chatSettings !== void 0) {
|
|
1540
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
1541
|
-
if (form === void 0) return;
|
|
1542
|
-
const values = form.getAll("enabled");
|
|
1543
|
-
if (form.getAll("token").length !== 1 || values.length !== 1 || values[0] !== "true" && values[0] !== "false" || [...form.keys()].some((key) => key !== "token" && key !== "enabled")) {
|
|
1544
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
1545
|
-
response.end(`Invalid ${chatKind} chat setting.`);
|
|
1546
|
-
return;
|
|
1547
|
-
}
|
|
1548
|
-
if (this.#saving) {
|
|
1549
|
-
await this.#chatSettingsError(request, response, chatKind, "\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");
|
|
1550
|
-
return;
|
|
1551
|
-
}
|
|
1552
|
-
this.#saving = true;
|
|
1553
|
-
try {
|
|
1554
|
-
await chatSettings.save(values[0] === "true");
|
|
1555
|
-
} catch (error) {
|
|
1556
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, `${chatKind}-chat.settings.save.failed`);
|
|
1557
|
-
await this.#chatSettingsError(
|
|
1558
|
-
request,
|
|
1559
|
-
response,
|
|
1560
|
-
chatKind,
|
|
1561
|
-
`${chatKind === "group" ? "\u7FA4\u804A" : "\u8DE8 PC \u901A\u4FE1"}\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002`
|
|
1562
|
-
);
|
|
1563
|
-
return;
|
|
1564
|
-
} finally {
|
|
1565
|
-
this.#saving = false;
|
|
1566
|
-
}
|
|
1567
|
-
if (wantsJson(request)) {
|
|
1568
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1569
|
-
response.end(JSON.stringify({ ok: true, enabled: chatSettings.enabled }));
|
|
1570
|
-
} else {
|
|
1571
|
-
response.writeHead(303, { location: "/", "cache-control": "no-store" });
|
|
1572
|
-
response.end();
|
|
1573
|
-
}
|
|
1574
|
-
return;
|
|
1575
|
-
}
|
|
1576
|
-
const selection = this.#options.agentSelection;
|
|
1577
|
-
if (request.method === "POST" && requestUrl.pathname === "/selection" && selection !== void 0) {
|
|
1578
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
1579
|
-
if (form === void 0) return;
|
|
1580
|
-
const parsed = AgentSelectionSchema2.safeParse({ agents: form.getAll("agents") });
|
|
1581
|
-
if (!parsed.success) {
|
|
1582
|
-
this.#writeHeaders(response, 400, "text/plain; charset=utf-8");
|
|
1583
|
-
response.end("Invalid agent selection.");
|
|
1584
|
-
return;
|
|
1585
|
-
}
|
|
1586
|
-
if (this.#saving) {
|
|
1587
|
-
await this.#selectionError(request, response, "\u6B63\u5728\u540C\u6B65\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002", parsed.data.agents);
|
|
1588
|
-
return;
|
|
1589
|
-
}
|
|
1590
|
-
this.#saving = true;
|
|
1591
|
-
try {
|
|
1592
|
-
await selection.saveSelection(parsed.data);
|
|
1593
|
-
} catch (error) {
|
|
1594
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "coding-agent.selection.failed");
|
|
1595
|
-
await this.#selectionError(request, response, toErrorDetails(error).message, parsed.data.agents);
|
|
1596
|
-
return;
|
|
1597
|
-
} finally {
|
|
1598
|
-
this.#saving = false;
|
|
1599
|
-
}
|
|
1600
|
-
if (wantsJson(request)) {
|
|
1601
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1602
|
-
response.end('{"ok":true}');
|
|
1603
|
-
} else {
|
|
1604
|
-
response.writeHead(303, { location: "/?saved=1", "cache-control": "no-store" });
|
|
1605
|
-
response.end();
|
|
1606
|
-
}
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
if (request.method === "POST" && requestUrl.pathname === "/pair/status") {
|
|
1610
|
-
const form = await this.#readAuthorizedForm(request, response);
|
|
1611
|
-
if (form === void 0) return;
|
|
1612
|
-
const statusId = PairingStatusRequestSchema.shape.statusId.safeParse(form.get("statusId"));
|
|
1613
|
-
if (!statusId.success || form.getAll("statusId").length !== 1) {
|
|
1614
|
-
this.#writeHeaders(response, 400, "application/json; charset=utf-8");
|
|
1615
|
-
response.end(JSON.stringify({ error: "Invalid pairing status identity." }));
|
|
1616
|
-
return;
|
|
1617
|
-
}
|
|
1618
|
-
const state = await this.#options.pairingProvider.getPairingStatus?.(statusId.data) ?? "unavailable";
|
|
1619
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1620
|
-
response.end(JSON.stringify({ state }));
|
|
1621
|
-
return;
|
|
1622
|
-
}
|
|
1623
|
-
if (request.method === "POST" && (requestUrl.pathname === "/pair" || requestUrl.pathname === "/refresh")) {
|
|
1624
|
-
if (await this.#readAuthorizedForm(request, response) === void 0) return;
|
|
1625
|
-
const registration = this.#options.getRegistrationStatus();
|
|
1626
|
-
if (registration.state !== "registered") {
|
|
1627
|
-
await this.#pairingError(request, response, registration.message);
|
|
1628
|
-
return;
|
|
1629
|
-
}
|
|
1630
|
-
try {
|
|
1631
|
-
const pairing = await this.#options.pairingProvider.getPairing({ force: requestUrl.pathname === "/refresh" });
|
|
1632
|
-
const svg = await QRCode.toString(pairing.uri, {
|
|
1633
|
-
type: "svg",
|
|
1634
|
-
errorCorrectionLevel: "M",
|
|
1635
|
-
margin: 3,
|
|
1636
|
-
width: 420,
|
|
1637
|
-
color: { dark: "#101820", light: "#ffffff" }
|
|
1638
|
-
});
|
|
1639
|
-
const rendered = {
|
|
1640
|
-
svg,
|
|
1641
|
-
expiresAt: pairing.expiresAt,
|
|
1642
|
-
...pairing.statusId === void 0 ? {} : { statusId: pairing.statusId }
|
|
1643
|
-
};
|
|
1644
|
-
if (wantsJson(request)) {
|
|
1645
|
-
this.#writeHeaders(response, 200, "application/json; charset=utf-8");
|
|
1646
|
-
response.end(JSON.stringify(rendered));
|
|
1647
|
-
} else {
|
|
1648
|
-
await this.#renderPage(response, 200, { pairing: rendered });
|
|
1649
|
-
}
|
|
1650
|
-
} catch (error) {
|
|
1651
|
-
this.#options.logger?.error({ error: toErrorDetails(error) }, "mobile.pairing-page.generate.failed");
|
|
1652
|
-
await this.#pairingError(request, response, toErrorDetails(error).message);
|
|
1653
|
-
}
|
|
1654
|
-
return;
|
|
1655
|
-
}
|
|
1656
|
-
if ([
|
|
1657
|
-
"/",
|
|
1658
|
-
"/pair",
|
|
1659
|
-
"/pair/status",
|
|
1660
|
-
"/selection",
|
|
1661
|
-
"/group-chat-settings",
|
|
1662
|
-
"/peer-chat-settings",
|
|
1663
|
-
"/refresh",
|
|
1664
|
-
"/local-page.js",
|
|
1665
|
-
"/relay-login.js",
|
|
1666
|
-
"/relay-login/start",
|
|
1667
|
-
"/relay-login/cancel",
|
|
1668
|
-
"/relay-login/callback",
|
|
1669
|
-
"/relay-reconnect",
|
|
1670
|
-
"/relay-disconnect",
|
|
1671
|
-
...this.#options.reconnectRelay === void 0 || relayLogin !== void 0 ? [] : ["/relay-status"],
|
|
1672
|
-
...relayLogin === void 0 ? [] : ["/relay-login/status"]
|
|
1673
|
-
].includes(requestUrl.pathname)) {
|
|
1674
|
-
response.setHeader("allow", requestUrl.pathname === "/pair" ? "GET, POST" : ["/", "/local-page.js", "/relay-login.js", "/relay-login/status", "/relay-login/callback", "/relay-status"].includes(requestUrl.pathname) ? "GET" : "POST");
|
|
1675
|
-
this.#writeHeaders(response, 405, "text/plain; charset=utf-8");
|
|
1676
|
-
response.end("Method not allowed.");
|
|
1677
|
-
return;
|
|
1678
|
-
}
|
|
1679
|
-
this.#writeHeaders(response, 404, "text/plain; charset=utf-8");
|
|
1680
|
-
response.end("Not found.");
|
|
1681
|
-
}
|
|
1682
|
-
async #readAuthorizedForm(request, response) {
|
|
1683
|
-
if (request.headers.origin !== void 0 && request.headers.origin !== this.url || request.headers["sec-fetch-site"] === "cross-site") {
|
|
1684
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
1685
|
-
response.end("Invalid request origin.");
|
|
1686
|
-
return void 0;
|
|
1687
|
-
}
|
|
1688
|
-
if (!request.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) {
|
|
1689
|
-
this.#writeHeaders(response, 415, "text/plain; charset=utf-8");
|
|
1690
|
-
response.end("Expected form data.");
|
|
1691
|
-
return void 0;
|
|
1692
|
-
}
|
|
1693
|
-
const form = new URLSearchParams(await readFormBody(request));
|
|
1694
|
-
if (!secureEqual(form.get("token"), this.#refreshToken)) {
|
|
1695
|
-
this.#writeHeaders(response, 403, "text/plain; charset=utf-8");
|
|
1696
|
-
response.end("Invalid local page token.");
|
|
1697
|
-
return void 0;
|
|
1698
|
-
}
|
|
1699
|
-
return form;
|
|
1700
|
-
}
|
|
1701
|
-
async #renderPage(response, status, state = {}) {
|
|
1702
|
-
if (this.#options.relayLogin !== void 0) {
|
|
1703
|
-
this.#renderLogin(response, status, this.#loginState(this.#options.relayLogin));
|
|
1704
|
-
return;
|
|
1705
|
-
}
|
|
1706
|
-
const agents = state.agents ?? await this.#options.agentSelection?.listAgents();
|
|
1707
|
-
const sessions = agents === void 0 ? await this.#options.sessions?.list() : void 0;
|
|
1708
|
-
const deploymentInfo = await this.#options.getDeploymentInfo?.();
|
|
1709
|
-
const account = await this.#options.getAccount?.();
|
|
1710
|
-
const registration = this.#options.getRegistrationStatus();
|
|
1711
|
-
this.#writeHeaders(response, status, "text/html; charset=utf-8");
|
|
1712
|
-
response.end(renderAgentSelectionPage({
|
|
1713
|
-
machineName: this.#options.machineName,
|
|
1714
|
-
token: this.#refreshToken,
|
|
1715
|
-
...this.#options.reconnectRelay === void 0 ? {} : { relayState: registration.state },
|
|
1716
|
-
...this.#options.disconnectRelay === void 0 ? {} : { canDisconnectRelay: true },
|
|
1717
|
-
...deploymentInfo === void 0 ? {} : { deploymentInfo },
|
|
1718
|
-
...account === void 0 ? {} : { account },
|
|
1719
|
-
...agents === void 0 ? {} : { agents },
|
|
1720
|
-
...sessions === void 0 ? {} : { sessions },
|
|
1721
|
-
canReadSessions: this.#options.sessions !== void 0,
|
|
1722
|
-
...this.#options.groupChatSettings === void 0 ? {} : { groupChatEnabled: this.#options.groupChatSettings.enabled },
|
|
1723
|
-
...this.#options.peerChatSettings === void 0 ? {} : { peerChatEnabled: this.#options.peerChatSettings.enabled },
|
|
1724
|
-
...registration.state === "registered" ? {} : { pairingError: registration.message },
|
|
1725
|
-
...state
|
|
1726
|
-
}));
|
|
1727
|
-
}
|
|
1728
|
-
#renderLogin(response, status, login) {
|
|
1729
|
-
this.#writeHeaders(response, status, "text/html; charset=utf-8");
|
|
1730
|
-
response.end(renderRelayLoginPage({
|
|
1731
|
-
machineName: this.#options.machineName,
|
|
1732
|
-
token: this.#refreshToken,
|
|
1733
|
-
login,
|
|
1734
|
-
...this.#loginFailureMessage === void 0 ? {} : { error: this.#loginFailureMessage }
|
|
1735
|
-
}));
|
|
1736
|
-
}
|
|
1737
|
-
#loginState(provider) {
|
|
1738
|
-
const login = provider.getState();
|
|
1739
|
-
return this.#loginFailureMessage !== void 0 && login.state === "signed-out" ? { state: "error", message: this.#loginFailureMessage } : login;
|
|
1740
|
-
}
|
|
1741
|
-
async #chatSettingsError(request, response, kind, error) {
|
|
1742
|
-
if (wantsJson(request)) {
|
|
1743
|
-
this.#writeHeaders(response, 409, "application/json; charset=utf-8");
|
|
1744
|
-
response.end(JSON.stringify({ error }));
|
|
1745
|
-
} else {
|
|
1746
|
-
await this.#renderPage(response, 409, kind === "group" ? { groupChatError: error } : { peerChatError: error });
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
async #selectionError(request, response, error, selected) {
|
|
1750
|
-
if (wantsJson(request)) {
|
|
1751
|
-
this.#writeHeaders(response, 409, "application/json; charset=utf-8");
|
|
1752
|
-
response.end(JSON.stringify({ error }));
|
|
1753
|
-
} else {
|
|
1754
|
-
const agents = (await this.#options.agentSelection?.listAgents())?.map((agent) => ({
|
|
1755
|
-
...agent,
|
|
1756
|
-
selected: selected.includes(agent.id)
|
|
1757
|
-
}));
|
|
1758
|
-
await this.#renderPage(response, 409, { error, ...agents === void 0 ? {} : { agents } });
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
async #pairingError(request, response, error) {
|
|
1762
|
-
if (wantsJson(request)) {
|
|
1763
|
-
this.#writeHeaders(response, 503, "application/json; charset=utf-8");
|
|
1764
|
-
response.end(JSON.stringify({ error }));
|
|
1765
|
-
} else {
|
|
1766
|
-
await this.#renderPage(response, 503, { pairingError: error });
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
#writeHeaders(response, status, contentType, referrerPolicy = "same-origin") {
|
|
1770
|
-
const formOrigins = this.#options.relayLogin === void 0 ? "'self'" : `'self' ${this.#options.relayLogin.relayOrigin} https://login.microsoftonline.com https://login.live.com`;
|
|
1771
|
-
response.writeHead(status, {
|
|
1772
|
-
"cache-control": "no-store, max-age=0",
|
|
1773
|
-
"content-security-policy": `default-src 'none'; img-src data:; script-src 'self'; connect-src 'self'; style-src 'unsafe-inline'; form-action ${formOrigins}; base-uri 'none'; frame-ancestors 'none'`,
|
|
1774
|
-
"content-type": contentType,
|
|
1775
|
-
// no-referrer turns native browser POST origins into "null".
|
|
1776
|
-
"referrer-policy": referrerPolicy,
|
|
1777
|
-
"x-content-type-options": "nosniff"
|
|
1778
|
-
});
|
|
1779
|
-
}
|
|
1780
|
-
#redirectLogin(response, location) {
|
|
1781
|
-
response.writeHead(303, {
|
|
1782
|
-
location,
|
|
1783
|
-
"cache-control": "no-store, max-age=0",
|
|
1784
|
-
"referrer-policy": "no-referrer",
|
|
1785
|
-
"x-content-type-options": "nosniff"
|
|
1786
|
-
});
|
|
1787
|
-
response.end();
|
|
1788
|
-
}
|
|
1789
|
-
};
|
|
1790
|
-
function wantsJson(request) {
|
|
1791
|
-
return request.headers.accept?.includes("application/json") === true;
|
|
1792
|
-
}
|
|
1793
|
-
async function readFormBody(request, maxBytes = MAX_FORM_BODY_BYTES) {
|
|
1794
|
-
const chunks = [];
|
|
1795
|
-
let size = 0;
|
|
1796
|
-
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
1797
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1798
|
-
size += buffer.length;
|
|
1799
|
-
if (size > maxBytes) {
|
|
1800
|
-
request.resume();
|
|
1801
|
-
throw new FormBodyTooLargeError("Pairing page form body exceeds the size limit");
|
|
1802
|
-
}
|
|
1803
|
-
chunks.push(buffer);
|
|
1804
|
-
}
|
|
1805
|
-
return Buffer.concat(chunks).toString("utf8");
|
|
1806
|
-
}
|
|
1807
|
-
function secureEqual(value, expected) {
|
|
1808
|
-
if (value === null) return false;
|
|
1809
|
-
const actualBuffer = Buffer.from(value);
|
|
1810
|
-
const expectedBuffer = Buffer.from(expected);
|
|
1811
|
-
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
|
1812
|
-
}
|
|
1813
|
-
|
|
1814
|
-
// src/relay-login.ts
|
|
1815
|
-
import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
1816
|
-
|
|
1817
|
-
// src/relay-credential-store.ts
|
|
1818
|
-
import { createHash } from "node:crypto";
|
|
1819
|
-
import { platform } from "node:os";
|
|
1820
|
-
import { brotliCompressSync, brotliDecompressSync } from "node:zlib";
|
|
1821
|
-
import { z as z2 } from "zod";
|
|
1822
|
-
var STORE_MESSAGES = {
|
|
1823
|
-
unavailable: "Unlock your operating system credential store and restart AgentKnight. No file-based credential fallback is available.",
|
|
1824
|
-
invalid: "The saved Relay credential is invalid. Recover it in your operating system credential manager before signing in.",
|
|
1825
|
-
conflict: "A different Relay account or enrollment is already saved for this PC. Resolve it before signing in again.",
|
|
1826
|
-
verification: "The operating system credential store did not retain the credential. Unlock it and restart AgentKnight.",
|
|
1827
|
-
address: "Use an HTTPS Relay origin without a path, credentials, query, or fragment. HTTP is allowed only for literal loopback addresses.",
|
|
1828
|
-
unsupported: "Microsoft sign-in requires Windows Credential Manager or macOS Keychain. This operating system is not supported.",
|
|
1829
|
-
tooLarge: "The Relay credential exceeds the operating system credential store capacity. Existing credentials were not changed. Contact your Relay administrator."
|
|
1830
|
-
};
|
|
1831
|
-
var MAX_RECORD_BYTES = 32 * 1024;
|
|
1832
|
-
var WINDOWS_MAX_SECRET_BYTES = 2560;
|
|
1833
|
-
var COMPRESSED_RECORD_PREFIX = Buffer.from("AKR2\0");
|
|
1834
|
-
var RelayCredentialStoreError = class extends Error {
|
|
1835
|
-
constructor(code) {
|
|
1836
|
-
super(STORE_MESSAGES[code]);
|
|
1837
|
-
this.code = code;
|
|
1838
|
-
this.name = "RelayCredentialStoreError";
|
|
1839
|
-
}
|
|
1840
|
-
code;
|
|
1841
|
-
};
|
|
1842
|
-
function normalizeRelayOrigin(value) {
|
|
1843
|
-
try {
|
|
1844
|
-
const url = new URL(value);
|
|
1845
|
-
const literalLoopback = /^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?\/?$/i.test(value);
|
|
1846
|
-
if (!/^https?:\/\/[^/?#\\@\s]+\/?$/i.test(value) || url.username || url.password || url.search || url.hash || url.pathname !== "/" || url.protocol !== "https:" && !literalLoopback) {
|
|
1847
|
-
throw new RelayCredentialStoreError("address");
|
|
1848
|
-
}
|
|
1849
|
-
return url.origin;
|
|
1850
|
-
} catch {
|
|
1851
|
-
throw new RelayCredentialStoreError("address");
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
var ConfirmationSchema = z2.discriminatedUnion("status", [
|
|
1855
|
-
z2.object({
|
|
1856
|
-
status: z2.literal("pending"),
|
|
1857
|
-
confirmBy: z2.number().int().positive(),
|
|
1858
|
-
enrollmentId: PcEnrollmentIdSchema,
|
|
1859
|
-
verifier: PcEnrollmentVerifierRequestSchema.shape.verifier
|
|
1860
|
-
}).strict(),
|
|
1861
|
-
z2.object({
|
|
1862
|
-
status: z2.literal("confirmed"),
|
|
1863
|
-
confirmBy: z2.number().int().positive()
|
|
1864
|
-
}).strict()
|
|
1865
|
-
]);
|
|
1866
|
-
var RelayCredentialSchema = z2.object({
|
|
1867
|
-
version: z2.literal(1),
|
|
1868
|
-
relayUrl: z2.string().max(2048),
|
|
1869
|
-
machineId: PcEnrollmentStartRequestSchema.shape.machineId,
|
|
1870
|
-
token: z2.string().min(32).max(4096),
|
|
1871
|
-
tokenId: z2.string().min(1).max(256),
|
|
1872
|
-
grantId: z2.uuid(),
|
|
1873
|
-
user: AuthUserSchema,
|
|
1874
|
-
confirmation: ConfirmationSchema
|
|
1875
|
-
}).strict();
|
|
1876
|
-
var SlotsSchema = z2.object({
|
|
1877
|
-
version: z2.literal(1),
|
|
1878
|
-
pending: RelayCredentialSchema.optional(),
|
|
1879
|
-
confirmed: RelayCredentialSchema.optional()
|
|
1880
|
-
}).strict();
|
|
1881
|
-
function validateRelayCredentialSlots(value, relayUrl, machineId) {
|
|
1882
|
-
const result = SlotsSchema.safeParse(value);
|
|
1883
|
-
if (!result.success) throw new RelayCredentialStoreError("invalid");
|
|
1884
|
-
const slots = result.data;
|
|
1885
|
-
for (const slot of ["pending", "confirmed"]) {
|
|
1886
|
-
const credential = slots[slot];
|
|
1887
|
-
if (credential !== void 0 && (credential.relayUrl !== relayUrl || credential.machineId !== machineId || credential.confirmation.status !== slot || normalizeRelayOrigin(credential.relayUrl) !== credential.relayUrl)) throw new RelayCredentialStoreError("invalid");
|
|
1888
|
-
}
|
|
1889
|
-
if (slots.pending && slots.confirmed && slots.pending.user.userId !== slots.confirmed.user.userId) {
|
|
1890
|
-
throw new RelayCredentialStoreError("conflict");
|
|
1891
|
-
}
|
|
1892
|
-
return slots;
|
|
1893
|
-
}
|
|
1894
|
-
function sameRelayCredential(left, right) {
|
|
1895
|
-
const first = RelayCredentialSchema.safeParse(left);
|
|
1896
|
-
const second = RelayCredentialSchema.safeParse(right);
|
|
1897
|
-
if (!first.success || !second.success) throw new RelayCredentialStoreError("invalid");
|
|
1898
|
-
return JSON.stringify(first.data) === JSON.stringify(second.data);
|
|
1899
|
-
}
|
|
1900
|
-
var transactions = /* @__PURE__ */ new Map();
|
|
1901
|
-
var OsRelayCredentialStore = class {
|
|
1902
|
-
constructor(entry, key, relayUrl, machineId, maxSecretBytes) {
|
|
1903
|
-
this.entry = entry;
|
|
1904
|
-
this.key = key;
|
|
1905
|
-
this.relayUrl = relayUrl;
|
|
1906
|
-
this.machineId = machineId;
|
|
1907
|
-
this.maxSecretBytes = maxSecretBytes;
|
|
1908
|
-
}
|
|
1909
|
-
entry;
|
|
1910
|
-
key;
|
|
1911
|
-
relayUrl;
|
|
1912
|
-
machineId;
|
|
1913
|
-
maxSecretBytes;
|
|
1914
|
-
async read() {
|
|
1915
|
-
try {
|
|
1916
|
-
const raw = await this.entry.getSecret();
|
|
1917
|
-
if (raw == null) return { version: 1 };
|
|
1918
|
-
const secret = raw instanceof Uint8Array ? Buffer.from(raw) : Array.isArray(raw) && raw.length <= MAX_RECORD_BYTES && raw.every((byte) => typeof byte === "number" && Number.isInteger(byte) && byte >= 0 && byte <= 255) ? Buffer.from(raw) : void 0;
|
|
1919
|
-
if (secret === void 0 || secret.byteLength > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("invalid");
|
|
1920
|
-
let text;
|
|
1921
|
-
if (secret.subarray(0, COMPRESSED_RECORD_PREFIX.length).equals(COMPRESSED_RECORD_PREFIX)) {
|
|
1922
|
-
try {
|
|
1923
|
-
text = brotliDecompressSync(secret.subarray(COMPRESSED_RECORD_PREFIX.length), {
|
|
1924
|
-
maxOutputLength: MAX_RECORD_BYTES
|
|
1925
|
-
}).toString("utf8");
|
|
1926
|
-
} catch {
|
|
1927
|
-
throw new RelayCredentialStoreError("invalid");
|
|
1928
|
-
}
|
|
1929
|
-
} else {
|
|
1930
|
-
text = await this.entry.getPassword();
|
|
1931
|
-
}
|
|
1932
|
-
if (typeof text !== "string") throw new RelayCredentialStoreError("invalid");
|
|
1933
|
-
if (Buffer.byteLength(text) > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("invalid");
|
|
1934
|
-
let value;
|
|
1935
|
-
try {
|
|
1936
|
-
value = JSON.parse(text);
|
|
1937
|
-
} catch {
|
|
1938
|
-
throw new RelayCredentialStoreError("invalid");
|
|
1939
|
-
}
|
|
1940
|
-
return validateRelayCredentialSlots(value, this.relayUrl, this.machineId);
|
|
1941
|
-
} catch (error) {
|
|
1942
|
-
throw error instanceof RelayCredentialStoreError ? error : new RelayCredentialStoreError("unavailable");
|
|
1943
|
-
}
|
|
1944
|
-
}
|
|
1945
|
-
savePending(credential) {
|
|
1946
|
-
return this.transaction(async () => {
|
|
1947
|
-
const candidate = validateRelayCredentialSlots(
|
|
1948
|
-
{ version: 1, pending: credential },
|
|
1949
|
-
this.relayUrl,
|
|
1950
|
-
this.machineId
|
|
1951
|
-
).pending;
|
|
1952
|
-
if (candidate === void 0) throw new RelayCredentialStoreError("invalid");
|
|
1953
|
-
const slots = await this.read();
|
|
1954
|
-
if (slots.pending && !sameRelayCredential(slots.pending, candidate) || slots.confirmed && slots.confirmed.user.userId !== candidate.user.userId || slots.confirmed && slots.confirmed.tokenId === candidate.tokenId) throw new RelayCredentialStoreError("conflict");
|
|
1955
|
-
await this.write({ ...slots, pending: candidate });
|
|
1956
|
-
});
|
|
1957
|
-
}
|
|
1958
|
-
confirmPending(tokenId) {
|
|
1959
|
-
return this.transaction(async () => {
|
|
1960
|
-
const slots = await this.read();
|
|
1961
|
-
const pending = slots.pending;
|
|
1962
|
-
if (pending === void 0 || pending.tokenId !== tokenId) {
|
|
1963
|
-
if (pending === void 0 && slots.confirmed?.tokenId === tokenId) return slots.confirmed;
|
|
1964
|
-
throw new RelayCredentialStoreError("conflict");
|
|
1965
|
-
}
|
|
1966
|
-
const confirmed = {
|
|
1967
|
-
...pending,
|
|
1968
|
-
confirmation: { status: "confirmed", confirmBy: pending.confirmation.confirmBy }
|
|
1969
|
-
};
|
|
1970
|
-
await this.write({ version: 1, confirmed });
|
|
1971
|
-
return confirmed;
|
|
1972
|
-
});
|
|
1973
|
-
}
|
|
1974
|
-
clearPending(tokenId) {
|
|
1975
|
-
return this.transaction(async () => {
|
|
1976
|
-
const slots = await this.read();
|
|
1977
|
-
if (slots.pending === void 0) return;
|
|
1978
|
-
if (slots.pending.tokenId !== tokenId) throw new RelayCredentialStoreError("conflict");
|
|
1979
|
-
await this.write({
|
|
1980
|
-
version: 1,
|
|
1981
|
-
...slots.confirmed === void 0 ? {} : { confirmed: slots.confirmed }
|
|
1982
|
-
});
|
|
1983
|
-
});
|
|
1984
|
-
}
|
|
1985
|
-
async write(slots) {
|
|
1986
|
-
const expected = validateRelayCredentialSlots(slots, this.relayUrl, this.machineId);
|
|
1987
|
-
const json = Buffer.from(JSON.stringify(expected));
|
|
1988
|
-
if (json.byteLength > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("tooLarge");
|
|
1989
|
-
const secret = Buffer.concat([COMPRESSED_RECORD_PREFIX, brotliCompressSync(json)]);
|
|
1990
|
-
if (secret.byteLength > this.maxSecretBytes) throw new RelayCredentialStoreError("tooLarge");
|
|
1991
|
-
await this.entry.setSecret(secret);
|
|
1992
|
-
const actual = await this.read();
|
|
1993
|
-
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new RelayCredentialStoreError("verification");
|
|
1994
|
-
}
|
|
1995
|
-
async transaction(action) {
|
|
1996
|
-
const previous = transactions.get(this.key) ?? Promise.resolve();
|
|
1997
|
-
let release = () => {
|
|
1998
|
-
};
|
|
1999
|
-
const completion = new Promise((resolve3) => {
|
|
2000
|
-
release = resolve3;
|
|
2001
|
-
});
|
|
2002
|
-
transactions.set(this.key, completion);
|
|
2003
|
-
await previous;
|
|
2004
|
-
try {
|
|
2005
|
-
return await action();
|
|
2006
|
-
} catch (error) {
|
|
2007
|
-
throw error instanceof RelayCredentialStoreError ? error : new RelayCredentialStoreError("unavailable");
|
|
2008
|
-
} finally {
|
|
2009
|
-
release();
|
|
2010
|
-
if (transactions.get(this.key) === completion) transactions.delete(this.key);
|
|
2011
|
-
}
|
|
2012
|
-
}
|
|
2013
|
-
};
|
|
2014
|
-
async function createRelayCredentialStore(relayUrl, machineId) {
|
|
2015
|
-
const os = platform();
|
|
2016
|
-
if (os !== "win32" && os !== "darwin") throw new RelayCredentialStoreError("unsupported");
|
|
2017
|
-
const origin = normalizeRelayOrigin(relayUrl);
|
|
2018
|
-
if (!PcEnrollmentStartRequestSchema.shape.machineId.safeParse(machineId).success) {
|
|
2019
|
-
throw new RelayCredentialStoreError("invalid");
|
|
2020
|
-
}
|
|
2021
|
-
const username = createHash("sha256").update(JSON.stringify([origin, machineId])).digest("hex");
|
|
2022
|
-
try {
|
|
2023
|
-
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
2024
|
-
const entry = new AsyncEntry("AgentKnight Relay", username);
|
|
2025
|
-
return new OsRelayCredentialStore(
|
|
2026
|
-
entry,
|
|
2027
|
-
username,
|
|
2028
|
-
origin,
|
|
2029
|
-
machineId,
|
|
2030
|
-
os === "win32" ? WINDOWS_MAX_SECRET_BYTES : MAX_RECORD_BYTES
|
|
2031
|
-
);
|
|
2032
|
-
} catch {
|
|
2033
|
-
throw new RelayCredentialStoreError("unavailable");
|
|
2034
|
-
}
|
|
2035
|
-
}
|
|
2036
|
-
|
|
2037
|
-
// src/relay-login.ts
|
|
2038
|
-
var MESSAGES = {
|
|
2039
|
-
network: "Cannot reach the Relay securely. Check the Relay address and connection, then try again.",
|
|
2040
|
-
response: "The Relay returned an invalid authorization response. Check the Relay configuration.",
|
|
2041
|
-
upgrade: "This Relay does not support browser sign-in. Ask its administrator to upgrade the Relay, then retry.",
|
|
2042
|
-
expired: "PC authorization expired. Cancel this request and sign in again.",
|
|
2043
|
-
denied: "The Relay did not authorize this account. Contact the Relay administrator.",
|
|
2044
|
-
limited: "Too many authorization attempts. Wait a minute and try again.",
|
|
2045
|
-
issued: "This authorization was already issued. Cancel this request before signing in again.",
|
|
2046
|
-
exchange: "The credential exchange outcome is uncertain. Cancel this request before signing in again; do not repeat the exchange.",
|
|
2047
|
-
confirmation: "Credential confirmation could not be verified. Restart AgentKnight to recover the saved credential.",
|
|
2048
|
-
confirmationService: "The Relay confirmation service is unavailable. The credential is saved; retry after its administrator restores the service.",
|
|
2049
|
-
credential: "The saved Relay credential is no longer authorized. Sign in again.",
|
|
2050
|
-
verification: "The Relay cannot verify saved credentials. Ask its administrator to enable Microsoft credential verification, then retry.",
|
|
2051
|
-
cleanup: "Authorization cleanup could not be verified. Retry, or restart AgentKnight after the request expires.",
|
|
2052
|
-
cancelled: "PC authorization was cancelled.",
|
|
2053
|
-
closed: "AgentKnight login is closed. Restart AgentKnight to sign in.",
|
|
2054
|
-
identity: "The Relay credential belongs to a different PC or account. Check the Relay configuration before signing in again."
|
|
2055
|
-
};
|
|
2056
|
-
var LoginError = class extends Error {
|
|
2057
|
-
constructor(code, retryAfterMs, responseStatus, rejectionEvidence) {
|
|
2058
|
-
super(MESSAGES[code]);
|
|
2059
|
-
this.code = code;
|
|
2060
|
-
this.retryAfterMs = retryAfterMs;
|
|
2061
|
-
this.responseStatus = responseStatus;
|
|
2062
|
-
this.rejectionEvidence = rejectionEvidence;
|
|
2063
|
-
this.name = "RelayLoginError";
|
|
2064
|
-
}
|
|
2065
|
-
code;
|
|
2066
|
-
retryAfterMs;
|
|
2067
|
-
responseStatus;
|
|
2068
|
-
rejectionEvidence;
|
|
2069
|
-
};
|
|
2070
|
-
function safeError(error) {
|
|
2071
|
-
if (error instanceof LoginError) {
|
|
2072
|
-
return new LoginError(error.code, error.retryAfterMs, error.responseStatus, error.rejectionEvidence);
|
|
2073
|
-
}
|
|
2074
|
-
if (error instanceof RelayCredentialStoreError) return new RelayCredentialStoreError(error.code);
|
|
2075
|
-
return new LoginError("network");
|
|
2076
|
-
}
|
|
2077
|
-
function failure(code, status, retryAfterMs) {
|
|
2078
|
-
if (status === 401 && code === "DEVICE_GRANT_INVALID") {
|
|
2079
|
-
return new LoginError("denied", void 0, status, "credential-invalid");
|
|
2080
|
-
}
|
|
2081
|
-
if (status === 404 && (code === "ENROLLMENT_NOT_FOUND" || code === "PC_ENROLLMENT_NOT_FOUND")) {
|
|
2082
|
-
return new LoginError("response", void 0, status, "enrollment-missing");
|
|
2083
|
-
}
|
|
2084
|
-
if (status === 429) return new LoginError("limited", retryAfterMs, status);
|
|
2085
|
-
if (status === 410 && (code === "ENROLLMENT_EXPIRED" || code === "PC_ENROLLMENT_EXPIRED")) {
|
|
2086
|
-
return new LoginError("expired", void 0, status, "enrollment-expired");
|
|
2087
|
-
}
|
|
2088
|
-
if (code === "ENROLLMENT_CONFLICT" || code === "PC_ENROLLMENT_INVALID_STATE") {
|
|
2089
|
-
return new LoginError("issued", void 0, status);
|
|
2090
|
-
}
|
|
2091
|
-
if (status === 401 || status === 403) return new LoginError("denied", void 0, status);
|
|
2092
|
-
return new LoginError(status >= 500 ? "network" : "response", void 0, status);
|
|
2093
|
-
}
|
|
2094
|
-
function aborted(signal) {
|
|
2095
|
-
if (signal.aborted) throw new LoginError("cancelled");
|
|
2096
|
-
}
|
|
2097
|
-
async function abortable(work, signal) {
|
|
2098
|
-
if (signal.aborted) {
|
|
2099
|
-
void work.catch(() => void 0);
|
|
2100
|
-
throw new LoginError("cancelled");
|
|
2101
|
-
}
|
|
2102
|
-
let onAbort = () => {
|
|
2103
|
-
};
|
|
2104
|
-
const cancellation = new Promise((_resolve, reject) => {
|
|
2105
|
-
onAbort = () => reject(new LoginError("cancelled"));
|
|
2106
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2107
|
-
});
|
|
2108
|
-
try {
|
|
2109
|
-
return await Promise.race([work, cancellation]);
|
|
2110
|
-
} finally {
|
|
2111
|
-
signal.removeEventListener("abort", onAbort);
|
|
2112
|
-
}
|
|
2113
|
-
}
|
|
2114
|
-
var MicrosoftRelayLogin = class {
|
|
2115
|
-
#relayUrl;
|
|
2116
|
-
#identity;
|
|
2117
|
-
#fetch;
|
|
2118
|
-
#getRedirectUri;
|
|
2119
|
-
#store;
|
|
2120
|
-
#state = { state: "signed-out" };
|
|
2121
|
-
#credential;
|
|
2122
|
-
#active;
|
|
2123
|
-
#cancelling;
|
|
2124
|
-
#closed = false;
|
|
2125
|
-
#reauthorize;
|
|
2126
|
-
#waiters = /* @__PURE__ */ new Set();
|
|
2127
|
-
constructor(options) {
|
|
2128
|
-
this.#relayUrl = normalizeRelayOrigin(options.relayUrl);
|
|
2129
|
-
this.#identity = { ...options.identity };
|
|
2130
|
-
this.#store = options.store;
|
|
2131
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
2132
|
-
this.#reauthorize = options.reauthorize ?? false;
|
|
2133
|
-
this.#getRedirectUri = options.getRedirectUri;
|
|
2134
|
-
}
|
|
2135
|
-
getState() {
|
|
2136
|
-
return { ...this.#state };
|
|
2137
|
-
}
|
|
2138
|
-
get relayOrigin() {
|
|
2139
|
-
return this.#relayUrl;
|
|
2140
|
-
}
|
|
2141
|
-
async restore() {
|
|
2142
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2143
|
-
if (this.#cancelling) await this.#cancelling;
|
|
2144
|
-
if (this.#credential) return structuredClone(this.#credential);
|
|
2145
|
-
const operation = this.#active ?? this.#launch(true);
|
|
2146
|
-
await operation.done;
|
|
2147
|
-
if (operation.error) return void 0;
|
|
2148
|
-
return this.#credential === void 0 ? void 0 : structuredClone(this.#credential);
|
|
2149
|
-
}
|
|
2150
|
-
async start() {
|
|
2151
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2152
|
-
if (this.#cancelling) await this.#cancelling;
|
|
2153
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2154
|
-
if (this.#credential) return;
|
|
2155
|
-
const previous = this.#active;
|
|
2156
|
-
if (previous?.error) {
|
|
2157
|
-
await previous.done;
|
|
2158
|
-
if (previous.confirmAttempted) {
|
|
2159
|
-
if (this.#active === previous) this.#active = void 0;
|
|
2160
|
-
} else {
|
|
2161
|
-
await this.cancel();
|
|
2162
|
-
}
|
|
2163
|
-
if (this.#closed) throw new LoginError("closed");
|
|
2164
|
-
}
|
|
2165
|
-
const operation = this.#active ?? this.#launch(false);
|
|
2166
|
-
await operation.ready;
|
|
2167
|
-
if (operation.restoreOnly) {
|
|
2168
|
-
await operation.done;
|
|
2169
|
-
if (!this.#credential) await this.start();
|
|
2170
|
-
}
|
|
2171
|
-
}
|
|
2172
|
-
acceptCallback(input, redirectUri) {
|
|
2173
|
-
const parsed = PcBrowserAuthorizationCallbackSchema.safeParse(input);
|
|
2174
|
-
const operation = this.#active;
|
|
2175
|
-
const browser = operation?.browser;
|
|
2176
|
-
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;
|
|
2177
|
-
const receivedState = Buffer.from(parsed.data.state);
|
|
2178
|
-
const expectedState = Buffer.from(browser.state);
|
|
2179
|
-
if (receivedState.length !== expectedState.length || !timingSafeEqual2(receivedState, expectedState)) return void 0;
|
|
2180
|
-
browser.received = true;
|
|
2181
|
-
let delivered = false;
|
|
2182
|
-
return () => {
|
|
2183
|
-
if (delivered) return;
|
|
2184
|
-
delivered = true;
|
|
2185
|
-
if (!operation.controller.signal.aborted && this.#active === operation && operation.enrollment && Date.now() < operation.enrollment.expiresAt) browser.deliver(parsed.data);
|
|
2186
|
-
};
|
|
2187
|
-
}
|
|
2188
|
-
async cancel() {
|
|
2189
|
-
if (this.#cancelling) return this.#cancelling;
|
|
2190
|
-
const cancellation = this.#cancel();
|
|
2191
|
-
this.#cancelling = cancellation;
|
|
2192
|
-
try {
|
|
2193
|
-
await cancellation;
|
|
2194
|
-
} finally {
|
|
2195
|
-
if (this.#cancelling === cancellation) this.#cancelling = void 0;
|
|
2196
|
-
}
|
|
2197
|
-
}
|
|
2198
|
-
async close() {
|
|
2199
|
-
this.#closed = true;
|
|
2200
|
-
for (const waiter of this.#waiters) waiter.reject(new LoginError("closed"));
|
|
2201
|
-
this.#waiters.clear();
|
|
2202
|
-
await this.cancel();
|
|
2203
|
-
}
|
|
2204
|
-
waitForCredential(signal) {
|
|
2205
|
-
if (this.#closed) return Promise.reject(new LoginError("closed"));
|
|
2206
|
-
if (signal?.aborted) return Promise.reject(new LoginError("cancelled"));
|
|
2207
|
-
if (this.#credential) return Promise.resolve(structuredClone(this.#credential));
|
|
2208
|
-
return new Promise((resolve3, reject) => {
|
|
2209
|
-
const cleanup = () => {
|
|
2210
|
-
this.#waiters.delete(waiter);
|
|
2211
|
-
signal?.removeEventListener("abort", onAbort);
|
|
2212
|
-
};
|
|
2213
|
-
const waiter = {
|
|
2214
|
-
resolve: (credential) => {
|
|
2215
|
-
cleanup();
|
|
2216
|
-
resolve3(structuredClone(credential));
|
|
2217
|
-
},
|
|
2218
|
-
reject: (error) => {
|
|
2219
|
-
cleanup();
|
|
2220
|
-
reject(error);
|
|
2221
|
-
}
|
|
2222
|
-
};
|
|
2223
|
-
const onAbort = () => waiter.reject(new LoginError("cancelled"));
|
|
2224
|
-
this.#waiters.add(waiter);
|
|
2225
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2226
|
-
});
|
|
2227
|
-
}
|
|
2228
|
-
#launch(restoreOnly) {
|
|
2229
|
-
let resolveReady = () => {
|
|
2230
|
-
};
|
|
2231
|
-
let rejectReady = (_error) => {
|
|
2232
|
-
};
|
|
2233
|
-
const ready = new Promise((resolve3, reject) => {
|
|
2234
|
-
resolveReady = resolve3;
|
|
2235
|
-
rejectReady = reject;
|
|
2236
|
-
});
|
|
2237
|
-
void ready.catch(() => void 0);
|
|
2238
|
-
const operation = {
|
|
2239
|
-
controller: new AbortController(),
|
|
2240
|
-
ready,
|
|
2241
|
-
resolveReady,
|
|
2242
|
-
rejectReady,
|
|
2243
|
-
done: Promise.resolve(),
|
|
2244
|
-
createAttempted: false,
|
|
2245
|
-
confirmAttempted: false,
|
|
2246
|
-
pendingRejected: false,
|
|
2247
|
-
restoreOnly
|
|
2248
|
-
};
|
|
2249
|
-
this.#active = operation;
|
|
2250
|
-
this.#state = { state: "starting" };
|
|
2251
|
-
operation.done = this.#execute(operation, restoreOnly).catch((error) => {
|
|
2252
|
-
const safe = safeError(error);
|
|
2253
|
-
operation.error = safe;
|
|
2254
|
-
if (!operation.controller.signal.aborted) this.#state = { state: "error", message: safe.message };
|
|
2255
|
-
operation.rejectReady(safe);
|
|
2256
|
-
}).finally(() => {
|
|
2257
|
-
if (this.#active === operation && (this.#credential !== void 0 || !operation.createAttempted && !operation.enrollment)) this.#active = void 0;
|
|
2258
|
-
});
|
|
2259
|
-
return operation;
|
|
2260
|
-
}
|
|
2261
|
-
async #readStore() {
|
|
2262
|
-
try {
|
|
2263
|
-
this.#store ??= await createRelayCredentialStore(this.#relayUrl, this.#identity.machineId);
|
|
2264
|
-
return validateRelayCredentialSlots(await this.#store.read(), this.#relayUrl, this.#identity.machineId);
|
|
2265
|
-
} catch (error) {
|
|
2266
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
async #execute(operation, restoreOnly) {
|
|
2270
|
-
let slots = await this.#readStore();
|
|
2271
|
-
aborted(operation.controller.signal);
|
|
2272
|
-
if (restoreOnly && this.#reauthorize) {
|
|
2273
|
-
this.#state = { state: "signed-out" };
|
|
2274
|
-
operation.resolveReady();
|
|
2275
|
-
return;
|
|
2276
|
-
}
|
|
2277
|
-
if (slots.pending) {
|
|
2278
|
-
const pending = slots.pending;
|
|
2279
|
-
if (pending.confirmation.status !== "pending") throw new RelayCredentialStoreError("invalid");
|
|
2280
|
-
operation.pending = pending;
|
|
2281
|
-
operation.confirmAttempted = true;
|
|
2282
|
-
operation.enrollment = {
|
|
2283
|
-
id: pending.confirmation.enrollmentId,
|
|
2284
|
-
verifier: pending.confirmation.verifier,
|
|
2285
|
-
expiresAt: pending.confirmation.confirmBy
|
|
2286
|
-
};
|
|
2287
|
-
if (!this.#reauthorize) {
|
|
2288
|
-
await this.#confirm(operation, pending);
|
|
2289
|
-
operation.resolveReady();
|
|
2290
|
-
return;
|
|
2291
|
-
}
|
|
2292
|
-
await this.#confirm(operation, pending, false);
|
|
2293
|
-
delete operation.pending;
|
|
2294
|
-
delete operation.enrollment;
|
|
2295
|
-
operation.confirmAttempted = false;
|
|
2296
|
-
slots = await this.#readStore();
|
|
2297
|
-
aborted(operation.controller.signal);
|
|
2298
|
-
}
|
|
2299
|
-
if (slots.confirmed && !this.#reauthorize) {
|
|
2300
|
-
await this.#verifyConfirmed(slots.confirmed);
|
|
2301
|
-
aborted(operation.controller.signal);
|
|
2302
|
-
this.#signedIn(slots.confirmed);
|
|
2303
|
-
operation.resolveReady();
|
|
2304
|
-
return;
|
|
2305
|
-
}
|
|
2306
|
-
if (restoreOnly) {
|
|
2307
|
-
this.#state = { state: "signed-out" };
|
|
2308
|
-
operation.resolveReady();
|
|
2309
|
-
return;
|
|
2310
|
-
}
|
|
2311
|
-
const redirectUri = this.#getRedirectUri();
|
|
2312
|
-
if (!PcBrowserRedirectUriSchema.safeParse(redirectUri).success) throw new LoginError("response");
|
|
2313
|
-
const verifier = randomBytes2(32).toString("base64url");
|
|
2314
|
-
const state = randomBytes2(32).toString("base64url");
|
|
2315
|
-
const input = PcBrowserAuthorizationStartRequestSchema.safeParse({
|
|
2316
|
-
machineId: this.#identity.machineId,
|
|
2317
|
-
deviceName: this.#identity.machineName,
|
|
2318
|
-
codeChallenge: createHash2("sha256").update(verifier).digest("base64url"),
|
|
2319
|
-
redirectUri,
|
|
2320
|
-
state
|
|
2321
|
-
});
|
|
2322
|
-
if (!input.success) throw new LoginError("identity");
|
|
2323
|
-
operation.createAttempted = true;
|
|
2324
|
-
let started;
|
|
2325
|
-
try {
|
|
2326
|
-
started = await this.#post("/pc-enrollments/browser", input.data, PcBrowserAuthorizationStartResultSchema);
|
|
2327
|
-
} catch (error) {
|
|
2328
|
-
if (error instanceof LoginError && error.responseStatus !== void 0 && error.responseStatus >= 400 && error.responseStatus < 500) {
|
|
2329
|
-
operation.createAttempted = false;
|
|
2330
|
-
}
|
|
2331
|
-
if (error instanceof LoginError && (error.responseStatus === 404 || error.responseStatus === 405)) {
|
|
2332
|
-
throw new LoginError("upgrade");
|
|
2333
|
-
}
|
|
2334
|
-
throw error;
|
|
2335
|
-
}
|
|
2336
|
-
if (!started.ok) throw new LoginError("response");
|
|
2337
|
-
operation.enrollment = {
|
|
2338
|
-
id: started.enrollmentId,
|
|
2339
|
-
verifier,
|
|
2340
|
-
expiresAt: started.expiresAt
|
|
2341
|
-
};
|
|
2342
|
-
aborted(operation.controller.signal);
|
|
2343
|
-
if (started.verificationUri !== `${this.#relayUrl}/pc-enrollments/browser/${started.enrollmentId}` || !Number.isSafeInteger(started.expiresAt) || started.expiresAt - Date.now() > 2147483647) throw new LoginError("response");
|
|
2344
|
-
if (started.expiresAt <= Date.now()) throw new LoginError("expired");
|
|
2345
|
-
let deliver = (_callback) => {
|
|
2346
|
-
};
|
|
2347
|
-
const callback = new Promise((resolve3) => {
|
|
2348
|
-
deliver = resolve3;
|
|
2349
|
-
});
|
|
2350
|
-
const browser = {
|
|
2351
|
-
state,
|
|
2352
|
-
redirectUri: input.data.redirectUri,
|
|
2353
|
-
received: false,
|
|
2354
|
-
callback,
|
|
2355
|
-
deliver
|
|
2356
|
-
};
|
|
2357
|
-
operation.browser = browser;
|
|
2358
|
-
this.#state = {
|
|
2359
|
-
state: "pending",
|
|
2360
|
-
verificationUri: started.verificationUri,
|
|
2361
|
-
expiresAt: started.expiresAt
|
|
2362
|
-
};
|
|
2363
|
-
operation.resolveReady();
|
|
2364
|
-
await this.#authorizeBrowser(operation, operation.enrollment, browser);
|
|
2365
|
-
}
|
|
2366
|
-
async #authorizeBrowser(operation, enrollment, browser) {
|
|
2367
|
-
let timer;
|
|
2368
|
-
let callback;
|
|
2369
|
-
try {
|
|
2370
|
-
callback = await abortable(Promise.race([
|
|
2371
|
-
browser.callback,
|
|
2372
|
-
new Promise((_resolve, reject) => {
|
|
2373
|
-
timer = setTimeout(() => reject(new LoginError("expired")), enrollment.expiresAt - Date.now());
|
|
2374
|
-
})
|
|
2375
|
-
]), operation.controller.signal);
|
|
2376
|
-
} finally {
|
|
2377
|
-
clearTimeout(timer);
|
|
2378
|
-
}
|
|
2379
|
-
aborted(operation.controller.signal);
|
|
2380
|
-
if (Date.now() >= enrollment.expiresAt) throw new LoginError("expired");
|
|
2381
|
-
if ("error" in callback) {
|
|
2382
|
-
throw new LoginError(callback.error === "access_denied" ? "denied" : callback.error);
|
|
2383
|
-
}
|
|
2384
|
-
this.#state = { state: "confirming" };
|
|
2385
|
-
let result;
|
|
2386
|
-
try {
|
|
2387
|
-
result = await this.#post(
|
|
2388
|
-
`/pc-enrollments/browser/${enrollment.id}/exchange`,
|
|
2389
|
-
{ verifier: enrollment.verifier, code: callback.code, redirectUri: browser.redirectUri },
|
|
2390
|
-
PcEnrollmentExchangeResultSchema,
|
|
2391
|
-
{ deadline: enrollment.expiresAt }
|
|
2392
|
-
);
|
|
2393
|
-
} catch {
|
|
2394
|
-
throw new LoginError("exchange");
|
|
2395
|
-
}
|
|
2396
|
-
aborted(operation.controller.signal);
|
|
2397
|
-
if (!result.ok) throw new LoginError("exchange");
|
|
2398
|
-
if (result.machineId !== this.#identity.machineId) throw new LoginError("identity");
|
|
2399
|
-
const pending = {
|
|
2400
|
-
version: 1,
|
|
2401
|
-
relayUrl: this.#relayUrl,
|
|
2402
|
-
machineId: result.machineId,
|
|
2403
|
-
token: result.token,
|
|
2404
|
-
tokenId: result.tokenId,
|
|
2405
|
-
grantId: result.grantId,
|
|
2406
|
-
user: result.user,
|
|
2407
|
-
confirmation: {
|
|
2408
|
-
status: "pending",
|
|
2409
|
-
confirmBy: result.confirmBy,
|
|
2410
|
-
enrollmentId: enrollment.id,
|
|
2411
|
-
verifier: enrollment.verifier
|
|
2412
|
-
}
|
|
2413
|
-
};
|
|
2414
|
-
operation.pending = pending;
|
|
2415
|
-
try {
|
|
2416
|
-
const store = this.#store;
|
|
2417
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2418
|
-
await store.savePending(pending);
|
|
2419
|
-
} catch (error) {
|
|
2420
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2421
|
-
}
|
|
2422
|
-
aborted(operation.controller.signal);
|
|
2423
|
-
await this.#confirm(operation, pending);
|
|
2424
|
-
}
|
|
2425
|
-
async #verifyConfirmed(credential) {
|
|
2426
|
-
this.#state = { state: "confirming" };
|
|
2427
|
-
try {
|
|
2428
|
-
await this.#post("/pc-enrollments/confirm", {}, MicrosoftMutationResultSchema, { token: credential.token });
|
|
2429
|
-
} catch (error) {
|
|
2430
|
-
if (error instanceof LoginError && error.rejectionEvidence === "credential-invalid") {
|
|
2431
|
-
this.#reauthorize = true;
|
|
2432
|
-
throw new LoginError("credential");
|
|
2433
|
-
}
|
|
2434
|
-
if (error instanceof LoginError && error.responseStatus === 404) throw new LoginError("verification");
|
|
2435
|
-
throw safeError(error);
|
|
2436
|
-
}
|
|
2437
|
-
}
|
|
2438
|
-
async #confirm(operation, credential, publish = true) {
|
|
2439
|
-
this.#state = { state: "confirming" };
|
|
2440
|
-
const saved = await this.#readStore();
|
|
2441
|
-
if (!saved.pending || !sameRelayCredential(saved.pending, credential)) {
|
|
2442
|
-
throw new RelayCredentialStoreError("verification");
|
|
2443
|
-
}
|
|
2444
|
-
aborted(operation.controller.signal);
|
|
2445
|
-
if (publish) this.#reauthorize = false;
|
|
2446
|
-
operation.confirmAttempted = true;
|
|
2447
|
-
try {
|
|
2448
|
-
await this.#post("/pc-enrollments/confirm", {}, MicrosoftMutationResultSchema, { token: credential.token });
|
|
2449
|
-
} catch (error) {
|
|
2450
|
-
if (error instanceof LoginError && error.rejectionEvidence === "credential-invalid") {
|
|
2451
|
-
this.#reauthorize = true;
|
|
2452
|
-
operation.confirmAttempted = false;
|
|
2453
|
-
operation.pendingRejected = true;
|
|
2454
|
-
throw new LoginError("credential");
|
|
2455
|
-
}
|
|
2456
|
-
if (error instanceof LoginError && error.responseStatus !== void 0 && error.responseStatus >= 500) {
|
|
2457
|
-
throw new LoginError("confirmationService", void 0, error.responseStatus);
|
|
2458
|
-
}
|
|
2459
|
-
throw new LoginError("confirmation");
|
|
2460
|
-
}
|
|
2461
|
-
try {
|
|
2462
|
-
const store = this.#store;
|
|
2463
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2464
|
-
await store.confirmPending(credential.tokenId);
|
|
2465
|
-
const confirmed = (await this.#readStore()).confirmed;
|
|
2466
|
-
const expected = {
|
|
2467
|
-
...credential,
|
|
2468
|
-
confirmation: { status: "confirmed", confirmBy: credential.confirmation.confirmBy }
|
|
2469
|
-
};
|
|
2470
|
-
if (!confirmed || !sameRelayCredential(confirmed, expected)) {
|
|
2471
|
-
throw new RelayCredentialStoreError("verification");
|
|
2472
|
-
}
|
|
2473
|
-
if (publish) this.#signedIn(confirmed);
|
|
2474
|
-
} catch (error) {
|
|
2475
|
-
throw error instanceof RelayCredentialStoreError ? safeError(error) : new RelayCredentialStoreError("unavailable");
|
|
2476
|
-
}
|
|
2477
|
-
}
|
|
2478
|
-
#signedIn(credential) {
|
|
2479
|
-
this.#credential = structuredClone(credential);
|
|
2480
|
-
this.#state = { state: "signed-in", userId: credential.user.userId };
|
|
2481
|
-
for (const waiter of this.#waiters) waiter.resolve(credential);
|
|
2482
|
-
this.#waiters.clear();
|
|
2483
|
-
}
|
|
2484
|
-
async #cancel() {
|
|
2485
|
-
const operation = this.#active;
|
|
2486
|
-
if (!operation) return;
|
|
2487
|
-
operation.controller.abort();
|
|
2488
|
-
await operation.done;
|
|
2489
|
-
if (this.#credential) return;
|
|
2490
|
-
try {
|
|
2491
|
-
if (operation.confirmAttempted) throw new LoginError("confirmation");
|
|
2492
|
-
if (!operation.enrollment && operation.createAttempted) throw new LoginError("cleanup");
|
|
2493
|
-
if (operation.enrollment) {
|
|
2494
|
-
try {
|
|
2495
|
-
await this.#post(
|
|
2496
|
-
`/pc-enrollments/${operation.enrollment.id}/cancel`,
|
|
2497
|
-
{ verifier: operation.enrollment.verifier },
|
|
2498
|
-
MicrosoftMutationResultSchema
|
|
2499
|
-
);
|
|
2500
|
-
} catch (error) {
|
|
2501
|
-
if (!(error instanceof LoginError && (error.rejectionEvidence === "enrollment-expired" || operation.pending !== void 0 && operation.pendingRejected && error.rejectionEvidence === "enrollment-missing"))) throw error;
|
|
2502
|
-
}
|
|
2503
|
-
}
|
|
2504
|
-
if (operation.pending) {
|
|
2505
|
-
const store = this.#store;
|
|
2506
|
-
if (!store) throw new RelayCredentialStoreError("unavailable");
|
|
2507
|
-
await store.clearPending(operation.pending.tokenId);
|
|
2508
|
-
}
|
|
2509
|
-
if (this.#active === operation) this.#active = void 0;
|
|
2510
|
-
this.#state = { state: "signed-out" };
|
|
2511
|
-
} catch (error) {
|
|
2512
|
-
const safe = error instanceof LoginError && error.code === "confirmation" ? new LoginError("confirmation") : new LoginError("cleanup");
|
|
2513
|
-
this.#state = { state: "error", message: safe.message };
|
|
2514
|
-
throw safe;
|
|
2515
|
-
}
|
|
2516
|
-
}
|
|
2517
|
-
async #post(path, body, schema, options = {}) {
|
|
2518
|
-
if (this.#relayUrl.startsWith("https:") && process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
2519
|
-
throw new LoginError("network");
|
|
2520
|
-
}
|
|
2521
|
-
const controller = new AbortController();
|
|
2522
|
-
const signal = options.signal === void 0 ? controller.signal : AbortSignal.any([controller.signal, options.signal]);
|
|
2523
|
-
const timeout = Math.min(15e3, (options.deadline ?? Infinity) - Date.now());
|
|
2524
|
-
if (timeout <= 0) throw new LoginError("expired");
|
|
2525
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
2526
|
-
try {
|
|
2527
|
-
const work = (async () => {
|
|
2528
|
-
const response = await this.#fetch(`${this.#relayUrl}${path}`, {
|
|
2529
|
-
method: "POST",
|
|
2530
|
-
redirect: "error",
|
|
2531
|
-
credentials: "omit",
|
|
2532
|
-
cache: "no-store",
|
|
2533
|
-
headers: {
|
|
2534
|
-
"content-type": "application/json",
|
|
2535
|
-
accept: "application/json",
|
|
2536
|
-
...options.token === void 0 ? {} : { authorization: `Bearer ${options.token}` }
|
|
2537
|
-
},
|
|
2538
|
-
body: JSON.stringify(body),
|
|
2539
|
-
signal
|
|
2540
|
-
});
|
|
2541
|
-
if (signal.aborted || response.redirected || response.url && response.url !== `${this.#relayUrl}${path}`) {
|
|
2542
|
-
await response.body?.cancel();
|
|
2543
|
-
throw new LoginError("response");
|
|
2544
|
-
}
|
|
2545
|
-
const reader = response.body?.getReader();
|
|
2546
|
-
if (!reader) throw new LoginError("response", void 0, response.status);
|
|
2547
|
-
const chunks = [];
|
|
2548
|
-
let size = 0;
|
|
2549
|
-
try {
|
|
2550
|
-
while (true) {
|
|
2551
|
-
const chunk = await abortable(reader.read(), signal);
|
|
2552
|
-
if (chunk.done) break;
|
|
2553
|
-
size += chunk.value.byteLength;
|
|
2554
|
-
if (size > 16 * 1024) throw new LoginError("response");
|
|
2555
|
-
chunks.push(chunk.value);
|
|
2556
|
-
}
|
|
2557
|
-
} finally {
|
|
2558
|
-
void reader.cancel().catch(() => void 0);
|
|
2559
|
-
reader.releaseLock();
|
|
2560
|
-
}
|
|
2561
|
-
let value;
|
|
2562
|
-
try {
|
|
2563
|
-
value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
2564
|
-
} catch {
|
|
2565
|
-
throw new LoginError("response", void 0, response.status);
|
|
2566
|
-
}
|
|
2567
|
-
const rejected = MicrosoftEnrollmentFailureSchema.safeParse(value);
|
|
2568
|
-
if (!response.ok || rejected.success) {
|
|
2569
|
-
const retry = response.headers.get("retry-after");
|
|
2570
|
-
const seconds = retry !== null && /^\d+$/.test(retry) ? Number(retry) : NaN;
|
|
2571
|
-
const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : retry === null ? 6e4 : Math.max(0, Date.parse(retry) - Date.now());
|
|
2572
|
-
throw failure(
|
|
2573
|
-
rejected.success ? rejected.data.error.code : "",
|
|
2574
|
-
response.status,
|
|
2575
|
-
Number.isFinite(retryAfterMs) ? retryAfterMs : 6e4
|
|
2576
|
-
);
|
|
2577
|
-
}
|
|
2578
|
-
const parsed = schema.safeParse(value);
|
|
2579
|
-
if (!parsed.success) throw new LoginError("response");
|
|
2580
|
-
return parsed.data;
|
|
2581
|
-
})();
|
|
2582
|
-
return await abortable(work, signal);
|
|
2583
|
-
} catch (error) {
|
|
2584
|
-
if (options.signal?.aborted) throw new LoginError("cancelled");
|
|
2585
|
-
if (controller.signal.aborted) throw new LoginError("network");
|
|
2586
|
-
throw safeError(error);
|
|
2587
|
-
} finally {
|
|
2588
|
-
clearTimeout(timer);
|
|
2589
|
-
}
|
|
2590
|
-
}
|
|
2591
|
-
};
|
|
2592
|
-
|
|
2593
|
-
// src/relay-login-startup.ts
|
|
2594
|
-
async function completeRelayLogin(options) {
|
|
2595
|
-
const { settings: settings2, identity, force, signal, report } = options;
|
|
2596
|
-
if (settings2.relayAuthentication.mode === "token") {
|
|
2597
|
-
if (force) {
|
|
2598
|
-
throw new Error("Set RELAY_AUTH=microsoft in the selected environment file to sign in. The existing token has not been changed.");
|
|
2599
|
-
}
|
|
2600
|
-
return void 0;
|
|
2601
|
-
}
|
|
2602
|
-
let page;
|
|
2603
|
-
let pageTransferred = false;
|
|
2604
|
-
const login = new MicrosoftRelayLogin({
|
|
2605
|
-
relayUrl: settings2.relayUrl,
|
|
2606
|
-
identity,
|
|
2607
|
-
reauthorize: force,
|
|
2608
|
-
getRedirectUri: () => {
|
|
2609
|
-
if (!page) throw new Error("Microsoft login page is not listening.");
|
|
2610
|
-
return `${page.url}/relay-login/callback`;
|
|
2611
|
-
}
|
|
2612
|
-
});
|
|
2613
|
-
try {
|
|
2614
|
-
if (!force) {
|
|
2615
|
-
const credential2 = await login.restore();
|
|
2616
|
-
signal.throwIfAborted();
|
|
2617
|
-
if (credential2 !== void 0) return credential2;
|
|
2618
|
-
}
|
|
2619
|
-
if (!settings2.pairingPageEnabled && !force) {
|
|
2620
|
-
const state = login.getState();
|
|
2621
|
-
if (state.state === "error") throw new Error(state.message);
|
|
2622
|
-
throw new Error("Microsoft sign-in is required. Run agentknight login with the same --env file and OS user before starting the headless Agent.");
|
|
2623
|
-
}
|
|
2624
|
-
signal.throwIfAborted();
|
|
2625
|
-
page = new PairingPageServer({
|
|
2626
|
-
machineName: identity.machineName,
|
|
2627
|
-
port: settings2.pairingPagePort,
|
|
2628
|
-
relayLogin: login,
|
|
2629
|
-
getRegistrationStatus: () => ({ state: "connecting", message: "Sign in with Microsoft." }),
|
|
2630
|
-
pairingProvider: { getPairing: async () => {
|
|
2631
|
-
throw new Error("Sign in before pairing.");
|
|
2632
|
-
} }
|
|
2633
|
-
});
|
|
2634
|
-
await page.start();
|
|
2635
|
-
options.onListening?.(Number(new URL(page.url).port));
|
|
2636
|
-
report(`Microsoft sign-in: ${page.url}`);
|
|
2637
|
-
const credential = await login.waitForCredential(signal);
|
|
2638
|
-
signal.throwIfAborted();
|
|
2639
|
-
if (!force) {
|
|
2640
|
-
options.onAuthorizedPage(page);
|
|
2641
|
-
pageTransferred = true;
|
|
2642
|
-
}
|
|
2643
|
-
return credential;
|
|
2644
|
-
} finally {
|
|
2645
|
-
try {
|
|
2646
|
-
if (!pageTransferred) await page?.stop();
|
|
2647
|
-
} finally {
|
|
2648
|
-
await login.close();
|
|
2649
|
-
}
|
|
2650
|
-
}
|
|
2651
|
-
}
|
|
2652
|
-
|
|
2653
|
-
// src/relay-account.ts
|
|
2654
|
-
var AccountReadError = class extends Error {
|
|
2655
|
-
constructor(message, state = "unavailable") {
|
|
2656
|
-
super(message);
|
|
2657
|
-
this.state = state;
|
|
2658
|
-
}
|
|
2659
|
-
state;
|
|
2660
|
-
};
|
|
2661
|
-
var RelayAccount = class {
|
|
2662
|
-
constructor(options) {
|
|
2663
|
-
this.options = options;
|
|
2664
|
-
this.#lastUser = options.user;
|
|
2665
|
-
this.#method = options.method;
|
|
2666
|
-
}
|
|
2667
|
-
options;
|
|
2668
|
-
#cached;
|
|
2669
|
-
#expiresAt = 0;
|
|
2670
|
-
#pending;
|
|
2671
|
-
#lastUser;
|
|
2672
|
-
#method;
|
|
2673
|
-
async read(registration) {
|
|
2674
|
-
if (registration.state !== "registered") {
|
|
2675
|
-
this.#expiresAt = 0;
|
|
2676
|
-
this.#pending = void 0;
|
|
2677
|
-
return this.#view(
|
|
2678
|
-
registration.state === "connecting" ? "connecting" : "disconnected",
|
|
2679
|
-
registration.state === "error" ? "Relay \u8FDE\u63A5\u5DF2\u65AD\u5F00\u3002" : void 0
|
|
2680
|
-
);
|
|
2681
|
-
}
|
|
2682
|
-
if (this.#cached !== void 0 && Date.now() < this.#expiresAt) return this.#cached;
|
|
2683
|
-
if (this.#pending !== void 0) return this.#pending;
|
|
2684
|
-
const pending = this.#load();
|
|
2685
|
-
this.#pending = pending;
|
|
2686
|
-
try {
|
|
2687
|
-
const account = await pending;
|
|
2688
|
-
if (this.#pending === pending) {
|
|
2689
|
-
this.#cached = account;
|
|
2690
|
-
this.#lastUser = account.user;
|
|
2691
|
-
this.#method = account.method;
|
|
2692
|
-
this.#expiresAt = Date.now() + (account.state === "signed-in" ? 3e4 : 5e3);
|
|
2693
|
-
}
|
|
2694
|
-
return account;
|
|
2695
|
-
} finally {
|
|
2696
|
-
if (this.#pending === pending) this.#pending = void 0;
|
|
2697
|
-
}
|
|
2698
|
-
}
|
|
2699
|
-
#view(state, error) {
|
|
2700
|
-
return {
|
|
2701
|
-
state,
|
|
2702
|
-
method: this.#method,
|
|
2703
|
-
userId: this.options.config.userId,
|
|
2704
|
-
...this.#lastUser === void 0 ? {} : { user: { ...this.#lastUser } },
|
|
2705
|
-
...error === void 0 ? {} : { error }
|
|
2706
|
-
};
|
|
2707
|
-
}
|
|
2708
|
-
async #load() {
|
|
2709
|
-
try {
|
|
2710
|
-
const { config, machineId } = this.options;
|
|
2711
|
-
const url = `${normalizeRelayOrigin(config.relayUrl)}/auth/pc/account`;
|
|
2712
|
-
if (url.startsWith("https:") && process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
2713
|
-
throw new AccountReadError("\u65E0\u6CD5\u5B89\u5168\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u542F\u7528 HTTPS \u8BC1\u4E66\u9A8C\u8BC1\u3002");
|
|
2714
|
-
}
|
|
2715
|
-
const response = await (this.options.fetch ?? globalThis.fetch)(url, {
|
|
2716
|
-
method: "POST",
|
|
2717
|
-
redirect: "error",
|
|
2718
|
-
credentials: "omit",
|
|
2719
|
-
cache: "no-store",
|
|
2720
|
-
signal: AbortSignal.timeout(3e3),
|
|
2721
|
-
headers: { authorization: `Bearer ${config.relayToken}`, "content-type": "application/json", accept: "application/json" },
|
|
2722
|
-
body: JSON.stringify(PcAccountRequestSchema.parse({ userId: config.userId, machineId }))
|
|
2723
|
-
});
|
|
2724
|
-
const reader = response.body?.getReader();
|
|
2725
|
-
try {
|
|
2726
|
-
if (response.redirected || response.url && response.url !== url) throw new AccountReadError("Relay \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8D26\u6237\u4FE1\u606F\u3002");
|
|
2727
|
-
if (response.status === 404) throw new AccountReadError("Relay \u5C1A\u4E0D\u652F\u6301\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u5347\u7EA7 Relay\u3002");
|
|
2728
|
-
if (response.status === 401 || response.status === 403) throw new AccountReadError("\u767B\u5F55\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002", "error");
|
|
2729
|
-
if (!response.ok || reader === void 0) throw new AccountReadError("\u65E0\u6CD5\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0\u3002");
|
|
2730
|
-
const chunks = [];
|
|
2731
|
-
let size = 0;
|
|
2732
|
-
while (true) {
|
|
2733
|
-
const chunk = await reader.read();
|
|
2734
|
-
if (chunk.done) break;
|
|
2735
|
-
size += chunk.value.byteLength;
|
|
2736
|
-
if (size > 16 * 1024) throw new AccountReadError("Relay \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8D26\u6237\u4FE1\u606F\u3002");
|
|
2737
|
-
chunks.push(chunk.value);
|
|
2738
|
-
}
|
|
2739
|
-
const parsed = PcAccountResultSchema.safeParse(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
2740
|
-
if (!parsed.success || !parsed.data.ok || parsed.data.user.userId !== config.userId || this.options.method === "microsoft" && parsed.data.method !== "microsoft") {
|
|
2741
|
-
throw new AccountReadError("Relay \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8D26\u6237\u4FE1\u606F\u3002");
|
|
2742
|
-
}
|
|
2743
|
-
return { state: "signed-in", method: parsed.data.method, userId: config.userId, user: parsed.data.user };
|
|
2744
|
-
} finally {
|
|
2745
|
-
await reader?.cancel();
|
|
2746
|
-
reader?.releaseLock();
|
|
2747
|
-
}
|
|
2748
|
-
} catch (error) {
|
|
2749
|
-
return this.#view(
|
|
2750
|
-
error instanceof AccountReadError ? error.state : "unavailable",
|
|
2751
|
-
error instanceof AccountReadError ? error.message : "\u65E0\u6CD5\u8BFB\u53D6\u8D26\u6237\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5 Relay \u8FDE\u63A5\u540E\u5237\u65B0\u3002"
|
|
2752
|
-
);
|
|
2753
|
-
}
|
|
2754
|
-
}
|
|
2755
|
-
};
|
|
2756
|
-
|
|
2757
|
-
// src/diagnostic-logger.ts
|
|
2758
|
-
import {
|
|
2759
|
-
appendFileSync,
|
|
2760
|
-
existsSync,
|
|
2761
|
-
mkdirSync,
|
|
2762
|
-
renameSync,
|
|
2763
|
-
statSync,
|
|
2764
|
-
unlinkSync
|
|
2765
|
-
} from "node:fs";
|
|
2766
|
-
import { join } from "node:path";
|
|
2767
|
-
import pino from "pino";
|
|
2768
|
-
var MAX_LOG_BYTES = 1024 * 1024;
|
|
2769
|
-
var MAX_LOG_ARCHIVES = 9;
|
|
2770
|
-
var REDACTED = "[REDACTED]";
|
|
2771
|
-
var SENSITIVE_FIELD = /password|token|secret|credential|authorization|cookie|message|stack|reason|prompt|content|payload|body/i;
|
|
2772
|
-
var BEARER_TOKEN = /bearer\s+[A-Za-z0-9._~+/=-]+/gi;
|
|
2773
|
-
var SENSITIVE_ASSIGNMENT = /(password|token|secret|credential|authorization)\s*(?:=|:|is)?\s*[^\s,;]+/gi;
|
|
2774
|
-
var SENSITIVE_QUERY = /([?&](?:password|token|secret|credential|authorization)=)[^&#\s]+/gi;
|
|
2775
|
-
var LONG_ENCODED_VALUE = /(?<![A-Za-z0-9_-])[A-Za-z0-9_+/=-]{40,}(?![A-Za-z0-9_-])/g;
|
|
2776
|
-
function createDiagnosticLogger(dataDirectory, level, options = {}) {
|
|
2777
|
-
const version = options.version ?? readAppVersion();
|
|
2778
|
-
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()) {
|
|
2779
|
-
throw new Error("Diagnostic log version must be a safe application version");
|
|
2780
|
-
}
|
|
2781
|
-
const logDirectory = join(dataDirectory, "logs", version);
|
|
2782
|
-
const logPath = join(logDirectory, "pc-agent.jsonl");
|
|
2783
|
-
mkdirSync(logDirectory, { recursive: true });
|
|
2784
|
-
const fileDestination = new RotatingFileDestination(
|
|
2785
|
-
logPath,
|
|
2786
|
-
options.maxLogBytes ?? MAX_LOG_BYTES,
|
|
2787
|
-
version
|
|
2788
|
-
);
|
|
2789
|
-
const logger = pino(
|
|
2790
|
-
{
|
|
2791
|
-
level,
|
|
2792
|
-
base: { component: "pc-agent", appVersion: version },
|
|
2793
|
-
redact: {
|
|
2794
|
-
paths: [
|
|
2795
|
-
"token",
|
|
2796
|
-
"relayToken",
|
|
2797
|
-
"password",
|
|
2798
|
-
"secret",
|
|
2799
|
-
"mobileCredential",
|
|
2800
|
-
"contentKey",
|
|
2801
|
-
"authorization",
|
|
2802
|
-
"*.token",
|
|
2803
|
-
"*.relayToken",
|
|
2804
|
-
"*.password",
|
|
2805
|
-
"*.secret",
|
|
2806
|
-
"*.mobileCredential",
|
|
2807
|
-
"*.contentKey",
|
|
2808
|
-
"*.authorization",
|
|
2809
|
-
"req.headers.authorization"
|
|
2810
|
-
],
|
|
2811
|
-
censor: REDACTED
|
|
2812
|
-
}
|
|
2813
|
-
},
|
|
2814
|
-
pino.multistream([
|
|
2815
|
-
{
|
|
2816
|
-
level: "trace",
|
|
2817
|
-
stream: new SanitizingDestination(
|
|
2818
|
-
options.terminalStream ?? process.stdout,
|
|
2819
|
-
(message) => fileDestination.sanitize(message)
|
|
2820
|
-
)
|
|
2821
|
-
},
|
|
2822
|
-
{ level: "trace", stream: fileDestination }
|
|
2823
|
-
])
|
|
2824
|
-
);
|
|
2825
|
-
return {
|
|
2826
|
-
logger,
|
|
2827
|
-
logPath,
|
|
2828
|
-
async close() {
|
|
2829
|
-
logger.flush();
|
|
2830
|
-
}
|
|
2831
|
-
};
|
|
2832
|
-
}
|
|
2833
|
-
var RotatingFileDestination = class {
|
|
2834
|
-
constructor(logPath, maxBytes, appVersion) {
|
|
2835
|
-
this.logPath = logPath;
|
|
2836
|
-
this.maxBytes = maxBytes;
|
|
2837
|
-
this.appVersion = appVersion;
|
|
2838
|
-
try {
|
|
2839
|
-
this.#currentBytes = existsSync(logPath) ? statSync(logPath).size : 0;
|
|
2840
|
-
if (this.#currentBytes >= maxBytes) {
|
|
2841
|
-
this.#rotate();
|
|
2842
|
-
}
|
|
2843
|
-
} catch (error) {
|
|
2844
|
-
this.#disable(error);
|
|
2845
|
-
}
|
|
2846
|
-
}
|
|
2847
|
-
logPath;
|
|
2848
|
-
maxBytes;
|
|
2849
|
-
appVersion;
|
|
2850
|
-
#currentBytes = 0;
|
|
2851
|
-
#disabled = false;
|
|
2852
|
-
write(message) {
|
|
2853
|
-
if (this.#disabled) {
|
|
2854
|
-
return;
|
|
2855
|
-
}
|
|
2856
|
-
try {
|
|
2857
|
-
let safeMessage = this.#sanitizePersistedLogLine(message);
|
|
2858
|
-
let messageBytes = Buffer.byteLength(safeMessage);
|
|
2859
|
-
if (messageBytes > this.maxBytes) {
|
|
2860
|
-
safeMessage = `${JSON.stringify({
|
|
2861
|
-
level: 40,
|
|
2862
|
-
time: Date.now(),
|
|
2863
|
-
component: "pc-agent",
|
|
2864
|
-
appVersion: this.appVersion,
|
|
2865
|
-
droppedBytes: messageBytes,
|
|
2866
|
-
msg: "pc-agent.diagnostics.oversized-entry-dropped"
|
|
2867
|
-
})}
|
|
2868
|
-
`;
|
|
2869
|
-
messageBytes = Buffer.byteLength(safeMessage);
|
|
2870
|
-
if (messageBytes > this.maxBytes) {
|
|
2871
|
-
throw new Error("Diagnostic log byte limit cannot fit a failure record");
|
|
2872
|
-
}
|
|
2873
|
-
}
|
|
2874
|
-
if (this.#currentBytes > 0 && this.#currentBytes + messageBytes > this.maxBytes) {
|
|
2875
|
-
this.#rotate();
|
|
2876
|
-
}
|
|
2877
|
-
appendFileSync(this.logPath, safeMessage, "utf8");
|
|
2878
|
-
this.#currentBytes += messageBytes;
|
|
2879
|
-
} catch (error) {
|
|
2880
|
-
this.#disable(error);
|
|
2881
|
-
}
|
|
2882
|
-
}
|
|
2883
|
-
sanitize(message) {
|
|
2884
|
-
return this.#sanitizePersistedLogLine(message);
|
|
2885
|
-
}
|
|
2886
|
-
#disable(error) {
|
|
2887
|
-
this.#disabled = true;
|
|
2888
|
-
const details = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
2889
|
-
process.stderr.write(
|
|
2890
|
-
`PC diagnostic file logging disabled after a write failure: ${details}
|
|
2891
|
-
`
|
|
2892
|
-
);
|
|
2893
|
-
}
|
|
2894
|
-
#sanitizePersistedLogLine(message) {
|
|
2895
|
-
let parsed;
|
|
2896
|
-
try {
|
|
2897
|
-
parsed = JSON.parse(message);
|
|
2898
|
-
} catch {
|
|
2899
|
-
return `${JSON.stringify({
|
|
2900
|
-
level: 40,
|
|
2901
|
-
time: Date.now(),
|
|
2902
|
-
component: "pc-agent",
|
|
2903
|
-
appVersion: this.appVersion,
|
|
2904
|
-
msg: "pc-agent.diagnostics.unstructured-entry-dropped"
|
|
2905
|
-
})}
|
|
2906
|
-
`;
|
|
2907
|
-
}
|
|
2908
|
-
const sanitized = this.#sanitizePersistedValue(parsed);
|
|
2909
|
-
return `${JSON.stringify(
|
|
2910
|
-
sanitized !== null && typeof sanitized === "object" && !Array.isArray(sanitized) ? { ...sanitized, appVersion: this.appVersion } : sanitized
|
|
2911
|
-
)}
|
|
2912
|
-
`;
|
|
2913
|
-
}
|
|
2914
|
-
#sanitizePersistedValue(value, key) {
|
|
2915
|
-
if (key !== void 0 && key !== "msg" && SENSITIVE_FIELD.test(key)) {
|
|
2916
|
-
return REDACTED;
|
|
2917
|
-
}
|
|
2918
|
-
if (typeof value === "string") {
|
|
2919
|
-
return this.#sanitizePersistedText(value);
|
|
2920
|
-
}
|
|
2921
|
-
if (Array.isArray(value)) {
|
|
2922
|
-
return value.map((item) => this.#sanitizePersistedValue(item));
|
|
2923
|
-
}
|
|
2924
|
-
if (value !== null && typeof value === "object") {
|
|
2925
|
-
return Object.fromEntries(
|
|
2926
|
-
Object.entries(value).map(([childKey, childValue]) => [
|
|
2927
|
-
childKey,
|
|
2928
|
-
this.#sanitizePersistedValue(childValue, childKey)
|
|
2929
|
-
])
|
|
2930
|
-
);
|
|
2931
|
-
}
|
|
2932
|
-
return value;
|
|
2933
|
-
}
|
|
2934
|
-
#sanitizePersistedText(value) {
|
|
2935
|
-
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);
|
|
2936
|
-
}
|
|
2937
|
-
#path(index) {
|
|
2938
|
-
return index === 0 ? this.logPath : `${this.logPath}.${index}`;
|
|
2939
|
-
}
|
|
2940
|
-
#rotate() {
|
|
2941
|
-
const oldestPath = this.#path(MAX_LOG_ARCHIVES);
|
|
2942
|
-
if (existsSync(oldestPath)) {
|
|
2943
|
-
unlinkSync(oldestPath);
|
|
2944
|
-
}
|
|
2945
|
-
for (let index = MAX_LOG_ARCHIVES - 1; index >= 0; index -= 1) {
|
|
2946
|
-
const path = this.#path(index);
|
|
2947
|
-
if (existsSync(path)) {
|
|
2948
|
-
renameSync(path, this.#path(index + 1));
|
|
2949
|
-
}
|
|
2950
|
-
}
|
|
2951
|
-
this.#currentBytes = 0;
|
|
2952
|
-
}
|
|
2953
|
-
};
|
|
2954
|
-
var SanitizingDestination = class {
|
|
2955
|
-
constructor(destination, sanitize) {
|
|
2956
|
-
this.destination = destination;
|
|
2957
|
-
this.sanitize = sanitize;
|
|
2958
|
-
}
|
|
2959
|
-
destination;
|
|
2960
|
-
sanitize;
|
|
2961
|
-
write(message) {
|
|
2962
|
-
this.destination.write(this.sanitize(message));
|
|
2963
|
-
}
|
|
2964
|
-
};
|
|
2965
|
-
|
|
2966
|
-
// src/chat-settings.ts
|
|
2967
|
-
import { join as join2 } from "node:path";
|
|
2968
|
-
import { z as z3 } from "zod";
|
|
2969
|
-
var settings = {
|
|
2970
|
-
groupChatEnabled: {
|
|
2971
|
-
file: "group-chat-settings.json",
|
|
2972
|
-
label: "Group chat",
|
|
2973
|
-
schema: z3.object({ groupChatEnabled: z3.boolean() }).strict().transform((value) => value.groupChatEnabled)
|
|
2974
|
-
},
|
|
2975
|
-
peerChatEnabled: {
|
|
2976
|
-
file: "peer-chat-settings.json",
|
|
2977
|
-
label: "Peer chat",
|
|
2978
|
-
schema: z3.object({ peerChatEnabled: z3.boolean() }).strict().transform((value) => value.peerChatEnabled)
|
|
2979
|
-
}
|
|
2980
|
-
};
|
|
2981
|
-
var ChatSettings = class _ChatSettings {
|
|
2982
|
-
constructor(path, key, enabled) {
|
|
2983
|
-
this.path = path;
|
|
2984
|
-
this.key = key;
|
|
2985
|
-
this.#enabled = enabled;
|
|
2986
|
-
}
|
|
2987
|
-
path;
|
|
2988
|
-
key;
|
|
2989
|
-
#enabled;
|
|
2990
|
-
#saving = false;
|
|
2991
|
-
static async load(directory, defaultEnabled, key = "groupChatEnabled") {
|
|
2992
|
-
const path = join2(directory, settings[key].file);
|
|
2993
|
-
const stored = await readOptionalJson(path);
|
|
2994
|
-
return new _ChatSettings(path, key, stored === void 0 ? defaultEnabled : settings[key].schema.parse(stored));
|
|
2995
|
-
}
|
|
2996
|
-
get enabled() {
|
|
2997
|
-
return this.#enabled;
|
|
2998
|
-
}
|
|
2999
|
-
async save(enabled, apply) {
|
|
3000
|
-
const label = settings[this.key].label;
|
|
3001
|
-
if (this.#saving) throw new Error(`${label} settings are being saved; try again.`);
|
|
3002
|
-
this.#saving = true;
|
|
3003
|
-
const previous = this.#enabled;
|
|
3004
|
-
try {
|
|
3005
|
-
await apply(enabled);
|
|
3006
|
-
await writePrivateJson(this.path, { [this.key]: enabled });
|
|
3007
|
-
this.#enabled = enabled;
|
|
3008
|
-
} catch (error) {
|
|
3009
|
-
try {
|
|
3010
|
-
await apply(previous);
|
|
3011
|
-
} catch (rollbackError) {
|
|
3012
|
-
throw new AggregateError([error, rollbackError], `${label} settings could not be saved or restored.`);
|
|
3013
|
-
}
|
|
3014
|
-
throw error;
|
|
3015
|
-
} finally {
|
|
3016
|
-
this.#saving = false;
|
|
3017
|
-
}
|
|
3018
|
-
}
|
|
3019
|
-
};
|
|
3020
|
-
|
|
3021
|
-
// src/device-identity.ts
|
|
3022
|
-
import { randomUUID } from "node:crypto";
|
|
3023
|
-
import { link, lstat, mkdir, readFile, readlink, rename, rm, writeFile } from "node:fs/promises";
|
|
3024
|
-
import { homedir, hostname } from "node:os";
|
|
3025
|
-
import { dirname, join as join3, resolve } from "node:path";
|
|
3026
|
-
import { z as z4 } from "zod";
|
|
3027
|
-
import { DeviceIdentitySchema, LEGACY_CLIENT_STATE_DIRECTORY } from "@agentknight/sdk/configuration";
|
|
3028
|
-
import { DeviceIdentitySchema as DeviceIdentitySchema2 } from "@agentknight/sdk/configuration";
|
|
3029
|
-
var LegacyDeviceIdentitySchema = z4.object({
|
|
3030
|
-
schemaVersion: z4.literal(1),
|
|
3031
|
-
machineId: z4.uuid(),
|
|
3032
|
-
machineName: z4.string().trim().min(1).max(120),
|
|
3033
|
-
createdAt: z4.iso.datetime({ offset: true })
|
|
3034
|
-
});
|
|
3035
|
-
function resolveMachineName(environment = process.env, fallback = hostname()) {
|
|
3036
|
-
const computerName = environment.COMPUTERNAME?.trim();
|
|
3037
|
-
return computerName === void 0 || computerName.length === 0 ? fallback : computerName;
|
|
3038
|
-
}
|
|
3039
|
-
function isMissing(error) {
|
|
3040
|
-
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
3041
|
-
}
|
|
3042
|
-
async function optionalStat(path) {
|
|
3043
|
-
try {
|
|
3044
|
-
return await lstat(path);
|
|
3045
|
-
} catch (error) {
|
|
3046
|
-
if (isMissing(error)) return void 0;
|
|
3047
|
-
throw error;
|
|
3048
|
-
}
|
|
3049
|
-
}
|
|
3050
|
-
async function readStableDeviceId(path) {
|
|
3051
|
-
const info = await optionalStat(path);
|
|
3052
|
-
if (info === void 0) return void 0;
|
|
3053
|
-
if (!info.isFile()) throw new Error(`Device ID must be a regular file, not a link: ${path}`);
|
|
3054
|
-
const parsed = z4.uuid().safeParse((await readFile(path, "utf8")).trim());
|
|
3055
|
-
if (!parsed.success) throw new Error(`Invalid device ID in ${path}`, { cause: parsed.error });
|
|
3056
|
-
return parsed.data;
|
|
3057
|
-
}
|
|
3058
|
-
async function requireDirectory(path) {
|
|
3059
|
-
const info = await optionalStat(path);
|
|
3060
|
-
if (info === void 0) return false;
|
|
3061
|
-
if (!info.isDirectory()) throw new Error(`Identity directory must not be linked or a special file: ${path}`);
|
|
3062
|
-
return true;
|
|
3063
|
-
}
|
|
3064
|
-
async function readLegacyStableDeviceId(userHome) {
|
|
3065
|
-
const defaultHome = defaultClientHome(userHome);
|
|
3066
|
-
const movedRoot = join3(defaultHome, LEGACY_CLIENT_STATE_DIRECTORY);
|
|
3067
|
-
const legacyRoot = join3(userHome, LEGACY_CLIENT_STATE_DIRECTORY);
|
|
3068
|
-
const movedExists = await requireDirectory(defaultHome) && await requireDirectory(movedRoot);
|
|
3069
|
-
const legacyInfo = await optionalStat(legacyRoot);
|
|
3070
|
-
let legacyDirectory;
|
|
3071
|
-
if (legacyInfo?.isSymbolicLink()) {
|
|
3072
|
-
const target = resolve(dirname(legacyRoot), await readlink(legacyRoot));
|
|
3073
|
-
if (!sameClientPath(target, movedRoot)) {
|
|
3074
|
-
throw new Error(`Legacy identity link must target ${movedRoot}: ${legacyRoot}`);
|
|
3075
|
-
}
|
|
3076
|
-
if (!movedExists) throw new Error(`Legacy identity link target is missing: ${movedRoot}`);
|
|
3077
|
-
legacyDirectory = movedRoot;
|
|
3078
|
-
} else if (legacyInfo !== void 0) {
|
|
3079
|
-
if (!legacyInfo.isDirectory()) {
|
|
3080
|
-
throw new Error(`Legacy identity root must be a directory: ${legacyRoot}`);
|
|
3081
|
-
}
|
|
3082
|
-
legacyDirectory = legacyRoot;
|
|
3083
|
-
}
|
|
3084
|
-
const paths = /* @__PURE__ */ new Set();
|
|
3085
|
-
if (legacyDirectory !== void 0) paths.add(join3(legacyDirectory, "device-id"));
|
|
3086
|
-
if (movedExists) paths.add(join3(movedRoot, "device-id"));
|
|
3087
|
-
let stableDeviceId;
|
|
3088
|
-
for (const path of paths) {
|
|
3089
|
-
const candidate = await readStableDeviceId(path);
|
|
3090
|
-
if (candidate === void 0) continue;
|
|
3091
|
-
if (stableDeviceId !== void 0 && stableDeviceId !== candidate) {
|
|
3092
|
-
throw new Error(`Conflicting legacy device IDs in ${legacyRoot} and ${movedRoot}; reconcile them before starting.`);
|
|
3093
|
-
}
|
|
3094
|
-
stableDeviceId = candidate;
|
|
3095
|
-
}
|
|
3096
|
-
return stableDeviceId;
|
|
3097
|
-
}
|
|
3098
|
-
async function writePrivateFile(path, contents, replace) {
|
|
3099
|
-
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
3100
|
-
try {
|
|
3101
|
-
await writeFile(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
3102
|
-
if (replace) {
|
|
3103
|
-
await rename(temporaryPath, path);
|
|
3104
|
-
} else {
|
|
3105
|
-
await link(temporaryPath, path);
|
|
3106
|
-
}
|
|
3107
|
-
} finally {
|
|
3108
|
-
await rm(temporaryPath, { force: true });
|
|
3109
|
-
}
|
|
3110
|
-
}
|
|
3111
|
-
async function loadOrCreateDeviceIdentity(dataDirectory, currentMachineName = resolveMachineName(), legacyUserHome = homedir()) {
|
|
3112
|
-
const path = join3(dataDirectory, "device.json");
|
|
3113
|
-
const stablePath = join3(dataDirectory, "device-id");
|
|
3114
|
-
await requireDirectory(dataDirectory);
|
|
3115
|
-
let existing;
|
|
3116
|
-
try {
|
|
3117
|
-
existing = z4.union([DeviceIdentitySchema, LegacyDeviceIdentitySchema]).parse(
|
|
3118
|
-
JSON.parse(await readFile(path, "utf8"))
|
|
3119
|
-
);
|
|
3120
|
-
} catch (error) {
|
|
3121
|
-
if (!isMissing(error)) throw error;
|
|
3122
|
-
}
|
|
3123
|
-
const canonicalId = await readStableDeviceId(stablePath);
|
|
3124
|
-
const existingStableId = existing?.schemaVersion === 2 ? existing.stableDeviceId : void 0;
|
|
3125
|
-
if (canonicalId !== void 0 && existingStableId !== void 0 && canonicalId !== existingStableId) {
|
|
3126
|
-
throw new Error(`Conflicting device IDs in ${stablePath} and ${path}; reconcile them before starting.`);
|
|
3127
|
-
}
|
|
3128
|
-
const isDefaultHome = sameClientPath(dataDirectory, defaultClientHome(legacyUserHome));
|
|
3129
|
-
const legacyId = canonicalId === void 0 && (isDefaultHome || existing?.schemaVersion === 1) ? await readLegacyStableDeviceId(legacyUserHome) : void 0;
|
|
3130
|
-
if (!isDefaultHome && existing?.schemaVersion === 1 && legacyId !== void 0 && legacyId !== existing.machineId) {
|
|
3131
|
-
throw new Error(`Ambiguous legacy device ID for ${path}. Stop the Agent and restore the known stable device ID into ${stablePath} before starting; the v1 machine ID differs from the legacy ID.`);
|
|
3132
|
-
}
|
|
3133
|
-
if (legacyId !== void 0 && existingStableId !== void 0 && legacyId !== existingStableId) {
|
|
3134
|
-
throw new Error(`Conflicting legacy device ID and ${path}; reconcile them before starting.`);
|
|
3135
|
-
}
|
|
3136
|
-
const identity = DeviceIdentitySchema.parse({
|
|
3137
|
-
schemaVersion: 2,
|
|
3138
|
-
machineId: existing?.machineId ?? randomUUID(),
|
|
3139
|
-
stableDeviceId: canonicalId ?? existingStableId ?? legacyId ?? existing?.machineId ?? randomUUID(),
|
|
3140
|
-
machineName: currentMachineName,
|
|
3141
|
-
createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3142
|
-
});
|
|
3143
|
-
await mkdir(dataDirectory, { recursive: true, mode: 448 });
|
|
3144
|
-
if (canonicalId === void 0) {
|
|
3145
|
-
await writePrivateFile(stablePath, `${identity.stableDeviceId}
|
|
3146
|
-
`, false);
|
|
3147
|
-
}
|
|
3148
|
-
if (existing === void 0 || existing.schemaVersion !== 2 || existing.machineName !== identity.machineName || existing.stableDeviceId !== identity.stableDeviceId) {
|
|
3149
|
-
await writePrivateFile(path, `${JSON.stringify(identity, null, 2)}
|
|
3150
|
-
`, existing !== void 0);
|
|
3151
|
-
}
|
|
3152
|
-
return identity;
|
|
3153
|
-
}
|
|
3154
|
-
|
|
3155
|
-
// src/pairing-qr.ts
|
|
3156
|
-
import qrcode from "qrcode-terminal";
|
|
3157
|
-
function printPairingQr(uri, expiresAt) {
|
|
3158
|
-
qrcode.generate(uri, { small: true }, (image) => {
|
|
3159
|
-
const expires = new Date(expiresAt).toLocaleTimeString();
|
|
3160
|
-
process.stdout.write(
|
|
3161
|
-
`
|
|
3162
|
-
Pair this PC with AgentKnight Android (expires ${expires}):
|
|
3163
|
-
${image}
|
|
3164
|
-
`
|
|
3165
|
-
);
|
|
3166
|
-
});
|
|
3167
|
-
}
|
|
3168
|
-
|
|
3169
|
-
// src/start-client.ts
|
|
3170
|
-
async function startClient(appVersion, cliOptions, resolved, cliPath) {
|
|
3171
|
-
clearClientConfiguration(process.env);
|
|
3172
|
-
Object.assign(process.env, resolved.environment);
|
|
3173
|
-
const settings2 = loadStartupConfig(resolved.environment, cliOptions);
|
|
3174
|
-
const upgradeId = cliOptions.command === "login" ? void 0 : await claimUpgradeStartup(settings2.dataDirectory, appVersion, cliPath);
|
|
3175
|
-
let diagnostics;
|
|
3176
|
-
let logger;
|
|
3177
|
-
try {
|
|
3178
|
-
diagnostics = createDiagnosticLogger(settings2.dataDirectory, settings2.logLevel, { version: appVersion });
|
|
3179
|
-
logger = diagnostics.logger;
|
|
3180
|
-
} catch (error) {
|
|
3181
|
-
logger = pino2({
|
|
3182
|
-
level: settings2.logLevel,
|
|
3183
|
-
base: { component: "pc-agent" }
|
|
3184
|
-
});
|
|
3185
|
-
logger.warn(
|
|
3186
|
-
{ error: toErrorDetails(error) },
|
|
3187
|
-
"pc-agent.diagnostics.file-disabled"
|
|
3188
|
-
);
|
|
3189
|
-
}
|
|
3190
|
-
logger.info(
|
|
3191
|
-
{
|
|
3192
|
-
diagnosticLogPath: diagnostics?.logPath,
|
|
3193
|
-
node: process.version,
|
|
3194
|
-
platform: process.platform,
|
|
3195
|
-
architecture: process.arch
|
|
3196
|
-
},
|
|
3197
|
-
"pc-agent.diagnostics.ready"
|
|
3198
|
-
);
|
|
3199
|
-
let agent;
|
|
3200
|
-
let identityHash = "initializing";
|
|
3201
|
-
const configHash = resolved.envFile === void 0 ? void 0 : await fileHash(resolved.envFile);
|
|
3202
|
-
const restart = restartEnvironment(
|
|
3203
|
-
resolved.environment,
|
|
3204
|
-
resolved.envFile === void 0 ? {} : parseEnv(readFileSync(resolved.envFile, "utf8")),
|
|
3205
|
-
settings2.dataDirectory
|
|
3206
|
-
);
|
|
3207
|
-
const restartArgs = [
|
|
3208
|
-
...cliOptions.noEnv ? ["--no-env"] : [],
|
|
3209
|
-
...resolved.envFile === void 0 ? [] : ["--env", resolved.envFile],
|
|
3210
|
-
...cliOptions.agents === void 0 ? [] : ["--agents", cliOptions.agents.length === 0 ? "none" : cliOptions.agents.join(",")]
|
|
3211
|
-
];
|
|
3212
|
-
const relayDisplay = new URL(settings2.relayUrl);
|
|
3213
|
-
relayDisplay.username = "";
|
|
3214
|
-
relayDisplay.password = "";
|
|
3215
|
-
relayDisplay.search = "";
|
|
3216
|
-
relayDisplay.hash = "";
|
|
3217
|
-
const control = await startRuntimeControl({
|
|
3218
|
-
directory: settings2.dataDirectory,
|
|
3219
|
-
...upgradeId === void 0 ? {} : { upgradeId },
|
|
3220
|
-
getStatus: async () => ({
|
|
3221
|
-
version: appVersion,
|
|
3222
|
-
...agent === void 0 ? { ready: false, busy: true } : await agent.getUpgradeStatus(),
|
|
3223
|
-
relayUrl: relayDisplay.toString(),
|
|
3224
|
-
identityHash,
|
|
3225
|
-
...resolved.envFile === void 0 ? {} : { configPath: resolved.envFile },
|
|
3226
|
-
...configHash === void 0 ? {} : { configHash },
|
|
3227
|
-
executable: process.execPath,
|
|
3228
|
-
cliPath,
|
|
3229
|
-
cwd: process.cwd(),
|
|
3230
|
-
args: restartArgs,
|
|
3231
|
-
canRestart: restart.canRestart,
|
|
3232
|
-
restartEnvironment: restart.environment,
|
|
3233
|
-
stopping: agent?.isStopping ?? false,
|
|
3234
|
-
...upgradeId === void 0 ? {} : { upgradeId }
|
|
3235
|
-
}),
|
|
3236
|
-
prepare: async () => {
|
|
3237
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3238
|
-
await agent.prepareForUpgrade();
|
|
3239
|
-
},
|
|
3240
|
-
cancel: () => agent?.cancelUpgrade(),
|
|
3241
|
-
stop: async () => {
|
|
3242
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3243
|
-
await agent.stopForUpgrade();
|
|
3244
|
-
},
|
|
3245
|
-
runPeerChat: async (request, signal) => {
|
|
3246
|
-
if (agent === void 0) throw new Error("Agent startup is still in progress.");
|
|
3247
|
-
return agent.runPeerChat(request, signal);
|
|
3248
|
-
},
|
|
3249
|
-
onError: (error) => logger.warn({ error: toErrorDetails(error) }, "pc-agent.control.failed")
|
|
3250
|
-
});
|
|
3251
|
-
let retainedPairingPage;
|
|
3252
|
-
try {
|
|
3253
|
-
const identity = settings2.machineName === void 0 ? await loadOrCreateDeviceIdentity(settings2.dataDirectory) : await loadOrCreateDeviceIdentity(
|
|
3254
|
-
settings2.dataDirectory,
|
|
3255
|
-
settings2.machineName
|
|
3256
|
-
);
|
|
3257
|
-
const loginAbort = new AbortController();
|
|
3258
|
-
const abortLogin = () => loginAbort.abort(new Error("Microsoft sign-in cancelled."));
|
|
3259
|
-
process.once("SIGINT", abortLogin);
|
|
3260
|
-
process.once("SIGTERM", abortLogin);
|
|
3261
|
-
let relayCredential;
|
|
3262
|
-
try {
|
|
3263
|
-
relayCredential = await completeRelayLogin({
|
|
3264
|
-
settings: settings2,
|
|
3265
|
-
identity,
|
|
3266
|
-
force: cliOptions.command === "login",
|
|
3267
|
-
signal: loginAbort.signal,
|
|
3268
|
-
report: (message) => process.stdout.write(`${message}
|
|
3269
|
-
`),
|
|
3270
|
-
onAuthorizedPage: (page) => {
|
|
3271
|
-
retainedPairingPage = page;
|
|
3272
|
-
}
|
|
3273
|
-
});
|
|
3274
|
-
} finally {
|
|
3275
|
-
process.off("SIGINT", abortLogin);
|
|
3276
|
-
process.off("SIGTERM", abortLogin);
|
|
3277
|
-
}
|
|
3278
|
-
if (cliOptions.command === "login") {
|
|
3279
|
-
process.stdout.write("Microsoft sign-in saved. Start AgentKnight to connect and pair.\n");
|
|
3280
|
-
return;
|
|
3281
|
-
}
|
|
3282
|
-
const config = loadConfig(resolved.environment, {
|
|
3283
|
-
...cliOptions,
|
|
3284
|
-
...relayCredential === void 0 ? {} : { relayCredential }
|
|
3285
|
-
});
|
|
3286
|
-
config.dataDirectory = resolve2(config.dataDirectory);
|
|
3287
|
-
if (retainedPairingPage !== void 0) config.pairingPagePort = Number(new URL(retainedPairingPage.url).port);
|
|
3288
|
-
const groupChatSettings = await ChatSettings.load(config.dataDirectory, config.groupChatEnabled !== false);
|
|
3289
|
-
config.groupChatEnabled = groupChatSettings.enabled;
|
|
3290
|
-
const peerChatSettings = await ChatSettings.load(config.dataDirectory, config.peerChatEnabled !== false, "peerChatEnabled");
|
|
3291
|
-
config.peerChatEnabled = peerChatSettings.enabled;
|
|
3292
|
-
const { initialize, supportsAgentSelection } = await import("@agentknight/sdk");
|
|
3293
|
-
const runningAgent = await initialize({
|
|
3294
|
-
...config,
|
|
3295
|
-
identity,
|
|
3296
|
-
appVersion,
|
|
3297
|
-
logger,
|
|
3298
|
-
directoryLease: control.directoryLease,
|
|
3299
|
-
...config.showPairingQr && process.stdout.isTTY ? {
|
|
3300
|
-
onPairing: (ticket) => printPairingQr(ticket.uri, ticket.expiresAt)
|
|
3301
|
-
} : {}
|
|
3302
|
-
});
|
|
3303
|
-
const { adapter, pairingProvider } = runningAgent;
|
|
3304
|
-
agent = runningAgent;
|
|
3305
|
-
identityHash = runningAgent.identityHash;
|
|
3306
|
-
if (upgradeId !== void 0) runningAgent.holdUpgradeStartup();
|
|
3307
|
-
const setGroupChatEnabled = adapter.setGroupChatEnabled?.bind(adapter);
|
|
3308
|
-
const relayAccount = new RelayAccount({
|
|
3309
|
-
config,
|
|
3310
|
-
machineId: identity.machineId,
|
|
3311
|
-
method: settings2.relayAuthentication.mode,
|
|
3312
|
-
...relayCredential === void 0 ? {} : { user: relayCredential.user }
|
|
3313
|
-
});
|
|
3314
|
-
let pairingPage;
|
|
3315
|
-
if (config.pairingPageEnabled) {
|
|
3316
|
-
const { createLocalSessions } = await import("./local-sessions-EZUANCR4.js");
|
|
3317
|
-
const pageOptions = {
|
|
3318
|
-
machineName: identity.machineName,
|
|
3319
|
-
port: config.pairingPagePort,
|
|
3320
|
-
pairingProvider,
|
|
3321
|
-
sessions: createLocalSessions(adapter, { userId: config.userId, machineId: identity.machineId }),
|
|
3322
|
-
getRegistrationStatus: () => runningAgent.relayRegistrationStatus,
|
|
3323
|
-
reconnectRelay: () => runningAgent.reconnectRelay(),
|
|
3324
|
-
disconnectRelay: () => runningAgent.disconnectRelay(),
|
|
3325
|
-
getAccount: () => relayAccount.read(runningAgent.relayRegistrationStatus),
|
|
3326
|
-
getDeploymentInfo: async () => {
|
|
3327
|
-
const lastUpgrade = await readLastUpgrade(config.dataDirectory);
|
|
3328
|
-
return {
|
|
3329
|
-
version: appVersion,
|
|
3330
|
-
relayUrl: config.relayUrl,
|
|
3331
|
-
...resolved.envFile === void 0 ? {} : { configPath: resolved.envFile },
|
|
3332
|
-
...lastUpgrade === void 0 ? {} : { upgradedAt: lastUpgrade.upgradedAt }
|
|
3333
|
-
};
|
|
3334
|
-
},
|
|
3335
|
-
...supportsAgentSelection(adapter) ? {
|
|
3336
|
-
agentSelection: {
|
|
3337
|
-
listAgents: () => adapter.listAgents(),
|
|
3338
|
-
saveSelection: (selection) => runningAgent.runLocalMutation(() => adapter.saveSelection(selection))
|
|
3339
|
-
}
|
|
3340
|
-
} : {},
|
|
3341
|
-
...setGroupChatEnabled === void 0 ? {} : {
|
|
3342
|
-
groupChatSettings: {
|
|
3343
|
-
get enabled() {
|
|
3344
|
-
return groupChatSettings.enabled;
|
|
3345
|
-
},
|
|
3346
|
-
save: (enabled) => runningAgent.runLocalMutation(() => groupChatSettings.save(enabled, setGroupChatEnabled))
|
|
3347
|
-
}
|
|
3348
|
-
},
|
|
3349
|
-
...adapter.setPeerChatEnabled === void 0 ? {} : {
|
|
3350
|
-
peerChatSettings: {
|
|
3351
|
-
get enabled() {
|
|
3352
|
-
return peerChatSettings.enabled;
|
|
3353
|
-
},
|
|
3354
|
-
save: (enabled) => runningAgent.runLocalMutation(() => peerChatSettings.save(enabled, (value) => runningAgent.setPeerChatEnabled(value)))
|
|
3355
|
-
}
|
|
3356
|
-
},
|
|
3357
|
-
logger
|
|
3358
|
-
};
|
|
3359
|
-
pairingPage = retainedPairingPage === void 0 ? new PairingPageServer(pageOptions) : retainedPairingPage.useRuntime(pageOptions);
|
|
3360
|
-
}
|
|
3361
|
-
let stopping = false;
|
|
3362
|
-
async function stop(reason) {
|
|
3363
|
-
if (stopping) {
|
|
3364
|
-
return;
|
|
3365
|
-
}
|
|
3366
|
-
stopping = true;
|
|
3367
|
-
logger.info({ reason }, "pc-agent.stopping");
|
|
3368
|
-
const results = await Promise.allSettled([runningAgent.stop(), pairingPage?.stop()]);
|
|
3369
|
-
const errors = results.filter(
|
|
3370
|
-
(result) => result.status === "rejected"
|
|
3371
|
-
).map((result) => result.reason);
|
|
3372
|
-
if (errors.length > 0) {
|
|
3373
|
-
throw new AggregateError(errors, "Failed to stop PC Agent resources");
|
|
3374
|
-
}
|
|
3375
|
-
}
|
|
3376
|
-
process.once("SIGINT", () => {
|
|
3377
|
-
void stop("SIGINT").catch((error) => {
|
|
3378
|
-
logger.error({ error: toErrorDetails(error) }, "pc-agent.stop.failed");
|
|
3379
|
-
});
|
|
3380
|
-
});
|
|
3381
|
-
process.once("SIGTERM", () => {
|
|
3382
|
-
void stop("SIGTERM").catch((error) => {
|
|
3383
|
-
logger.error({ error: toErrorDetails(error) }, "pc-agent.stop.failed");
|
|
3384
|
-
});
|
|
3385
|
-
});
|
|
3386
|
-
try {
|
|
3387
|
-
await pairingPage?.start();
|
|
3388
|
-
if (pairingPage !== void 0) {
|
|
3389
|
-
logger.info({ url: pairingPage.url }, "mobile.pairing-page.listening");
|
|
3390
|
-
}
|
|
3391
|
-
await runningAgent.start();
|
|
3392
|
-
await runningAgent.waitUntilStopped();
|
|
3393
|
-
await stop("normal-completion");
|
|
3394
|
-
} catch (error) {
|
|
3395
|
-
logger.fatal({ error: toErrorDetails(error) }, "pc-agent.failed");
|
|
3396
|
-
process.exitCode = 1;
|
|
3397
|
-
await stop("startup-failure").catch((stopError) => {
|
|
3398
|
-
logger.error(
|
|
3399
|
-
{ error: toErrorDetails(stopError) },
|
|
3400
|
-
"pc-agent.stop.failed"
|
|
3401
|
-
);
|
|
3402
|
-
});
|
|
3403
|
-
}
|
|
3404
|
-
} finally {
|
|
3405
|
-
try {
|
|
3406
|
-
try {
|
|
3407
|
-
await agent?.stop();
|
|
3408
|
-
} finally {
|
|
3409
|
-
await retainedPairingPage?.stop();
|
|
3410
|
-
}
|
|
3411
|
-
} finally {
|
|
3412
|
-
await control.close();
|
|
3413
|
-
if (diagnostics !== void 0) {
|
|
3414
|
-
try {
|
|
3415
|
-
await diagnostics.close();
|
|
3416
|
-
} catch (error) {
|
|
3417
|
-
process.stderr.write(
|
|
3418
|
-
`Unable to close PC diagnostic log: ${toErrorDetails(error).message}
|
|
3419
|
-
`
|
|
3420
|
-
);
|
|
3421
|
-
}
|
|
3422
|
-
}
|
|
3423
|
-
}
|
|
3424
|
-
}
|
|
3425
|
-
}
|
|
3426
|
-
export {
|
|
3427
|
-
startClient
|
|
3428
|
-
};
|