The best way to control Claude Code, Codex and more from any computer or phone

main
ts 382 lines 14.5 KB
Raw
1 import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2
3 // Protocol 4 launchers coordinate selection writes and reconcile the unit. A remote update
4 // replaces only the child, so an installed protocol-3 launcher stays until a local update or
5 // service install restarts the service.
6 export const SERVICE_LAUNCHER_PROTOCOL = 4 as const;
7 /** Launchers this runtime runs under. Protocol 3 has the same IPC and durable format, and
8 refusing it stops every remote update until someone opens a shell on the host. */
9 export type SupportedLauncherProtocol = 3 | typeof SERVICE_LAUNCHER_PROTOCOL;
10 export const isSupportedLauncherProtocol = (
11 protocol: unknown,
12 ): protocol is SupportedLauncherProtocol =>
13 protocol === 3 || protocol === SERVICE_LAUNCHER_PROTOCOL;
14 export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
15 export const SERVICE_ENV_FILE = "service.env";
16 export const SERVICE_STATE_FILE = "service-state.json";
17 /** Set by the unit or launch agent to its own file name, so the launcher can
18 find the definition that started it. */
19 export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
20 /** Written before explicit stop to distinguish shutdown from update handoff. */
21 export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
22 /** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
23 export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
24 /** Held by a Windows launcher while it runs: Task Scheduler tracks only the task's console host. */
25 export const SERVICE_LAUNCHER_LOCK_FILE = "service-launcher.lock";
26 /** Held by a launcher while it has, or is about to start, a server: an SSH launch waits for that
27 server instead of starting its own. Released while the launcher idles. */
28 export const SERVICE_SERVING_LOCK_FILE = "service-serving.lock";
29
30 const unquoteSystemdValue = (raw: string) =>
31 (raw.startsWith('"') && raw.endsWith('"')
32 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
33 : raw
34 ).replaceAll("%%", "%");
35
36 const unescapeXmlText = (value: string) =>
37 value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
38
39 const unquoteWindowsArgument = (raw: string) =>
40 unescapeXmlText(raw).replace(/(\\+)$/, (slashes) => slashes.slice(slashes.length / 2));
41
42 /** Whether Task Scheduler's copy of a task is disabled as a whole, not one of its triggers. */
43 export const serviceTaskIsDisabled = (taskXml: string): boolean =>
44 /<Settings>[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("<Enabled>false</Enabled>") === true;
45
46 /** schtasks reads undeclared XML in the ANSI code page, but UTF-16LE with a BOM as written. */
47 export const encodeServiceTask = (taskXml: string): Uint8Array =>
48 Buffer.from(`\uFEFF${taskXml}`, "utf16le");
49
50 /** A unit file's text: UTF-16LE task files have a BOM, other units (and older tasks) are UTF-8. */
51 export const decodeServiceUnit = (bytes: Uint8Array): string =>
52 bytes[0] === 0xff && bytes[1] === 0xfe
53 ? Buffer.from(bytes.buffer, bytes.byteOffset + 2, bytes.byteLength - 2).toString("utf16le")
54 : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf8");
55
56 /** A task as Task Scheduler should hold it while its service must stay stopped. */
57 export const disabledServiceTask = (taskXml: string): string =>
58 serviceTaskIsDisabled(taskXml)
59 ? taskXml
60 : taskXml.replace(" </Settings>", " <Enabled>false</Enabled>\n </Settings>");
61
62 export function serviceUnitEnvironmentValueOf(
63 contents: string,
64 name: "T3CODE_HOME" | "T3CODE_INSTALL_BIN_DIR",
65 ): string | undefined {
66 const systemd = new RegExp(`^Environment=${name}=(.*)$`, "m").exec(contents)?.[1];
67 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
68 const plist = new RegExp(`<key>${name}</key>\\s*<string>([^<]*)</string>`).exec(contents)?.[1];
69 return plist === undefined ? undefined : unescapeXmlText(plist);
70 }
71
72 export function serviceUnitBaseDirOf(contents: string): string | undefined {
73 const unix = serviceUnitEnvironmentValueOf(contents, "T3CODE_HOME");
74 if (unix !== undefined) return unix;
75 const task = /<Arguments>[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1];
76 return task === undefined ? undefined : unquoteWindowsArgument(task);
77 }
78
79 /**
80 * The user unit directory a systemd manager reads, from its UnitPath property. The persistent
81 * control directory identifies the manager's config root despite UnitPath overrides.
82 */
83 export function systemdUnitDirectoryOf(unitPath: ReadonlyArray<string>): string | undefined {
84 const controlDirectory = unitPath.find(
85 (directory) =>
86 directory.startsWith("/") &&
87 directory.endsWith("/systemd/user.control") &&
88 unitPath.includes(directory.slice(0, -".control".length)),
89 );
90 return controlDirectory?.slice(0, -".control".length);
91 }
92
93 /** The file systemd or launchd appends the service's output to. */
94 export function serviceUnitLogPathOf(contents: string): string | undefined {
95 const systemd = /^StandardOutput=append:(.*)$/m.exec(contents)?.[1];
96 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
97 const plist = /<key>StandardOutPath<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
98 return plist === undefined ? undefined : unescapeXmlText(plist);
99 }
100
101 /** The executable an installed unit, plist, or task starts: the launcher's runtime. */
102 export function serviceUnitProgramOf(contents: string): string | undefined {
103 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
104 if (systemd !== undefined) return unquoteSystemdValue(systemd);
105 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
106 contents,
107 )?.[1];
108 if (plist !== undefined) return unescapeXmlText(plist);
109 const task = /<Arguments>--headless "([^"]*)"/.exec(contents)?.[1];
110 return task === undefined ? undefined : unquoteWindowsArgument(task);
111 }
112
113 export interface PendingServiceUpdate {
114 readonly id: string;
115 readonly fromVersion: string;
116 readonly targetVersion: string;
117 readonly dbPath: string;
118 readonly status: "pending";
119 }
120
121 export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
122
123 export interface ServiceState {
124 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
125 readonly activeVersion: string;
126 readonly update?: ServiceUpdateRecord;
127 }
128
129 export interface ServiceLauncherContext {
130 readonly protocol: SupportedLauncherProtocol;
131 readonly childVersion: string;
132 readonly update?: ServiceUpdateRecord;
133 }
134
135 export type ServiceLauncherChildMessage =
136 | {
137 readonly type: "request-update";
138 readonly targetVersion: string;
139 readonly dbPath: string;
140 }
141 | {
142 readonly type: "prepared";
143 readonly updateId: string;
144 };
145
146 export type ServiceLauncherParentMessage =
147 | {
148 readonly type: "update-accepted";
149 readonly updateId: string;
150 }
151 | {
152 readonly type: "update-rejected";
153 readonly reason: string;
154 }
155 | {
156 readonly type: "committed";
157 readonly updateId: string;
158 }
159 | {
160 /** Shut down as on SIGTERM, which Windows cannot deliver. */
161 readonly type: "stop";
162 };
163
164 const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
165 const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
166 const EXACT_SERVICE_VERSION = new RegExp(
167 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
168 );
169
170 export const isExactServiceVersion = (version: string): boolean =>
171 EXACT_SERVICE_VERSION.test(version);
172
173 const isRecord = (value: unknown): value is Record<string, unknown> =>
174 typeof value === "object" && value !== null && !Array.isArray(value);
175
176 function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
177 if (!isRecord(value)) return undefined;
178 const { id, fromVersion, targetVersion, status } = value;
179 if (
180 typeof id !== "string" ||
181 id.trim() === "" ||
182 typeof fromVersion !== "string" ||
183 !isExactServiceVersion(fromVersion) ||
184 typeof targetVersion !== "string" ||
185 !isExactServiceVersion(targetVersion)
186 ) {
187 return undefined;
188 }
189 if (status === "pending") {
190 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
191 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
192 : undefined;
193 }
194 if (
195 (status === "committed" || status === "rolled-back" || status === "failed") &&
196 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
197 ) {
198 return {
199 id,
200 fromVersion,
201 targetVersion,
202 status,
203 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
204 };
205 }
206 return undefined;
207 }
208
209 export function compareExactServiceVersions(left: string, right: string): number {
210 const parse = (version: string) => {
211 const withoutBuild = version.split("+", 1)[0] ?? version;
212 const separator = withoutBuild.indexOf("-");
213 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
214 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
215 const [major = "0", minor = "0", patch = "0"] = core.split(".");
216 return {
217 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
218 prerelease: prerelease?.split(".") ?? [],
219 };
220 };
221 const a = parse(left);
222 const b = parse(right);
223 for (let index = 0; index < 3; index += 1) {
224 const x = a.core[index] ?? 0n;
225 const y = b.core[index] ?? 0n;
226 if (x !== y) return x < y ? -1 : 1;
227 }
228 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
229 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
230 }
231 const count = Math.max(a.prerelease.length, b.prerelease.length);
232 for (let index = 0; index < count; index += 1) {
233 const x = a.prerelease[index];
234 const y = b.prerelease[index];
235 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
236 if (x === y) continue;
237 const xNumeric = /^\d+$/.test(x);
238 const yNumeric = /^\d+$/.test(y);
239 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
240 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
241 return x < y ? -1 : 1;
242 }
243 return 0;
244 }
245
246 export function decodeServiceState(value: unknown): ServiceState | undefined {
247 if (!isRecord(value)) return undefined;
248 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
249 if (
250 // A protocol-3 installer can select a protocol-4 runtime.
251 !isSupportedLauncherProtocol(value.protocol) ||
252 typeof value.activeVersion !== "string" ||
253 !isExactServiceVersion(value.activeVersion) ||
254 (value.update !== undefined && update === undefined) ||
255 (update !== undefined &&
256 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
257 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
258 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
259 ((update?.status === "rolled-back" || update?.status === "failed") &&
260 update.fromVersion !== value.activeVersion)
261 ) {
262 return undefined;
263 }
264 return {
265 protocol: SERVICE_LAUNCHER_PROTOCOL,
266 activeVersion: value.activeVersion,
267 ...(update === undefined ? {} : { update }),
268 };
269 }
270
271 export function parseServiceState(value: string): ServiceState | undefined {
272 try {
273 return decodeServiceState(JSON.parse(value) as unknown);
274 } catch {
275 return undefined;
276 }
277 }
278
279 export function parseLegacyServiceState(value: string) {
280 try {
281 const parsed: unknown = JSON.parse(value);
282 if (
283 !isRecord(parsed) ||
284 Object.keys(parsed).length !== 2 ||
285 parsed.protocol !== 2 ||
286 typeof parsed.activeVersion !== "string" ||
287 !isExactServiceVersion(parsed.activeVersion)
288 ) {
289 return undefined;
290 }
291 return { protocol: 2, activeVersion: parsed.activeVersion } as const;
292 } catch {
293 return undefined;
294 }
295 }
296
297 export function serviceStateHasPendingUpdate(value: string): boolean {
298 try {
299 const parsed: unknown = JSON.parse(value);
300 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
301 } catch {
302 return false;
303 }
304 }
305
306 export function serviceStateActiveVersion(value: string): string | undefined {
307 try {
308 const parsed: unknown = JSON.parse(value);
309 return isRecord(parsed) &&
310 typeof parsed.activeVersion === "string" &&
311 isExactServiceVersion(parsed.activeVersion)
312 ? parsed.activeVersion
313 : undefined;
314 } catch {
315 return undefined;
316 }
317 }
318
319 export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
320 let parsed: unknown;
321 try {
322 parsed = JSON.parse(value) as unknown;
323 } catch {
324 return undefined;
325 }
326 if (
327 !isRecord(parsed) ||
328 !isSupportedLauncherProtocol(parsed.protocol) ||
329 typeof parsed.childVersion !== "string" ||
330 !isExactServiceVersion(parsed.childVersion)
331 ) {
332 return undefined;
333 }
334 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
335 if (parsed.update !== undefined && update === undefined) return undefined;
336 const selectedVersion =
337 update?.status === "pending" || update?.status === "committed"
338 ? update.targetVersion
339 : update === undefined
340 ? parsed.childVersion
341 : update.fromVersion;
342 if (parsed.childVersion !== selectedVersion) {
343 return undefined;
344 }
345 return {
346 protocol: parsed.protocol,
347 childVersion: parsed.childVersion,
348 ...(update === undefined ? {} : { update }),
349 };
350 }
351
352 export function decodeServiceLauncherChildMessage(
353 value: unknown,
354 ): ServiceLauncherChildMessage | undefined {
355 if (!isRecord(value)) return undefined;
356 if (
357 value.type === "request-update" &&
358 typeof value.targetVersion === "string" &&
359 typeof value.dbPath === "string"
360 ) {
361 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
362 }
363 return value.type === "prepared" && typeof value.updateId === "string"
364 ? { type: value.type, updateId: value.updateId }
365 : undefined;
366 }
367
368 export function decodeServiceLauncherParentMessage(
369 value: unknown,
370 ): ServiceLauncherParentMessage | undefined {
371 if (!isRecord(value)) return undefined;
372 if (value.type === "update-rejected" && typeof value.reason === "string") {
373 return { type: value.type, reason: value.reason };
374 }
375 if (value.type === "update-accepted" && typeof value.updateId === "string") {
376 return { type: value.type, updateId: value.updateId };
377 }
378 if (value.type === "stop") return { type: value.type };
379 return value.type === "committed" && typeof value.updateId === "string"
380 ? { type: value.type, updateId: value.updateId }
381 : undefined;
382 }