@enhance-eng/enhance 0.1.6 → 0.1.13

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.
@@ -1,17 +1,70 @@
1
1
  #!/usr/bin/env node
2
- import { $ as downloadCanvasRenderOutputSchema, A as getPrototypePublishStatusOutputSchema, D as createPrototypeArtifactOutputSchema, E as attachPrototypeArtifactOutputSchema, G as getCanvasDocumentOutputSchema, H as applyCanvasOperationsOutputSchema, J as getCanvasConversionOutputSchema, M as prototypeArtifactPathSchema, N as submitPrototypeArtifactOutputSchema, O as foldPrototypeArtifactPath, Q as createRecordingSnapshotOutputSchema, T as PROTOTYPE_ARTIFACT_MANIFEST_PATH, Z as createCanvasRenderOutputSchema, _ as CliError, d as canvasWriteHtmlCapabilityInputSchema, et as getCanvasRenderOutputSchema, f as commentAttentionCapabilityInputSchema, g as PartialBatchError, h as transcriptReadCapabilityInputSchema, j as prototypeArtifactManifestSchema, k as getPrototypeArtifactCapabilitiesOutputSchema, l as canvasApplyCapabilityInputSchema, m as recordingSnapshotCapabilityInputSchema, p as prototypePublishCapabilityInputSchema, q as createCanvasConversionOutputSchema, tt as canvasSceneDocumentSchema, u as canvasRenderCapabilityInputSchema, v as transcriptOutputSchema, z as beginCanvasActivityOutputSchema } from "./failure.mapper-CNRVSTrf.mjs";
2
+ import { B as getMeOutputSchema, C as CliError, F as getPrototypeArtifactCapabilitiesOutputSchema, H as cliAuthConfigurationSchema, I as getPrototypePublishStatusOutputSchema, L as prototypeArtifactManifestSchema, M as attachPrototypeArtifactOutputSchema, N as createPrototypeArtifactOutputSchema, P as foldPrototypeArtifactPath, R as prototypeArtifactPathSchema, S as PartialBatchError, U as createAgentTokenOutputSchema, X as applyCanvasOperationsOutputSchema, _ as canvasWriteHtmlCapabilityInputSchema, b as recordingSnapshotCapabilityInputSchema, ct as downloadCanvasRenderOutputSchema, et as getCanvasDocumentOutputSchema, g as canvasRenderCapabilityInputSchema, h as canvasApplyCapabilityInputSchema, j as PROTOTYPE_ARTIFACT_MANIFEST_PATH, lt as getCanvasRenderOutputSchema, nt as createCanvasConversionOutputSchema, ot as createCanvasRenderOutputSchema, q as beginCanvasActivityOutputSchema, rt as getCanvasConversionOutputSchema, st as createRecordingSnapshotOutputSchema, ut as canvasReadableSceneDocumentSchema, v as commentAttentionCapabilityInputSchema, w as transcriptOutputSchema, x as transcriptReadCapabilityInputSchema, y as prototypePublishCapabilityInputSchema, z as submitPrototypeArtifactOutputSchema } from "./cli-output-identity.lib-DAJiBMGX.mjs";
3
3
  import { z } from "zod";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import process from "node:process";
6
6
  import { chmodSync, createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
7
7
  import path from "node:path";
8
- import { createHash, randomUUID } from "node:crypto";
9
- import { setTimeout } from "node:timers/promises";
8
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { mkdtemp, realpath, rm, stat } from "node:fs/promises";
11
11
  import { Readable, Transform } from "node:stream";
12
12
  import { pipeline } from "node:stream/promises";
13
13
  import { ZipFile } from "yazl";
14
14
  import { createTRPCUntypedClient, httpLink } from "@trpc/client";
15
+ import { spawn } from "node:child_process";
16
+ import { createServer } from "node:http";
17
+
18
+ //#region src/application/auth.use-case.ts
19
+ const TOKEN = /^enh_[\w-]{43}$/;
20
+ const authenticated = (value) => {
21
+ const parsed = getMeOutputSchema.parse(value);
22
+ if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "Run 'enhance auth login' and complete authentication in the browser.");
23
+ return {
24
+ authenticated: true,
25
+ personId: parsed.person.id,
26
+ displayName: parsed.person.displayName,
27
+ tokenId: parsed.authentication.tokenId,
28
+ tokenLabel: parsed.authentication.tokenLabel,
29
+ expiresAt: parsed.authentication.expiresAt
30
+ };
31
+ };
32
+ const createAuthUseCase = (credentials, remote, browser) => ({
33
+ loginWithToken: async (token) => {
34
+ if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass a manual token from Settings to 'enhance auth login' through stdin.");
35
+ const status = authenticated(await remote.queryWithToken("person.me", {}, token));
36
+ await credentials.write(token);
37
+ return status;
38
+ },
39
+ loginWithBrowser: async (input) => {
40
+ const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
41
+ if (configuration.method === "token") throw new CliError("BAD_REQUEST", "Browser authentication is not configured for this Enhance environment.", "Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.");
42
+ const accessToken = await browser.authorize({
43
+ issuer: configuration.issuer,
44
+ clientId: configuration.clientId,
45
+ scope: configuration.scope,
46
+ openBrowser: input.openBrowser,
47
+ onReady: input.onReady,
48
+ ...input.signal !== void 0 && { signal: input.signal }
49
+ });
50
+ input.signal?.throwIfAborted();
51
+ const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
52
+ label: input.label,
53
+ expiresAt: null
54
+ }, accessToken));
55
+ const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
56
+ input.signal?.throwIfAborted();
57
+ await credentials.write(created.token);
58
+ return status;
59
+ },
60
+ status: async () => {
61
+ if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
62
+ return authenticated(await remote.query("person.me", {}));
63
+ },
64
+ logout: async () => ({ loggedOut: await credentials.remove() })
65
+ });
66
+
67
+ //#endregion
15
68
  //#region src/application/render-png.use-case.ts
16
69
  const PNG_SIGNATURE = Uint8Array.from(globalThis.atob("iVBORw0KGgo="), (character) => character.codePointAt(0) ?? 0);
17
70
  const PNG_HEADER_BYTE_LENGTH = 24;
@@ -33,6 +86,7 @@ const downloadVerifiedRenderPng = async (remote, job) => {
33
86
  if (dimensions === null || body.byteLength !== job.result.bytes || dimensions.width !== job.result.width || dimensions.height !== job.result.height) throw new CliError("INTERNAL", "The downloaded render did not match its completed job metadata.", `Do not use the image. Report render job ${job.id}.`);
34
87
  return body;
35
88
  };
89
+
36
90
  //#endregion
37
91
  //#region src/application/render-canvas.composite.ts
38
92
  const POLL_MS$2 = 250;
@@ -151,6 +205,7 @@ const createRenderCanvasComposite = (remote, files, now, progress = () => null)
151
205
  now,
152
206
  progress
153
207
  }, input) });
208
+
154
209
  //#endregion
155
210
  //#region src/application/canvas-activity.composite.ts
156
211
  const PROCEDURES = {
@@ -219,6 +274,7 @@ const createCanvasActivityComposite = (remote) => ({
219
274
  activityId
220
275
  }))
221
276
  });
277
+
222
278
  //#endregion
223
279
  //#region src/application/apply-canvas.composite.ts
224
280
  const APPLY_PROCEDURE = "canvas.applyOperations";
@@ -243,7 +299,7 @@ const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operati
243
299
  const operationBox = (operation) => {
244
300
  if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
245
301
  if (operation.op === "insertNode") return operation.node.box ?? null;
246
- if (hasOperationBox(operation)) return operation.box;
302
+ if (hasOperationBox(operation)) return operation.box === "default" ? null : operation.box;
247
303
  return null;
248
304
  };
249
305
  const union = (boxes) => {
@@ -267,7 +323,10 @@ const union = (boxes) => {
267
323
  };
268
324
  };
269
325
  const apply = async (remote, input) => {
270
- const response = await remote.mutate(APPLY_PROCEDURE, input);
326
+ const response = await remote.mutate(APPLY_PROCEDURE, {
327
+ ...input,
328
+ documentFormatVersion: 3
329
+ });
271
330
  const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
272
331
  if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
273
332
  return parsed.data;
@@ -289,6 +348,7 @@ const createApplyCanvasComposite = (remote) => ({ execute: async (input, options
289
348
  await activity?.finish();
290
349
  }
291
350
  } });
351
+
292
352
  //#endregion
293
353
  //#region src/application/write-html-canvas.composite.ts
294
354
  const READ_DOCUMENT_PROCEDURE = "canvas.document.get";
@@ -390,7 +450,7 @@ const renderReview = async (render, input, imported) => {
390
450
  const createdNodes = async (remote, imported) => {
391
451
  const held = getCanvasDocumentOutputSchema.safeParse(await remote.query(READ_DOCUMENT_PROCEDURE, { canvasId: imported.canvasId }));
392
452
  if (!held.success) throw invalidResponse$1("canvas document");
393
- const scene = canvasSceneDocumentSchema.safeParse(held.data.document);
453
+ const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
394
454
  if (!scene.success) throw invalidResponse$1("editable canvas document");
395
455
  return imported.result.insertedNodeIds.map((nodeId) => {
396
456
  const node = scene.data.nodes[nodeId];
@@ -434,6 +494,7 @@ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (in
434
494
  await activity?.finish();
435
495
  }
436
496
  } });
497
+
437
498
  //#endregion
438
499
  //#region src/infrastructure/render-file.adapter.ts
439
500
  const DIRECTORY_MODE = 448;
@@ -475,6 +536,7 @@ const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
475
536
  deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
476
537
  };
477
538
  } });
539
+
478
540
  //#endregion
479
541
  //#region src/application/publish-prototype.composite.ts
480
542
  const PUBLISH_WAIT_MS = 3e5;
@@ -496,7 +558,7 @@ const waitUntilSettled = async (remote, input) => {
496
558
  if (!parsed.success) throw invalidResponse("status");
497
559
  if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
498
560
  if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
499
- await setTimeout(pollMs);
561
+ await setTimeout$1(pollMs);
500
562
  pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
501
563
  }
502
564
  throw new Error("prototype ingestion is still running");
@@ -572,6 +634,7 @@ const executePublish = async (remote, artifacts, input) => {
572
634
  }
573
635
  };
574
636
  const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
637
+
575
638
  //#endregion
576
639
  //#region src/application/read-transcript.composite.ts
577
640
  const MAX_PREVIEW_COMMANDS = 3;
@@ -587,6 +650,7 @@ const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
587
650
  next: previewCommands(input.canvasId, input.recordingId, parsed.data.cues.map((cue) => cue.startMs))
588
651
  };
589
652
  } });
653
+
590
654
  //#endregion
591
655
  //#region src/application/snapshot-recording.composite.ts
592
656
  const POLL_MS = 250;
@@ -661,6 +725,7 @@ const executeSnapshot = async (remote, progress, input) => {
661
725
  };
662
726
  };
663
727
  const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
728
+
664
729
  //#endregion
665
730
  //#region src/infrastructure/prototype-zip.adapter.ts
666
731
  const NORMALIZED_MTIME = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
@@ -749,6 +814,7 @@ const createPrototypeZipAdapter = async (input) => {
749
814
  sha256: hash.digest("hex")
750
815
  };
751
816
  };
817
+
752
818
  //#endregion
753
819
  //#region src/infrastructure/prototype-artifact.adapter.ts
754
820
  const CONTENT_TYPES = {
@@ -873,6 +939,7 @@ const packageArtifact = async (input) => {
873
939
  }
874
940
  };
875
941
  const createPrototypeArtifactAdapter = () => ({ package: packageArtifact });
942
+
876
943
  //#endregion
877
944
  //#region src/infrastructure/capability-invocation.adapter.ts
878
945
  const renderFor = (input) => createRenderCanvasComposite(input.remote, createRenderFileAdapter(input.configDirectory), input.now ?? (() => /* @__PURE__ */ new Date()), input.progress ?? (() => null));
@@ -942,19 +1009,163 @@ const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capabil
942
1009
  if (capability.execution.kind === "composite") return invokeComposite(input, capability.id, parsed, selectedClientToken);
943
1010
  return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
944
1011
  } });
1012
+
945
1013
  //#endregion
946
- //#region src/infrastructure/environment.config.ts
947
- const MIN_PORT = 1;
948
- const MAX_PORT = 65535;
949
- const DEFAULT_MCP_PORT = 3e3;
950
- const configuredDirectory = process.env["ENHANCE3_CONFIG_DIR"];
951
- const configuredApi = process.env["ENHANCE3_API_URL"];
952
- const CLI_CONFIG = {
953
- apiUrl: configuredApi === void 0 || configuredApi === "" ? "https://api.enhancelabs.ai" : configuredApi,
954
- configDirectory: configuredDirectory === void 0 || configuredDirectory === "" ? path.join(homedir(), ".config", "enhance") : configuredDirectory
1014
+ //#region src/infrastructure/oauth-loopback.adapter.ts
1015
+ const CALLBACK_PATH = "/callback";
1016
+ const AUTHORIZATION_TIMEOUT_MS = 12e4;
1017
+ const ENTROPY_BYTES = 32;
1018
+ const HTTP_OK = 200;
1019
+ const HTTP_BAD_REQUEST = 400;
1020
+ const HTTP_NOT_FOUND = 404;
1021
+ const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
1022
+ const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
1023
+ const launchBrowser = (url) => {
1024
+ const command = process.platform === "darwin" ? {
1025
+ executable: "open",
1026
+ arguments: [url]
1027
+ } : process.platform === "win32" ? {
1028
+ executable: "rundll32.exe",
1029
+ arguments: ["url.dll,FileProtocolHandler", url]
1030
+ } : {
1031
+ executable: "xdg-open",
1032
+ arguments: [url]
1033
+ };
1034
+ const child = spawn(command.executable, command.arguments, {
1035
+ detached: true,
1036
+ stdio: "ignore"
1037
+ });
1038
+ child.once("error", () => false);
1039
+ child.unref();
1040
+ };
1041
+ const handleCallback = (input, request, response) => {
1042
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
1043
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
1044
+ response.writeHead(HTTP_NOT_FOUND).end();
1045
+ return;
1046
+ }
1047
+ if (url.searchParams.get("state") !== input.state) {
1048
+ response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
1049
+ return;
1050
+ }
1051
+ const error = url.searchParams.get("error");
1052
+ const received = url.searchParams.get("code");
1053
+ if (error !== null || received === null || received === "") {
1054
+ response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
1055
+ input.completion.reject(new Error(error ?? "the authorization response carried no code"));
1056
+ return;
1057
+ }
1058
+ response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
1059
+ input.completion.resolve(received);
1060
+ };
1061
+ const authorizeUrl = (input) => {
1062
+ const authorize = endpoint(input.issuer, "oauth/authorize");
1063
+ authorize.search = new URLSearchParams({
1064
+ response_type: "code",
1065
+ client_id: input.clientId,
1066
+ redirect_uri: input.redirectUri,
1067
+ scope: input.scope,
1068
+ state: input.state,
1069
+ code_challenge: input.challenge,
1070
+ code_challenge_method: "S256"
1071
+ }).toString();
1072
+ return authorize.href;
1073
+ };
1074
+ const authorizationCode = async (input) => {
1075
+ input.signal?.throwIfAborted();
1076
+ const completion = Promise.withResolvers();
1077
+ const server = createServer((request, response) => {
1078
+ handleCallback({
1079
+ state: input.state,
1080
+ completion
1081
+ }, request, response);
1082
+ });
1083
+ await new Promise((resolve, reject) => {
1084
+ server.once("error", reject);
1085
+ server.listen(0, "127.0.0.1", resolve);
1086
+ });
1087
+ const address = server.address();
1088
+ if (address === null || typeof address === "string") {
1089
+ server.close();
1090
+ throw new Error("the OAuth callback listener has no TCP port");
1091
+ }
1092
+ const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
1093
+ const url = authorizeUrl({
1094
+ ...input,
1095
+ redirectUri
1096
+ });
1097
+ const abort = () => {
1098
+ completion.reject(/* @__PURE__ */ new Error("browser authorization cancelled"));
1099
+ };
1100
+ input.signal?.addEventListener("abort", abort, { once: true });
1101
+ const timeout = setTimeout(() => {
1102
+ completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
1103
+ }, AUTHORIZATION_TIMEOUT_MS);
1104
+ try {
1105
+ input.signal?.throwIfAborted();
1106
+ input.onReady(url);
1107
+ if (input.openBrowser) launchBrowser(url);
1108
+ return {
1109
+ code: await completion.promise,
1110
+ redirectUri
1111
+ };
1112
+ } finally {
1113
+ clearTimeout(timeout);
1114
+ input.signal?.removeEventListener("abort", abort);
1115
+ await new Promise((resolve) => {
1116
+ server.close(() => {
1117
+ resolve();
1118
+ });
1119
+ });
1120
+ }
1121
+ };
1122
+ const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
1123
+ try {
1124
+ const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
1125
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
1126
+ const state = randomBytes(ENTROPY_BYTES).toString("base64url");
1127
+ const authorized = await authorizationCode({
1128
+ ...input,
1129
+ challenge,
1130
+ state
1131
+ });
1132
+ return await remote.exchangeOauthCode({
1133
+ issuer: input.issuer,
1134
+ clientId: input.clientId,
1135
+ code: authorized.code,
1136
+ redirectUri: authorized.redirectUri,
1137
+ verifier
1138
+ });
1139
+ } catch (error) {
1140
+ throw new CliError("UNAUTHORIZED", error instanceof Error ? `Browser authentication failed: ${error.message}.` : "Browser authentication failed.", "Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.");
1141
+ }
1142
+ } });
1143
+
1144
+ //#endregion
1145
+ //#region src/infrastructure/environment-profile.lib.ts
1146
+ const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
1147
+ const resolveCliConfig = (variables, homeDirectory, release) => {
1148
+ const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
1149
+ if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
1150
+ const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
1151
+ const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
1152
+ const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
1153
+ if (release.environment === "development") {
1154
+ if (requestedApi !== void 0 && requestedApi !== release.apiUrl) throw new TypeError(`Enhance development cannot use ${requestedApi}`);
1155
+ if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
1156
+ }
1157
+ return {
1158
+ apiUrl: requestedApi ?? release.apiUrl,
1159
+ commandName: release.commandName,
1160
+ configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
1161
+ mcpServiceName: release.mcpServiceName
1162
+ };
955
1163
  };
1164
+
1165
+ //#endregion
1166
+ //#region src/infrastructure/remote-mcp.config.ts
956
1167
  const remoteMcpConfigSchema = z.object({
957
- PORT: z.coerce.number().int().min(MIN_PORT).max(MAX_PORT).default(DEFAULT_MCP_PORT),
1168
+ PORT: z.coerce.number().int().min(1).max(65535).default(3e3),
958
1169
  MCP_HOST: z.string().min(1).default("0.0.0.0"),
959
1170
  ENHANCE_API_URL: z.url(),
960
1171
  MCP_AUTH_ISSUER: z.url(),
@@ -963,15 +1174,54 @@ const remoteMcpConfigSchema = z.object({
963
1174
  MCP_ALLOWED_HOSTS: z.string().min(1),
964
1175
  MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
965
1176
  });
966
- const readRemoteMcpConfig = () => remoteMcpConfigSchema.parse(process.env);
1177
+ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables);
1178
+
1179
+ //#endregion
1180
+ //#region src/infrastructure/environment.config.ts
1181
+ const releaseProfile = {
1182
+ apiUrl: "https://api.enhancelabs.ai",
1183
+ commandName: "enhance",
1184
+ configDirectoryName: "enhance",
1185
+ environment: "production",
1186
+ mcpServiceName: "enhance-mcp"
1187
+ };
1188
+ const CLI_CONFIG = resolveCliConfig(process.env, homedir(), releaseProfile);
1189
+ const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
1190
+
967
1191
  //#endregion
968
1192
  //#region src/infrastructure/http-remote.adapter.ts
969
1193
  const HEALTH_TIMEOUT_MS = 4e3;
970
1194
  const NOT_FOUND_STATUS = 404;
971
1195
  const FORBIDDEN_STATUS = 403;
972
1196
  const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
1197
+ const networkCodeSchema = z.object({ code: z.string().regex(/^[A-Z][A-Z_0-9]+$/u) });
1198
+ const NETWORK_REMEDIATION = "Check network access and proxy settings for this API, then run enhance doctor again.";
1199
+ const originOf = (input) => new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
1200
+ const networkReason = (error) => {
1201
+ const parsed = networkCodeSchema.safeParse(error);
1202
+ if (parsed.success) return parsed.data.code;
1203
+ if (error instanceof Error && error.cause !== void 0) return networkReason(error.cause);
1204
+ return error instanceof Error ? error.name : "Network request failed";
1205
+ };
1206
+ const httpFailure = (url, status) => new CliError("INTERNAL", `${originOf(url)} answered HTTP ${String(status)}.`, NETWORK_REMEDIATION);
1207
+ const fetchNetwork = async (input, init) => {
1208
+ try {
1209
+ return await fetch(input, init);
1210
+ } catch (error) {
1211
+ throw new CliError("INTERNAL", `Could not reach ${originOf(input)}: ${networkReason(error)}.`, NETWORK_REMEDIATION);
1212
+ }
1213
+ };
1214
+ const fetchApi = async (input, init) => {
1215
+ const response = await fetchNetwork(input, init);
1216
+ if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
1217
+ return response;
1218
+ };
973
1219
  const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
974
1220
  url: `${apiUrl}/trpc`,
1221
+ fetch: async (input, init) => fetchApi(input, {
1222
+ ...init,
1223
+ signal: init?.signal ?? null
1224
+ }),
975
1225
  headers: {
976
1226
  ...token !== null && { authorization: `Bearer ${token}` },
977
1227
  ...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
@@ -983,21 +1233,21 @@ const download = async (url) => {
983
1233
  return new Uint8Array(await response.arrayBuffer());
984
1234
  };
985
1235
  const authenticationConfig = async (apiUrl) => {
986
- const response = await fetch(`${apiUrl}/v1/cli-auth`);
1236
+ const response = await fetchNetwork(`${apiUrl}/v1/cli-auth`);
987
1237
  if (!response.ok) {
988
1238
  if (response.status === NOT_FOUND_STATUS) throw new CliError("BAD_REQUEST", "This Enhance API does not support browser authentication.", "Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.");
989
- throw new CliError("INTERNAL", `CLI authentication discovery answered HTTP ${String(response.status)}.`, "Run 'enhance doctor', report the result, and stop.");
1239
+ throw new CliError("INTERNAL", `${originOf(apiUrl)} CLI authentication discovery answered HTTP ${String(response.status)}.`, NETWORK_REMEDIATION);
990
1240
  }
991
1241
  return response.json();
992
1242
  };
993
1243
  const oauthMetadata = async (issuer) => {
994
1244
  const base = issuer.endsWith("/") ? issuer : `${issuer}/`;
995
- const response = await fetch(new URL(".well-known/oauth-authorization-server", base));
996
- if (!response.ok) throw new Error(`OAuth discovery answered HTTP ${String(response.status)}`);
1245
+ const response = await fetchNetwork(new URL(".well-known/oauth-authorization-server", base));
1246
+ if (!response.ok) throw httpFailure(issuer, response.status);
997
1247
  return response.json();
998
1248
  };
999
1249
  const exchangeOauthCode = async (input) => {
1000
- const response = await fetch(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
1250
+ const response = await fetchNetwork(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
1001
1251
  method: "POST",
1002
1252
  headers: { "content-type": "application/x-www-form-urlencoded" },
1003
1253
  body: new URLSearchParams({
@@ -1008,22 +1258,24 @@ const exchangeOauthCode = async (input) => {
1008
1258
  code_verifier: input.verifier
1009
1259
  })
1010
1260
  });
1011
- if (!response.ok) throw new Error(`token exchange answered HTTP ${String(response.status)}`);
1261
+ if (!response.ok) throw new CliError("INTERNAL", `${originOf(input.issuer)} token exchange answered HTTP ${String(response.status)}`, NETWORK_REMEDIATION);
1012
1262
  return oauthTokenResponseSchema.parse(await response.json()).access_token;
1013
1263
  };
1014
1264
  const health = async (apiUrl) => {
1015
1265
  try {
1016
- const response = await fetch(`${apiUrl}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
1266
+ const response = await fetchNetwork(`${apiUrl}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
1017
1267
  return {
1018
1268
  url: apiUrl,
1019
1269
  reachable: response.ok,
1020
- status: response.status
1270
+ status: response.status,
1271
+ ...!response.ok && { error: httpFailure(apiUrl, response.status).message }
1021
1272
  };
1022
- } catch {
1273
+ } catch (error) {
1023
1274
  return {
1024
1275
  url: apiUrl,
1025
1276
  reachable: false,
1026
- status: null
1277
+ status: null,
1278
+ error: error instanceof Error ? error.message : `Could not reach ${originOf(apiUrl)}.`
1027
1279
  };
1028
1280
  }
1029
1281
  };
@@ -1056,6 +1308,7 @@ const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
1056
1308
  health: async () => health(normalized)
1057
1309
  };
1058
1310
  };
1311
+
1059
1312
  //#endregion
1060
1313
  //#region src/infrastructure/mutation-key.adapter.ts
1061
1314
  const ordered = (value) => {
@@ -1077,5 +1330,6 @@ const createMutationKeyAdapter = () => {
1077
1330
  }
1078
1331
  };
1079
1332
  };
1333
+
1080
1334
  //#endregion
1081
- export { createCapabilityInvocationAdapter as a, createApplyCanvasComposite as c, readRemoteMcpConfig as i, createCanvasActivityComposite as l, createHttpRemoteAdapter as n, createRenderFileAdapter as o, CLI_CONFIG as r, createWriteHtmlCanvasComposite as s, createMutationKeyAdapter as t, createRenderCanvasComposite as u };
1335
+ export { createOauthLoopbackAdapter as a, createWriteHtmlCanvasComposite as c, createRenderCanvasComposite as d, createAuthUseCase as f, readRemoteMcpEnvironment as i, createApplyCanvasComposite as l, createHttpRemoteAdapter as n, createCapabilityInvocationAdapter as o, CLI_CONFIG as r, createRenderFileAdapter as s, createMutationKeyAdapter as t, createCanvasActivityComposite as u };
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { F as MCP_AUTH_SCOPE, P as getMeOutputSchema, i as createCapabilityCatalogAdapter } from "./failure.mapper-CNRVSTrf.mjs";
3
- import { i as readRemoteMcpConfig, n as createHttpRemoteAdapter, t as createMutationKeyAdapter } from "./mutation-key.adapter-B7Ss_464.mjs";
4
- import { t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-D0o0vb_-.mjs";
5
- import { t as createMcpServerAdapter } from "./mcp-server.adapter-T8UqHf6A.mjs";
2
+ import { B as getMeOutputSchema, V as MCP_AUTH_SCOPE, l as createCapabilityCatalogAdapter } from "./cli-output-identity.lib-DAJiBMGX.mjs";
3
+ import { i as readRemoteMcpEnvironment, n as createHttpRemoteAdapter, t as createMutationKeyAdapter } from "./mutation-key.adapter-BffKsNR-.mjs";
4
+ import { t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-BG-WBGEr.mjs";
5
+ import { t as createMcpServerAdapter } from "./mcp-server.adapter-BgUZCdl4.mjs";
6
6
  import os from "node:os";
7
7
  import process from "node:process";
8
8
  import path from "node:path";
@@ -10,6 +10,7 @@ import { createServer } from "node:http";
10
10
  import { OAuthError, OAuthErrorCode, createMcpHandler, getOAuthProtectedResourceMetadataUrl, hostHeaderValidationResponse, oauthMetadataResponse, originValidationResponse, requireBearerAuth } from "@modelcontextprotocol/server";
11
11
  import { OAuthMetadataSchema } from "@modelcontextprotocol/core";
12
12
  import { toNodeHandler } from "@modelcontextprotocol/node";
13
+
13
14
  //#region src/infrastructure/remote-mcp-http.adapter.ts
14
15
  const SECOND_MS = 1e3;
15
16
  const BAD_REQUEST = 400;
@@ -106,7 +107,7 @@ const createRemoteMcpHttpAdapter = async (config) => {
106
107
  const credentials = credentialFor(authInfo.token, config.configDirectory);
107
108
  return createMcpServerAdapter({
108
109
  version: config.version,
109
- invocation: createMcpInvocationAdapter(config.apiUrl, credentials, config.configDirectory),
110
+ invocation: createMcpInvocationAdapter(config.apiUrl, credentials, config.configDirectory, config.version),
110
111
  catalog,
111
112
  delivery: "embedded"
112
113
  });
@@ -132,9 +133,10 @@ const createRemoteMcpHttpAdapter = async (config) => {
132
133
  }
133
134
  };
134
135
  };
136
+
135
137
  //#endregion
136
138
  //#region src/remote-mcp-main.ts
137
- const config = readRemoteMcpConfig();
139
+ const config = readRemoteMcpEnvironment();
138
140
  const server = await createRemoteMcpHttpAdapter({
139
141
  apiUrl: config.ENHANCE_API_URL,
140
142
  issuer: config.MCP_AUTH_ISSUER,
@@ -143,7 +145,7 @@ const server = await createRemoteMcpHttpAdapter({
143
145
  configDirectory: path.join(os.tmpdir(), "enhance-remote-mcp"),
144
146
  allowedHosts: config.MCP_ALLOWED_HOSTS.split(",").map((value) => value.trim()),
145
147
  allowedOrigins: config.MCP_ALLOWED_ORIGINS.split(",").map((value) => value.trim()),
146
- version: "0.1.6",
148
+ version: "0.1.13",
147
149
  onerror: (error) => process.stderr.write(`${error.message}\n`)
148
150
  });
149
151
  await server.listen(config.PORT, config.MCP_HOST);
@@ -157,5 +159,6 @@ const shutdown = () => {
157
159
  };
158
160
  process.once("SIGINT", shutdown);
159
161
  process.once("SIGTERM", shutdown);
162
+
160
163
  //#endregion
161
- export {};
164
+ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enhance-eng/enhance",
3
- "version": "0.1.6",
3
+ "version": "0.1.13",
4
4
  "private": false,
5
5
  "description": "Agent-first command-line interface for Enhance.",
6
6
  "keywords": [
@@ -1,17 +0,0 @@
1
- #!/usr/bin/env node
2
- import { a as createCapabilityInvocationAdapter, n as createHttpRemoteAdapter, t as createMutationKeyAdapter } from "./mutation-key.adapter-B7Ss_464.mjs";
3
- //#region src/infrastructure/mcp-invocation.adapter.ts
4
- const createMcpInvocationAdapter = (apiUrl, credentials, configDirectory) => ({ invoke: async ({ capability, arguments: offered, clientToken }) => {
5
- const mutationKey = createMutationKeyAdapter();
6
- return createCapabilityInvocationAdapter({
7
- remote: createHttpRemoteAdapter(apiUrl, credentials, mutationKey),
8
- mutationKey,
9
- configDirectory
10
- }).invoke({
11
- capability,
12
- arguments: offered,
13
- clientToken
14
- });
15
- } });
16
- //#endregion
17
- export { createMcpInvocationAdapter as t };