@agentknight/client 0.9.48 → 0.9.49

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.
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/upgrade-state.ts
4
+ import { randomUUID } from "node:crypto";
5
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import { z } from "zod";
8
+ var UpgradeStateSchema = z.object({
9
+ id: z.uuid(),
10
+ phase: z.enum(["preparing", "ready", "waiting-idle", "switching", "verifying", "succeeded", "rolled-back", "failed"]),
11
+ fromVersion: z.string(),
12
+ toVersion: z.string(),
13
+ updatedAt: z.iso.datetime(),
14
+ error: z.string().optional()
15
+ });
16
+ var UpgradeSuccessSchema = z.object({ version: z.string(), upgradedAt: z.iso.datetime() });
17
+ async function readOptionalJson(path) {
18
+ try {
19
+ return JSON.parse(await readFile(path, "utf8"));
20
+ } catch (error) {
21
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
22
+ throw error;
23
+ }
24
+ }
25
+ async function writePrivateJson(path, value) {
26
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
27
+ const temporary = `${path}.${randomUUID()}.tmp`;
28
+ try {
29
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}
30
+ `, { mode: 384 });
31
+ await rename(temporary, path);
32
+ } finally {
33
+ await rm(temporary, { force: true });
34
+ }
35
+ }
36
+ async function readUpgradeState(directory) {
37
+ const value = await readOptionalJson(join(directory, "upgrades", "status.json"));
38
+ return value === void 0 ? void 0 : UpgradeStateSchema.parse(value);
39
+ }
40
+ async function readLastUpgrade(directory) {
41
+ const value = await readOptionalJson(join(directory, "upgrades", "last-success.json"));
42
+ return value === void 0 ? void 0 : UpgradeSuccessSchema.parse(value);
43
+ }
44
+
45
+ export {
46
+ UpgradeStateSchema,
47
+ UpgradeSuccessSchema,
48
+ readOptionalJson,
49
+ writePrivateJson,
50
+ readUpgradeState,
51
+ readLastUpgrade
52
+ };
@@ -0,0 +1,318 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ readOptionalJson,
4
+ writePrivateJson
5
+ } from "./chunk-SPZWIFFP.js";
6
+
7
+ // src/runtime.ts
8
+ import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
9
+ import { mkdtemp, rm } from "node:fs/promises";
10
+ import { createConnection, createServer } from "node:net";
11
+ import { tmpdir } from "node:os";
12
+ import { join, resolve } from "node:path";
13
+ import { z } from "zod";
14
+ import { DataDirectoryLease } from "@agentknight/sdk/runtime";
15
+ import {
16
+ PEER_CHAT_TIMEOUT_MS,
17
+ PeerChatRequestSchema,
18
+ PeerChatResultSchema
19
+ } from "@agentknight/sdk/runtime";
20
+ var RuntimeDescriptorSchema = z.object({
21
+ pid: z.number().int().positive(),
22
+ instanceId: z.uuid(),
23
+ endpoint: z.string().min(1),
24
+ token: z.string().min(32),
25
+ upgradeId: z.uuid().optional()
26
+ });
27
+ var RuntimeStatusSchema = z.object({
28
+ version: z.string().min(1),
29
+ pid: z.number().int().positive(),
30
+ instanceId: z.uuid(),
31
+ ready: z.boolean(),
32
+ busy: z.boolean(),
33
+ relayUrl: z.string().url(),
34
+ identityHash: z.string().min(1),
35
+ configPath: z.string().optional(),
36
+ configHash: z.string().optional(),
37
+ executable: z.string().min(1),
38
+ cliPath: z.string().min(1),
39
+ cwd: z.string().min(1),
40
+ args: z.array(z.string()),
41
+ canRestart: z.boolean().default(false),
42
+ restartEnvironment: z.record(z.string(), z.string()).default({}),
43
+ upgradeId: z.uuid().optional(),
44
+ stopping: z.boolean().optional()
45
+ });
46
+ var RequestSchema = z.discriminatedUnion("command", [
47
+ z.object({ token: z.string(), command: z.enum(["status", "prepare", "cancel", "stop"]) }),
48
+ z.object({ token: z.string(), command: z.literal("peer-chat"), payload: PeerChatRequestSchema })
49
+ ]);
50
+ var ResponseSchema = z.discriminatedUnion("ok", [
51
+ z.object({ ok: z.literal(true), status: RuntimeStatusSchema.optional(), reply: PeerChatResultSchema.optional() }),
52
+ z.object({ ok: z.literal(false), error: z.string() })
53
+ ]);
54
+ var MAX_MESSAGE_BYTES = 32 * 1024;
55
+ var MAX_PEER_REQUEST_BYTES = 128 * 1024;
56
+ var MAX_PEER_RESPONSE_BYTES = 2 * 1024 * 1024;
57
+ var PEER_RESPONSE_BUFFER_MS = 5e3;
58
+ var MAX_SOCKET_PATH_BYTES = 103;
59
+ var RuntimeCommandError = class extends Error {
60
+ };
61
+ function processExists(pid) {
62
+ try {
63
+ process.kill(pid, 0);
64
+ return true;
65
+ } catch (error) {
66
+ if (error instanceof Error && "code" in error && error.code === "ESRCH") return false;
67
+ throw error;
68
+ }
69
+ }
70
+ async function readRuntimeDescriptor(directory) {
71
+ const value = await readOptionalJson(join(directory, "run", "runtime.json"));
72
+ return value === void 0 ? void 0 : RuntimeDescriptorSchema.parse(value);
73
+ }
74
+ function equalToken(actual, expected) {
75
+ const left = Buffer.from(actual);
76
+ const right = Buffer.from(expected);
77
+ return left.length === right.length && timingSafeEqual(left, right);
78
+ }
79
+ async function requestRuntime(descriptor, command, timeoutMs = 15e3) {
80
+ return exchangeRuntime(descriptor, { token: descriptor.token, command }, (response) => {
81
+ if (command === "status" && (response.status === void 0 || response.status.instanceId !== descriptor.instanceId || response.status.pid !== descriptor.pid)) {
82
+ throw new Error("Agent instance changed; retry the command.");
83
+ }
84
+ return response.status;
85
+ }, timeoutMs, MAX_MESSAGE_BYTES);
86
+ }
87
+ async function requestPeerChat(descriptor, request, signal) {
88
+ const payload = PeerChatRequestSchema.safeParse(request);
89
+ if (!payload.success) throw new Error("Invalid peer-chat request.");
90
+ return exchangeRuntime(descriptor, { token: descriptor.token, command: "peer-chat", payload: payload.data }, (response) => {
91
+ if (response.reply === void 0) throw new Error("Agent returned no peer-chat reply.");
92
+ return response.reply;
93
+ }, PEER_CHAT_TIMEOUT_MS + PEER_RESPONSE_BUFFER_MS, MAX_PEER_RESPONSE_BYTES, signal);
94
+ }
95
+ function exchangeRuntime(descriptor, request, select, timeoutMs, maxResponseBytes, signal) {
96
+ signal?.throwIfAborted();
97
+ return new Promise((fulfill, reject) => {
98
+ const socket = createConnection(descriptor.endpoint);
99
+ let data = "";
100
+ let completed = false;
101
+ const cleanup = () => {
102
+ clearTimeout(timeout);
103
+ signal?.removeEventListener("abort", abort);
104
+ };
105
+ const fail = (error) => {
106
+ if (completed) return;
107
+ completed = true;
108
+ cleanup();
109
+ socket.destroy();
110
+ reject(error);
111
+ };
112
+ const abort = () => fail(signal?.reason instanceof Error ? signal.reason : new Error("Peer chat cancelled."));
113
+ const onTimeout = () => fail(new Error(`Agent ${request.command} request timed out.`));
114
+ const timeout = request.command === "peer-chat" ? setTimeout(onTimeout, timeoutMs) : void 0;
115
+ if (request.command !== "peer-chat") socket.setTimeout(timeoutMs, onTimeout);
116
+ signal?.addEventListener("abort", abort, { once: true });
117
+ socket.on("error", fail);
118
+ socket.on("connect", () => socket.write(`${JSON.stringify(request)}
119
+ `));
120
+ socket.setEncoding("utf8");
121
+ socket.on("data", (chunk) => {
122
+ if (completed) return;
123
+ data += chunk;
124
+ if (Buffer.byteLength(data) > maxResponseBytes) {
125
+ fail(new Error("Agent control response exceeds its size limit."));
126
+ return;
127
+ }
128
+ if (!data.includes("\n")) return;
129
+ try {
130
+ const response = ResponseSchema.parse(JSON.parse(data.slice(0, data.indexOf("\n"))));
131
+ if (!response.ok) throw new RuntimeCommandError(response.error);
132
+ const result = select(response);
133
+ completed = true;
134
+ cleanup();
135
+ socket.end();
136
+ fulfill(result);
137
+ } catch (error) {
138
+ fail(error instanceof Error ? error : new Error(String(error)));
139
+ }
140
+ });
141
+ socket.on("end", () => {
142
+ if (!completed) fail(new Error("Agent closed its control connection without a response."));
143
+ });
144
+ socket.on("close", () => {
145
+ if (!completed) fail(new Error("Agent closed its control connection without a response."));
146
+ });
147
+ });
148
+ }
149
+ async function runPeerChat(handler, request, controller) {
150
+ const { signal } = controller;
151
+ signal.throwIfAborted();
152
+ let abort = () => {
153
+ };
154
+ const cancelled = new Promise((_fulfill, reject) => {
155
+ abort = () => reject(signal.reason);
156
+ signal.addEventListener("abort", abort, { once: true });
157
+ });
158
+ const timeout = setTimeout(() => controller.abort(new Error("Peer chat timed out.")), PEER_CHAT_TIMEOUT_MS);
159
+ try {
160
+ return await Promise.race([Promise.resolve().then(() => {
161
+ signal.throwIfAborted();
162
+ return handler(request, signal);
163
+ }), cancelled]);
164
+ } finally {
165
+ clearTimeout(timeout);
166
+ signal.removeEventListener("abort", abort);
167
+ }
168
+ }
169
+ async function startRuntimeControl(options) {
170
+ const directoryLease = await DataDirectoryLease.acquire(resolve(options.directory));
171
+ const directory = join(options.directory, "run");
172
+ const descriptorPath = join(directory, "runtime.json");
173
+ const instanceId = directoryLease.instanceId;
174
+ const hash = createHash("sha256").update(resolve(options.directory)).digest("hex").slice(0, 24);
175
+ const endpoint = process.platform === "win32" ? `\\\\.\\pipe\\agentknight-${hash}-${instanceId}` : join(directory, `${instanceId}.sock`);
176
+ const descriptor = {
177
+ pid: process.pid,
178
+ instanceId,
179
+ endpoint,
180
+ token: randomBytes(32).toString("hex"),
181
+ ...options.upgradeId === void 0 ? {} : { upgradeId: options.upgradeId }
182
+ };
183
+ const connections = /* @__PURE__ */ new Set();
184
+ const peerConnections = /* @__PURE__ */ new Map();
185
+ let socketDirectory;
186
+ const server = createServer((socket) => {
187
+ connections.add(socket);
188
+ const disconnect = () => {
189
+ peerConnections.get(socket)?.abort(new Error("Peer chat control connection closed."));
190
+ };
191
+ socket.on("end", disconnect);
192
+ socket.on("close", () => {
193
+ disconnect();
194
+ connections.delete(socket);
195
+ });
196
+ socket.on("error", (error) => {
197
+ disconnect();
198
+ options.onError(error);
199
+ });
200
+ socket.setTimeout(15e3, () => socket.destroy());
201
+ socket.setEncoding("utf8");
202
+ let data = "";
203
+ let handled = false;
204
+ socket.on("data", (chunk) => {
205
+ if (handled) return;
206
+ data += chunk;
207
+ if (Buffer.byteLength(data) > MAX_PEER_REQUEST_BYTES) {
208
+ handled = true;
209
+ socket.end(`${JSON.stringify({ ok: false, error: "Control request exceeds its size limit." })}
210
+ `);
211
+ return;
212
+ }
213
+ if (!data.includes("\n")) return;
214
+ handled = true;
215
+ void (async () => {
216
+ const parsed = RequestSchema.safeParse(JSON.parse(data.slice(0, data.indexOf("\n"))));
217
+ if (!parsed.success) throw new Error("Invalid local Agent control request.");
218
+ const request = parsed.data;
219
+ if (!equalToken(request.token, descriptor.token)) throw new Error("Invalid local Agent credential.");
220
+ if (request.command !== "peer-chat" && Buffer.byteLength(data) > MAX_MESSAGE_BYTES) {
221
+ throw new Error("Control request exceeds its size limit.");
222
+ }
223
+ if (request.command === "stop") socket.setTimeout(65e3);
224
+ let status;
225
+ let reply;
226
+ switch (request.command) {
227
+ case "status":
228
+ status = { ...await options.getStatus(), pid: process.pid, instanceId };
229
+ break;
230
+ case "prepare":
231
+ await options.prepare();
232
+ break;
233
+ case "cancel":
234
+ options.cancel();
235
+ break;
236
+ case "stop":
237
+ await options.stop();
238
+ break;
239
+ case "peer-chat": {
240
+ if (options.runPeerChat === void 0) throw new Error("Peer chat is not available on this Agent.");
241
+ const controller = new AbortController();
242
+ peerConnections.set(socket, controller);
243
+ socket.setTimeout(PEER_CHAT_TIMEOUT_MS + PEER_RESPONSE_BUFFER_MS);
244
+ try {
245
+ reply = PeerChatResultSchema.parse(await runPeerChat(options.runPeerChat, request.payload, controller));
246
+ } finally {
247
+ peerConnections.delete(socket);
248
+ }
249
+ break;
250
+ }
251
+ }
252
+ const response = `${JSON.stringify({
253
+ ok: true,
254
+ ...status === void 0 ? {} : { status },
255
+ ...reply === void 0 ? {} : { reply }
256
+ })}
257
+ `;
258
+ if (reply !== void 0 && Buffer.byteLength(response) > MAX_PEER_RESPONSE_BYTES) {
259
+ throw new Error("Peer chat response exceeds its size limit.");
260
+ }
261
+ if (!socket.destroyed && !socket.writableEnded) socket.end(response);
262
+ })().catch((error) => {
263
+ options.onError(error);
264
+ if (!socket.destroyed && !socket.writableEnded) {
265
+ socket.end(`${JSON.stringify({ ok: false, error: error instanceof Error ? error.message : "Agent control failed." })}
266
+ `);
267
+ }
268
+ });
269
+ });
270
+ });
271
+ try {
272
+ if (process.platform !== "win32" && Buffer.byteLength(descriptor.endpoint) > MAX_SOCKET_PATH_BYTES) {
273
+ const prefix = join(tmpdir(), "ak-");
274
+ socketDirectory = await mkdtemp(Buffer.byteLength(`${prefix}XXXXXX/control.sock`) <= MAX_SOCKET_PATH_BYTES ? prefix : "/tmp/ak-");
275
+ descriptor.endpoint = join(socketDirectory, "control.sock");
276
+ }
277
+ await new Promise((fulfill, reject) => {
278
+ server.once("error", reject);
279
+ server.listen(descriptor.endpoint, () => {
280
+ server.off("error", reject);
281
+ fulfill();
282
+ });
283
+ });
284
+ await writePrivateJson(descriptorPath, descriptor);
285
+ } catch (error) {
286
+ server.close();
287
+ await rm(descriptorPath, { force: true });
288
+ await directoryLease.release();
289
+ if (socketDirectory !== void 0) await rm(socketDirectory, { recursive: true, force: true });
290
+ throw error;
291
+ }
292
+ server.on("error", options.onError);
293
+ return {
294
+ directoryLease,
295
+ async close() {
296
+ for (const [socket, controller] of peerConnections) {
297
+ controller.abort(new Error("Agent control is stopping."));
298
+ socket.destroy();
299
+ }
300
+ await new Promise((fulfill, reject) => server.close((error) => error ? reject(error) : fulfill()));
301
+ for (const socket of connections) socket.destroy();
302
+ await rm(descriptorPath, { force: true });
303
+ await directoryLease.release();
304
+ if (process.platform !== "win32") await rm(descriptor.endpoint, { force: true });
305
+ if (socketDirectory !== void 0) await rm(socketDirectory, { recursive: true, force: true });
306
+ }
307
+ };
308
+ }
309
+
310
+ export {
311
+ RuntimeStatusSchema,
312
+ RuntimeCommandError,
313
+ processExists,
314
+ readRuntimeDescriptor,
315
+ requestRuntime,
316
+ requestPeerChat,
317
+ startRuntimeControl
318
+ };
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/client-environment.ts
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ var directoryAliases = [
8
+ ["COPILOT_REMOTE_HOME", "AGENTKNIGHT_HOME"],
9
+ ["AGENTKNIGHT_PI_DIRECTORY", "PI_CODING_AGENT_DIR"]
10
+ ];
11
+ var defaultPairingPagePort = 17888;
12
+ function defaultClientHome(userHome = homedir()) {
13
+ return join(userHome, ".ak");
14
+ }
15
+ function sameClientPath(left, right, cwd = process.cwd()) {
16
+ const leftPath = resolve(cwd, left);
17
+ const rightPath = resolve(cwd, right);
18
+ return process.platform === "win32" ? leftPath.toLowerCase() === rightPath.toLowerCase() : leftPath === rightPath;
19
+ }
20
+ function hasDeprecatedClientEnvironment(environment) {
21
+ return directoryAliases.some(([legacy]) => environment[legacy] !== void 0);
22
+ }
23
+ function isClientConfigurationKey(key) {
24
+ return directoryAliases.some(([legacy]) => key === legacy) || /^(?:RELAY_|USER_ID$|AGENTKNIGHT_|PAIRING_|SESSION_REFRESH_|SESSION_IMAGES_|HEARTBEAT_|LOG_LEVEL$|SHOW_PAIRING_|PC_AGENT_|SNAPSHOT_|TIMELINE_|SECURE_MESSAGE_)/u.test(key);
25
+ }
26
+ function clearClientConfiguration(environment) {
27
+ for (const key of Object.keys(environment)) {
28
+ if (isClientConfigurationKey(key)) delete environment[key];
29
+ }
30
+ }
31
+ function normalizePiDirectory(value) {
32
+ let path = value.trim();
33
+ if (process.platform === "win32" && !path.includes("\\")) {
34
+ const drive = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i.exec(path);
35
+ if (drive?.[1] !== void 0) path = `${drive[1].toUpperCase()}:\\${drive[2]?.replaceAll("/", "\\") ?? ""}`;
36
+ }
37
+ if (path === "~") return homedir();
38
+ if (path.startsWith("~/") || process.platform === "win32" && path.startsWith("~\\")) {
39
+ return join(homedir(), path.slice(2));
40
+ }
41
+ return path.startsWith("file://") ? fileURLToPath(path) : path;
42
+ }
43
+ function normalizeClientEnvironment(source, cwd = process.cwd(), onDeprecated) {
44
+ const environment = { ...source };
45
+ for (const [legacy, canonical] of directoryAliases) {
46
+ if (canonical === "PI_CODING_AGENT_DIR") {
47
+ for (const key of [canonical, legacy]) {
48
+ const value = environment[key];
49
+ if (value !== void 0) environment[key] = normalizePiDirectory(value);
50
+ }
51
+ }
52
+ const oldValue = environment[legacy]?.trim();
53
+ const newValue = environment[canonical]?.trim();
54
+ if (oldValue !== void 0) {
55
+ if (newValue !== void 0 && oldValue !== newValue && (oldValue === "" || newValue === "" || !sameClientPath(oldValue, newValue, cwd))) {
56
+ throw new Error(`Conflicting ${legacy} and ${canonical}; keep only ${canonical}.`);
57
+ }
58
+ if (newValue === void 0) environment[canonical] = oldValue;
59
+ onDeprecated?.(`${legacy} is deprecated; use ${canonical}.`);
60
+ }
61
+ delete environment[legacy];
62
+ }
63
+ return environment;
64
+ }
65
+
66
+ export {
67
+ defaultPairingPagePort,
68
+ defaultClientHome,
69
+ sameClientPath,
70
+ hasDeprecatedClientEnvironment,
71
+ isClientConfigurationKey,
72
+ clearClientConfiguration,
73
+ normalizeClientEnvironment
74
+ };