@hallohuman/hightea-ahp-host 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,582 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ string,
4
+ array,
5
+ object,
6
+ union,
7
+ _enum,
8
+ literal
9
+ } from "./chunk-7eha6eh3.js";
10
+
11
+ // src/cli.ts
12
+ import { homedir } from "node:os";
13
+ import { isAbsolute as isAbsolute2, join as join4, resolve } from "node:path";
14
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
15
+ import { parseArgs } from "node:util";
16
+ import { fromEnvRef as fromEnvRef2, isRecord as isRecord3, readSecret, secretRef as secretRef2 } from "@ahpd/sdk";
17
+ import { fileVault as fileVault2 } from "@ahpd/server/dist/vault.js";
18
+ // package.json
19
+ var package_default = {
20
+ name: "@hallohuman/hightea-ahp-host",
21
+ version: "0.0.1",
22
+ publishConfig: { access: "public" },
23
+ type: "module",
24
+ exports: {
25
+ ".": "./dist/index.js",
26
+ "./plugin": "./dist/plugin.js"
27
+ },
28
+ bin: { hightea: "./dist/bin.js" },
29
+ files: ["dist", "plugin.json"],
30
+ engines: { node: ">=26.13.1" },
31
+ scripts: { build: "bun build.ts", prepack: "bun run build" },
32
+ dependencies: {
33
+ "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/turnid-fix-3c0500e36c28/ahpd-sdk-0.15.0-rc.4-beorn.3c0500e36c28.tgz",
34
+ "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/turnid-fix-3c0500e36c28/ahpd-server-0.15.0-rc.4-beorn.3c0500e36c28.tgz",
35
+ ws: "8.21.0"
36
+ },
37
+ devDependencies: {
38
+ "@hallohuman/hightea-ahp": "workspace:*",
39
+ "@hallohuman/hightea-members": "workspace:*",
40
+ "@types/ws": "8.18.2"
41
+ }
42
+ };
43
+
44
+ // src/claim.ts
45
+ import { createHash, randomBytes } from "node:crypto";
46
+ import { constants } from "node:fs";
47
+ import { link, lstat, mkdir, mkdtemp, open, realpath, rm } from "node:fs/promises";
48
+ import { dirname, join } from "node:path";
49
+ import { isDeepStrictEqual } from "node:util";
50
+ import { fileVault } from "@ahpd/server/dist/vault.js";
51
+ // ../members/src/members-store.ts
52
+ var DEFAULT_SESSION_TTL_MS = 30 * 86400000;
53
+ // ../members/src/host-join-types.ts
54
+ var id = string().min(1).max(256);
55
+ var digest = string().regex(/^sha256:[a-f0-9]{64}$/u);
56
+ var version = string().min(1).max(64);
57
+ var HostJoinRedemptionSchema = object({ code: string(), credentialHash: digest, pluginVersion: version, ahpdVersion: version }).strict();
58
+ var HostJoinCommandSchema = object({
59
+ workspaceId: id,
60
+ hostId: id,
61
+ ownerAccountId: id,
62
+ credentialHash: digest,
63
+ agentMemberIds: array(id),
64
+ pluginVersion: version,
65
+ ahpdVersion: version,
66
+ registrationFingerprint: digest
67
+ }).strict();
68
+ var HostJoinGatewayReceiptSchema = object({ workspaceId: id, hostId: id, registrationFingerprint: digest, state: _enum(["registered", "cancelled"]) }).strict();
69
+ var HostJoinGatewayResultSchema = union([
70
+ object({ ok: literal(true), value: HostJoinGatewayReceiptSchema }).strict(),
71
+ object({ ok: literal(false), code: _enum(["HOST_REGISTRATION_CONFLICT", "AGENT_HOST_CONFLICT", "HOST_REGISTRATION_MISSING"]), message: string() }).strict()
72
+ ]);
73
+ var HostJoinEffectSchema = union([
74
+ object({ kind: literal("register"), command: HostJoinCommandSchema }).strict(),
75
+ object({ kind: literal("cancel"), cancellation: union([
76
+ object({ kind: literal("pending"), command: HostJoinCommandSchema }).strict(),
77
+ object({ kind: literal("registered"), receipt: HostJoinGatewayReceiptSchema }).strict()
78
+ ]) }).strict()
79
+ ]);
80
+
81
+ // ../members/src/join-links.ts
82
+ var JOIN_LINK_TTL_MS = 15 * 60000;
83
+ var CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
84
+ var CODE_LENGTH = 12;
85
+ function normalizeJoinCode(input) {
86
+ const code = input.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1");
87
+ if (code.length !== CODE_LENGTH)
88
+ return null;
89
+ for (const symbol of code)
90
+ if (!CODE_ALPHABET.includes(symbol))
91
+ return null;
92
+ return code;
93
+ }
94
+
95
+ // ../members/src/workspace-directory.ts
96
+ var RESERVED_WORKSPACE_SLUGS = new Set([
97
+ "www",
98
+ "app",
99
+ "api",
100
+ "mcp",
101
+ "ahp",
102
+ "pages",
103
+ "share",
104
+ "host",
105
+ "docs",
106
+ "admin",
107
+ "status",
108
+ "mail"
109
+ ]);
110
+
111
+ // ../members/src/auth-routes.ts
112
+ var HIGHTEA_SESSION_COOKIE = "ht_session";
113
+ var HIGHTEA_STATE_COOKIE = "ht_auth_state";
114
+ var CLEAR_STATE_COOKIE = `${HIGHTEA_STATE_COOKIE}=; Path=/auth; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
115
+ var CLEAR_SESSION_COOKIE = `${HIGHTEA_SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
116
+ // ../../node_modules/.bun/hono@4.13.19/node_modules/hono/dist/utils/jwt/utf8.js
117
+ var utf8Encoder = new TextEncoder;
118
+ var utf8Decoder = new TextDecoder;
119
+
120
+ // ../members/src/mcp-oauth.ts
121
+ var AGENT_LAST_SEEN_INTERVAL_MS = 5 * 60000;
122
+ // ../members/src/agent-token.ts
123
+ var AGENT_TOKEN_TTL_MS = 15 * 60 * 1000;
124
+ // src/claim.ts
125
+ function refusal(code) {
126
+ throw new Error(code);
127
+ }
128
+ function errorCode(error) {
129
+ return error !== null && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
130
+ }
131
+ async function privateHostDirectory(path) {
132
+ await mkdir(path, { mode: 448 }).catch((error) => {
133
+ if (errorCode(error) !== "EEXIST")
134
+ refusal("HOST_JOIN_CUSTODY_IO");
135
+ });
136
+ const stat = await lstat(path);
137
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 63) !== 0) {
138
+ refusal("HOST_JOIN_UNSAFE_PATH");
139
+ }
140
+ }
141
+ async function flushDirectory(path) {
142
+ const directory = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
143
+ try {
144
+ await directory.sync();
145
+ } finally {
146
+ await directory.close();
147
+ }
148
+ }
149
+ async function flushHostFile(path) {
150
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
151
+ try {
152
+ await file.sync();
153
+ } finally {
154
+ await file.close();
155
+ }
156
+ for (let directory = dirname(path);; directory = dirname(directory)) {
157
+ await flushDirectory(directory);
158
+ if (directory === dirname(directory))
159
+ break;
160
+ }
161
+ }
162
+ function canonicalIntent(input) {
163
+ if (typeof input.origin !== "string" || typeof input.workspaceSlug !== "string" || typeof input.code !== "string" || typeof input.pluginVersion !== "string" || typeof input.ahpdVersion !== "string")
164
+ refusal("HOST_JOIN_INVALID_INTENT");
165
+ let origin;
166
+ try {
167
+ origin = new URL(input.origin);
168
+ } catch {
169
+ return refusal("HOST_JOIN_INVALID_INTENT");
170
+ }
171
+ const code = normalizeJoinCode(input.code);
172
+ 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)
173
+ refusal("HOST_JOIN_INVALID_INTENT");
174
+ let ownerConfiguration;
175
+ try {
176
+ ownerConfiguration = JSON.parse(JSON.stringify(input.ownerConfiguration));
177
+ } catch {
178
+ return refusal("HOST_JOIN_INVALID_INTENT");
179
+ }
180
+ if (ownerConfiguration === null || typeof ownerConfiguration !== "object" || !isDeepStrictEqual(ownerConfiguration, input.ownerConfiguration))
181
+ refusal("HOST_JOIN_INVALID_INTENT");
182
+ return { ...input, origin: origin.origin, code, ownerConfiguration };
183
+ }
184
+ async function selectHostClaim(configHome, input) {
185
+ const requested = canonicalIntent(input);
186
+ let root;
187
+ try {
188
+ await mkdir(configHome, { recursive: true, mode: 448 });
189
+ const stat = await lstat(configHome);
190
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 18) !== 0)
191
+ refusal("HOST_JOIN_UNSAFE_PATH");
192
+ root = await realpath(configHome);
193
+ } catch {
194
+ return refusal("HOST_JOIN_UNSAFE_PATH");
195
+ }
196
+ const application = join(root, "hightea");
197
+ const claims = join(application, "claims");
198
+ const scope = createHash("sha256").update(JSON.stringify([requested.origin, requested.workspaceSlug, requested.code])).digest("hex");
199
+ const home = join(claims, scope);
200
+ const daemon = join(home, "ahpd");
201
+ try {
202
+ for (const directory of [application, claims, home, daemon])
203
+ await privateHostDirectory(directory);
204
+ const vaultFile = join(daemon, "vault.json");
205
+ const candidate = await mkdtemp(join(daemon, ".claim-"));
206
+ try {
207
+ const candidateVault = join(candidate, "vault.json");
208
+ const vault = fileVault({ file: candidateVault });
209
+ await vault.set("host:hightea", `Bearer ${randomBytes(32).toString("base64url")}`);
210
+ await vault.set("host:hightea-join", JSON.stringify({ schema: 1, ...requested }));
211
+ try {
212
+ await link(candidateVault, vaultFile);
213
+ } catch (error) {
214
+ if (errorCode(error) !== "EEXIST")
215
+ refusal("HOST_JOIN_CUSTODY_PUBLICATION_FAILED");
216
+ }
217
+ const stat = await lstat(vaultFile);
218
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 384)
219
+ refusal("HOST_JOIN_UNSAFE_PATH");
220
+ const selected = fileVault({ file: vaultFile });
221
+ const authorization = await selected.get("host:hightea");
222
+ const saved = await selected.get("host:hightea-join");
223
+ if (!authorization || !/^Bearer [A-Za-z0-9_-]{43}$/u.test(authorization) || !saved)
224
+ refusal("HOST_JOIN_CLAIM_CORRUPT");
225
+ let metadata;
226
+ try {
227
+ metadata = JSON.parse(saved);
228
+ } catch {
229
+ return refusal("HOST_JOIN_CLAIM_CORRUPT");
230
+ }
231
+ if (!metadata || typeof metadata !== "object" || !("schema" in metadata) || metadata.schema !== 1)
232
+ refusal("HOST_JOIN_CLAIM_CORRUPT");
233
+ let original;
234
+ try {
235
+ original = canonicalIntent(metadata);
236
+ } catch {
237
+ return refusal("HOST_JOIN_CLAIM_CORRUPT");
238
+ }
239
+ if (original.origin !== requested.origin || original.workspaceSlug !== requested.workspaceSlug || original.code !== requested.code || !isDeepStrictEqual(original.ownerConfiguration, requested.ownerConfiguration))
240
+ refusal("HOST_JOIN_CLAIM_CONFLICT");
241
+ await flushHostFile(vaultFile);
242
+ return { home, vaultFile, authorization, credentialHash: createHash("sha256").update(authorization.slice(7), "utf8").digest("hex"), intent: original };
243
+ } finally {
244
+ await rm(candidate, { recursive: true });
245
+ }
246
+ } catch (error) {
247
+ if (error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message))
248
+ throw error;
249
+ return refusal("HOST_JOIN_CUSTODY_IO");
250
+ }
251
+ }
252
+
253
+ // src/configuration.ts
254
+ import { link as link2, lstat as lstat2, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
255
+ import { join as join2 } from "node:path";
256
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
257
+ import { isRecordSlug, readJsonObject, writeJsonAtomic } from "@ahpd/sdk";
258
+ async function saveHostConfiguration(claim, configuration) {
259
+ return saveHostJson(claim, join2(claim.home, "ahpd"), "config.json", configuration);
260
+ }
261
+ async function saveHostAgentRecord(claim, record) {
262
+ if (!isRecordSlug(record.id))
263
+ throw new Error("HOST_JOIN_CONFIG_CONFLICT");
264
+ const directory = join2(claim.home, "ahpd", "agents");
265
+ await privateHostDirectory(directory);
266
+ await saveHostJson(claim, directory, `${record.id}.json`, { ...record });
267
+ }
268
+ async function saveHostJson(claim, directory, name, configuration) {
269
+ const destination = join2(directory, name);
270
+ let candidate;
271
+ try {
272
+ if (JSON.stringify(configuration).includes(claim.authorization))
273
+ throw new Error("HOST_JOIN_CONFIG_SECRET");
274
+ candidate = await mkdtemp2(join2(directory, ".config-"));
275
+ const staged = join2(candidate, "config.json");
276
+ writeJsonAtomic(staged, configuration, { mode: 384 });
277
+ try {
278
+ await link2(staged, destination);
279
+ } catch (error) {
280
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
281
+ throw new Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED");
282
+ }
283
+ const stat = await lstat2(destination);
284
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 384)
285
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
286
+ const existing = readJsonObject(destination);
287
+ if (!existing.ok)
288
+ throw new Error("HOST_JOIN_CONFIG_CORRUPT");
289
+ const addApprovalDefault = name === "config.json" && configuration.unattendedAutoApprove === false && !Object.hasOwn(existing.value, "unattendedAutoApprove");
290
+ for (const [key, value] of Object.entries(configuration)) {
291
+ if (addApprovalDefault && key === "unattendedAutoApprove")
292
+ continue;
293
+ if (!isDeepStrictEqual2(existing.value[key], value))
294
+ throw new Error("HOST_JOIN_CONFIG_CONFLICT");
295
+ }
296
+ if (addApprovalDefault) {
297
+ writeJsonAtomic(destination, { ...existing.value, unattendedAutoApprove: false }, { mode: 384 });
298
+ }
299
+ await flushHostFile(destination);
300
+ return destination;
301
+ } catch (error) {
302
+ if (error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message))
303
+ throw error;
304
+ throw new Error("HOST_JOIN_CONFIG_IO");
305
+ } finally {
306
+ if (candidate !== undefined)
307
+ await rm2(candidate, { recursive: true });
308
+ }
309
+ }
310
+
311
+ // src/join.ts
312
+ import { isRecord } from "@ahpd/sdk";
313
+ async function redeemHostClaim(claim) {
314
+ await flushHostFile(claim.vaultFile);
315
+ const intent = claim.intent;
316
+ const request = new Request(`${intent.origin}/api/ws/${encodeURIComponent(intent.workspaceSlug)}/join/${encodeURIComponent(intent.code)}`, {
317
+ method: "POST",
318
+ redirect: "error",
319
+ headers: { "content-type": "application/json" },
320
+ signal: AbortSignal.timeout(1e4),
321
+ body: JSON.stringify({ credentialHash: claim.credentialHash, pluginVersion: intent.pluginVersion, ahpdVersion: intent.ahpdVersion })
322
+ });
323
+ let response;
324
+ try {
325
+ response = await fetch(request);
326
+ } catch {
327
+ throw new Error("HOST_JOIN_NETWORK_UNKNOWN");
328
+ }
329
+ if (response.status === 410) {
330
+ let error;
331
+ try {
332
+ error = await response.json();
333
+ } catch {}
334
+ if (isRecord(error) && isRecord(error.error) && error.error.code === "HOST_REGISTRATION_CANCELLED")
335
+ throw new Error("HOST_JOIN_CANCELLED");
336
+ throw new Error("HOST_JOIN_LINK_UNAVAILABLE");
337
+ }
338
+ if (response.status >= 500)
339
+ throw new Error("HOST_JOIN_REMOTE_UNAVAILABLE");
340
+ if (!response.ok)
341
+ throw new Error("HOST_JOIN_REJECTED");
342
+ let receipt;
343
+ try {
344
+ receipt = await response.json();
345
+ } catch {
346
+ throw new Error("HOST_JOIN_RECEIPT_INVALID");
347
+ }
348
+ 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")
349
+ throw new Error("HOST_JOIN_RECEIPT_INVALID");
350
+ return { workspaceId: receipt.workspaceId, hostId: receipt.hostId, state: receipt.state };
351
+ }
352
+
353
+ // src/owner.ts
354
+ import { access, stat } from "node:fs/promises";
355
+ import { constants as constants2 } from "node:fs";
356
+ import { delimiter, dirname as dirname2, isAbsolute, join as join3 } from "node:path";
357
+ import { fileURLToPath } from "node:url";
358
+ import { fromEnvRef, isRecord as isRecord2, isRecordSlug as isRecordSlug2, readJsonObject as readJsonObject2, scopeOf, secretPaths, secretRef } from "@ahpd/sdk";
359
+ import { checkManifest, checkStandalone, readManifest, readStandalone, resolvePlugin } from "@ahpd/server/dist/plugins.js";
360
+ function fail(code = "HOST_JOIN_OWNER_RESOURCE") {
361
+ throw new Error(code);
362
+ }
363
+ function reference(value) {
364
+ const variable = fromEnvRef(value);
365
+ if (variable !== undefined) {
366
+ if (!process.env[variable])
367
+ fail();
368
+ return true;
369
+ }
370
+ const secret = secretRef(value);
371
+ if (secret === undefined)
372
+ return false;
373
+ scopeOf(secret);
374
+ return true;
375
+ }
376
+ async function executable(command) {
377
+ const candidates = isAbsolute(command) ? [command] : (process.env.PATH ?? "").split(delimiter).map((path) => join3(path, command));
378
+ for (const candidate of candidates) {
379
+ try {
380
+ await access(candidate, constants2.X_OK);
381
+ if ((await stat(candidate)).isFile())
382
+ return;
383
+ } catch {}
384
+ }
385
+ fail();
386
+ }
387
+ async function readOwnerConfiguration(file) {
388
+ const read = readJsonObject2(file);
389
+ if (!read.ok)
390
+ fail("HOST_JOIN_OWNER_INPUT");
391
+ const body = read.value;
392
+ if (!Array.isArray(body.agents) || body.agents.length === 0 || !Array.isArray(body.plugins) || body.plugins.length === 0 || !Array.isArray(body.records))
393
+ fail();
394
+ const engines = new Set;
395
+ const direct = new Set;
396
+ const plugins = [];
397
+ try {
398
+ for (const value of body.plugins) {
399
+ const entry = typeof value === "string" ? { source: value } : value;
400
+ if (!isRecord2(entry) || typeof entry.source !== "string" || entry.enabled === false)
401
+ fail();
402
+ const spec = entry;
403
+ const resolved = resolvePlugin(spec, { cwd: dirname2(file), configDir: dirname2(file) });
404
+ if (!resolved.path || !(await stat(resolved.path)).isFile())
405
+ fail();
406
+ const manifest = resolved.manifestPath ? readStandalone(resolved.manifestPath) : resolved.packageDir ? readManifest(resolved.packageDir) : undefined;
407
+ if (!manifest || manifest.problem || (manifest.standalone ? checkStandalone(manifest) : checkManifest(manifest, resolved.packageDir)))
408
+ fail();
409
+ for (const name of manifest.contracts?.engines ?? [])
410
+ engines.add(name);
411
+ for (const name of manifest.contracts?.agents ?? [])
412
+ direct.add(name);
413
+ if (entry.options !== undefined && !isRecord2(entry.options))
414
+ fail();
415
+ const options = isRecord2(entry.options) ? entry.options : {};
416
+ for (const path of secretPaths(manifest.optionsSchema ?? {}, options)) {
417
+ let held = options;
418
+ for (const part of path.split("."))
419
+ held = isRecord2(held) ? held[part] : undefined;
420
+ if (held !== undefined && !reference(held))
421
+ fail("HOST_JOIN_OWNER_SECRET");
422
+ }
423
+ plugins.push({ ...entry, source: resolved.manifestPath ?? resolved.packageDir ?? resolved.path });
424
+ }
425
+ const records = [];
426
+ const providers = new Set(direct);
427
+ for (const record of body.records) {
428
+ 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")
429
+ fail();
430
+ if (record.model !== undefined && (typeof record.model !== "string" || record.model.trim() === ""))
431
+ fail();
432
+ if (record.engine === "acp" && typeof record.config.command !== "string")
433
+ fail();
434
+ if (record.config.command !== undefined) {
435
+ if (typeof record.config.command !== "string" || !record.config.command)
436
+ fail();
437
+ await executable(record.config.command);
438
+ }
439
+ if (record.config.env !== undefined) {
440
+ if (!isRecord2(record.config.env))
441
+ fail();
442
+ for (const value of Object.values(record.config.env))
443
+ if (!reference(value))
444
+ fail("HOST_JOIN_OWNER_SECRET");
445
+ }
446
+ providers.add(record.id);
447
+ records.push(record);
448
+ }
449
+ const agents = [];
450
+ const members = new Set;
451
+ for (const entry of body.agents) {
452
+ 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")
453
+ fail();
454
+ const work = new URL(entry[1].workingDirectory);
455
+ if (work.protocol !== "file:" || work.hostname || !(await stat(fileURLToPath(work))).isDirectory())
456
+ fail();
457
+ members.add(entry[0]);
458
+ agents.push([entry[0], { provider: entry[1].provider, workingDirectory: work.href }]);
459
+ }
460
+ return { agents, plugins, records };
461
+ } catch (error) {
462
+ if (error instanceof Error && /^HOST_JOIN_OWNER_[A-Z_]+$/u.test(error.message))
463
+ throw error;
464
+ return fail();
465
+ }
466
+ }
467
+
468
+ // src/cli.ts
469
+ var HELP = "hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json";
470
+ var DIAGNOSTICS = {
471
+ HOST_JOIN_USAGE: `Expected: ${HELP}`,
472
+ HOST_JOIN_INPUT: "Command input could not be read. Use --help for the supported options.",
473
+ HOST_JOIN_INVALID_INTENT: "Use an HTTPS deployment origin, workspace slug and valid join code.",
474
+ HOST_JOIN_OWNER_INPUT: "The --owner-config file must exist and contain a JSON object; its contents were not printed.",
475
+ HOST_JOIN_OWNER_RESOURCE: "Check the explicit agent mappings, provider plugins, working directories, executables and referenced credentials in --owner-config. No code was redeemed.",
476
+ HOST_JOIN_OWNER_SECRET: "Replace inline provider secrets with existing ahpd fromEnv or SecretRef values; the referenced resource must be available locally.",
477
+ HOST_JOIN_UNSAFE_PATH: "The selected configuration path must be owned by this user and private; symlinks and shared files are not used.",
478
+ HOST_JOIN_CLAIM_CONFLICT: "This claim already holds different deployment or owner settings. Keep its vault and use the original settings to resume.",
479
+ HOST_JOIN_CLAIM_CORRUPT: "The selected claim vault is invalid. Keep it for recovery; joining will not replace its credential.",
480
+ HOST_JOIN_NETWORK_UNKNOWN: "The registration result is unknown. Keep this claim and rerun the same command to recover its receipt.",
481
+ HOST_JOIN_REMOTE_UNAVAILABLE: "The deployment could not complete registration. Keep this claim and rerun the same command later.",
482
+ HOST_JOIN_CANCELLED: "The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",
483
+ HOST_JOIN_LINK_UNAVAILABLE: "This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",
484
+ HOST_JOIN_REJECTED: "The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",
485
+ HOST_JOIN_RECEIPT_INVALID: "The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",
486
+ HOST_JOIN_CONFIG_CONFLICT: "Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",
487
+ HOST_JOIN_CONFIG_CORRUPT: "Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it."
488
+ };
489
+ async function runHostCli(arguments_) {
490
+ try {
491
+ const parsed = parseArgs({ args: arguments_, allowPositionals: true, strict: true, options: {
492
+ origin: { type: "string" },
493
+ workspace: { type: "string" },
494
+ code: { type: "string" },
495
+ "owner-config": { type: "string" },
496
+ help: { type: "boolean" },
497
+ version: { type: "boolean" }
498
+ } });
499
+ if (parsed.values.help) {
500
+ console.log(HELP);
501
+ return 0;
502
+ }
503
+ if (parsed.values.version) {
504
+ console.log(package_default.version);
505
+ return 0;
506
+ }
507
+ const { origin, workspace, code } = parsed.values;
508
+ const ownerFile = parsed.values["owner-config"];
509
+ if (parsed.positionals.join(" ") !== "host join" || !origin || !workspace || !code || !ownerFile)
510
+ throw new Error("HOST_JOIN_USAGE");
511
+ const ownerConfiguration = await readOwnerConfiguration(resolve(ownerFile));
512
+ const configHome = process.env.XDG_CONFIG_HOME || join4(homedir(), ".config");
513
+ if (!isAbsolute2(configHome))
514
+ throw new Error("HOST_JOIN_UNSAFE_PATH");
515
+ const claim = await selectHostClaim(configHome, {
516
+ origin,
517
+ workspaceSlug: workspace,
518
+ code,
519
+ pluginVersion: package_default.version,
520
+ ahpdVersion: "0.15.0-rc.4",
521
+ ownerConfiguration
522
+ });
523
+ const vault = fileVault2({ file: claim.vaultFile });
524
+ const checkReferences = async (value) => {
525
+ const name = secretRef2(value);
526
+ const variable = fromEnvRef2(value);
527
+ if (variable !== undefined) {
528
+ if (!process.env[variable])
529
+ throw new Error("HOST_JOIN_OWNER_RESOURCE");
530
+ } else if (name !== undefined) {
531
+ try {
532
+ await readSecret(vault, name);
533
+ } catch {
534
+ throw new Error("HOST_JOIN_OWNER_RESOURCE");
535
+ }
536
+ } else if (Array.isArray(value)) {
537
+ for (const child of value)
538
+ await checkReferences(child);
539
+ } else if (isRecord3(value)) {
540
+ for (const child of Object.values(value))
541
+ await checkReferences(child);
542
+ }
543
+ };
544
+ await checkReferences(ownerConfiguration);
545
+ const receipt = await redeemHostClaim(claim);
546
+ if (receipt.state === "pending") {
547
+ console.log("Host registration pending. Run the same command again to resume.");
548
+ return 2;
549
+ }
550
+ for (const record of ownerConfiguration.records)
551
+ await saveHostAgentRecord(claim, record);
552
+ const cloud = new URL(`/gateway/${encodeURIComponent(receipt.workspaceId)}/host`, claim.intent.origin);
553
+ cloud.protocol = "wss:";
554
+ await saveHostConfiguration(claim, {
555
+ host: "127.0.0.1",
556
+ updateCheck: false,
557
+ httpApi: false,
558
+ modelApi: false,
559
+ mcpTools: "none",
560
+ unattendedAutoApprove: false,
561
+ plugins: [...ownerConfiguration.plugins, {
562
+ source: fileURLToPath2(new URL("../plugin.json", import.meta.url)),
563
+ grants: ["session:write", "session:state", "chat:turns"],
564
+ options: {
565
+ cloudUrl: cloud.href,
566
+ houseId: receipt.workspaceId,
567
+ agents: ownerConfiguration.agents,
568
+ headers: { "x-hightea-host": receipt.hostId, authorization: { $secret: "host:hightea" } }
569
+ }
570
+ }]
571
+ });
572
+ console.log("Host registered; local configuration saved. Daemon startup requires platform setup.");
573
+ return 0;
574
+ } catch (error) {
575
+ const code = error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message) ? error.message : "HOST_JOIN_INPUT";
576
+ 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."}`);
577
+ return 1;
578
+ }
579
+ }
580
+
581
+ // src/bin.ts
582
+ process.exitCode = await runHostCli(process.argv.slice(2));