@hallohuman/hightea 0.1.15 → 0.1.30

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,1491 @@
1
+ import {
2
+ isJoinRouteRefusalCode,
3
+ isHostAgentApp,
4
+ normalizeJoinCode,
5
+ HOST_HEADER,
6
+ LEGACY_HOST_HEADER,
7
+ installLineOf2,
8
+ describedApp2,
9
+ appInstalled2
10
+ } from "./chunk-dvnzt54t.js";
11
+
12
+ // ../ahp-host/src/commands.ts
13
+ import { readdir, readFile as readFile3, realpath as realpath2, rm as rm4 } from "node:fs/promises";
14
+ import { createRequire as createRequire2 } from "node:module";
15
+ import { homedir, hostname } from "node:os";
16
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute3, join as join7, resolve as resolve2 } from "node:path";
17
+ import { fromEnvRef as fromEnvRef2, isRecord as isRecord3, readJsonObject as readJsonObject3, readSecret, secretRef as secretRef2, writeJsonAtomic as writeJsonAtomic2 } from "@ahpd/sdk";
18
+ import { fileVault as fileVault2 } from "@ahpd/server/dist/vault.js";
19
+
20
+ // ../ahp-host/src/claim.ts
21
+ import { createHash, randomBytes } from "node:crypto";
22
+ import { constants } from "node:fs";
23
+ import { link, lstat, mkdir, mkdtemp, open, realpath, rm } from "node:fs/promises";
24
+ import { dirname, join } from "node:path";
25
+ import { isDeepStrictEqual } from "node:util";
26
+ import { fileVault } from "@ahpd/server/dist/vault.js";
27
+ function refusal(code) {
28
+ throw new Error(code);
29
+ }
30
+ function errorCode(error) {
31
+ return error !== null && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
32
+ }
33
+ async function privateHostDirectory(path) {
34
+ await mkdir(path, { mode: 448 }).catch((error) => {
35
+ if (errorCode(error) !== "EEXIST")
36
+ refusal("HOST_JOIN_CUSTODY_IO");
37
+ });
38
+ const stat = await lstat(path);
39
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 63) !== 0) {
40
+ refusal("HOST_JOIN_UNSAFE_PATH");
41
+ }
42
+ }
43
+ async function flushDirectory(path) {
44
+ const directory = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
45
+ try {
46
+ await directory.sync();
47
+ } finally {
48
+ await directory.close();
49
+ }
50
+ }
51
+ async function flushHostFile(path) {
52
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
53
+ try {
54
+ await file.sync();
55
+ } finally {
56
+ await file.close();
57
+ }
58
+ for (let directory = dirname(path);; directory = dirname(directory)) {
59
+ await flushDirectory(directory);
60
+ if (directory === dirname(directory))
61
+ break;
62
+ }
63
+ }
64
+ function canonicalIntent(input) {
65
+ if (typeof input.origin !== "string" || typeof input.workspaceSlug !== "string" || typeof input.code !== "string" || typeof input.pluginVersion !== "string" || typeof input.ahpdVersion !== "string")
66
+ refusal("HOST_JOIN_INVALID_INTENT");
67
+ let origin;
68
+ try {
69
+ origin = new URL(input.origin);
70
+ } catch {
71
+ return refusal("HOST_JOIN_INVALID_INTENT");
72
+ }
73
+ const code = normalizeJoinCode(input.code);
74
+ if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/" || !code || !input.workspaceSlug || /[\s/\\?#]/u.test(input.workspaceSlug) || !input.pluginVersion || !input.ahpdVersion)
75
+ refusal("HOST_JOIN_INVALID_INTENT");
76
+ if (input.name !== undefined && (typeof input.name !== "string" || input.name.trim() === "" || input.name.length > 64 || [...input.name].some((character) => {
77
+ const code = character.codePointAt(0) ?? 0;
78
+ return code < 32 || code === 127;
79
+ })))
80
+ refusal("HOST_JOIN_INVALID_INTENT");
81
+ if (input.app !== undefined && !isHostAgentApp(input.app))
82
+ refusal("HOST_JOIN_INVALID_INTENT");
83
+ if (input.hostId !== undefined && (typeof input.hostId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(input.hostId)))
84
+ refusal("HOST_JOIN_INVALID_INTENT");
85
+ if (input.ownerConfiguration === null && input.app === undefined)
86
+ refusal("HOST_JOIN_INVALID_INTENT");
87
+ let ownerConfiguration;
88
+ try {
89
+ ownerConfiguration = input.ownerConfiguration === null ? null : JSON.parse(JSON.stringify(input.ownerConfiguration));
90
+ } catch {
91
+ return refusal("HOST_JOIN_INVALID_INTENT");
92
+ }
93
+ if (ownerConfiguration !== null && (typeof ownerConfiguration !== "object" || !isDeepStrictEqual(ownerConfiguration, input.ownerConfiguration)))
94
+ refusal("HOST_JOIN_INVALID_INTENT");
95
+ return { ...input, origin: origin.origin, code, ownerConfiguration };
96
+ }
97
+ async function selectHostClaim(configHome, input) {
98
+ const requested = canonicalIntent(input);
99
+ const root = await privateConfigHome(configHome);
100
+ const application = join(root, "hightea");
101
+ const claims = join(application, "claims");
102
+ const scope = createHash("sha256").update(JSON.stringify([requested.origin, requested.workspaceSlug, requested.code])).digest("hex");
103
+ const home = join(claims, scope);
104
+ const daemon = join(home, "ahpd");
105
+ try {
106
+ for (const directory of [application, claims, home, daemon])
107
+ await privateHostDirectory(directory);
108
+ const vaultFile = join(daemon, "vault.json");
109
+ const candidate = await mkdtemp(join(daemon, ".claim-"));
110
+ try {
111
+ const candidateVault = join(candidate, "vault.json");
112
+ const vault = fileVault({ file: candidateVault });
113
+ await vault.set("host:hightea", `Bearer ${randomBytes(32).toString("base64url")}`);
114
+ await vault.set("host:hightea-join", JSON.stringify({ schema: 1, ...requested }));
115
+ try {
116
+ await link(candidateVault, vaultFile);
117
+ } catch (error) {
118
+ if (errorCode(error) !== "EEXIST")
119
+ refusal("HOST_JOIN_CUSTODY_PUBLICATION_FAILED");
120
+ }
121
+ const { authorization, credentialHash, intent: original } = await openClaimVault(vaultFile);
122
+ if (original.origin !== requested.origin || original.workspaceSlug !== requested.workspaceSlug || original.code !== requested.code || original.app !== requested.app || original.hostId !== requested.hostId || !isDeepStrictEqual(original.ownerConfiguration, requested.ownerConfiguration))
123
+ refusal("HOST_JOIN_CLAIM_CONFLICT");
124
+ await flushHostFile(vaultFile);
125
+ return { home, vaultFile, authorization, credentialHash, intent: original };
126
+ } finally {
127
+ await rm(candidate, { recursive: true });
128
+ }
129
+ } catch (error) {
130
+ if (error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message))
131
+ throw error;
132
+ return refusal("HOST_JOIN_CUSTODY_IO");
133
+ }
134
+ }
135
+ async function extendHostClaim(configHome, home, input) {
136
+ const requested = canonicalIntent(input);
137
+ if (requested.hostId === undefined)
138
+ refusal("HOST_JOIN_INVALID_INTENT");
139
+ try {
140
+ const root = await privateConfigHome(configHome);
141
+ const application = join(root, "hightea");
142
+ const claims = join(application, "claims");
143
+ if (dirname(home) !== claims)
144
+ refusal("HOST_JOIN_NO_CLAIM_FOR_HOST");
145
+ const daemon = join(home, "ahpd");
146
+ for (const directory of [application, claims, home, daemon])
147
+ await privateHostDirectory(directory);
148
+ const vaultFile = join(daemon, "vault.json");
149
+ const opened = await openClaimVault(vaultFile);
150
+ if (opened.intent.origin !== requested.origin || opened.intent.workspaceSlug !== requested.workspaceSlug || opened.intent.hostId !== undefined && requested.hostId !== opened.intent.hostId)
151
+ refusal("HOST_JOIN_CLAIM_CONFLICT");
152
+ await flushHostFile(vaultFile);
153
+ return { home, vaultFile, authorization: opened.authorization, credentialHash: opened.credentialHash, intent: requested };
154
+ } catch (error) {
155
+ if (error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message))
156
+ throw error;
157
+ return refusal("HOST_JOIN_NO_CLAIM_FOR_HOST");
158
+ }
159
+ }
160
+ async function privateConfigHome(configHome) {
161
+ try {
162
+ await mkdir(configHome, { recursive: true, mode: 448 });
163
+ const stat = await lstat(configHome);
164
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 18) !== 0)
165
+ refusal("HOST_JOIN_UNSAFE_PATH");
166
+ return await realpath(configHome);
167
+ } catch {
168
+ return refusal("HOST_JOIN_UNSAFE_PATH");
169
+ }
170
+ }
171
+ async function openClaimVault(vaultFile) {
172
+ const stat = await lstat(vaultFile);
173
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 384)
174
+ refusal("HOST_JOIN_UNSAFE_PATH");
175
+ const selected = fileVault({ file: vaultFile });
176
+ const authorization = await selected.get("host:hightea");
177
+ const saved = await selected.get("host:hightea-join");
178
+ if (!authorization || !/^Bearer [A-Za-z0-9_-]{43}$/u.test(authorization) || !saved)
179
+ refusal("HOST_JOIN_CLAIM_CORRUPT");
180
+ let metadata;
181
+ try {
182
+ metadata = JSON.parse(saved);
183
+ } catch {
184
+ return refusal("HOST_JOIN_CLAIM_CORRUPT");
185
+ }
186
+ if (!metadata || typeof metadata !== "object" || !("schema" in metadata) || metadata.schema !== 1)
187
+ refusal("HOST_JOIN_CLAIM_CORRUPT");
188
+ let intent;
189
+ try {
190
+ intent = canonicalIntent(metadata);
191
+ } catch {
192
+ return refusal("HOST_JOIN_CLAIM_CORRUPT");
193
+ }
194
+ return { authorization, credentialHash: `sha256:${createHash("sha256").update(authorization.slice(7), "utf8").digest("hex")}`, intent };
195
+ }
196
+
197
+ // ../ahp-host/src/configuration.ts
198
+ import { link as link2, lstat as lstat2, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
199
+ import { join as join2 } from "node:path";
200
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
201
+ import { isRecordSlug, readJsonObject, writeJsonAtomic } from "@ahpd/sdk";
202
+ async function saveHostConfiguration(claim, configuration) {
203
+ return saveHostJson(claim, join2(claim.home, "ahpd"), "config.json", configuration);
204
+ }
205
+ async function saveHostAgentRecord(claim, record) {
206
+ if (!isRecordSlug(record.id))
207
+ throw new Error("HOST_JOIN_CONFIG_CONFLICT");
208
+ const directory = join2(claim.home, "ahpd", "agents");
209
+ await privateHostDirectory(directory);
210
+ await saveHostJson(claim, directory, `${record.id}.json`, { ...record });
211
+ }
212
+ async function saveHostJson(claim, directory, name, configuration) {
213
+ const destination = join2(directory, name);
214
+ let candidate;
215
+ try {
216
+ if (JSON.stringify(configuration).includes(claim.authorization))
217
+ throw new Error("HOST_JOIN_CONFIG_SECRET");
218
+ candidate = await mkdtemp2(join2(directory, ".config-"));
219
+ const staged = join2(candidate, "config.json");
220
+ writeJsonAtomic(staged, configuration, { mode: 384 });
221
+ try {
222
+ await link2(staged, destination);
223
+ } catch (error) {
224
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
225
+ throw new Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED");
226
+ }
227
+ const stat = await lstat2(destination);
228
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 384)
229
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
230
+ const existing = readJsonObject(destination);
231
+ if (!existing.ok)
232
+ throw new Error("HOST_JOIN_CONFIG_CORRUPT");
233
+ const backfill = {};
234
+ for (const [key, value] of Object.entries(configuration)) {
235
+ const restriction = key === "unattendedAutoApprove" && value === false || key === "pluginMarketplaces" && Array.isArray(value) && value.length === 0;
236
+ if (name === "config.json" && restriction && !Object.hasOwn(existing.value, key)) {
237
+ backfill[key] = value;
238
+ continue;
239
+ }
240
+ if (!isDeepStrictEqual2(existing.value[key], value))
241
+ throw new Error("HOST_JOIN_CONFIG_CONFLICT");
242
+ }
243
+ if (Object.keys(backfill).length > 0) {
244
+ writeJsonAtomic(destination, { ...existing.value, ...backfill }, { mode: 384 });
245
+ }
246
+ await flushHostFile(destination);
247
+ return destination;
248
+ } catch (error) {
249
+ if (error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message))
250
+ throw error;
251
+ throw new Error("HOST_JOIN_CONFIG_IO");
252
+ } finally {
253
+ if (candidate !== undefined)
254
+ await rm2(candidate, { recursive: true });
255
+ }
256
+ }
257
+
258
+ // ../ahp-host/src/join.ts
259
+ import { isRecord } from "@ahpd/sdk";
260
+ class HostJoinRefusal extends Error {
261
+ kind;
262
+ status;
263
+ serverCode;
264
+ constructor(kind, status, serverCode) {
265
+ super(kind);
266
+ this.kind = kind;
267
+ this.status = status;
268
+ this.serverCode = serverCode;
269
+ }
270
+ }
271
+ function refusalKind(status, serverCode) {
272
+ if (status === 401 || status === 403)
273
+ return "HOST_JOIN_NOT_AUTHORIZED";
274
+ if (serverCode === "AGENT_HOST_CONFLICT" || serverCode === "HOST_REGISTRATION_CONFLICT")
275
+ return "HOST_JOIN_AGENT_BOUND";
276
+ if (serverCode === "HOST_REGISTRATION_UNSETTLED")
277
+ return "HOST_JOIN_UNSETTLED";
278
+ return "HOST_JOIN_REJECTED";
279
+ }
280
+ async function redeemHostClaim(claim) {
281
+ await flushHostFile(claim.vaultFile);
282
+ const intent = claim.intent;
283
+ const request = new Request(`${intent.origin}/api/ws/${encodeURIComponent(intent.workspaceSlug)}/join/${encodeURIComponent(intent.code)}`, {
284
+ method: "POST",
285
+ redirect: "error",
286
+ headers: { "content-type": "application/json" },
287
+ signal: AbortSignal.timeout(1e4),
288
+ body: JSON.stringify({
289
+ credentialHash: claim.credentialHash,
290
+ pluginVersion: intent.pluginVersion,
291
+ ahpdVersion: intent.ahpdVersion,
292
+ ...intent.name === undefined ? {} : { name: intent.name },
293
+ ...intent.app === undefined ? {} : { app: intent.app },
294
+ ...intent.hostId === undefined ? {} : { hostId: intent.hostId }
295
+ })
296
+ });
297
+ let response;
298
+ try {
299
+ response = await fetch(request);
300
+ } catch {
301
+ throw new Error("HOST_JOIN_NETWORK_UNKNOWN");
302
+ }
303
+ if (response.status === 410) {
304
+ let error;
305
+ try {
306
+ error = await response.json();
307
+ } catch {}
308
+ if (isRecord(error) && isRecord(error.error) && error.error.code === "HOST_REGISTRATION_CANCELLED")
309
+ throw new Error("HOST_JOIN_CANCELLED");
310
+ throw new Error("HOST_JOIN_LINK_UNAVAILABLE");
311
+ }
312
+ if (response.status >= 500) {
313
+ let error;
314
+ try {
315
+ error = await response.json();
316
+ } catch {}
317
+ const serverCode = isRecord(error) && isRecord(error.error) && isJoinRouteRefusalCode(error.error.code) ? error.error.code : undefined;
318
+ if (serverCode === "HOST_REGISTRATION_UNSETTLED")
319
+ throw new HostJoinRefusal("HOST_JOIN_UNSETTLED", response.status, serverCode);
320
+ throw new Error("HOST_JOIN_REMOTE_UNAVAILABLE");
321
+ }
322
+ if (!response.ok) {
323
+ let error;
324
+ try {
325
+ error = await response.json();
326
+ } catch {}
327
+ const serverCode = isRecord(error) && isRecord(error.error) && isJoinRouteRefusalCode(error.error.code) ? error.error.code : undefined;
328
+ throw new HostJoinRefusal(refusalKind(response.status, serverCode), response.status, serverCode);
329
+ }
330
+ let receipt;
331
+ try {
332
+ receipt = await response.json();
333
+ } catch {
334
+ throw new Error("HOST_JOIN_RECEIPT_INVALID");
335
+ }
336
+ if (!isRecord(receipt) || typeof receipt.workspaceId !== "string" || !/^ws_[A-Za-z0-9_-]{1,64}$/u.test(receipt.workspaceId) || typeof receipt.hostId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(receipt.hostId) || receipt.state !== "pending" && receipt.state !== "registered" || receipt.agentMemberId !== undefined && (typeof receipt.agentMemberId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(receipt.agentMemberId)))
337
+ throw new Error("HOST_JOIN_RECEIPT_INVALID");
338
+ return {
339
+ workspaceId: receipt.workspaceId,
340
+ hostId: receipt.hostId,
341
+ state: receipt.state,
342
+ ...receipt.agentMemberId === undefined ? {} : { agentMemberId: receipt.agentMemberId }
343
+ };
344
+ }
345
+
346
+ // ../ahp-host/src/owner.ts
347
+ import { access, stat } from "node:fs/promises";
348
+ import { constants as constants2 } from "node:fs";
349
+ import { delimiter, dirname as dirname2, isAbsolute, join as join3 } from "node:path";
350
+ import { fileURLToPath } from "node:url";
351
+ import { fromEnvRef, isRecord as isRecord2, isRecordSlug as isRecordSlug2, readJsonObject as readJsonObject2, scopeOf, secretPaths, secretRef } from "@ahpd/sdk";
352
+ import { checkManifest, checkStandalone, readManifest, readStandalone, resolvePlugin } from "@ahpd/server/dist/plugins.js";
353
+ function fail(code = "HOST_JOIN_OWNER_RESOURCE") {
354
+ throw new Error(code);
355
+ }
356
+ function reference(value) {
357
+ const variable = fromEnvRef(value);
358
+ if (variable !== undefined) {
359
+ if (!process.env[variable])
360
+ fail();
361
+ return true;
362
+ }
363
+ const secret = secretRef(value);
364
+ if (secret === undefined)
365
+ return false;
366
+ scopeOf(secret);
367
+ return true;
368
+ }
369
+ async function executable(command) {
370
+ const candidates = isAbsolute(command) ? [command] : (process.env.PATH ?? "").split(delimiter).map((path) => join3(path, command));
371
+ for (const candidate of candidates) {
372
+ try {
373
+ await access(candidate, constants2.X_OK);
374
+ if ((await stat(candidate)).isFile())
375
+ return;
376
+ } catch {}
377
+ }
378
+ fail();
379
+ }
380
+ async function readOwnerConfiguration(file) {
381
+ const read = readJsonObject2(file);
382
+ if (!read.ok)
383
+ fail("HOST_JOIN_OWNER_INPUT");
384
+ const body = read.value;
385
+ if (!Array.isArray(body.agents) || body.agents.length === 0 || !Array.isArray(body.plugins) || body.plugins.length === 0 || !Array.isArray(body.records))
386
+ fail();
387
+ const engines = new Set;
388
+ const direct = new Set;
389
+ const plugins = [];
390
+ try {
391
+ for (const value of body.plugins) {
392
+ const entry = typeof value === "string" ? { source: value } : value;
393
+ if (!isRecord2(entry) || typeof entry.source !== "string" || entry.enabled === false)
394
+ fail();
395
+ const spec = entry;
396
+ const resolved = resolvePlugin(spec, { cwd: dirname2(file), configDir: dirname2(file) });
397
+ if (!resolved.path || !(await stat(resolved.path)).isFile())
398
+ fail();
399
+ const manifest = resolved.manifestPath ? readStandalone(resolved.manifestPath) : resolved.packageDir ? readManifest(resolved.packageDir) : undefined;
400
+ if (!manifest || manifest.problem || (manifest.standalone ? checkStandalone(manifest) : checkManifest(manifest, resolved.packageDir)))
401
+ fail();
402
+ if (manifest.name === "@ahpd/bot" || manifest.name === "bot")
403
+ fail("HOST_JOIN_OWNER_BOT");
404
+ for (const name of manifest.contracts?.engines ?? [])
405
+ engines.add(name);
406
+ for (const name of manifest.contracts?.agents ?? [])
407
+ direct.add(name);
408
+ if (entry.options !== undefined && !isRecord2(entry.options))
409
+ fail();
410
+ const options = isRecord2(entry.options) ? entry.options : {};
411
+ for (const path of secretPaths(manifest.optionsSchema ?? {}, options)) {
412
+ let held = options;
413
+ for (const part of path.split("."))
414
+ held = isRecord2(held) ? held[part] : undefined;
415
+ if (held !== undefined && !reference(held))
416
+ fail("HOST_JOIN_OWNER_SECRET");
417
+ }
418
+ plugins.push({ ...entry, source: resolved.manifestPath ?? resolved.packageDir ?? resolved.path });
419
+ }
420
+ const records = [];
421
+ const providers = new Set(direct);
422
+ for (const record of body.records) {
423
+ if (!isRecord2(record) || typeof record.id !== "string" || !isRecordSlug2(record.id) || providers.has(record.id) || typeof record.engine !== "string" || !engines.has(record.engine) || typeof record.owner !== "string" || typeof record.name !== "string" || !isRecord2(record.config) || record.mode !== undefined && record.mode !== "enabled")
424
+ fail();
425
+ if (record.model !== undefined && (typeof record.model !== "string" || record.model.trim() === ""))
426
+ fail();
427
+ if (record.engine === "acp" && typeof record.config.command !== "string")
428
+ fail();
429
+ if (record.config.command !== undefined) {
430
+ if (typeof record.config.command !== "string" || !record.config.command)
431
+ fail();
432
+ await executable(record.config.command);
433
+ }
434
+ if (record.config.env !== undefined) {
435
+ if (!isRecord2(record.config.env))
436
+ fail();
437
+ for (const value of Object.values(record.config.env))
438
+ if (!reference(value))
439
+ fail("HOST_JOIN_OWNER_SECRET");
440
+ }
441
+ providers.add(record.id);
442
+ records.push(record);
443
+ }
444
+ const agents = [];
445
+ const members = new Set;
446
+ for (const entry of body.agents) {
447
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !entry[0] || members.has(entry[0]) || !isRecord2(entry[1]) || typeof entry[1].provider !== "string" || !providers.has(entry[1].provider) || typeof entry[1].workingDirectory !== "string")
448
+ fail();
449
+ const work = new URL(entry[1].workingDirectory);
450
+ if (work.protocol !== "file:" || work.hostname || !(await stat(fileURLToPath(work))).isDirectory())
451
+ fail();
452
+ if (entry[1].settings !== undefined && !isRecord2(entry[1].settings))
453
+ fail();
454
+ members.add(entry[0]);
455
+ agents.push([entry[0], {
456
+ provider: entry[1].provider,
457
+ workingDirectory: work.href,
458
+ ...entry[1].settings === undefined ? {} : { settings: entry[1].settings }
459
+ }]);
460
+ }
461
+ return { agents, plugins, records };
462
+ } catch (error) {
463
+ if (error instanceof Error && /^HOST_JOIN_OWNER_[A-Z_]+$/u.test(error.message))
464
+ throw error;
465
+ return fail();
466
+ }
467
+ }
468
+
469
+ // ../ahp-host/src/owner-file.ts
470
+ import { constants as constants3 } from "node:fs";
471
+ import { access as access2, mkdir as mkdir2, stat as stat2, writeFile } from "node:fs/promises";
472
+ import { createRequire } from "node:module";
473
+ import { dirname as dirname3, resolve } from "node:path";
474
+ import { pathToFileURL } from "node:url";
475
+ class OwnerFileNeedsAgent extends Error {
476
+ file;
477
+ entry;
478
+ constructor(file, entry) {
479
+ super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");
480
+ this.file = file;
481
+ this.entry = entry;
482
+ }
483
+ }
484
+ function agentPluginDirectory() {
485
+ try {
486
+ return dirname3(createRequire(import.meta.url).resolve("@ahpd/agent-acp/package.json"));
487
+ } catch {
488
+ throw new Error("HOST_JOIN_AGENT_PLUGIN_MISSING");
489
+ }
490
+ }
491
+ function agentEntry(app, agentMemberId, workingDirectory) {
492
+ return [agentMemberId, { provider: app.id, workingDirectory: pathToFileURL(resolve(workingDirectory)).href }];
493
+ }
494
+ function agentEntryText(app, agentMemberId, workingDirectory) {
495
+ return JSON.stringify(agentEntry(app, agentMemberId, workingDirectory));
496
+ }
497
+ function ownerFileBody(write, plugin) {
498
+ const [member, configuration] = agentEntry(write.app, write.agentMemberId, write.workingDirectory);
499
+ return `${JSON.stringify({
500
+ plugins: [plugin],
501
+ records: [{ id: write.app.id, engine: "acp", owner: "host", name: write.app.name, config: { command: write.app.command } }],
502
+ agents: [[member, configuration]]
503
+ }, null, 2)}
504
+ `;
505
+ }
506
+ async function ownerConfigurationFor(write) {
507
+ const file = resolve(write.file);
508
+ if (await access2(file, constants3.F_OK).then(() => true, () => false))
509
+ return existing(file, write);
510
+ await mkdir2(dirname3(file), { recursive: true, mode: 448 });
511
+ try {
512
+ await writeFile(file, ownerFileBody(write, agentPluginDirectory()), { flag: "wx", mode: 384 });
513
+ } catch (error) {
514
+ if (error !== null && typeof error === "object" && "code" in error && error.code === "EEXIST")
515
+ return existing(file, write);
516
+ throw new Error("HOST_JOIN_OWNER_FILE_IO");
517
+ }
518
+ const written = await stat2(file);
519
+ if (!written.isFile() || written.uid !== process.getuid?.() || (written.mode & 511) !== 384)
520
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
521
+ return readOwnerConfiguration(file);
522
+ }
523
+ async function existing(file, write) {
524
+ const configuration = await readOwnerConfiguration(file);
525
+ if (configuration.agents.some(([member]) => member === write.agentMemberId))
526
+ return configuration;
527
+ throw new OwnerFileNeedsAgent(file, agentEntryText(write.app, write.agentMemberId, write.workingDirectory));
528
+ }
529
+
530
+ // ../ahp-host/src/commands.ts
531
+ import { access as access3 } from "node:fs/promises";
532
+ import { constants as constants4 } from "node:fs";
533
+
534
+ // ../ahp-host/src/plugin-bundle.ts
535
+ import { createHash as createHash2 } from "node:crypto";
536
+ import { lstat as lstat3, mkdir as mkdir3, mkdtemp as mkdtemp3, readFile, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
537
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "node:path";
538
+ var PLUGIN_ID = "hightea-pipe";
539
+ var RECORD = "bundle.json";
540
+ function pluginBundleRoot(dataHome) {
541
+ return join4(dataHome, "hightea", "plugins");
542
+ }
543
+ async function readSource(source) {
544
+ let manifestBytes;
545
+ try {
546
+ manifestBytes = await readFile(join4(source, "plugin.json"));
547
+ } catch {
548
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE");
549
+ }
550
+ let manifest;
551
+ try {
552
+ manifest = JSON.parse(manifestBytes.toString("utf8"));
553
+ } catch {
554
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE");
555
+ }
556
+ const main = typeof manifest === "object" && manifest !== null && "main" in manifest ? manifest.main : undefined;
557
+ const id = typeof manifest === "object" && manifest !== null && "id" in manifest ? manifest.id : undefined;
558
+ const version = typeof manifest === "object" && manifest !== null && "version" in manifest ? manifest.version : undefined;
559
+ if (id !== PLUGIN_ID || typeof version !== "string" || typeof main !== "string" || isAbsolute2(main) || normalize(main).startsWith("..") || normalize(main).includes("/") || ["plugin.json", RECORD].includes(normalize(main))) {
560
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE");
561
+ }
562
+ let mainBytes;
563
+ try {
564
+ mainBytes = await readFile(join4(source, main));
565
+ } catch {
566
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE");
567
+ }
568
+ return { manifestBytes, version, main: normalize(main), mainBytes, sha256: bundleHash(manifestBytes, mainBytes) };
569
+ }
570
+ function bundleHash(manifestBytes, mainBytes) {
571
+ return createHash2("sha256").update(manifestBytes).update("\x00").update(mainBytes).digest("hex");
572
+ }
573
+ async function readInstalledBundle(manifest) {
574
+ const directory = join4(manifest, "..");
575
+ let record;
576
+ try {
577
+ record = JSON.parse(await readFile(join4(directory, RECORD), "utf8"));
578
+ } catch (error) {
579
+ return { ok: false, reason: isMissing(error) ? "missing" : "corrupt" };
580
+ }
581
+ let source;
582
+ try {
583
+ source = await readSource(directory);
584
+ } catch {
585
+ return { ok: false, reason: "corrupt" };
586
+ }
587
+ if (typeof record !== "object" || record === null || !("version" in record) || !("sha256" in record) || typeof record.version !== "string" || record.sha256 !== source.sha256)
588
+ return { ok: false, reason: "corrupt" };
589
+ return { ok: true, bundle: { manifest, version: record.version, sha256: source.sha256 } };
590
+ }
591
+ async function installPluginBundle(dataHome, source, version) {
592
+ if (!isAbsolute2(dataHome) || !/^[0-9A-Za-z.+-]+$/u.test(version))
593
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
594
+ const wanted = await readSource(source);
595
+ if (wanted.version !== version)
596
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE");
597
+ try {
598
+ await mkdir3(dataHome, { recursive: true, mode: 448 });
599
+ const stat = await lstat3(dataHome);
600
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 18) !== 0)
601
+ throw new Error("unsafe");
602
+ } catch {
603
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
604
+ }
605
+ const root = pluginBundleRoot(dataHome);
606
+ for (const directory of [join4(dataHome, "hightea"), root])
607
+ await privateHostDirectory(directory);
608
+ const destination = join4(root, version);
609
+ const manifest = join4(destination, "plugin.json");
610
+ if (!await exists(destination)) {
611
+ const staged = await mkdtemp3(join4(root, `.${version}-`));
612
+ try {
613
+ await writeFile2(join4(staged, "plugin.json"), wanted.manifestBytes, { mode: 384 });
614
+ await writeFile2(join4(staged, wanted.main), wanted.mainBytes, { mode: 384 });
615
+ await writeFile2(join4(staged, RECORD), `${JSON.stringify({ version, sha256: wanted.sha256 })}
616
+ `, { mode: 384 });
617
+ try {
618
+ await rename(staged, destination);
619
+ } catch (error) {
620
+ if (!isCode(error, "EEXIST") && !isCode(error, "ENOTEMPTY"))
621
+ throw new Error("HOST_JOIN_CONFIG_IO");
622
+ }
623
+ } finally {
624
+ await rm3(staged, { recursive: true, force: true });
625
+ }
626
+ }
627
+ const installed = await readInstalledBundle(manifest);
628
+ if (!installed.ok || installed.bundle.sha256 !== wanted.sha256 || installed.bundle.version !== version) {
629
+ throw new Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");
630
+ }
631
+ return installed.bundle;
632
+ }
633
+ async function exists(path) {
634
+ try {
635
+ await lstat3(path);
636
+ return true;
637
+ } catch (error) {
638
+ if (isMissing(error))
639
+ return false;
640
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
641
+ }
642
+ }
643
+ function isMissing(error) {
644
+ return isCode(error, "ENOENT");
645
+ }
646
+ function isCode(error, code) {
647
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
648
+ }
649
+
650
+ // ../ahp-host/src/ask-gate.ts
651
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "node:crypto";
652
+ import { appendFile, chmod, readFile as readFile2, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
653
+ import { join as join6 } from "node:path";
654
+
655
+ // ../ahp-host/src/signed-asks.ts
656
+ var ED25519_SPKI_HEADER = Buffer.from("302a300506032b6570032100", "hex");
657
+
658
+ // ../ahp-host/src/trusted-keys.ts
659
+ import { createHash as createHash3 } from "node:crypto";
660
+ import { existsSync, readFileSync } from "node:fs";
661
+ import { join as join5 } from "node:path";
662
+ var TRUSTED_KEYS_FILE = "trusted-keys.json";
663
+ var TRUSTED_KEY_NAME = /^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u;
664
+ var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u;
665
+ var base64url = (bytes) => Buffer.from(bytes).toString("base64url");
666
+ function trustedKeyId(publicKey) {
667
+ if (!BASE64URL_32_BYTES.test(publicKey)) {
668
+ return { error: "TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it" };
669
+ }
670
+ return { keyId: base64url(createHash3("sha256").update(Buffer.from(publicKey, "base64url")).digest()) };
671
+ }
672
+ function readTrustedKeys(configDir) {
673
+ const file = join5(configDir, TRUSTED_KEYS_FILE);
674
+ if (!existsSync(file))
675
+ return { state: "missing", file };
676
+ let parsed;
677
+ try {
678
+ parsed = JSON.parse(readFileSync(file, "utf8"));
679
+ } catch (error) {
680
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not JSON (${error.message})`);
681
+ }
682
+ const record = parsed;
683
+ if (typeof parsed !== "object" || parsed === null || record.v !== 1 || !Array.isArray(record.keys)) {
684
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not a version 1 list of trusted keys`);
685
+ }
686
+ for (const key of record.keys) {
687
+ const row = key;
688
+ const id = typeof row.publicKey === "string" ? trustedKeyId(row.publicKey) : undefined;
689
+ if (typeof row.name !== "string" || !TRUSTED_KEY_NAME.test(row.name) || id === undefined || "error" in id || row.keyId !== id.keyId || typeof row.addedAt !== "string") {
690
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} holds an entry that is not a valid trusted key: ${JSON.stringify(key)}`);
691
+ }
692
+ }
693
+ return { state: "read", file, keys: record.keys };
694
+ }
695
+
696
+ // ../ahp-host/src/ask-gate.ts
697
+ var HOST_SIGNING_KEY_FILE = "host-signing-key";
698
+ var ASK_FRESH_MS = 10 * 60000;
699
+ var ACTED_KEEP_MS = 30 * 24 * 60 * 60000;
700
+ async function readHostSigningKey(configDir) {
701
+ try {
702
+ await readFile2(join6(configDir, HOST_SIGNING_KEY_FILE));
703
+ } catch (error) {
704
+ if (error.code === "ENOENT")
705
+ return { state: "missing" };
706
+ }
707
+ try {
708
+ return { state: "ok", key: await hostSigningKey(configDir) };
709
+ } catch (error) {
710
+ return { state: "unreadable", reason: error instanceof Error ? error.message : String(error) };
711
+ }
712
+ }
713
+ async function hostSigningKey(configDir, now = () => Date.now()) {
714
+ const file = join6(configDir, HOST_SIGNING_KEY_FILE);
715
+ let pem;
716
+ try {
717
+ pem = await readFile2(file, "utf8");
718
+ } catch (error) {
719
+ if (error.code !== "ENOENT") {
720
+ throw new Error(`HOST_KEY_UNREADABLE: ${file} exists but cannot be read (${String(error)}); it is never regenerated, fix or remove it by hand`);
721
+ }
722
+ }
723
+ if (pem === undefined) {
724
+ const made = generateKeyPairSync("ed25519").privateKey.export({ format: "pem", type: "pkcs8" }).toString();
725
+ const temporary = `${file}.${String(process.pid)}.tmp`;
726
+ await writeFile3(temporary, made, { mode: 384, flag: "wx" });
727
+ await chmod(temporary, 384);
728
+ await rename2(temporary, file);
729
+ pem = made;
730
+ }
731
+ let privateKey;
732
+ try {
733
+ privateKey = createPrivateKey({ key: pem, format: "pem" });
734
+ if (privateKey.asymmetricKeyType !== "ed25519")
735
+ throw new Error(`a ${String(privateKey.asymmetricKeyType)} key, not Ed25519`);
736
+ } catch (error) {
737
+ throw new Error(`HOST_KEY_UNREADABLE: ${file} is not an Ed25519 PKCS8 key (${String(error)}); it is never regenerated, fix or remove it by hand`);
738
+ }
739
+ const publicKey = createPublicKey(privateKey).export({ format: "jwk" }).x;
740
+ const id = publicKey === undefined ? { error: "no public key" } : trustedKeyId(publicKey);
741
+ if ("error" in id)
742
+ throw new Error(`HOST_KEY_UNREADABLE: ${file}: ${id.error}`);
743
+ return { privateKey, trusted: { name: "this-host", keyId: id.keyId, publicKey, addedAt: new Date(now()).toISOString() } };
744
+ }
745
+
746
+ // ../ahp-host/src/host-tools-port.ts
747
+ import { createServer } from "node:net";
748
+ var HOST_TOOLS_NAME = "hightea";
749
+ function hostToolsUrl(port) {
750
+ return `http://127.0.0.1:${String(port)}/mcp`;
751
+ }
752
+ function derivedHostToolsPort(claimHome) {
753
+ let hash = 2166136261;
754
+ for (const byte of new TextEncoder().encode(claimHome)) {
755
+ hash ^= byte;
756
+ hash = Math.imul(hash, 16777619) >>> 0;
757
+ }
758
+ return 40000 + hash % 20000;
759
+ }
760
+ async function chooseHostToolsPort(claimHome) {
761
+ const start = derivedHostToolsPort(claimHome);
762
+ for (let step = 0;step < 200; step += 1) {
763
+ const port = 40000 + (start - 40000 + step) % 20000;
764
+ if (await free(port))
765
+ return port;
766
+ }
767
+ throw new Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(start)} to ${String(start + 199)} on 127.0.0.1 is taken`);
768
+ }
769
+ async function free(port) {
770
+ const probe = createServer();
771
+ return await new Promise((resolve) => {
772
+ probe.once("error", () => {
773
+ resolve(false);
774
+ });
775
+ probe.listen(port, "127.0.0.1", () => {
776
+ probe.close(() => {
777
+ resolve(true);
778
+ });
779
+ });
780
+ });
781
+ }
782
+
783
+ // ../ahp-host/src/commands.ts
784
+ var USAGE = "hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json";
785
+ var hasControlCharacter = (value) => [...value].some((character) => {
786
+ const code = character.codePointAt(0) ?? 0;
787
+ return code < 32 || code === 127;
788
+ });
789
+ function machineName(raw = hostname()) {
790
+ const name = raw.trim();
791
+ return name === "" || name.length > 64 || hasControlCharacter(name) ? undefined : name;
792
+ }
793
+ var OWNER_CONFIG_DOC = "https://hightea.ai/docs/host#owner";
794
+
795
+ class HostOwnerConfigMissing extends Error {
796
+ file;
797
+ constructor(file) {
798
+ super("HOST_JOIN_OWNER_CONFIG_MISSING");
799
+ this.file = file;
800
+ }
801
+ }
802
+ var ownerConfigLine = (file) => `no owner config at ${file}: write one listing the plugins, agent records and agents this computer runs — ` + `the three fields with an example of each are at ${OWNER_CONFIG_DOC} — then run the same command again. Nothing was redeemed and nothing was written.`;
803
+ var ownerConfigNeedsAgentLine = (file, entry) => `the owner config at ${file} does not map the agent this computer just created. Add this pair to its "agents" array — ` + `${entry} — then run the same command again; the registration is pending and resumes.`;
804
+
805
+ class HostAgentAppMissing extends Error {
806
+ appName;
807
+ install;
808
+ constructor(appName, install) {
809
+ super("HOST_JOIN_APP_MISSING");
810
+ this.appName = appName;
811
+ this.install = install;
812
+ }
813
+ }
814
+ var agentAppMissingLine = (error) => `${error.appName} is not on this computer: install it with \`${error.install}\`, then run the same command again. ` + `Nothing was redeemed and nothing was written.`;
815
+ var DIAGNOSTICS = {
816
+ HOST_JOIN_USAGE: `Expected: ${USAGE}`,
817
+ HOST_JOIN_INPUT: "Command input could not be read. Use --help for the supported options.",
818
+ HOST_JOIN_INVALID_INTENT: "Use an HTTPS deployment origin, workspace slug and valid join code.",
819
+ HOST_JOIN_OWNER_INPUT: "The --owner-config file must exist and contain a JSON object; its contents were not printed.",
820
+ HOST_JOIN_OWNER_RESOURCE: "Check the explicit agent mappings, provider plugins, working directories, executables and referenced credentials in --owner-config. No code was redeemed.",
821
+ HOST_JOIN_OWNER_SECRET: "Replace inline provider secrets with existing ahpd fromEnv or SecretRef values; the referenced resource must be available locally.",
822
+ HOST_JOIN_OWNER_BOT: "@ahpd/bot is not allowed on a member host (bots run on the server); remove it from this owner's plugin list",
823
+ HOST_JOIN_UNSAFE_PATH: "The selected configuration path must be owned by this user and private; symlinks and shared files are not used.",
824
+ HOST_JOIN_CLAIM_CONFLICT: "This claim already holds different deployment or owner settings. Keep its vault and use the original settings to resume.",
825
+ HOST_JOIN_CLAIM_CORRUPT: "The selected claim vault is invalid. Keep it for recovery; joining will not replace its credential.",
826
+ HOST_JOIN_NO_CLAIM_FOR_HOST: "This computer holds no claim for that host. Join without --host to register this computer as a new host; --host only extends a host this computer already holds, reusing its credential.",
827
+ HOST_JOIN_NETWORK_UNKNOWN: "The registration result is unknown. Keep this claim and rerun the same command to recover its receipt.",
828
+ HOST_JOIN_REMOTE_UNAVAILABLE: "The deployment could not complete registration. Keep this claim and rerun the same command later.",
829
+ HOST_JOIN_CANCELLED: "The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",
830
+ HOST_JOIN_LINK_UNAVAILABLE: "This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",
831
+ HOST_JOIN_REJECTED: "The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",
832
+ HOST_JOIN_NOT_AUTHORIZED: "The deployment refused this account for that workspace or agent. Join with the account that owns the agents in --owner-config; the selected credential was retained.",
833
+ HOST_JOIN_AGENT_BOUND: "The deployment refused this registration; the server code on this line says which case it is. AGENT_HOST_CONFLICT: an agent in --owner-config already belongs to another active host — revoke that host, then mint a new code. HOST_REGISTRATION_CONFLICT: this code was already redeemed by a different host registration — join with the claim that computer already holds, or mint a new code. Never revoke a host on the strength of this line alone; the selected credential was retained.",
834
+ HOST_JOIN_UNSETTLED: "The workspace did not answer this registration within a minute. The code is unspent and this claim is intact; wait a minute, then run the same command again.",
835
+ HOST_JOIN_RECEIPT_INVALID: "The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",
836
+ HOST_JOIN_CONFIG_CONFLICT: "Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",
837
+ HOST_JOIN_CONFIG_CORRUPT: "Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it.",
838
+ HOST_JOIN_CLAIM_VERSION: "This join code's claim was started by another hightea version. Finish it with that version, or request a new join code; nothing was redeemed or written.",
839
+ HOST_JOIN_PLUGIN_BUNDLE: "This installation's host plugin is missing or unreadable. Reinstall @hallohuman/hightea; no configuration was written.",
840
+ HOST_JOIN_PLUGIN_BUNDLE_CONFLICT: "The installed host plugin for this version differs from this installation's copy. It was preserved; reinstall the same version or repair that directory. No configuration was written.",
841
+ HOST_JOIN_AGENT_PLUGIN_MISSING: "This installation cannot find @ahpd/agent-acp, the plugin that runs agent apps. Reinstall @hallohuman/hightea; nothing was redeemed.",
842
+ HOST_JOIN_APPS_ROW_MISSING: "This installation's app list and the daemon's rows disagree. Reinstall @hallohuman/hightea; nothing was redeemed.",
843
+ HOST_JOIN_OWNER_FILE_IO: "The owner config could not be written. No existing file was replaced; check the folder's permissions and retry."
844
+ };
845
+ function xdgHome(variable, fallback) {
846
+ const home = process.env[variable] || join7(homedir(), fallback);
847
+ if (!isAbsolute3(home))
848
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
849
+ return home;
850
+ }
851
+ function installedDaemon() {
852
+ const manifest = createRequire2(import.meta.url).resolve("@ahpd/server/package.json");
853
+ return { node: process.execPath, main: join7(dirname4(manifest), "dist", "main.js") };
854
+ }
855
+ var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
856
+ function hostStartCommand(claim, daemon = installedDaemon()) {
857
+ return `XDG_CONFIG_HOME=${shellQuote(claim)} ${shellQuote(daemon.node)} ${shellQuote(daemon.main)} start`;
858
+ }
859
+ var SERVER_REFUSALS = {
860
+ JOIN_LINK_INVALID: "the join code is no longer valid",
861
+ JOIN_LINK_NOT_FOUND: "no such join code in that workspace",
862
+ ROLE_NOT_ALLOWED: "the join code does not allow this role",
863
+ NOT_A_MEMBER: "the signed-in account is not a member of that workspace",
864
+ FORBIDDEN: "an agent in --owner-config belongs to another account",
865
+ HOST_REGISTRATION_CANCELLED: "the owner cancelled this registration",
866
+ HOST_REGISTRATION_CONFLICT: "this code was redeemed for a different host registration; a computer that already has a host joins with the claim it already holds",
867
+ AGENT_HOST_CONFLICT: "an agent already belongs to another active host; revoke that host, then mint a new code",
868
+ HOST_REGISTRATION_MISSING: "the pending registration is gone",
869
+ HOST_REGISTRATION_UNSETTLED: "the workspace has not answered the registration within a minute; run the same command again",
870
+ INVALID_REQUEST: "the deployment did not accept this request's shape",
871
+ BAD_ORIGIN: "the request came from another site",
872
+ UNAUTHENTICATED: "the request carried no signed-in account",
873
+ WORKSPACE_NOT_FOUND: "no such workspace for this account",
874
+ PEOPLE_LIMIT: "that workspace is at its beta limit of people",
875
+ AGENTS_LIMIT: "that workspace is at its beta limit of agents"
876
+ };
877
+ var REFUSAL_EXIT = { HOST_JOIN_NOT_AUTHORIZED: 3, HOST_JOIN_AGENT_BOUND: 4, HOST_JOIN_REJECTED: 1, HOST_JOIN_UNSETTLED: 2 };
878
+ function refusalLine(refusal) {
879
+ const meaning = refusal.serverCode === undefined ? "" : ` The deployment says ${SERVER_REFUSALS[refusal.serverCode]}.`;
880
+ return `${refusal.kind}: ${DIAGNOSTICS[refusal.kind]}${meaning} (HTTP ${refusal.status}, server code ${refusal.serverCode ?? "unrecognised"})`;
881
+ }
882
+ async function hostJoin2(input, plugin) {
883
+ try {
884
+ const { origin, workspace, code, ownerConfig: ownerFile } = input;
885
+ if (!origin || !workspace || !code || !ownerFile)
886
+ throw new Error("HOST_JOIN_USAGE");
887
+ const ownerPath = resolve2(ownerFile);
888
+ const ownerPresent = await access3(ownerPath, constants4.F_OK).then(() => true, () => false);
889
+ if (!ownerPresent && input.ownerConfigIsDefault !== true)
890
+ throw new Error("HOST_JOIN_OWNER_INPUT");
891
+ if (!ownerPresent && input.app === undefined)
892
+ throw new HostOwnerConfigMissing(ownerPath);
893
+ const app = input.app === undefined ? undefined : describedApp2(input.app);
894
+ if (app !== undefined && !await appInstalled2(app))
895
+ throw new HostAgentAppMissing(app.name, installLineOf2(app));
896
+ const existingConfiguration = ownerPresent ? await readOwnerConfiguration(ownerPath) : null;
897
+ const configHome = xdgHome("XDG_CONFIG_HOME", ".config");
898
+ const dataHome = xdgHome("XDG_DATA_HOME", join7(".local", "share"));
899
+ const name = machineName();
900
+ const intent = {
901
+ origin,
902
+ workspaceSlug: workspace,
903
+ code,
904
+ pluginVersion: plugin.version,
905
+ ahpdVersion: "0.15.0-rc.4",
906
+ ownerConfiguration: existingConfiguration,
907
+ ...name === undefined ? {} : { name },
908
+ ...input.app === undefined ? {} : { app: input.app },
909
+ ...input.hostId === undefined ? {} : { hostId: input.hostId }
910
+ };
911
+ let claim;
912
+ if (input.hostId === undefined)
913
+ claim = await selectHostClaim(configHome, intent);
914
+ else {
915
+ const existing = await localHost2(input.hostId);
916
+ if ("error" in existing)
917
+ throw new Error("HOST_JOIN_NO_CLAIM_FOR_HOST");
918
+ claim = await extendHostClaim(configHome, existing.claim, intent);
919
+ }
920
+ if (claim.intent.pluginVersion !== plugin.version)
921
+ throw new Error("HOST_JOIN_CLAIM_VERSION");
922
+ const vault = fileVault2({ file: claim.vaultFile });
923
+ const checkReferences = async (value) => {
924
+ const name = secretRef2(value);
925
+ const variable = fromEnvRef2(value);
926
+ if (variable !== undefined) {
927
+ if (!process.env[variable])
928
+ throw new Error("HOST_JOIN_OWNER_RESOURCE");
929
+ } else if (name !== undefined) {
930
+ try {
931
+ await readSecret(vault, name);
932
+ } catch {
933
+ throw new Error("HOST_JOIN_OWNER_RESOURCE");
934
+ }
935
+ } else if (Array.isArray(value)) {
936
+ for (const child of value)
937
+ await checkReferences(child);
938
+ } else if (isRecord3(value)) {
939
+ for (const child of Object.values(value))
940
+ await checkReferences(child);
941
+ }
942
+ };
943
+ if (existingConfiguration !== null)
944
+ await checkReferences(existingConfiguration);
945
+ const bundle = await installPluginBundle(dataHome, plugin.directory, plugin.version);
946
+ const receipt = await redeemHostClaim(claim);
947
+ if (receipt.state === "pending") {
948
+ console.log("Host registration pending. Run the same command again to resume.");
949
+ return 2;
950
+ }
951
+ const ownerConfiguration = app === undefined ? existingConfiguration : await ownerConfigurationFor({
952
+ file: ownerPath,
953
+ app,
954
+ agentMemberId: requiredAgentMember(receipt.agentMemberId),
955
+ workingDirectory: input.workingDirectory ?? process.cwd()
956
+ });
957
+ if (ownerConfiguration === null)
958
+ throw new Error("HOST_JOIN_OWNER_INPUT");
959
+ if (app !== undefined)
960
+ await checkReferences(ownerConfiguration);
961
+ for (const record of ownerConfiguration.records)
962
+ await saveHostAgentRecord(claim, record);
963
+ const cloud = new URL(`/gateway/${encodeURIComponent(receipt.workspaceId)}/host`, claim.intent.origin);
964
+ cloud.protocol = "wss:";
965
+ const hostToolsPort = await chooseHostToolsPort(claim.home);
966
+ await saveHostConfiguration(claim, {
967
+ host: "127.0.0.1",
968
+ updateCheck: false,
969
+ httpApi: false,
970
+ modelApi: false,
971
+ mcpTools: "none",
972
+ unattendedAutoApprove: false,
973
+ pluginMarketplaces: [],
974
+ mcpServers: { [HOST_TOOLS_NAME]: { type: "http", url: hostToolsUrl(hostToolsPort) } },
975
+ plugins: [...ownerConfiguration.plugins, {
976
+ source: bundle.manifest,
977
+ grants: [...JOINED_GRANTS],
978
+ options: {
979
+ cloudUrl: cloud.href,
980
+ workspaceId: receipt.workspaceId,
981
+ agents: ownerConfiguration.agents,
982
+ mcpUrl: new URL(`/w/${encodeURIComponent(receipt.workspaceId)}`, claim.intent.origin).href,
983
+ hostToolsPort,
984
+ headers: { [HOST_HEADER]: receipt.hostId, authorization: { $secret: "host:hightea" } }
985
+ }
986
+ }]
987
+ });
988
+ console.log(`Host registered; local configuration saved. Start it with: ${hostStartCommand(claim.home)}`);
989
+ return 0;
990
+ } catch (error) {
991
+ if (error instanceof HostJoinRefusal) {
992
+ console.error(refusalLine(error));
993
+ return REFUSAL_EXIT[error.kind];
994
+ }
995
+ if (error instanceof HostOwnerConfigMissing) {
996
+ console.error(ownerConfigLine(error.file));
997
+ return 1;
998
+ }
999
+ if (error instanceof OwnerFileNeedsAgent) {
1000
+ console.error(ownerConfigNeedsAgentLine(error.file, error.entry));
1001
+ return 1;
1002
+ }
1003
+ if (error instanceof HostAgentAppMissing) {
1004
+ console.error(agentAppMissingLine(error));
1005
+ return 1;
1006
+ }
1007
+ const code = error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message) ? error.message : "HOST_JOIN_INPUT";
1008
+ console.error(`${code}: ${DIAGNOSTICS[code] ?? "Local claim storage could not be safely published or flushed. Keep the existing files, check filesystem access and retry; no replacement credential was selected."}`);
1009
+ return 1;
1010
+ }
1011
+ }
1012
+ function isHighteaPipeEntry(entry) {
1013
+ return isRecord3(entry) && isRecord3(entry.options) && typeof (entry.options.workspaceId ?? entry.options.houseId) === "string" && isRecord3(entry.options.headers) && typeof (entry.options.headers[HOST_HEADER] ?? entry.options.headers[LEGACY_HOST_HEADER]) === "string";
1014
+ }
1015
+ async function readStatusEntry(claim) {
1016
+ const config = join7(claim, "ahpd", "config.json");
1017
+ let text;
1018
+ try {
1019
+ text = await readFile3(config, "utf8");
1020
+ } catch (error) {
1021
+ const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1022
+ return missing ? { claim, state: "pending" } : { claim, state: "unreadable", config };
1023
+ }
1024
+ let saved;
1025
+ try {
1026
+ saved = JSON.parse(text);
1027
+ } catch {
1028
+ return { claim, state: "unreadable", config };
1029
+ }
1030
+ const plugins = isRecord3(saved) && Array.isArray(saved.plugins) ? saved.plugins : [];
1031
+ const ours = plugins.find(isHighteaPipeEntry);
1032
+ if (ours === undefined || typeof ours.source !== "string" || !isRecord3(ours.options) || !isRecord3(ours.options.headers)) {
1033
+ return { claim, state: "unreadable", config };
1034
+ }
1035
+ const pluginBundle = ours.source;
1036
+ const installed = await readInstalledBundle(pluginBundle);
1037
+ const bundle = !installed.ok ? installed.reason : installed.bundle.version === basename(dirname4(pluginBundle)) ? "ok" : "wrong-version";
1038
+ return {
1039
+ claim,
1040
+ state: "joined",
1041
+ config,
1042
+ start: hostStartCommand(claim),
1043
+ pluginBundle,
1044
+ bundle,
1045
+ ...installed.ok ? { pluginVersion: installed.bundle.version } : {},
1046
+ workspaceId: String(ours.options.workspaceId ?? ours.options.houseId),
1047
+ hostId: String(ours.options.headers[HOST_HEADER] ?? ours.options.headers[LEGACY_HOST_HEADER]),
1048
+ ...typeof ours.options.cloudUrl === "string" ? { gateway: ours.options.cloudUrl } : {},
1049
+ signingKey: await statusSigningKey(dirname4(config)),
1050
+ ...await statusHeldBundle(dirname4(config))
1051
+ };
1052
+ }
1053
+ async function statusHeldBundle(configDir) {
1054
+ const held = await readPipeUpdate(configDir);
1055
+ if (held === undefined || held instanceof Error)
1056
+ return {};
1057
+ return { heldBundle: { from: held.from, toVersion: held.toVersion, connected: await readPipeConnected(configDir) === held.toVersion } };
1058
+ }
1059
+ async function statusSigningKey(configDir) {
1060
+ const read = await readHostSigningKey(configDir);
1061
+ if (read.state === "ok")
1062
+ return { state: "ok", keyId: read.key.trusted.keyId, publicKey: read.key.trusted.publicKey };
1063
+ return read;
1064
+ }
1065
+ function signingKeyLine(key) {
1066
+ if (key === undefined || key.state === "missing")
1067
+ return "(made on this host's first start)";
1068
+ if (key.state === "unreadable")
1069
+ return `unreadable: ${key.reason}`;
1070
+ return `${key.keyId} public ${key.publicKey} (another machine trusts it with: hightea host trust add <name> ${key.publicKey})`;
1071
+ }
1072
+ function versionNote(bundleVersion, cliVersion) {
1073
+ if (bundleVersion === undefined)
1074
+ return "";
1075
+ return bundleVersion === cliVersion ? `, version ${bundleVersion}` : `, version ${bundleVersion}; this CLI is ${cliVersion}`;
1076
+ }
1077
+ async function hostStatus2(options) {
1078
+ let claimsDirectory;
1079
+ try {
1080
+ claimsDirectory = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
1081
+ } catch {
1082
+ console.error(`HOST_STATUS_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}`);
1083
+ return 1;
1084
+ }
1085
+ let names = [];
1086
+ try {
1087
+ names = (await readdir(claimsDirectory)).filter((name) => !name.startsWith(".")).sort();
1088
+ } catch (error) {
1089
+ const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1090
+ if (!missing) {
1091
+ console.error(`HOST_STATUS_UNREADABLE: cannot list ${claimsDirectory}`);
1092
+ return 1;
1093
+ }
1094
+ }
1095
+ const entries = await Promise.all(names.map((name) => readStatusEntry(join7(claimsDirectory, name))));
1096
+ if (options.json)
1097
+ console.log(JSON.stringify({ version: options.version, claims: claimsDirectory, hosts: entries }, null, 2));
1098
+ else {
1099
+ for (const entry of entries) {
1100
+ if (entry.state === "pending")
1101
+ console.log(`pending ${entry.claim} (registration not finished; rerun the same join command)`);
1102
+ else if (entry.state === "unreadable")
1103
+ console.log(`unreadable ${entry.config}`);
1104
+ else
1105
+ console.log([
1106
+ `joined workspace ${entry.workspaceId} host ${entry.hostId}`,
1107
+ ` gateway ${entry.gateway ?? "(none)"}`,
1108
+ ` config ${entry.config}`,
1109
+ ` start ${entry.start}`,
1110
+ ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`,
1111
+ ` key ${signingKeyLine(entry.signingKey)}`,
1112
+ ...entry.heldBundle === undefined ? [] : [` held ${entry.heldBundle.from} until this host connects at ${entry.heldBundle.toVersion}${entry.heldBundle.connected ? " (it has; the next `hightea host update` removes it)" : ""}`]
1113
+ ].join(`
1114
+ `));
1115
+ }
1116
+ }
1117
+ const broken = entries.filter((entry) => entry.state === "joined" && entry.bundle !== "ok");
1118
+ for (const entry of broken) {
1119
+ const why = entry.bundle === "missing" ? "is missing" : entry.bundle === "corrupt" ? "does not match its recorded hash" : `records version ${entry.pluginVersion}, not the version its directory names`;
1120
+ const cure = entry.bundle === "wrong-version" ? "Restore the bundle that directory name records, or re-join with a new code to install this CLI's bundle." : "Re-join with a new code to install this version's bundle.";
1121
+ console.error(`HOST_STATUS_PLUGIN_BUNDLE: the plugin bundle ${entry.pluginBundle} ${why}; the host cannot load it. ${cure}`);
1122
+ }
1123
+ if (broken.length > 0)
1124
+ return 2;
1125
+ if (entries.some((entry) => entry.state === "unreadable")) {
1126
+ console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged.");
1127
+ return 1;
1128
+ }
1129
+ if (!entries.some((entry) => entry.state === "joined")) {
1130
+ console.error(`HOST_STATUS_NONE: no joined host under ${claimsDirectory}.`);
1131
+ return 1;
1132
+ }
1133
+ return 0;
1134
+ }
1135
+ var JOINED_GRANTS = ["session:write", "session:state", "session:list", "chat:turns", "agent:list"];
1136
+ var SERVICES_GRANTS = [
1137
+ "service:watch",
1138
+ "service:logs",
1139
+ "service:put",
1140
+ "service:remove",
1141
+ "service:start",
1142
+ "service:stop",
1143
+ "service:restart",
1144
+ "service:accept"
1145
+ ];
1146
+ var RETIRED_SERVICES_GRANTS = ["services:list", "services:get", "services:put", "services:delete", "services:control"];
1147
+ async function localHost2(host) {
1148
+ let claims;
1149
+ try {
1150
+ claims = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
1151
+ } catch {
1152
+ return { error: `SERVICE_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}` };
1153
+ }
1154
+ let names = [];
1155
+ try {
1156
+ names = (await readdir(claims)).filter((name) => !name.startsWith(".")).sort();
1157
+ } catch (error) {
1158
+ const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1159
+ if (!missing)
1160
+ return { error: `SERVICE_HOST_UNREADABLE: cannot list ${claims}` };
1161
+ }
1162
+ const entries = await Promise.all(names.map((name) => readStatusEntry(join7(claims, name))));
1163
+ const joined = entries.filter((entry) => entry.state === "joined");
1164
+ const wanted = host?.trim();
1165
+ if (wanted !== undefined && wanted !== "") {
1166
+ const named = joined.find((entry) => entry.hostId === wanted);
1167
+ if (named === undefined) {
1168
+ return { error: `SERVICE_HOST_UNKNOWN: no joined host ${wanted} on this machine (joined here: ${joined.map((entry) => entry.hostId).join(", ") || "none"})` };
1169
+ }
1170
+ return toLocalHost(named);
1171
+ }
1172
+ if (joined.length === 0) {
1173
+ const unreadable = entries.find((entry) => entry.state === "unreadable");
1174
+ return { error: unreadable === undefined ? `SERVICE_NO_HOST: no joined host under ${claims}; join this machine with \`hightea host join\` first` : `SERVICE_HOST_UNREADABLE: ${unreadable.config} could not be read; it was left unchanged` };
1175
+ }
1176
+ if (joined.length > 1) {
1177
+ return { error: `SERVICE_HOST_AMBIGUOUS: this machine holds ${joined.length} joined hosts (${joined.map((entry) => entry.hostId).join(", ")}); name one with --host <id>` };
1178
+ }
1179
+ return toLocalHost(joined[0]);
1180
+ }
1181
+ function toLocalHost(entry) {
1182
+ const config = entry.config;
1183
+ return {
1184
+ claim: entry.claim,
1185
+ configDir: dirname4(config),
1186
+ config,
1187
+ workspaceId: entry.workspaceId,
1188
+ hostId: entry.hostId,
1189
+ ...entry.gateway === undefined ? {} : { gateway: entry.gateway }
1190
+ };
1191
+ }
1192
+ async function runningAhpds2(proc = "/proc") {
1193
+ let entries;
1194
+ try {
1195
+ entries = await readdir(proc);
1196
+ } catch {
1197
+ return [];
1198
+ }
1199
+ const rows = [];
1200
+ const seen = new Set;
1201
+ for (const entry of entries) {
1202
+ if (!/^\d+$/u.test(entry))
1203
+ continue;
1204
+ let argv;
1205
+ try {
1206
+ argv = (await readFile3(join7(proc, entry, "cmdline"), "utf8")).split("\x00").filter((part) => part !== "");
1207
+ } catch {
1208
+ continue;
1209
+ }
1210
+ const at = argv.indexOf("--config-file");
1211
+ const config = at < 0 ? undefined : argv[at + 1];
1212
+ if (config === undefined || !isAbsolute3(config) || seen.has(config))
1213
+ continue;
1214
+ seen.add(config);
1215
+ const configDir = dirname4(config);
1216
+ const flag = (name) => {
1217
+ const found = argv.indexOf(name);
1218
+ const value = found < 0 ? undefined : argv[found + 1];
1219
+ return value === undefined || value === "" ? undefined : value;
1220
+ };
1221
+ const portText = flag("--port");
1222
+ const port = portText !== undefined && /^\d{1,5}$/u.test(portText) ? Number(portText) : undefined;
1223
+ const connectionTokenFile = flag("--connection-token-file");
1224
+ const host = flag("--host") ?? "127.0.0.1";
1225
+ rows.push({
1226
+ pid: Number(entry),
1227
+ config,
1228
+ configDir,
1229
+ hostIds: await hostIdsIn(config),
1230
+ host,
1231
+ ...port === undefined ? {} : { port },
1232
+ ...connectionTokenFile === undefined ? {} : { connectionTokenFile }
1233
+ });
1234
+ }
1235
+ return rows;
1236
+ }
1237
+ async function hostIdsIn(config) {
1238
+ let parsed;
1239
+ try {
1240
+ parsed = JSON.parse(await readFile3(config, "utf8"));
1241
+ } catch {
1242
+ return [];
1243
+ }
1244
+ if (!isRecord3(parsed) || !Array.isArray(parsed.plugins))
1245
+ return [];
1246
+ const ids = new Set;
1247
+ for (const entry of parsed.plugins) {
1248
+ if (!isRecord3(entry) || !isRecord3(entry.options) || !isRecord3(entry.options.headers))
1249
+ continue;
1250
+ const named = entry.options.headers[HOST_HEADER] ?? entry.options.headers[LEGACY_HOST_HEADER];
1251
+ if (typeof named === "string" && named !== "")
1252
+ ids.add(named);
1253
+ }
1254
+ return [...ids];
1255
+ }
1256
+ async function hostServicesGrants2(options) {
1257
+ const found = await localHost2(options.host);
1258
+ if ("error" in found) {
1259
+ console.error(found.error);
1260
+ return 1;
1261
+ }
1262
+ const read = readJsonObject3(found.config);
1263
+ if (!read.ok) {
1264
+ console.error(`SERVICE_CONFIG_UNREADABLE: ${found.config} could not be read as a JSON object; it was left unchanged`);
1265
+ return 1;
1266
+ }
1267
+ const plugins = Array.isArray(read.value.plugins) ? read.value.plugins : [];
1268
+ const at = plugins.findIndex(isHighteaPipeEntry);
1269
+ const ours = plugins[at];
1270
+ if (ours === undefined) {
1271
+ console.error(`SERVICE_CONFIG_UNREADABLE: ${found.config} holds no Hightea plugin entry; it was left unchanged`);
1272
+ return 1;
1273
+ }
1274
+ if (ours.grants !== undefined && !(Array.isArray(ours.grants) && ours.grants.every((grant) => typeof grant === "string"))) {
1275
+ console.error(`SERVICE_CONFIG_UNREADABLE: the Hightea plugin entry's grants in ${found.config} are not a list of grants; it was left unchanged`);
1276
+ return 1;
1277
+ }
1278
+ const held = ours.grants ?? [];
1279
+ const services = [...SERVICES_GRANTS, ...RETIRED_SERVICES_GRANTS];
1280
+ const retired = RETIRED_SERVICES_GRANTS;
1281
+ const kept = held.filter((grant) => !retired.includes(grant));
1282
+ const grants = options.enable ? [...kept, ...SERVICES_GRANTS.filter((grant) => !kept.includes(grant))] : held.filter((grant) => !services.includes(grant));
1283
+ const what = `Hightea managing this machine's services (host ${found.hostId})`;
1284
+ if (grants.length === held.length && grants.every((grant, index) => grant === held[index])) {
1285
+ console.log(`${what} is already ${options.enable ? "enabled" : "disabled"}; ${found.config} was left unchanged.`);
1286
+ return 0;
1287
+ }
1288
+ const next = plugins.slice();
1289
+ next[at] = { ...ours, grants };
1290
+ try {
1291
+ writeJsonAtomic2(found.config, { ...read.value, plugins: next }, { mode: 384 });
1292
+ } catch (error) {
1293
+ console.error(`SERVICE_CONFIG_UNWRITABLE: ${found.config}: ${error.message}`);
1294
+ return 1;
1295
+ }
1296
+ console.log(`${what} is now ${options.enable ? "enabled" : "disabled"}: ${options.enable ? "added" : "removed"} ${SERVICES_GRANTS.join(", ")} in ${found.config}.`);
1297
+ console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${hostStartCommand(found.claim)}`);
1298
+ return 0;
1299
+ }
1300
+ function versionParts(version) {
1301
+ const match = /^(\d+)\.(\d+)\.(\d+)(-dev\.[0-9a-f]{8})?$/u.exec(version);
1302
+ return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3]), match[4] === undefined ? 1 : 0];
1303
+ }
1304
+ function compareVersions(a, b) {
1305
+ for (let index = 0;index < 4; index++)
1306
+ if (a[index] !== b[index])
1307
+ return a[index] - b[index];
1308
+ return 0;
1309
+ }
1310
+ var PIPE_UPDATE_FILE = "pipe-update.json";
1311
+ var PIPE_CONNECTED_FILE = "pipe-connected.json";
1312
+ async function readPipeUpdate(configDir) {
1313
+ let text;
1314
+ try {
1315
+ text = await readFile3(join7(configDir, PIPE_UPDATE_FILE), "utf8");
1316
+ } catch (error) {
1317
+ return isRecord3(error) && error.code === "ENOENT" ? undefined : new Error(`cannot read ${join7(configDir, PIPE_UPDATE_FILE)}`);
1318
+ }
1319
+ let value;
1320
+ try {
1321
+ value = JSON.parse(text);
1322
+ } catch {
1323
+ return new Error(`${join7(configDir, PIPE_UPDATE_FILE)} is not JSON`);
1324
+ }
1325
+ if (!isRecord3(value) || typeof value.from !== "string" || typeof value.to !== "string" || typeof value.fromVersion !== "string" || typeof value.toVersion !== "string" || typeof value.at !== "string")
1326
+ return new Error(`${join7(configDir, PIPE_UPDATE_FILE)} is not an update record`);
1327
+ return { from: value.from, to: value.to, fromVersion: value.fromVersion, toVersion: value.toVersion, at: value.at };
1328
+ }
1329
+ async function readPipeConnected(configDir) {
1330
+ try {
1331
+ const value = JSON.parse(await readFile3(join7(configDir, PIPE_CONNECTED_FILE), "utf8"));
1332
+ return isRecord3(value) && typeof value.version === "string" ? value.version : undefined;
1333
+ } catch {
1334
+ return;
1335
+ }
1336
+ }
1337
+ async function machineEntries() {
1338
+ let claims;
1339
+ try {
1340
+ claims = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
1341
+ } catch {
1342
+ return { error: `HOST_UPDATE_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}` };
1343
+ }
1344
+ let names;
1345
+ try {
1346
+ names = (await readdir(claims)).filter((name) => !name.startsWith(".")).sort();
1347
+ } catch {
1348
+ return { error: `HOST_UPDATE_HOST_UNREADABLE: cannot list ${claims}` };
1349
+ }
1350
+ return { claims, entries: await Promise.all(names.map((name) => readStatusEntry(join7(claims, name)))) };
1351
+ }
1352
+ async function prunableBundleDirectory(held, entries) {
1353
+ let directory;
1354
+ let root;
1355
+ try {
1356
+ directory = await realpath2(dirname4(held.from));
1357
+ } catch {
1358
+ return { refused: "it cannot be resolved" };
1359
+ }
1360
+ try {
1361
+ root = await realpath2(pluginBundleRoot(xdgHome("XDG_DATA_HOME", join7(".local", "share"))));
1362
+ } catch {
1363
+ return { refused: "the plugin bundles root cannot be resolved" };
1364
+ }
1365
+ if (dirname4(directory) !== root)
1366
+ return { refused: `it is not directly under the plugin bundles root ${root}` };
1367
+ if (basename(directory) !== held.fromVersion)
1368
+ return { refused: `it is not the bundle directory of version ${held.fromVersion}` };
1369
+ for (const entry of entries) {
1370
+ if (entry.pluginBundle === undefined)
1371
+ continue;
1372
+ let named;
1373
+ try {
1374
+ named = await realpath2(dirname4(entry.pluginBundle));
1375
+ } catch {
1376
+ continue;
1377
+ }
1378
+ if (named === directory)
1379
+ return { refused: `${entry.config} names it now` };
1380
+ }
1381
+ return { directory };
1382
+ }
1383
+ async function pruneHeldBundle(found) {
1384
+ const held = await readPipeUpdate(found.configDir);
1385
+ if (held === undefined)
1386
+ return;
1387
+ if (held instanceof Error) {
1388
+ console.error(`HOST_UPDATE_RECORD_UNREADABLE: ${held.message}; no bundle was removed`);
1389
+ return;
1390
+ }
1391
+ const connected = await readPipeConnected(found.configDir);
1392
+ if (connected !== held.toVersion) {
1393
+ console.log(`Keeping the previous plugin bundle ${dirname4(held.from)} until this host connects at ${held.toVersion}; restart it with: ${hostStartCommand(found.claim)}`);
1394
+ return;
1395
+ }
1396
+ const machine = await machineEntries();
1397
+ if ("error" in machine) {
1398
+ console.error(`${machine.error}; the previous bundle ${dirname4(held.from)} was kept`);
1399
+ return;
1400
+ }
1401
+ const users = machine.entries.filter((entry) => entry.pluginBundle === held.from || entry.state === "unreadable");
1402
+ if (users.length > 0) {
1403
+ console.log(`Keeping the previous plugin bundle ${dirname4(held.from)}: ${users.map((entry) => entry.state === "unreadable" ? `${entry.config} (unreadable)` : entry.config).join(", ")} may still name it.`);
1404
+ return;
1405
+ }
1406
+ const target = await prunableBundleDirectory(held, machine.entries);
1407
+ if ("refused" in target) {
1408
+ console.error(`HOST_UPDATE_PRUNE_REFUSED: ${dirname4(held.from)}: ${target.refused}; nothing was removed`);
1409
+ return;
1410
+ }
1411
+ try {
1412
+ await rm4(target.directory, { recursive: true, force: true });
1413
+ await rm4(join7(found.configDir, PIPE_UPDATE_FILE), { force: true });
1414
+ } catch (error) {
1415
+ console.error(`HOST_UPDATE_PRUNE_FAILED: ${dirname4(held.from)}: ${error.message}`);
1416
+ return;
1417
+ }
1418
+ console.log(`Removed the previous plugin bundle ${dirname4(held.from)} (${held.fromVersion}); this host has connected at ${held.toVersion}.`);
1419
+ }
1420
+ async function hostUpdate2(options, plugin) {
1421
+ const found = await localHost2(options.host);
1422
+ if ("error" in found) {
1423
+ console.error(found.error.replace(/^SERVICE_/u, "HOST_UPDATE_"));
1424
+ return 1;
1425
+ }
1426
+ const read = readJsonObject3(found.config);
1427
+ if (!read.ok) {
1428
+ console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${found.config} could not be read as a JSON object; it was left unchanged`);
1429
+ return 1;
1430
+ }
1431
+ const plugins = Array.isArray(read.value.plugins) ? read.value.plugins : [];
1432
+ const at = plugins.findIndex(isHighteaPipeEntry);
1433
+ const ours = plugins[at];
1434
+ if (ours === undefined || typeof ours.source !== "string") {
1435
+ console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${found.config} holds no Hightea plugin entry with a source; it was left unchanged`);
1436
+ return 1;
1437
+ }
1438
+ const installed = await readInstalledBundle(ours.source);
1439
+ if (!installed.ok) {
1440
+ console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${ours.source} is ${installed.reason}; nothing changed. \`hightea host status\` names the repair.`);
1441
+ return 1;
1442
+ }
1443
+ const from = installed.bundle.version;
1444
+ const fromParts = versionParts(from);
1445
+ const toParts = versionParts(plugin.version);
1446
+ if (fromParts === undefined || toParts === undefined) {
1447
+ console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${from} against this CLI's ${plugin.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`);
1448
+ return 1;
1449
+ }
1450
+ const order = compareVersions(toParts, fromParts) || (plugin.version === from ? 0 : 1);
1451
+ if (order < 0) {
1452
+ console.error(`HOST_UPDATE_DOWNGRADE: host ${found.hostId} runs plugin bundle ${from}, newer than this CLI's ${plugin.version}; nothing changed. Update the CLI instead.`);
1453
+ return 1;
1454
+ }
1455
+ if (order === 0) {
1456
+ console.log(`Host ${found.hostId} already runs plugin bundle ${from}; ${found.config} was left unchanged.`);
1457
+ await pruneHeldBundle(found);
1458
+ return 0;
1459
+ }
1460
+ await pruneHeldBundle(found);
1461
+ let bundle;
1462
+ try {
1463
+ bundle = await installPluginBundle(xdgHome("XDG_DATA_HOME", join7(".local", "share")), plugin.directory, plugin.version);
1464
+ } catch (error) {
1465
+ const code = error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message) ? error.message : "HOST_JOIN_CONFIG_IO";
1466
+ console.error(`${code.replace(/^HOST_JOIN_/u, "HOST_UPDATE_")}: ${DIAGNOSTICS[code] ?? "the new bundle could not be installed"} ${found.config} was left unchanged.`);
1467
+ return 1;
1468
+ }
1469
+ const record = { from: ours.source, to: bundle.manifest, fromVersion: from, toVersion: bundle.version, at: new Date().toISOString() };
1470
+ const next = plugins.slice();
1471
+ const held = Array.isArray(ours.grants) ? ours.grants.filter((one) => typeof one === "string") : [];
1472
+ const missing = JOINED_GRANTS.filter((grant) => !held.includes(grant));
1473
+ next[at] = { ...ours, source: bundle.manifest, ...missing.length === 0 ? {} : { grants: [...held, ...missing] } };
1474
+ try {
1475
+ writeJsonAtomic2(join7(found.configDir, PIPE_UPDATE_FILE), record, { mode: 384 });
1476
+ writeJsonAtomic2(found.config, { ...read.value, plugins: next }, { mode: 384 });
1477
+ } catch (error) {
1478
+ console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${found.config}: ${error.message}`);
1479
+ return 1;
1480
+ }
1481
+ console.log(`Host ${found.hostId} now loads plugin bundle ${bundle.version} (was ${from}), same host id and credentials; ${found.config} changed only its source${missing.length === 0 ? "" : ` and added the missing ${missing.join(", ")} grants`}.`);
1482
+ console.log(`The previous bundle ${dirname4(ours.source)} is kept until the host connects at ${bundle.version}. Restart it with: ${hostStartCommand(found.claim)}`);
1483
+ return 0;
1484
+ }
1485
+ function requiredAgentMember(agentMemberId) {
1486
+ if (agentMemberId === undefined || agentMemberId === "")
1487
+ throw new Error("HOST_JOIN_RECEIPT_INVALID");
1488
+ return agentMemberId;
1489
+ }
1490
+
1491
+ export { TRUSTED_KEY_NAME, trustedKeyId, readTrustedKeys, hostJoin2, hostStatus2, localHost2, runningAhpds2, hostServicesGrants2, hostUpdate2 };