@temps-sdk/cli 0.2.0-beta.2 → 0.2.0-beta.3

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/index.js CHANGED
@@ -29594,6 +29594,10 @@ var getPlatformInfo = (options) => (options?.client ?? client).get({
29594
29594
  security: [{ scheme: "bearer", type: "http" }],
29595
29595
  url: "/platform/features",
29596
29596
  ...options
29597
+ }), getHostFacts = (options) => (options?.client ?? client).get({
29598
+ security: [{ scheme: "bearer", type: "http" }],
29599
+ url: "/platform/host-facts",
29600
+ ...options
29597
29601
  }), getPrivateIp = (options) => (options?.client ?? client).get({
29598
29602
  security: [{ scheme: "bearer", type: "http" }],
29599
29603
  url: "/platform/private-ip",
@@ -30895,6 +30899,22 @@ var getPlatformInfo = (options) => (options?.client ?? client).get({
30895
30899
  "Content-Type": null,
30896
30900
  ...options.headers
30897
30901
  }
30902
+ }), getEnvironmentEgressRecording = (options) => (options.client ?? client).get({
30903
+ security: [{ scheme: "bearer", type: "http" }],
30904
+ url: "/projects/{project_id}/environments/{environment_id}/egress-recording",
30905
+ ...options
30906
+ }), setEnvironmentEgressRecording = (options) => (options.client ?? client).put({
30907
+ security: [{ scheme: "bearer", type: "http" }],
30908
+ url: "/projects/{project_id}/environments/{environment_id}/egress-recording",
30909
+ ...options,
30910
+ headers: {
30911
+ "Content-Type": "application/json",
30912
+ ...options.headers
30913
+ }
30914
+ }), listEnvironmentEgressRecords = (options) => (options.client ?? client).get({
30915
+ security: [{ scheme: "bearer", type: "http" }],
30916
+ url: "/projects/{project_id}/environments/{environment_id}/egress-records",
30917
+ ...options
30898
30918
  }), deleteEnvironmentIpAccess = (options) => (options.client ?? client).delete({
30899
30919
  security: [{ scheme: "bearer", type: "http" }],
30900
30920
  url: "/projects/{project_id}/environments/{environment_id}/ip-access",
@@ -32567,10 +32587,38 @@ var getPlatformInfo = (options) => (options?.client ?? client).get({
32567
32587
  security: [{ scheme: "bearer", type: "http" }],
32568
32588
  url: "/settings/mcp-servers/{slug}/config/{field}",
32569
32589
  ...options
32590
+ }), getOnboarding = (options) => (options?.client ?? client).get({
32591
+ security: [{ scheme: "bearer", type: "http" }],
32592
+ url: "/settings/onboarding",
32593
+ ...options
32594
+ }), updateOnboarding = (options) => (options.client ?? client).patch({
32595
+ security: [{ scheme: "bearer", type: "http" }],
32596
+ url: "/settings/onboarding",
32597
+ ...options,
32598
+ headers: {
32599
+ "Content-Type": "application/json",
32600
+ ...options.headers
32601
+ }
32570
32602
  }), getPreviewDomainStatus = (options) => (options?.client ?? client).get({
32571
32603
  security: [{ scheme: "bearer", type: "http" }],
32572
32604
  url: "/settings/preview-domain/status",
32573
32605
  ...options
32606
+ }), deletePrivateIngress = (options) => (options?.client ?? client).delete({
32607
+ security: [{ scheme: "bearer", type: "http" }],
32608
+ url: "/settings/private-ingress",
32609
+ ...options
32610
+ }), getPrivateIngress = (options) => (options?.client ?? client).get({
32611
+ security: [{ scheme: "bearer", type: "http" }],
32612
+ url: "/settings/private-ingress",
32613
+ ...options
32614
+ }), putPrivateIngress = (options) => (options.client ?? client).put({
32615
+ security: [{ scheme: "bearer", type: "http" }],
32616
+ url: "/settings/private-ingress",
32617
+ ...options,
32618
+ headers: {
32619
+ "Content-Type": "application/json",
32620
+ ...options.headers
32621
+ }
32574
32622
  }), getPublicIngressStatus = (options) => (options?.client ?? client).get({
32575
32623
  security: [{ scheme: "bearer", type: "http" }],
32576
32624
  url: "/settings/public-ingress",
@@ -33143,6 +33191,22 @@ var getPlatformInfo = (options) => (options?.client ?? client).get({
33143
33191
  security: [{ scheme: "bearer", type: "http" }],
33144
33192
  url: "/v1/sandboxes/{id}/creation",
33145
33193
  ...options
33194
+ }), getEgressRecording = (options) => (options.client ?? client).get({
33195
+ security: [{ scheme: "bearer", type: "http" }],
33196
+ url: "/v1/sandboxes/{id}/egress-recording",
33197
+ ...options
33198
+ }), setEgressRecording = (options) => (options.client ?? client).put({
33199
+ security: [{ scheme: "bearer", type: "http" }],
33200
+ url: "/v1/sandboxes/{id}/egress-recording",
33201
+ ...options,
33202
+ headers: {
33203
+ "Content-Type": "application/json",
33204
+ ...options.headers
33205
+ }
33206
+ }), listEgressRecords = (options) => (options.client ?? client).get({
33207
+ security: [{ scheme: "bearer", type: "http" }],
33208
+ url: "/v1/sandboxes/{id}/egress-records",
33209
+ ...options
33146
33210
  }), listDir = (options) => (options.client ?? client).get({
33147
33211
  security: [{ scheme: "bearer", type: "http" }],
33148
33212
  url: "/v1/sandboxes/{id}/fs/list",
@@ -68689,6 +68753,1461 @@ var require_jsx_dev_runtime = __commonJS(function(exports, module) {
68689
68753
  }
68690
68754
  });
68691
68755
 
68756
+ // ../../web/src/lib/claude-extension/deploy.cjs
68757
+ var require_deploy = __commonJS(function(exports, module) {
68758
+ var fs = __require("node:fs");
68759
+ var os = __require("node:os");
68760
+ var path = __require("node:path");
68761
+ var zlib = __require("node:zlib");
68762
+ var crypto2 = __require("node:crypto");
68763
+ var { promisify } = __require("node:util");
68764
+ var fsp = fs.promises;
68765
+ var deflateRaw = promisify(zlib.deflateRaw);
68766
+ var DEPLOY_TOOL_NAME = "temps_deploy_folder";
68767
+ var LIMITS = {
68768
+ files: 1e4,
68769
+ bytes: 100 * 1024 * 1024,
68770
+ ignoreBytes: 1024 * 1024,
68771
+ entries: 200000
68772
+ };
68773
+ var LEFT_OUT_SHOWN = 12;
68774
+ var DEPLOY_TOOL = {
68775
+ name: DEPLOY_TOOL_NAME,
68776
+ title: "Deploy a folder",
68777
+ description: "Deploy a project folder on the user's computer to a Temps project in one step: it uploads the source and Temps builds and deploys it. The app asks the user before it runs this tool, so tell them what you are about to deploy and where. The folder must be inside one the user allowed for Temps deploys. It leaves out .git, node_modules, build caches, .env files, keys and whatever .gitignore lists. The project must accept uploaded source (a project created for upload does). Find project_id, and environment_id if the project has several environments, with the temps tool. Returns the deployment id; follow the build with the temps tool.",
68778
+ inputSchema: {
68779
+ type: "object",
68780
+ properties: {
68781
+ path: {
68782
+ type: "string",
68783
+ description: "Full path of the project folder on this computer, such as /Users/me/code/my-app or ~/code/my-app."
68784
+ },
68785
+ project_id: {
68786
+ type: "integer",
68787
+ minimum: 1,
68788
+ description: "The Temps project to deploy to."
68789
+ },
68790
+ environment_id: {
68791
+ type: "integer",
68792
+ minimum: 1,
68793
+ description: "The environment to deploy to. Optional: by default the production environment, or the only one."
68794
+ }
68795
+ },
68796
+ required: ["path", "project_id"],
68797
+ additionalProperties: false
68798
+ },
68799
+ annotations: {
68800
+ title: "Deploy a folder",
68801
+ readOnlyHint: false,
68802
+ destructiveHint: true,
68803
+ idempotentHint: false,
68804
+ openWorldHint: false
68805
+ }
68806
+ };
68807
+ var LEFT_OUT_DIRECTORIES = new Set([
68808
+ ".git",
68809
+ ".hg",
68810
+ ".svn",
68811
+ "node_modules",
68812
+ ".next",
68813
+ ".nuxt",
68814
+ ".output",
68815
+ ".svelte-kit",
68816
+ ".turbo",
68817
+ ".vercel",
68818
+ ".netlify",
68819
+ ".cache",
68820
+ "__pycache__",
68821
+ ".venv",
68822
+ ".terraform"
68823
+ ]);
68824
+ var CREDENTIAL_DIRECTORIES = new Set([
68825
+ ".aws",
68826
+ ".azure",
68827
+ ".docker",
68828
+ ".gnupg",
68829
+ ".kube",
68830
+ ".ssh"
68831
+ ]);
68832
+ var SECRET_FILE_NAMES = new Set([
68833
+ ".envrc",
68834
+ ".netrc",
68835
+ ".pypirc",
68836
+ ".git-credentials",
68837
+ ".htpasswd",
68838
+ "credentials.json",
68839
+ ".ds_store"
68840
+ ]);
68841
+ var SECRET_EXTENSIONS = new Set([
68842
+ ".pem",
68843
+ ".key",
68844
+ ".p12",
68845
+ ".pfx",
68846
+ ".jks",
68847
+ ".keystore",
68848
+ ".ppk"
68849
+ ]);
68850
+ var REGISTRY_SETTINGS = new Set([".npmrc", ".yarnrc", ".yarnrc.yml"]);
68851
+ var REGISTRY_CREDENTIAL = /_auth|_password|npmAuthToken|npmAuthIdent/i;
68852
+ var IGNORE_CASE = process.platform === "darwin" || process.platform === "win32";
68853
+ function alwaysLeftOut(given, isDirectory) {
68854
+ const name = given.toLowerCase();
68855
+ if (name === ".git")
68856
+ return true;
68857
+ if (isDirectory) {
68858
+ return LEFT_OUT_DIRECTORIES.has(name) || CREDENTIAL_DIRECTORIES.has(name);
68859
+ }
68860
+ if (SECRET_FILE_NAMES.has(name))
68861
+ return true;
68862
+ if (/^\.env(\..+)?$/i.test(name)) {
68863
+ return !/^\.env\.(example|sample|template|dist)$/i.test(name);
68864
+ }
68865
+ if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(name))
68866
+ return true;
68867
+ if (/^terraform\.tfstate/.test(name))
68868
+ return true;
68869
+ return SECRET_EXTENSIONS.has(path.extname(name));
68870
+ }
68871
+ function gitBytes(name) {
68872
+ return Buffer.from(name, "utf8").toString("latin1");
68873
+ }
68874
+ function foldAscii(text) {
68875
+ return text.replace(/[A-Z]/g, (c) => c.toLowerCase());
68876
+ }
68877
+ function otherCase(char) {
68878
+ if (char >= "a" && char <= "z")
68879
+ return char.toUpperCase();
68880
+ if (char >= "A" && char <= "Z")
68881
+ return char.toLowerCase();
68882
+ return null;
68883
+ }
68884
+ function literalRegex(char, ignoreCase) {
68885
+ const other = ignoreCase ? otherCase(char) : null;
68886
+ return other ? `[${char}${other}]` : escapeRegex(char);
68887
+ }
68888
+ function escapeRegex(char) {
68889
+ return /[.*+?^${}()|[\]\\/]/.test(char) ? `\\${char}` : char;
68890
+ }
68891
+ var isUpper = (c) => c >= 65 && c <= 90;
68892
+ var isLower = (c) => c >= 97 && c <= 122;
68893
+ var isDigit = (c) => c >= 48 && c <= 57;
68894
+ var isAlnum = (c) => isUpper(c) || isLower(c) || isDigit(c);
68895
+ var POSIX_CLASSES = {
68896
+ alnum: isAlnum,
68897
+ alpha: (c) => isUpper(c) || isLower(c),
68898
+ blank: (c) => c === 32 || c === 9,
68899
+ cntrl: (c) => c < 32 || c === 127,
68900
+ digit: isDigit,
68901
+ graph: (c) => c > 32 && c < 127,
68902
+ lower: isLower,
68903
+ print: (c) => c >= 32 && c < 127,
68904
+ punct: (c) => c > 32 && c < 127 && !isAlnum(c),
68905
+ space: (c) => c === 32 || c >= 9 && c <= 13,
68906
+ upper: isUpper,
68907
+ xdigit: (c) => isDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102
68908
+ };
68909
+ function wildBracket(glob, start, t, ignoreCase) {
68910
+ let i = start + 1;
68911
+ let p = glob.charCodeAt(i);
68912
+ if (p === 94)
68913
+ p = 33;
68914
+ const negated = p === 33;
68915
+ if (negated)
68916
+ p = glob.charCodeAt(++i);
68917
+ let prev = 0;
68918
+ let matched = false;
68919
+ do {
68920
+ if (Number.isNaN(p))
68921
+ return null;
68922
+ if (p === 92) {
68923
+ p = glob.charCodeAt(++i);
68924
+ if (Number.isNaN(p))
68925
+ return null;
68926
+ if (t === p)
68927
+ matched = true;
68928
+ } else if (p === 45 && prev && i + 1 < glob.length && glob[i + 1] !== "]") {
68929
+ p = glob.charCodeAt(++i);
68930
+ if (p === 92) {
68931
+ p = glob.charCodeAt(++i);
68932
+ if (Number.isNaN(p))
68933
+ return null;
68934
+ }
68935
+ if (t <= p && t >= prev)
68936
+ matched = true;
68937
+ else if (ignoreCase && isLower(t) && t - 32 <= p && t - 32 >= prev)
68938
+ matched = true;
68939
+ p = 0;
68940
+ } else if (p === 91 && glob[i + 1] === ":") {
68941
+ const s = i + 2;
68942
+ let j = s;
68943
+ while (j < glob.length && glob[j] !== "]")
68944
+ j++;
68945
+ if (j >= glob.length)
68946
+ return null;
68947
+ if (j - s - 1 < 0 || glob[j - 1] !== ":") {
68948
+ i = s - 2;
68949
+ p = 91;
68950
+ if (t === p)
68951
+ matched = true;
68952
+ } else {
68953
+ const name = glob.slice(s, j - 1);
68954
+ const test = Object.prototype.hasOwnProperty.call(POSIX_CLASSES, name) ? POSIX_CLASSES[name] : null;
68955
+ if (!test)
68956
+ return null;
68957
+ if (test(t) || name === "upper" && ignoreCase && isLower(t))
68958
+ matched = true;
68959
+ i = j;
68960
+ p = 0;
68961
+ }
68962
+ } else if (t === p) {
68963
+ matched = true;
68964
+ }
68965
+ prev = p;
68966
+ p = glob.charCodeAt(++i);
68967
+ } while (p !== 93);
68968
+ return { matched: matched !== negated, end: i };
68969
+ }
68970
+ function byteClass(member) {
68971
+ const hex = (byte) => `\\x${byte.toString(16).padStart(2, "0")}`;
68972
+ let out = "";
68973
+ for (let byte = 0;byte < 256; byte++) {
68974
+ if (!member[byte])
68975
+ continue;
68976
+ let last = byte;
68977
+ while (last + 1 < 256 && member[last + 1])
68978
+ last++;
68979
+ out += last === byte ? hex(byte) : `${hex(byte)}-${hex(last)}`;
68980
+ byte = last;
68981
+ }
68982
+ return out ? `[${out}]` : "(?!)";
68983
+ }
68984
+ function bracketToRegex(glob, start, ignoreCase = false) {
68985
+ const shape = wildBracket(glob, start, 0, ignoreCase);
68986
+ if (!shape)
68987
+ return null;
68988
+ const member = new Array(256).fill(false);
68989
+ for (let byte = 0;byte < 256; byte++) {
68990
+ if (byte === 47)
68991
+ continue;
68992
+ const t = ignoreCase && isUpper(byte) ? byte + 32 : byte;
68993
+ member[byte] = wildBracket(glob, start, t, ignoreCase).matched;
68994
+ }
68995
+ return { regex: byteClass(member), end: shape.end };
68996
+ }
68997
+ function globToRegex(glob, ignoreCase = false) {
68998
+ let out = "";
68999
+ for (let i = 0;i < glob.length; i++) {
69000
+ const char = glob[i];
69001
+ if (char === "*") {
69002
+ let stars = 1;
69003
+ while (glob[i + stars] === "*")
69004
+ stars += 1;
69005
+ if (stars > 1) {
69006
+ const atStart = i === 0 || glob[i - 1] === "/";
69007
+ const after = i + stars;
69008
+ if (atStart && glob[after] === "/") {
69009
+ out += "(?:.*/)?";
69010
+ i = after;
69011
+ continue;
69012
+ }
69013
+ if (atStart && after === glob.length) {
69014
+ out += ".*";
69015
+ i = after - 1;
69016
+ continue;
69017
+ }
69018
+ out += "[^/]*";
69019
+ i = after - 1;
69020
+ continue;
69021
+ }
69022
+ out += "[^/]*";
69023
+ } else if (char === "?") {
69024
+ out += "[^/]";
69025
+ } else if (char === "[") {
69026
+ const bracket = bracketToRegex(glob, i, ignoreCase);
69027
+ if (!bracket)
69028
+ return "(?!)";
69029
+ out += bracket.regex;
69030
+ i = bracket.end;
69031
+ } else if (char === "\\" && i + 1 < glob.length) {
69032
+ out += literalRegex(glob[i + 1], ignoreCase);
69033
+ i += 1;
69034
+ } else {
69035
+ out += literalRegex(char, ignoreCase);
69036
+ }
69037
+ }
69038
+ return out;
69039
+ }
69040
+ function parseIgnore(text, base, ignoreCase = IGNORE_CASE) {
69041
+ const rules = [];
69042
+ for (const raw of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
69043
+ let line = raw.replace(/(?<!\\)\s+$/, "");
69044
+ if (!line || line.startsWith("#"))
69045
+ continue;
69046
+ let negate = false;
69047
+ if (line.startsWith("!")) {
69048
+ negate = true;
69049
+ line = line.slice(1);
69050
+ } else if (line.startsWith("\\!") || line.startsWith("\\#")) {
69051
+ line = line.slice(1);
69052
+ }
69053
+ let directoryOnly = false;
69054
+ if (line.endsWith("/")) {
69055
+ directoryOnly = true;
69056
+ line = line.slice(0, -1);
69057
+ }
69058
+ const anchored = line.includes("/");
69059
+ if (line.startsWith("/"))
69060
+ line = line.slice(1);
69061
+ if (!line)
69062
+ continue;
69063
+ const folds = ignoreCase && !negate;
69064
+ let regex;
69065
+ try {
69066
+ const body = globToRegex(gitBytes(line), folds);
69067
+ regex = new RegExp(anchored ? `^${body}$` : `(?:^|/)${body}$`, "s");
69068
+ } catch {
69069
+ continue;
69070
+ }
69071
+ rules.push({
69072
+ base,
69073
+ baseBytes: folds ? foldAscii(gitBytes(base)) : gitBytes(base),
69074
+ ignoreCase: folds,
69075
+ negate,
69076
+ directoryOnly,
69077
+ regex
69078
+ });
69079
+ }
69080
+ return rules;
69081
+ }
69082
+ function isIgnored(rules, relative, isDirectory) {
69083
+ let ignored = false;
69084
+ const name = gitBytes(relative);
69085
+ let folded;
69086
+ for (const rule of rules) {
69087
+ if (rule.directoryOnly && !isDirectory)
69088
+ continue;
69089
+ const prefix = rule.ignoreCase ? folded ??= foldAscii(name) : name;
69090
+ if (!prefix.startsWith(rule.baseBytes))
69091
+ continue;
69092
+ if (rule.regex.test(name.slice(rule.baseBytes.length))) {
69093
+ ignored = !rule.negate;
69094
+ }
69095
+ }
69096
+ return ignored;
69097
+ }
69098
+ function megabytes(bytes) {
69099
+ if (bytes < 1024 * 1024)
69100
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
69101
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
69102
+ }
69103
+ var HOSTS = {
69104
+ extension: {
69105
+ settings: "the extension settings",
69106
+ folders: "the folders Claude may deploy",
69107
+ noFolders: 'No folder may be deployed yet. In Claude, open Settings, then Extensions, then Temps, add the project folder (or a folder above it) under "Folders Claude may deploy", and try again.',
69108
+ addFolder: "To allow it, add it or a folder above it in Claude: Settings, then Extensions, then Temps."
69109
+ },
69110
+ cli: {
69111
+ settings: "the app’s Temps MCP settings (run temps mcp add again)",
69112
+ folders: "the folders this agent may deploy",
69113
+ noFolders: "No folder may be deployed yet. Run temps mcp add <app> --deploy-folder <folder> with the folder that holds your projects, restart the app, and try again.",
69114
+ addFolder: "To allow it, run temps mcp add <app> --deploy-folder <folder> with it or a folder above it, and restart the app."
69115
+ }
69116
+ };
69117
+ function hostFor(env) {
69118
+ return env && env.TEMPS_BRIDGE_HOST === "cli" ? HOSTS.cli : HOSTS.extension;
69119
+ }
69120
+ async function allowedRoot(input, folders, host = HOSTS.extension) {
69121
+ if (folders.length === 0)
69122
+ throw new Error(host.noFolders);
69123
+ let requested = input.trim();
69124
+ if (requested === "~" || requested.startsWith("~/")) {
69125
+ requested = path.join(os.homedir(), requested.slice(1));
69126
+ }
69127
+ if (!path.isAbsolute(requested)) {
69128
+ throw new Error(`"${input}" is not a full path. Give the full path of the project folder, such as ${path.join(os.homedir(), "code", "my-app")}.`);
69129
+ }
69130
+ let root;
69131
+ try {
69132
+ root = await fsp.realpath(requested);
69133
+ } catch (error) {
69134
+ if (error && error.code === "ENOENT") {
69135
+ throw new Error(`${requested} does not exist on this computer.`, {
69136
+ cause: error
69137
+ });
69138
+ }
69139
+ throw new Error(`Could not open ${requested}: ${error.message}`, {
69140
+ cause: error
69141
+ });
69142
+ }
69143
+ if (!(await fsp.stat(root)).isDirectory()) {
69144
+ throw new Error(`${requested} is a file. Give the project's folder.`);
69145
+ }
69146
+ if (root === path.parse(root).root || root === os.homedir()) {
69147
+ throw new Error(`${requested} is not a project folder. Give the folder of the project itself.`);
69148
+ }
69149
+ for (const folder of folders) {
69150
+ let allowed;
69151
+ try {
69152
+ allowed = await fsp.realpath(folder);
69153
+ } catch {
69154
+ continue;
69155
+ }
69156
+ const relative2 = path.relative(allowed, root);
69157
+ if (relative2 === "" || relative2.split(path.sep)[0] !== ".." && !path.isAbsolute(relative2)) {
69158
+ const leftOut = relative2.split(path.sep).find((segment) => segment && alwaysLeftOut(segment, true));
69159
+ if (leftOut) {
69160
+ throw new Error(`${requested} is inside ${leftOut}, which is never deployed. Give the folder of the project itself.`);
69161
+ }
69162
+ return root;
69163
+ }
69164
+ }
69165
+ throw new Error(`${requested} is outside ${host.folders} (${folders.join(", ")}). ${host.addFolder}`);
69166
+ }
69167
+ async function readBounded(file, max, tooLarge) {
69168
+ const noFollow = fs.constants.O_NOFOLLOW || 0;
69169
+ const handle = await fsp.open(file, fs.constants.O_RDONLY | noFollow);
69170
+ try {
69171
+ const stat = await handle.stat();
69172
+ if (!stat.isFile())
69173
+ return null;
69174
+ if (stat.size > max)
69175
+ throw tooLarge(stat.size);
69176
+ return await readHandle(handle, stat.size, max, tooLarge, file);
69177
+ } finally {
69178
+ await handle.close();
69179
+ }
69180
+ }
69181
+ async function readHandle(handle, size, max, tooLarge, file) {
69182
+ const capacity = Math.min(size, max) + 1;
69183
+ const buffer = Buffer.alloc(capacity);
69184
+ let read = 0;
69185
+ while (read < capacity) {
69186
+ const { bytesRead } = await handle.read(buffer, read, capacity - read, read);
69187
+ if (bytesRead === 0)
69188
+ break;
69189
+ read += bytesRead;
69190
+ }
69191
+ if (read > max)
69192
+ throw tooLarge(read);
69193
+ if (read > size) {
69194
+ throw new Error(`${file} changed while it was read. Try again once the folder has stopped changing.`);
69195
+ }
69196
+ return buffer.subarray(0, read);
69197
+ }
69198
+ async function readIgnore(directory, base, limits) {
69199
+ const file = path.join(directory, ".gitignore");
69200
+ const text = await readBounded(file, limits.ignoreBytes, (size) => new Error(`${file} is ${megabytes(size)}, more than the ${megabytes(limits.ignoreBytes)} a .gitignore may be here. Shorten it, then try again.`));
69201
+ return text ? parseIgnore(text.toString("utf8"), base) : [];
69202
+ }
69203
+ async function repositoryAbove(root) {
69204
+ const isRepository = async (directory) => {
69205
+ try {
69206
+ await fsp.lstat(path.join(directory, ".git"));
69207
+ return true;
69208
+ } catch {
69209
+ return false;
69210
+ }
69211
+ };
69212
+ if (await isRepository(root))
69213
+ return null;
69214
+ let directory = path.dirname(root);
69215
+ for (;; ) {
69216
+ if (await isRepository(directory))
69217
+ return directory;
69218
+ const parent = path.dirname(directory);
69219
+ if (parent === directory)
69220
+ return null;
69221
+ directory = parent;
69222
+ }
69223
+ }
69224
+ async function rulesAbove(root, limits) {
69225
+ const repository = await repositoryAbove(root);
69226
+ if (!repository)
69227
+ return { prefix: "", rules: [], ignored: null };
69228
+ const segments = path.relative(repository, root).split(path.sep);
69229
+ let rules = [];
69230
+ let directory = repository;
69231
+ let base = "";
69232
+ for (const segment of segments) {
69233
+ rules = rules.concat(await readIgnoreIfFile(directory, base, limits));
69234
+ const relative = `${base}${segment}`;
69235
+ if (isIgnored(rules, relative, true)) {
69236
+ return { prefix: `${relative}/`, rules, ignored: `${relative}/` };
69237
+ }
69238
+ directory = path.join(directory, segment);
69239
+ base = `${relative}/`;
69240
+ }
69241
+ return { prefix: base, rules, ignored: null };
69242
+ }
69243
+ async function localIgnore(directory, base, limits) {
69244
+ const file = path.join(directory, ".gitignore");
69245
+ let stat;
69246
+ try {
69247
+ stat = await fsp.lstat(file);
69248
+ } catch (error) {
69249
+ if (error && error.code === "ENOENT")
69250
+ return { rules: [], read: null };
69251
+ throw new Error(`${file} could not be read (${error && error.code ? error.code : error}), so what it leaves out is unknown. Try again.`, { cause: error });
69252
+ }
69253
+ if (!stat.isFile())
69254
+ return { rules: [], read: null };
69255
+ return { rules: await readIgnore(directory, base, limits), read: stat };
69256
+ }
69257
+ async function readIgnoreIfFile(directory, base, limits) {
69258
+ return (await localIgnore(directory, base, limits)).rules;
69259
+ }
69260
+ async function sameIgnore(directory, read, listed) {
69261
+ if (!read)
69262
+ return !listed;
69263
+ if (!listed)
69264
+ return false;
69265
+ try {
69266
+ const now = await fsp.lstat(path.join(directory, ".gitignore"));
69267
+ return now.isFile() && now.ino === read.ino && now.dev === read.dev && now.size === read.size && now.mtimeMs === read.mtimeMs;
69268
+ } catch {
69269
+ return false;
69270
+ }
69271
+ }
69272
+ async function stillInside(absolute, stat, directory, listed) {
69273
+ try {
69274
+ if (await fsp.realpath(absolute) !== absolute)
69275
+ return false;
69276
+ const again = await fsp.lstat(absolute);
69277
+ if (!again.isFile() || again.ino !== stat.ino || again.dev !== stat.dev) {
69278
+ return false;
69279
+ }
69280
+ if (!listed)
69281
+ return true;
69282
+ const now = await fsp.lstat(directory);
69283
+ return now.isDirectory() && now.ino === listed.ino && now.dev === listed.dev;
69284
+ } catch {
69285
+ return false;
69286
+ }
69287
+ }
69288
+ async function openedPath(handle) {
69289
+ if (process.platform !== "linux")
69290
+ return null;
69291
+ try {
69292
+ return await fsp.readlink(`/proc/self/fd/${handle.fd}`);
69293
+ } catch {
69294
+ return null;
69295
+ }
69296
+ }
69297
+ async function collectFiles(root, limits = LIMITS) {
69298
+ limits = { ...LIMITS, ...limits };
69299
+ const files = [];
69300
+ const leftOut = [];
69301
+ let leftOutCount = 0;
69302
+ let listed = 0;
69303
+ let total = 0;
69304
+ const leaveOut = (name) => {
69305
+ leftOutCount += 1;
69306
+ if (leftOut.length < LEFT_OUT_SHOWN)
69307
+ leftOut.push(name);
69308
+ };
69309
+ const above = await rulesAbove(root, limits);
69310
+ if (above.ignored) {
69311
+ leaveOut(`${path.basename(root)}/ (${above.ignored} is in a .gitignore above it)`);
69312
+ return { files, leftOut, leftOutCount, total };
69313
+ }
69314
+ const { prefix } = above;
69315
+ const changed = (what) => new Error(`${what} changed while the folder was read. Try again once the folder has stopped changing.`);
69316
+ const walk = async (directory, relative, rules) => {
69317
+ const before = await fsp.lstat(directory);
69318
+ if (!before.isDirectory())
69319
+ return;
69320
+ if (await fsp.realpath(directory) !== directory) {
69321
+ throw new Error(`${directory} changed while it was read. Try again once the folder has stopped changing.`);
69322
+ }
69323
+ const ignore = await localIgnore(directory, `${prefix}${relative}`, limits);
69324
+ rules = rules.concat(ignore.rules);
69325
+ let listedIgnore = false;
69326
+ const kept = [];
69327
+ const handle = await fsp.opendir(directory);
69328
+ for await (const entry of handle) {
69329
+ listed += 1;
69330
+ if (listed > limits.entries) {
69331
+ await handle.close().catch(() => {});
69332
+ throw new Error(`${root} has more than ${limits.entries} files and folders, counting those left out. Deploy a smaller folder, or move what the build doesn't need (generated files, data, media) out of it, then try again.`);
69333
+ }
69334
+ const name = `${relative}${entry.name}`;
69335
+ if (entry.name === ".gitignore" && entry.isFile())
69336
+ listedIgnore = true;
69337
+ if (entry.isSymbolicLink()) {
69338
+ leaveOut(name);
69339
+ continue;
69340
+ }
69341
+ const isDirectory = entry.isDirectory();
69342
+ if (!isDirectory && !entry.isFile())
69343
+ continue;
69344
+ if (alwaysLeftOut(entry.name, isDirectory) || isIgnored(rules, `${prefix}${name}`, isDirectory)) {
69345
+ leaveOut(isDirectory ? `${name}/` : name);
69346
+ continue;
69347
+ }
69348
+ kept.push({ name: entry.name, isDirectory });
69349
+ }
69350
+ const after = await fsp.lstat(directory);
69351
+ if (!after.isDirectory() || after.ino !== before.ino || after.dev !== before.dev || await fsp.realpath(directory) !== directory || !await sameIgnore(directory, ignore.read, listedIgnore)) {
69352
+ throw new Error(`${directory} changed while it was read. Try again once the folder has stopped changing.`);
69353
+ }
69354
+ kept.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
69355
+ for (const entry of kept) {
69356
+ const name = `${relative}${entry.name}`;
69357
+ const absolute = path.join(directory, entry.name);
69358
+ if (entry.isDirectory) {
69359
+ await walk(absolute, `${name}/`, rules);
69360
+ continue;
69361
+ }
69362
+ const stat = await fsp.lstat(absolute);
69363
+ if (!stat.isFile())
69364
+ continue;
69365
+ if (!await stillInside(absolute, stat, directory, before)) {
69366
+ throw changed(name);
69367
+ }
69368
+ files.push({
69369
+ name,
69370
+ absolute,
69371
+ size: stat.size,
69372
+ mode: stat.mode,
69373
+ dev: stat.dev,
69374
+ ino: stat.ino
69375
+ });
69376
+ total += stat.size;
69377
+ if (files.length > limits.files) {
69378
+ throw new Error(`${root} has more than ${limits.files} files to upload. Add what the build doesn't need (generated files, data, media) to .gitignore, then try again.`);
69379
+ }
69380
+ if (total > limits.bytes) {
69381
+ throw new Error(`${root} has more than ${megabytes(limits.bytes)} to upload. Add large files the build doesn't need to .gitignore, then try again.`);
69382
+ }
69383
+ }
69384
+ };
69385
+ await walk(root, "", above.rules);
69386
+ return { files, leftOut, leftOutCount, total };
69387
+ }
69388
+ var CRC_TABLE = (() => {
69389
+ const table = new Uint32Array(256);
69390
+ for (let n = 0;n < 256; n++) {
69391
+ let c = n;
69392
+ for (let k = 0;k < 8; k++)
69393
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
69394
+ table[n] = c >>> 0;
69395
+ }
69396
+ return table;
69397
+ })();
69398
+ function crc32(bytes) {
69399
+ let crc = 4294967295;
69400
+ for (let i = 0;i < bytes.length; i++) {
69401
+ crc = CRC_TABLE[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
69402
+ }
69403
+ return (crc ^ 4294967295) >>> 0;
69404
+ }
69405
+ var DOS_TIME = 0;
69406
+ var DOS_DATE = 0 << 9 | 1 << 5 | 1;
69407
+ async function packZip(collected, limits = LIMITS) {
69408
+ limits = { ...LIMITS, ...limits };
69409
+ const locals = [];
69410
+ const central = [];
69411
+ const packed = [];
69412
+ let offset = 0;
69413
+ let read = 0;
69414
+ const noFollow = fs.constants.O_NOFOLLOW || 0;
69415
+ for (const file of collected.files) {
69416
+ const handle = await fsp.open(file.absolute, fs.constants.O_RDONLY | noFollow);
69417
+ const grew = () => new Error(`The folder grew past ${megabytes(limits.bytes)} while it was packed. Try again once it has stopped changing.`);
69418
+ let data;
69419
+ try {
69420
+ const stat = await handle.stat();
69421
+ if (!stat.isFile())
69422
+ continue;
69423
+ const opened = await openedPath(handle);
69424
+ if (file.ino === undefined || stat.ino !== file.ino || stat.dev !== file.dev || opened !== null && opened !== file.absolute || !await stillInside(file.absolute, stat)) {
69425
+ throw new Error(`${file.name} changed while the folder was packed. Try again once it has stopped changing.`);
69426
+ }
69427
+ const remaining = limits.bytes - read;
69428
+ if (stat.size > remaining)
69429
+ throw grew();
69430
+ data = await readHandle(handle, stat.size, remaining, grew, file.name);
69431
+ } finally {
69432
+ await handle.close();
69433
+ }
69434
+ read += data.length;
69435
+ if (REGISTRY_SETTINGS.has(path.basename(file.name).toLowerCase()) && REGISTRY_CREDENTIAL.test(data.toString("utf8"))) {
69436
+ collected.leftOutCount = (collected.leftOutCount ?? collected.leftOut.length) + 1;
69437
+ collected.leftOut.unshift(file.name);
69438
+ collected.leftOut.length = Math.min(collected.leftOut.length, LEFT_OUT_SHOWN);
69439
+ continue;
69440
+ }
69441
+ const deflated = await deflateRaw(data);
69442
+ const stored = deflated.length >= data.length;
69443
+ const body = stored ? data : deflated;
69444
+ const name = Buffer.from(file.name, "utf8");
69445
+ const crc = crc32(data);
69446
+ const method = stored ? 0 : 8;
69447
+ const mode = (file.mode & 73 ? 493 : 420) | 32768;
69448
+ const local = Buffer.alloc(30);
69449
+ local.writeUInt32LE(67324752, 0);
69450
+ local.writeUInt16LE(20, 4);
69451
+ local.writeUInt16LE(2048, 6);
69452
+ local.writeUInt16LE(method, 8);
69453
+ local.writeUInt16LE(DOS_TIME, 10);
69454
+ local.writeUInt16LE(DOS_DATE, 12);
69455
+ local.writeUInt32LE(crc, 14);
69456
+ local.writeUInt32LE(body.length, 18);
69457
+ local.writeUInt32LE(data.length, 22);
69458
+ local.writeUInt16LE(name.length, 26);
69459
+ local.writeUInt16LE(0, 28);
69460
+ const entry = Buffer.alloc(46);
69461
+ entry.writeUInt32LE(33639248, 0);
69462
+ entry.writeUInt16LE(3 << 8 | 20, 4);
69463
+ entry.writeUInt16LE(20, 6);
69464
+ entry.writeUInt16LE(2048, 8);
69465
+ entry.writeUInt16LE(method, 10);
69466
+ entry.writeUInt16LE(DOS_TIME, 12);
69467
+ entry.writeUInt16LE(DOS_DATE, 14);
69468
+ entry.writeUInt32LE(crc, 16);
69469
+ entry.writeUInt32LE(body.length, 20);
69470
+ entry.writeUInt32LE(data.length, 24);
69471
+ entry.writeUInt16LE(name.length, 28);
69472
+ entry.writeUInt32LE(mode << 16 >>> 0, 38);
69473
+ entry.writeUInt32LE(offset, 42);
69474
+ locals.push(local, name, body);
69475
+ central.push(entry, name);
69476
+ packed.push(file.name);
69477
+ offset += local.length + name.length + body.length;
69478
+ }
69479
+ const directory = Buffer.concat(central);
69480
+ const end = Buffer.alloc(22);
69481
+ end.writeUInt32LE(101010256, 0);
69482
+ end.writeUInt16LE(packed.length, 8);
69483
+ end.writeUInt16LE(packed.length, 10);
69484
+ end.writeUInt32LE(directory.length, 12);
69485
+ end.writeUInt32LE(offset, 16);
69486
+ return {
69487
+ zip: Buffer.concat([...locals, directory, end]),
69488
+ packed,
69489
+ bytes: read
69490
+ };
69491
+ }
69492
+ function positiveId(value, field) {
69493
+ const number = typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value) : value;
69494
+ if (!Number.isInteger(number) || number < 1 || number > 2147483647) {
69495
+ throw new Error(`${field} must be a Temps id, a whole number such as 4.`);
69496
+ }
69497
+ return number;
69498
+ }
69499
+ function readArguments(args) {
69500
+ const input = args && typeof args === "object" ? args : {};
69501
+ if (typeof input.path !== "string" || !input.path.trim()) {
69502
+ throw new Error("Give path: the full path of the project folder on this computer.");
69503
+ }
69504
+ return {
69505
+ path: input.path,
69506
+ projectId: positiveId(input.project_id, "project_id"),
69507
+ environmentId: input.environment_id === undefined || input.environment_id === null ? null : positiveId(input.environment_id, "environment_id")
69508
+ };
69509
+ }
69510
+ async function packFolder(root) {
69511
+ const collected = await collectFiles(root);
69512
+ return { collected, ...await packZip(collected) };
69513
+ }
69514
+ async function requireMcpEnabled(api, config) {
69515
+ const res = await api("GET", "/mcp/tools", { accept: "application/json" });
69516
+ if (res.status === 404) {
69517
+ throw new Error(`The Temps MCP server is turned off at ${config.origin}, so nothing is deployed. An administrator can turn it on in Settings.`);
69518
+ }
69519
+ apiJson(res, config, "check that the Temps MCP server is on");
69520
+ }
69521
+ function rejectedKey(origin, host = HOSTS.extension) {
69522
+ return `Temps at ${origin} rejected the API key. Create a new key in the Temps console and update it in ${host.settings}.`;
69523
+ }
69524
+ function problemDetail(text) {
69525
+ try {
69526
+ const problem = JSON.parse(text);
69527
+ return String(problem.detail || problem.title || "").slice(0, 500);
69528
+ } catch {
69529
+ return "";
69530
+ }
69531
+ }
69532
+ function apiJson(res, config, action) {
69533
+ const { origin } = config;
69534
+ const host = config.host || HOSTS.extension;
69535
+ if (res.status >= 300 && res.status < 400) {
69536
+ throw new Error(`Temps at ${origin} redirected the request. The extension does not follow redirects, so your key only goes to the address you set.`);
69537
+ }
69538
+ if (res.status === 401)
69539
+ throw new Error(rejectedKey(origin, host));
69540
+ if (res.status < 200 || res.status >= 300) {
69541
+ const detail = problemDetail(res.text);
69542
+ if (res.status === 403) {
69543
+ throw new Error(`The API key may not ${action}${detail ? `: ${detail}` : "."} Use a key that can make changes: create one in the Temps console and update it in ${host.settings}.`);
69544
+ }
69545
+ if (res.status === 404) {
69546
+ throw new Error(`Could not ${action}: ${detail || "not found"}. Check the ids with the temps tool.`);
69547
+ }
69548
+ throw new Error(`Could not ${action}: Temps at ${origin} answered ${res.status}${detail ? `: ${detail}` : "."}`);
69549
+ }
69550
+ const type = String(res.headers["content-type"] || "").toLowerCase();
69551
+ try {
69552
+ if (!type.includes("json"))
69553
+ throw new Error("not JSON");
69554
+ return JSON.parse(res.text);
69555
+ } catch {
69556
+ throw new Error(`${origin} answered with ${type ? type.split(";")[0] : "something"} instead of the Temps API. Set the server address to the address of your Temps console.`);
69557
+ }
69558
+ }
69559
+ async function chooseEnvironment(api, config, projectId, environmentId) {
69560
+ if (environmentId !== null)
69561
+ return { id: environmentId, name: null };
69562
+ const action = `list the environments of project ${projectId}`;
69563
+ const list = apiJson(await api("GET", `/api/projects/${projectId}/environments`), config, action);
69564
+ const standing = (Array.isArray(list) ? list : []).filter((env) => env && Number.isInteger(env.id) && !env.is_preview);
69565
+ const production = standing.find((env) => env.slug === "production" || String(env.name || "").toLowerCase() === "production");
69566
+ const chosen = production || (standing.length === 1 ? standing[0] : null);
69567
+ if (chosen)
69568
+ return { id: chosen.id, name: chosen.name || null };
69569
+ if (standing.length === 0) {
69570
+ throw new Error(`Project ${projectId} has no environment to deploy to, or there is no project ${projectId}. Check the id with the temps tool.`);
69571
+ }
69572
+ throw new Error(`Project ${projectId} has several environments and none is production. Pass environment_id: ${standing.map((env) => `${env.name} (${env.id})`).join(", ")}.`);
69573
+ }
69574
+ function leftOutLine({ leftOut, leftOutCount }) {
69575
+ if (leftOutCount === 0)
69576
+ return "Nothing was left out.";
69577
+ const shown = leftOut.join(", ");
69578
+ const rest = leftOutCount - leftOut.length;
69579
+ const more = rest > 0 ? ` and ${rest} more` : "";
69580
+ return `Left out: ${shown}${more}.`;
69581
+ }
69582
+ async function deployFolder(config, args, api) {
69583
+ const input = readArguments(args);
69584
+ const root = await allowedRoot(input.path, config.folders, config.host);
69585
+ await requireMcpEnabled(api, config);
69586
+ const environment = await chooseEnvironment(api, config, input.projectId, input.environmentId);
69587
+ const target = `project ${input.projectId}${environment.name ? ` (${environment.name})` : ` (environment ${environment.id})`}`;
69588
+ const { collected, zip, packed, bytes } = await packFolder(root);
69589
+ if (packed.length === 0) {
69590
+ throw new Error(`${root} has nothing to deploy once secrets, dependencies and what .gitignore lists are left out. ${leftOutLine(collected)}`);
69591
+ }
69592
+ const boundary = `temps-${crypto2.randomBytes(16).toString("hex")}`;
69593
+ const body = Buffer.concat([
69594
+ Buffer.from(`--${boundary}\r
69595
+ Content-Disposition: form-data; name="file"; filename="source.zip"\r
69596
+ Content-Type: application/zip\r
69597
+ \r
69598
+ `),
69599
+ zip,
69600
+ Buffer.from(`\r
69601
+ --${boundary}--\r
69602
+ `)
69603
+ ]);
69604
+ const deployment = apiJson(await api("POST", `/api/projects/${input.projectId}/environments/${environment.id}/deploy/source`, {
69605
+ "content-type": `multipart/form-data; boundary=${boundary}`,
69606
+ accept: "application/json"
69607
+ }, body), config, `deploy ${target}`);
69608
+ const id = deployment && deployment.id;
69609
+ if (id === undefined || id === null || id === "") {
69610
+ throw new Error(`Temps took the upload for ${target} but did not say which deployment it started, so the deploy may not have begun. Check the project in Temps before you try again.`);
69611
+ }
69612
+ return [
69613
+ `Deployment ${id} of ${target} started: Temps is building it now.`,
69614
+ `Uploaded ${packed.length} file${packed.length === 1 ? "" : "s"} (${megabytes(bytes)}, ${megabytes(zip.length)} zipped) from ${root}.`,
69615
+ leftOutLine(collected),
69616
+ `Follow the build and its logs with the temps tool (deployment ${id}).`
69617
+ ].join(`
69618
+ `);
69619
+ }
69620
+ module.exports = {
69621
+ DEPLOY_TOOL,
69622
+ DEPLOY_TOOL_NAME,
69623
+ LIMITS,
69624
+ alwaysLeftOut,
69625
+ parseIgnore,
69626
+ isIgnored,
69627
+ allowedRoot,
69628
+ collectFiles,
69629
+ packZip,
69630
+ deployFolder,
69631
+ rejectedKey,
69632
+ HOSTS,
69633
+ hostFor
69634
+ };
69635
+ });
69636
+
69637
+ // ../../web/src/lib/claude-extension/bridge.cjs
69638
+ var require_bridge = __commonJS(function(exports, module) {
69639
+ var http = __require("node:http");
69640
+ var https = __require("node:https");
69641
+ var dns = __require("node:dns");
69642
+ var net = __require("node:net");
69643
+ var os = __require("node:os");
69644
+ var nodePath = __require("node:path");
69645
+ var deploy = require_deploy();
69646
+ var MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
69647
+ var REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
69648
+ var CONNECT_TIMEOUT_MS = 10 * 1000;
69649
+ var USER_AGENT = "temps-claude-extension/1";
69650
+ function normalizeIp(address) {
69651
+ let ip = String(address).toLowerCase();
69652
+ if (ip.startsWith("[") && ip.endsWith("]"))
69653
+ ip = ip.slice(1, -1);
69654
+ const zone = ip.indexOf("%");
69655
+ if (zone !== -1)
69656
+ ip = ip.slice(0, zone);
69657
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
69658
+ return mapped ? mapped[1] : ip;
69659
+ }
69660
+ function isLoopback(address) {
69661
+ const ip = normalizeIp(address);
69662
+ if (net.isIPv4(ip))
69663
+ return ip.split(".")[0] === "127";
69664
+ return ip === "::1";
69665
+ }
69666
+ function inTailscaleIpv6(ip) {
69667
+ return net.isIPv6(ip) && ip.startsWith("fd7a:115c:a1e0:");
69668
+ }
69669
+ function plainHttpAllowed(address) {
69670
+ const ip = normalizeIp(address);
69671
+ if (isLoopback(ip))
69672
+ return true;
69673
+ if (net.isIPv4(ip)) {
69674
+ const [a, b] = ip.split(".").map(Number);
69675
+ return a === 100 && b >= 64 && b <= 127;
69676
+ }
69677
+ return inTailscaleIpv6(ip);
69678
+ }
69679
+ function tailnetLocalAddresses(interfaces = os.networkInterfaces()) {
69680
+ const local = new Set;
69681
+ for (const addresses of Object.values(interfaces || {})) {
69682
+ const list = (addresses || []).map((a) => normalizeIp(a.address));
69683
+ if (list.some(inTailscaleIpv6))
69684
+ for (const ip of list)
69685
+ local.add(ip);
69686
+ }
69687
+ return local;
69688
+ }
69689
+ function notThroughTailscale(origin, address) {
69690
+ return `The extension does not send your API key over plain HTTP to ${origin}: ${address} is in Tailscale's range, but this computer does not reach it through Tailscale, and other networks (an ISP's CGNAT) use that range unencrypted. Connect this computer to the tailnet, or serve Temps over HTTPS.`;
69691
+ }
69692
+ async function plainHttpSource(origin, address, port, local = tailnetLocalAddresses(), connect2 = net.connect) {
69693
+ if (isLoopback(address))
69694
+ return;
69695
+ if (local.size === 0)
69696
+ throw new Error(notThroughTailscale(origin, address));
69697
+ const source = await new Promise((resolve, reject) => {
69698
+ const socket = connect2({ host: address, port });
69699
+ const timer = setTimeout(() => {
69700
+ socket.destroy();
69701
+ const error = new Error(`Could not connect to ${origin} within ${CONNECT_TIMEOUT_MS / 1000} seconds.`);
69702
+ error.code = "ETIMEDOUT";
69703
+ reject(error);
69704
+ }, CONNECT_TIMEOUT_MS);
69705
+ socket.once("connect", () => {
69706
+ clearTimeout(timer);
69707
+ const from = socket.localAddress;
69708
+ socket.destroy();
69709
+ resolve(from);
69710
+ });
69711
+ socket.once("error", (error) => {
69712
+ clearTimeout(timer);
69713
+ socket.destroy();
69714
+ reject(error);
69715
+ });
69716
+ });
69717
+ const from = normalizeIp(source || "");
69718
+ if (!local.has(from))
69719
+ throw new Error(notThroughTailscale(origin, address));
69720
+ return from;
69721
+ }
69722
+ function allowedFolders(argv) {
69723
+ return (argv || []).filter((folder) => typeof folder === "string" && folder.trim() !== "" && !folder.includes("${") && nodePath.isAbsolute(folder));
69724
+ }
69725
+ function readConfig(env, argv) {
69726
+ const host = deploy.hostFor(env);
69727
+ const raw = String(env.TEMPS_URL || "").trim();
69728
+ if (!raw) {
69729
+ throw new Error(`Set the Temps server address in ${host.settings}, for example https://temps.example.com.`);
69730
+ }
69731
+ let url;
69732
+ try {
69733
+ url = new URL(raw);
69734
+ } catch {
69735
+ throw new Error(`"${raw}" is not a valid Temps server address.`);
69736
+ }
69737
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
69738
+ throw new Error(`The Temps server address must start with https://, not ${url.protocol}//.`);
69739
+ }
69740
+ if (url.username || url.password) {
69741
+ throw new Error("The Temps server address must not contain a user name or password. Put the API key in its own setting.");
69742
+ }
69743
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
69744
+ if (url.protocol === "http:" && net.isIP(hostname) && !plainHttpAllowed(hostname)) {
69745
+ throw new Error(plainHttpRefusal(url.origin));
69746
+ }
69747
+ let key = String(env.TEMPS_API_KEY || "").trim();
69748
+ if (/^bearer\s+/i.test(key))
69749
+ key = key.replace(/^bearer\s+/i, "");
69750
+ if (!key) {
69751
+ throw new Error(`Set your Temps API key in ${host.settings}.`);
69752
+ }
69753
+ if (!/^[\x21-\x7e]+$/.test(key)) {
69754
+ throw new Error("The Temps API key contains spaces or characters a key never has. Paste it again.");
69755
+ }
69756
+ const endpoint = new URL("/mcp", url.origin);
69757
+ endpoint.searchParams.set("write", "1");
69758
+ return {
69759
+ endpoint,
69760
+ origin: url.origin,
69761
+ key,
69762
+ folders: allowedFolders(argv),
69763
+ host
69764
+ };
69765
+ }
69766
+ function plainHttpRefusal(origin) {
69767
+ return `The extension does not send your API key over plain HTTP to ${origin}: only to this computer or a Tailscale address. Serve Temps over HTTPS, or reach it through Tailscale, and update the server address.`;
69768
+ }
69769
+ async function resolvePlainHttp(endpoint) {
69770
+ const host = endpoint.hostname.replace(/^\[|\]$/g, "");
69771
+ const addresses = net.isIP(host) ? [{ address: host }] : await dns.promises.lookup(host, { all: true, verbatim: true });
69772
+ if (addresses.length === 0 || !addresses.every((a) => plainHttpAllowed(a.address))) {
69773
+ throw new Error(plainHttpRefusal(endpoint.origin));
69774
+ }
69775
+ return addresses.map((a) => a.address);
69776
+ }
69777
+ var UNREACHABLE = new Set([
69778
+ "ETIMEDOUT",
69779
+ "ECONNREFUSED",
69780
+ "EHOSTUNREACH",
69781
+ "ENETUNREACH",
69782
+ "EADDRNOTAVAIL"
69783
+ ]);
69784
+ async function send(config, method, path, headers, body) {
69785
+ if (!path.startsWith("/") || path.startsWith("//")) {
69786
+ throw new Error(`Refusing to send the key to ${path}.`);
69787
+ }
69788
+ const request = { method, path, headers: headers || {}, body };
69789
+ if (config.endpoint.protocol === "https:") {
69790
+ return sendTo(config, config.endpoint.hostname.replace(/^\[|\]$/g, ""), request);
69791
+ }
69792
+ const addresses = await resolvePlainHttp(config.endpoint);
69793
+ const port = Number(config.endpoint.port || 80);
69794
+ for (let i = 0;; i++) {
69795
+ try {
69796
+ const source = await plainHttpSource(config.origin, addresses[i], port);
69797
+ return await sendTo(config, addresses[i], request, source);
69798
+ } catch (error) {
69799
+ const code = error && typeof error === "object" ? error.code : undefined;
69800
+ if (i + 1 >= addresses.length || !UNREACHABLE.has(code))
69801
+ throw error;
69802
+ }
69803
+ }
69804
+ }
69805
+ function post(config, body, sessionId) {
69806
+ const headers = {
69807
+ "content-type": "application/json",
69808
+ accept: "application/json, text/event-stream"
69809
+ };
69810
+ if (sessionId)
69811
+ headers["mcp-session-id"] = sessionId;
69812
+ const { endpoint } = config;
69813
+ return send(config, "POST", `${endpoint.pathname}${endpoint.search}`, headers, body);
69814
+ }
69815
+ async function sendTo(config, hostname, request, localAddress) {
69816
+ const { endpoint } = config;
69817
+ const limit = config.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
69818
+ const secure = endpoint.protocol === "https:";
69819
+ const headers = {
69820
+ ...request.headers,
69821
+ authorization: `Bearer ${config.key}`,
69822
+ "user-agent": USER_AGENT,
69823
+ host: endpoint.host
69824
+ };
69825
+ if (request.body !== undefined) {
69826
+ headers["content-length"] = Buffer.byteLength(request.body);
69827
+ }
69828
+ const options = {
69829
+ method: request.method,
69830
+ protocol: endpoint.protocol,
69831
+ hostname,
69832
+ port: endpoint.port || (secure ? 443 : 80),
69833
+ path: request.path,
69834
+ headers,
69835
+ timeout: limit,
69836
+ agent: false
69837
+ };
69838
+ if (localAddress)
69839
+ options.localAddress = localAddress;
69840
+ return new Promise((resolve, reject) => {
69841
+ const deadline = setTimeout(() => {
69842
+ req.destroy(new Error(`Temps did not answer within ${limit / 1000} seconds.`));
69843
+ }, limit);
69844
+ const settle = (fn) => (value) => {
69845
+ clearTimeout(deadline);
69846
+ fn(value);
69847
+ };
69848
+ resolve = settle(resolve);
69849
+ reject = settle(reject);
69850
+ const req = (secure ? https : http).request(options, (res) => {
69851
+ const chunks = [];
69852
+ let size = 0;
69853
+ res.on("data", (chunk) => {
69854
+ size += chunk.length;
69855
+ if (size > MAX_MESSAGE_BYTES) {
69856
+ req.destroy(new Error(`Temps sent a response larger than ${MAX_MESSAGE_BYTES} bytes; it was dropped.`));
69857
+ return;
69858
+ }
69859
+ chunks.push(chunk);
69860
+ });
69861
+ res.on("end", () => resolve({
69862
+ status: res.statusCode || 0,
69863
+ headers: res.headers,
69864
+ text: Buffer.concat(chunks).toString("utf8")
69865
+ }));
69866
+ res.on("error", reject);
69867
+ });
69868
+ req.on("socket", (socket) => {
69869
+ if (!socket.connecting)
69870
+ return;
69871
+ const timer = setTimeout(() => {
69872
+ const error = new Error(`Could not connect to ${config.origin} within ${CONNECT_TIMEOUT_MS / 1000} seconds.`);
69873
+ error.code = "ETIMEDOUT";
69874
+ req.destroy(error);
69875
+ }, CONNECT_TIMEOUT_MS);
69876
+ socket.once("connect", () => clearTimeout(timer));
69877
+ socket.once("close", () => clearTimeout(timer));
69878
+ });
69879
+ req.on("timeout", () => req.destroy(new Error(`Temps did not answer within ${limit / 1000} seconds.`)));
69880
+ req.on("error", reject);
69881
+ req.end(request.body);
69882
+ });
69883
+ }
69884
+ function parseSse(text) {
69885
+ const messages = [];
69886
+ for (const event of text.split(/\r?\n\r?\n/)) {
69887
+ const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join(`
69888
+ `);
69889
+ if (data)
69890
+ messages.push(JSON.parse(data));
69891
+ }
69892
+ return messages;
69893
+ }
69894
+ function statusError(status, text, origin, host) {
69895
+ if (status === 401)
69896
+ return deploy.rejectedKey(origin, host);
69897
+ if (status === 403) {
69898
+ return `The API key cannot read projects on ${origin}. Use a key with at least the reader role.`;
69899
+ }
69900
+ if (status === 404) {
69901
+ return `The MCP server is off on ${origin}, or the address is not a Temps console. An admin turns it on in the Temps console under Settings, MCP server.`;
69902
+ }
69903
+ let detail = "";
69904
+ try {
69905
+ const problem = JSON.parse(text);
69906
+ detail = problem.detail || problem.title || "";
69907
+ } catch {}
69908
+ return `Temps at ${origin} answered ${status}${detail ? `: ${String(detail).slice(0, 500)}` : "."}`;
69909
+ }
69910
+ async function forward(config, message, session) {
69911
+ const res = await post(config, JSON.stringify(message), session.id);
69912
+ const sessionHeader = res.headers["mcp-session-id"];
69913
+ if (typeof sessionHeader === "string" && sessionHeader)
69914
+ session.id = sessionHeader;
69915
+ if (res.status >= 300 && res.status < 400) {
69916
+ throw new Error(`Temps at ${config.origin} redirected the request. The extension does not follow redirects, so your key only goes to the address you set. Set the server address to the console's final address.`);
69917
+ }
69918
+ if (res.status === 202 || res.status === 204)
69919
+ return [];
69920
+ if (res.status < 200 || res.status >= 300) {
69921
+ throw new Error(statusError(res.status, res.text, config.origin, config.host));
69922
+ }
69923
+ const type = String(res.headers["content-type"] || "").toLowerCase();
69924
+ if (type.includes("text/event-stream"))
69925
+ return parseSse(res.text);
69926
+ if (!res.text.trim())
69927
+ return [];
69928
+ const notMcp = () => new Error(`${config.origin}/mcp answered with ${type ? type.split(";")[0] : "something"} instead of Temps' MCP endpoint. Set the server address to the address of your Temps console.`);
69929
+ if (type && !type.includes("json"))
69930
+ throw notMcp();
69931
+ let body;
69932
+ try {
69933
+ body = JSON.parse(res.text);
69934
+ } catch {
69935
+ throw notMcp();
69936
+ }
69937
+ return Array.isArray(body) ? body : [body];
69938
+ }
69939
+ function errorReply(id, code, message) {
69940
+ return { jsonrpc: "2.0", id, error: { code, message } };
69941
+ }
69942
+ function toolResult(id, text, isError) {
69943
+ return {
69944
+ jsonrpc: "2.0",
69945
+ id,
69946
+ result: { content: [{ type: "text", text }], isError }
69947
+ };
69948
+ }
69949
+ function cancelledRequestId(message) {
69950
+ if (!message || message.method !== "notifications/cancelled")
69951
+ return;
69952
+ const params = message.params;
69953
+ return params && typeof params === "object" ? params.requestId : undefined;
69954
+ }
69955
+ function isDeployCall(message) {
69956
+ return message.method === "tools/call" && message.params && message.params.name === deploy.DEPLOY_TOOL_NAME;
69957
+ }
69958
+ function withDeployTool(message, replies) {
69959
+ if (!message || message.method !== "tools/list" || message.params && message.params.cursor) {
69960
+ return replies;
69961
+ }
69962
+ return replies.map((reply) => {
69963
+ const tools = reply && reply.result && reply.result.tools;
69964
+ if (reply.id !== message.id || !Array.isArray(tools))
69965
+ return reply;
69966
+ if (tools.some((tool) => tool && tool.name === deploy.DEPLOY_TOOL_NAME)) {
69967
+ return reply;
69968
+ }
69969
+ return {
69970
+ ...reply,
69971
+ result: { ...reply.result, tools: [...tools, deploy.DEPLOY_TOOL] }
69972
+ };
69973
+ });
69974
+ }
69975
+ var MAX_WAITING_DEPLOYS = 4;
69976
+ var MAX_IN_FLIGHT = 16;
69977
+ function serialQueue(maxWaiting) {
69978
+ const waiting = [];
69979
+ let running = false;
69980
+ const next = () => {
69981
+ if (running)
69982
+ return;
69983
+ const entry = waiting.shift();
69984
+ if (!entry)
69985
+ return;
69986
+ running = true;
69987
+ Promise.resolve().then(entry.task).then(entry.resolve, entry.reject).finally(() => {
69988
+ running = false;
69989
+ next();
69990
+ });
69991
+ };
69992
+ const queue = (task, token) => {
69993
+ if (running && waiting.length >= maxWaiting) {
69994
+ return Promise.reject(new Error(`${waiting.length} folder deployments are already waiting for the one running. Try again once they finish.`));
69995
+ }
69996
+ return new Promise((resolve, reject) => {
69997
+ waiting.push({ task, token, resolve, reject });
69998
+ next();
69999
+ });
70000
+ };
70001
+ queue.withdraw = (token) => {
70002
+ const at = waiting.findIndex((entry) => entry.token === token);
70003
+ if (at === -1)
70004
+ return false;
70005
+ const [entry] = waiting.splice(at, 1);
70006
+ entry.resolve(null);
70007
+ return true;
70008
+ };
70009
+ return queue;
70010
+ }
70011
+ function isCancellation(line) {
70012
+ if (!line.includes("notifications/cancelled"))
70013
+ return false;
70014
+ try {
70015
+ const message = JSON.parse(line);
70016
+ return message !== null && typeof message === "object" && message.method === "notifications/cancelled" && !("id" in message);
70017
+ } catch {
70018
+ return false;
70019
+ }
70020
+ }
70021
+ function run(config, input, output, log) {
70022
+ const session = { id: null };
70023
+ let buffer = "";
70024
+ let discarding = false;
70025
+ let pending = 0;
70026
+ let cancelling = 0;
70027
+ let ended = false;
70028
+ const deployOneAtATime = serialQueue(MAX_WAITING_DEPLOYS);
70029
+ const localCalls = new Map;
70030
+ let drained = null;
70031
+ const write = (message) => {
70032
+ if (output.write(`${JSON.stringify(message)}
70033
+ `))
70034
+ return Promise.resolve();
70035
+ if (output.destroyed || output.writableEnded)
70036
+ return Promise.resolve();
70037
+ if (!drained) {
70038
+ drained = new Promise((resolve) => {
70039
+ const done = () => {
70040
+ output.off("drain", done);
70041
+ output.off("close", done);
70042
+ output.off("error", done);
70043
+ drained = null;
70044
+ resolve();
70045
+ };
70046
+ output.on("drain", done);
70047
+ output.on("close", done);
70048
+ output.on("error", done);
70049
+ });
70050
+ }
70051
+ return drained;
70052
+ };
70053
+ const maybeExit = () => {
70054
+ if (ended && pending === 0 && !buffer.includes(`
70055
+ `)) {
70056
+ if (output !== process.stdout)
70057
+ output.end();
70058
+ }
70059
+ };
70060
+ const handle = async (line) => {
70061
+ let message;
70062
+ try {
70063
+ message = JSON.parse(line);
70064
+ } catch {
70065
+ await write(errorReply(null, -32700, "The extension received a message that is not JSON."));
70066
+ return;
70067
+ }
70068
+ const id = message && typeof message === "object" && "id" in message ? message.id : undefined;
70069
+ const isRequest = id !== undefined && id !== null;
70070
+ const method = message && typeof message.method === "string" ? message.method : "reply";
70071
+ const started = Date.now();
70072
+ const cancelled = cancelledRequestId(message);
70073
+ if (cancelled !== undefined && localCalls.has(cancelled)) {
70074
+ const call = localCalls.get(cancelled);
70075
+ call.cancelled = true;
70076
+ deployOneAtATime.withdraw(call);
70077
+ log(`temps: ${deploy.DEPLOY_TOOL_NAME} request ${cancelled} cancelled`);
70078
+ return;
70079
+ }
70080
+ if (isRequest && isDeployCall(message)) {
70081
+ const call = { cancelled: false };
70082
+ localCalls.set(id, call);
70083
+ try {
70084
+ if (config instanceof Error)
70085
+ throw config;
70086
+ const text = await deployOneAtATime(() => deploy.deployFolder(config, message.params.arguments, (verb, path, headers, body) => {
70087
+ if (call.cancelled) {
70088
+ return Promise.reject(new Error(`${deploy.DEPLOY_TOOL_NAME} request ${id} was cancelled; nothing more is sent to Temps.`));
70089
+ }
70090
+ return send(config, verb, path, headers, body);
70091
+ }), call);
70092
+ if (!call.cancelled)
70093
+ await write(toolResult(id, text, false));
70094
+ } catch (error) {
70095
+ const text = error instanceof Error ? error.message : String(error);
70096
+ if (!call.cancelled)
70097
+ await write(toolResult(id, text, true));
70098
+ } finally {
70099
+ localCalls.delete(id);
70100
+ }
70101
+ log(`temps: ${deploy.DEPLOY_TOOL_NAME} ${call.cancelled ? "cancelled" : "answered"} in ${Date.now() - started} ms`);
70102
+ return;
70103
+ }
70104
+ try {
70105
+ if (config instanceof Error)
70106
+ throw config;
70107
+ const replies = withDeployTool(message, await forward(config, message, session));
70108
+ for (const reply of replies)
70109
+ await write(reply);
70110
+ log(`temps: ${method} answered in ${Date.now() - started} ms`);
70111
+ } catch (error) {
70112
+ const text = error instanceof Error ? error.message : String(error);
70113
+ log(`temps: ${text}`);
70114
+ if (isRequest)
70115
+ await write(errorReply(id, -32000, text));
70116
+ }
70117
+ };
70118
+ const start = (line, cancellation = false) => {
70119
+ pending++;
70120
+ if (cancellation)
70121
+ cancelling++;
70122
+ handle(line).finally(() => {
70123
+ pending--;
70124
+ if (cancellation)
70125
+ cancelling--;
70126
+ pump();
70127
+ maybeExit();
70128
+ });
70129
+ };
70130
+ const pump = () => {
70131
+ let newline;
70132
+ while (pending < MAX_IN_FLIGHT && (newline = buffer.indexOf(`
70133
+ `)) !== -1) {
70134
+ const line = buffer.slice(0, newline).trim();
70135
+ buffer = buffer.slice(newline + 1);
70136
+ if (discarding) {
70137
+ discarding = false;
70138
+ continue;
70139
+ }
70140
+ if (line)
70141
+ start(line);
70142
+ }
70143
+ if (pending >= MAX_IN_FLIGHT && buffer.includes(`
70144
+ `)) {
70145
+ const lines = buffer.split(`
70146
+ `);
70147
+ const partial = lines.pop();
70148
+ const kept = lines.filter((line, at) => {
70149
+ if (discarding && at === 0 || cancelling >= MAX_IN_FLIGHT || !isCancellation(line.trim())) {
70150
+ return true;
70151
+ }
70152
+ start(line.trim(), true);
70153
+ return false;
70154
+ });
70155
+ buffer = kept.length > 0 ? `${kept.join(`
70156
+ `)}
70157
+ ${partial}` : partial;
70158
+ }
70159
+ const full = buffer.includes(`
70160
+ `);
70161
+ if (full && !input.isPaused())
70162
+ input.pause();
70163
+ if (!full && input.isPaused() && !ended)
70164
+ input.resume();
70165
+ if (!full && Buffer.byteLength(buffer) > MAX_MESSAGE_BYTES) {
70166
+ log(`temps: dropped a message larger than ${MAX_MESSAGE_BYTES} bytes`);
70167
+ buffer = "";
70168
+ discarding = true;
70169
+ }
70170
+ };
70171
+ input.setEncoding("utf8");
70172
+ input.on("data", (chunk) => {
70173
+ buffer += chunk;
70174
+ pump();
70175
+ });
70176
+ input.on("end", () => {
70177
+ ended = true;
70178
+ maybeExit();
70179
+ });
70180
+ }
70181
+ function main(env = process.env, argv = process.argv.slice(2)) {
70182
+ const log = (line) => process.stderr.write(`${line}
70183
+ `);
70184
+ let config;
70185
+ try {
70186
+ config = readConfig(env, argv);
70187
+ log(`temps: ready, forwarding MCP to ${config.endpoint.href}`);
70188
+ log(config.folders.length > 0 ? `temps: may deploy from ${config.folders.join(", ")}` : "temps: no folder may be deployed yet");
70189
+ } catch (error) {
70190
+ config = error instanceof Error ? error : new Error(String(error));
70191
+ log(`temps: ${config.message}`);
70192
+ }
70193
+ run(config, process.stdin, process.stdout, log);
70194
+ }
70195
+ module.exports = {
70196
+ serialQueue,
70197
+ MAX_WAITING_DEPLOYS,
70198
+ MAX_IN_FLIGHT,
70199
+ plainHttpAllowed,
70200
+ tailnetLocalAddresses,
70201
+ plainHttpSource,
70202
+ readConfig,
70203
+ parseSse,
70204
+ sendTo,
70205
+ statusError,
70206
+ run,
70207
+ main
70208
+ };
70209
+ });
70210
+
68692
70211
  // node_modules/commander/index.js
68693
70212
  var exports_commander = {};
68694
70213
  __exportCjs(exports_commander, {
@@ -75213,12 +76732,27 @@ function ghAttestationArgs(archive, version) {
75213
76732
  RELEASE_REPO,
75214
76733
  "--cert-identity",
75215
76734
  releaseIdentity(version),
75216
- "--source-ref",
75217
- `refs/tags/${version}`,
75218
76735
  "--cert-oidc-issuer",
75219
- GITHUB_ACTIONS_ISSUER
76736
+ GITHUB_ACTIONS_ISSUER,
76737
+ "--format",
76738
+ "json"
75220
76739
  ];
75221
76740
  }
76741
+ function attestationBuiltFromTag(ghJson, version) {
76742
+ const expected = `refs/tags/${version}`;
76743
+ let results;
76744
+ try {
76745
+ results = JSON.parse(ghJson);
76746
+ } catch {
76747
+ return false;
76748
+ }
76749
+ if (!Array.isArray(results))
76750
+ return false;
76751
+ return results.some((result) => {
76752
+ const ref = result?.verificationResult?.signature?.certificate?.sourceRepositoryRef;
76753
+ return ref === expected;
76754
+ });
76755
+ }
75222
76756
  function pickRelease(releases, channel, target) {
75223
76757
  const asset = `${target}.tar.gz`;
75224
76758
  for (const release of releases) {
@@ -75277,6 +76811,13 @@ function parsePort(value) {
75277
76811
  }
75278
76812
  return port;
75279
76813
  }
76814
+ function parseAdminEmail(value) {
76815
+ const email = value.trim();
76816
+ if (!/^[^\s@]+@[^\s@]+$/.test(email)) {
76817
+ throw new StartError("preflight", "bad_email", `--email must be an email address such as you@example.com (got "${value}").`);
76818
+ }
76819
+ return email;
76820
+ }
75280
76821
  function isLocalState(value) {
75281
76822
  if (typeof value !== "object" || value === null)
75282
76823
  return false;
@@ -75686,6 +77227,9 @@ async function verifyArchiveOrigin(archive, version, target, allowUnsigned, deps
75686
77227
  if (!gh || gh.code !== 0) {
75687
77228
  throw new StartError("download", "signature_failed", `The ${asset} archive for ${version} has no build attestation from ${identity}; it may have been ` + `tampered with. Nothing was installed. gh said: ${lastLines(gh?.stderr || gh?.stdout || "", 4)}`);
75688
77229
  }
77230
+ if (!attestationBuiltFromTag(gh.stdout, version)) {
77231
+ throw new StartError("download", "signature_failed", `The ${asset} archive for ${version} is attested by ${identity}, but not as built from ` + `refs/tags/${version}; it may have been tampered with. Nothing was installed.`);
77232
+ }
75689
77233
  return { kind: "gh", identity };
75690
77234
  }
75691
77235
  return { kind: "unverified", identity };
@@ -76238,7 +77782,26 @@ async function signInCli(bin, state, paths, options) {
76238
77782
  }
76239
77783
  return { minted, active: activate, previous };
76240
77784
  }
76241
- async function freshState(options, target) {
77785
+ async function adminEmailFor(options) {
77786
+ if (options.email !== undefined)
77787
+ return parseAdminEmail(options.email);
77788
+ if (options.json || isQuietMode() || !process.stdin.isTTY)
77789
+ return LOCAL_ADMIN_EMAIL;
77790
+ const answer = await promptText({
77791
+ message: "Email for your Temps admin account",
77792
+ default: LOCAL_ADMIN_EMAIL,
77793
+ validate: (value) => {
77794
+ try {
77795
+ parseAdminEmail(value);
77796
+ return true;
77797
+ } catch (error) {
77798
+ return error instanceof Error ? error.message.replace("--email", "The email") : "Enter an email address";
77799
+ }
77800
+ }
77801
+ });
77802
+ return parseAdminEmail(answer);
77803
+ }
77804
+ async function freshState(options, target, adminEmail) {
76242
77805
  const preferred = options.port === undefined ? undefined : parsePort(options.port);
76243
77806
  const isRoot = typeof process.getuid === "function" && process.getuid() === 0;
76244
77807
  const proxyPort = await pickPort(proxyPortCandidates(preferred, process.platform, isRoot), [], "apps and console");
@@ -76251,7 +77814,7 @@ async function freshState(options, target) {
76251
77814
  dbPassword: generateDbPassword(),
76252
77815
  proxyPort,
76253
77816
  consolePort,
76254
- adminEmail: LOCAL_ADMIN_EMAIL,
77817
+ adminEmail,
76255
77818
  adminPassword: generateAdminPassword(),
76256
77819
  setupComplete: false
76257
77820
  };
@@ -76268,17 +77831,23 @@ async function startLocked(options, paths) {
76268
77831
  parseChannel(options.channel);
76269
77832
  if (options.port !== undefined)
76270
77833
  parsePort(options.port);
77834
+ if (options.email !== undefined)
77835
+ parseAdminEmail(options.email);
76271
77836
  const cwd = process.cwd();
76272
77837
  const scope = resolveSkillsScope(options.skills, await readdir3(cwd));
76273
77838
  try {
76274
77839
  await steps.time("Checking Docker", dockerVersion, (version) => `Docker found (${version})`);
76275
77840
  let state = await readState2(paths);
76276
77841
  const running = Boolean(state && await isLocalServer(state.pid, paths) && await serverHealthy(state.consolePort));
77842
+ if (state && options.email !== undefined && parseAdminEmail(options.email) !== state.adminEmail) {
77843
+ console.error(colors.warning(`Temps is already set up here with the admin ${state.adminEmail}; --email only applies to a fresh install.`));
77844
+ }
76277
77845
  if (!state) {
76278
77846
  if (await containerState(DB_CONTAINER) !== "missing") {
76279
77847
  throw new StartError("state", "orphan_database", `A ${DB_CONTAINER} container exists but ${paths.state} is missing, so its password is unknown. ` + "Run `temps stop --delete-data` to remove it, then `temps start` again.");
76280
77848
  }
76281
- state = await steps.time("Resolving version", () => freshState(options, target), (s) => `Using Temps ${s.version}`);
77849
+ const adminEmail = await adminEmailFor(options);
77850
+ state = await steps.time("Resolving version", () => freshState(options, target, adminEmail), (s) => `Using Temps ${s.version}`);
76282
77851
  await writeState(paths, state);
76283
77852
  } else if (options.runtimeVersion && options.runtimeVersion !== state.version) {
76284
77853
  if (running) {
@@ -76454,7 +78023,7 @@ async function removeSandboxes(state) {
76454
78023
  };
76455
78024
  }
76456
78025
  function registerStartCommands(program) {
76457
- program.command("start").description("Run Temps on this computer, sign in the CLI and add the Temps skill for your coding agent").option("--channel <channel>", "Release channel for a fresh install: stable, beta or nightly", "beta").option("--runtime-version <tag>", "Run this exact Temps release").option("--allow-unsigned", "Run a release that publishes no Sigstore signature (only releases from before signing), trusting its checksum alone").option("--skills <scope>", "Where to add the Temps agent skill: project, global or none (default: project inside a project, otherwise global)").option("--port <port>", "Port for your apps and the console on a fresh install (default: 8080 or the next free port)").option("--make-default", 'Make "local" the default CLI context even if another one is active').option("--json", "Print the result as JSON, for scripts and agents").addHelpText("after", `
78026
+ program.command("start").description("Run Temps on this computer, sign in the CLI and add the Temps skill for your coding agent").option("--channel <channel>", "Release channel for a fresh install: stable, beta or nightly", "beta").option("--runtime-version <tag>", "Run this exact Temps release").option("--allow-unsigned", "Run a release that publishes no Sigstore signature (only releases from before signing), trusting its checksum alone").option("--skills <scope>", "Where to add the Temps agent skill: project, global or none (default: project inside a project, otherwise global)").option("--port <port>", "Port for your apps and the console on a fresh install (default: 8080 or the next free port)").option("--email <email>", "Email for the admin account of a fresh install (asked in a terminal; default: admin@localhost)").option("--make-default", 'Make "local" the default CLI context even if another one is active').option("--json", "Print the result as JSON, for scripts and agents").addHelpText("after", `
76458
78027
  Needs Docker (Docker Desktop, OrbStack or Colima). Everything listens on 127.0.0.1 only.
76459
78028
  ` + `State, logs and the admin password live in ~/.temps/local. The API key is stored in the "local" CLI context.
76460
78029
  `).action(startAction);
@@ -77364,6 +78933,120 @@ async function resolveWorkspaceSource(options) {
77364
78933
  };
77365
78934
  }
77366
78935
 
78936
+ // src/commands/sandbox/recording.ts
78937
+ init_sdk_gen();
78938
+
78939
+ // src/lib/egress-recording.ts
78940
+ init_output();
78941
+ var OUTCOME_FILTERS = ["allowed", "refused", "failed"];
78942
+ function parseOutcomeFilter(value) {
78943
+ if (value === undefined)
78944
+ return;
78945
+ const outcome = OUTCOME_FILTERS.find((candidate) => candidate === value.trim().toLowerCase());
78946
+ if (!outcome) {
78947
+ throw new Error(`Unknown --outcome '${value}'. Expected one of: ${OUTCOME_FILTERS.join(", ")}`);
78948
+ }
78949
+ return outcome;
78950
+ }
78951
+ function recordingChange(options) {
78952
+ if (options.on && options.off)
78953
+ throw new Error("--on and --off cannot be combined");
78954
+ if (options.on)
78955
+ return true;
78956
+ if (options.off)
78957
+ return false;
78958
+ return;
78959
+ }
78960
+ function describeDestination(record) {
78961
+ if (record.relay)
78962
+ return `${record.relay} relay`;
78963
+ const bare = record.host ?? "(no destination)";
78964
+ const host = bare.includes(":") && !bare.startsWith("[") ? `[${bare}]` : bare;
78965
+ const where = record.port ? `${host}:${record.port}` : host;
78966
+ return record.method && record.path ? `${record.method} ${where}${record.path}` : where;
78967
+ }
78968
+ function printRecordingStatus(title, status) {
78969
+ newline();
78970
+ header(`${icons.info} ${title}`);
78971
+ keyValue("Recording", status.enabled ? colors.success("on") : "off");
78972
+ keyValue("Can record", status.configured ? "yes" : "no");
78973
+ if (!status.configured && status.reason) {
78974
+ warning2(status.reason);
78975
+ if (status.setup_path)
78976
+ keyValue("Set it up at", status.setup_path);
78977
+ }
78978
+ for (const node of status.nodes) {
78979
+ const name = node.node_name ?? `node ${node.node_id}`;
78980
+ keyValue(` ${name}`, node.recording ? "records" : node.reason ?? "does not record");
78981
+ }
78982
+ if (status.logs_path)
78983
+ keyValue("Logs", status.logs_path);
78984
+ newline();
78985
+ }
78986
+ function printActivity(title, page) {
78987
+ newline();
78988
+ header(`${icons.info} ${title}`);
78989
+ printTable(page.records, [
78990
+ { header: "Time", accessor: (r) => r.timestamp },
78991
+ { header: "Outcome", accessor: (r) => r.outcome },
78992
+ { header: "Destination", accessor: describeDestination },
78993
+ { header: "Reason", accessor: (r) => r.reason ?? "" },
78994
+ { header: "Count", accessor: (r) => r.count, align: "right" }
78995
+ ]);
78996
+ keyValue("Page", `${page.page} (${page.records.length} of ${page.total})`);
78997
+ if (page.has_more)
78998
+ keyValue("More", `--page ${page.page + 1}`);
78999
+ newline();
79000
+ }
79001
+
79002
+ // src/commands/sandbox/recording.ts
79003
+ init_spinner();
79004
+ init_output();
79005
+ function registerSandboxRecordingCommands(sandbox) {
79006
+ sandbox.command("recording <id>").description("Show or set whether the sandbox records its outbound connections (destination, outcome, bytes; never headers or bodies)").option("--on", "Record its outbound connections").option("--off", "Stop recording").option("--json", "Output as JSON").action(recordingAction);
79007
+ sandbox.command("outbound <id>").description("List the outbound connections a recording sandbox made, newest first").option("--page <n>", "Page number (default 1)").option("--per-page <n>", "Records per page (default 20, max 100)").option("--outcome <outcome>", "Only allowed, refused or failed connections").option("--json", "Output as JSON").action(outboundAction);
79008
+ }
79009
+ async function recordingAction(id, options) {
79010
+ const enabled = recordingChange(options);
79011
+ await requireAuth();
79012
+ await setupClient();
79013
+ const status = await withSpinner(enabled === undefined ? "Fetching recording..." : "Updating recording...", async () => {
79014
+ const { data, error } = enabled === undefined ? await getEgressRecording({ client, path: { id } }) : await setEgressRecording({ client, path: { id }, body: { enabled } });
79015
+ if (error || !data)
79016
+ throw new Error(`Sandbox ${id}: ${getErrorMessage(error)}`);
79017
+ return data;
79018
+ });
79019
+ if (options.json) {
79020
+ json(status);
79021
+ return;
79022
+ }
79023
+ if (enabled !== undefined)
79024
+ success2(`Recording ${enabled ? "on" : "off"} for ${id}`);
79025
+ printRecordingStatus(`Outbound recording of ${id}`, status);
79026
+ }
79027
+ async function outboundAction(id, options) {
79028
+ const page = options.page === undefined ? undefined : parseIntegerFlag(options.page, "--page", 1);
79029
+ const perPage = options.perPage === undefined ? undefined : parseIntegerFlag(options.perPage, "--per-page", 1, 100);
79030
+ const outcome = parseOutcomeFilter(options.outcome);
79031
+ await requireAuth();
79032
+ await setupClient();
79033
+ const result = await withSpinner("Fetching outbound connections...", async () => {
79034
+ const { data, error } = await listEgressRecords({
79035
+ client,
79036
+ path: { id },
79037
+ query: { page, per_page: perPage, outcome }
79038
+ });
79039
+ if (error || !data)
79040
+ throw new Error(`Sandbox ${id}: ${getErrorMessage(error)}`);
79041
+ return data;
79042
+ });
79043
+ if (options.json) {
79044
+ json(result);
79045
+ return;
79046
+ }
79047
+ printActivity(`Outbound connections of ${id}`, result);
79048
+ }
79049
+
77367
79050
  // src/commands/sandbox/access.ts
77368
79051
  var PREVIEW_ACCESS_VALUES = [
77369
79052
  "temps_login",
@@ -77641,6 +79324,7 @@ function registerSandboxCommands(program) {
77641
79324
  sandbox.command("password <id>").description("Generate, rotate, or clear the preview-URL password for a sandbox").option("--rotate", "Generate a new random password and set it (default when no flag is given)").option("--length <n>", "Length of the generated password (8..=256, default 24)").option("--clear", "Remove the preview password — preview URLs become open again").action(passwordAction);
77642
79325
  sandbox.command("preview-access <id>").description("Show or set who may open the preview URLs: Temps login (default), the preview password, or anyone, optionally from listed networks only").option("--access <mode>", "temps_login (alias 'login'), password, or public. 'password' needs a preview password first (`sandbox password`)").option("--allow-ip <ip|cidr>", "Only these client networks may open previews, in every mode (repeatable; replaces the list)", (val, prev) => prev ? [...prev, val] : [val]).option("--any-ip", "Clear the allow-list: any client address may open previews").option("--json", "Output as JSON").action(previewAccessAction);
77643
79326
  sandbox.command("egress <id>").description("Show or set where the sandbox may connect to: the internet, nothing, or only listed hosts and CIDRs. Private, loopback and metadata addresses are always refused").option("--internet", "Remove the restriction").option("--deny-all", "Allow no outbound traffic at all").option("--allow <host|cidr[:ports]>", "Allow only these destinations (repeatable; replaces the policy; no ports = 80 and 443). IPv6 with ports: [addr/prefix]:port", (val, prev) => prev ? [...prev, val] : [val]).option("--json", "Output as JSON").action(egressAction);
79327
+ registerSandboxRecordingCommands(sandbox);
77644
79328
  const fs = sandbox.command("fs").description("Filesystem operations inside a sandbox");
77645
79329
  fs.command("read <id>").description("Read a file from the sandbox").requiredOption("--path <path>", "Absolute file path inside the sandbox").option("--out <localPath>", "Write to this local file (stdout when omitted)").action(fsReadAction);
77646
79330
  fs.command("write <id>").description("Write a file to the sandbox").requiredOption("--path <path>", "Absolute target path inside the sandbox").option("--file <localPath>", "Local source file to upload (mutually exclusive with --content)").option("--content <string>", "Inline string content to write").option("--mode <octal>", "Unix permission mask (default: 0644)").action(fsWriteAction);
@@ -83499,6 +85183,8 @@ function registerOtelEndpoints(program) {
83499
85183
  attribute_type: { kind: "string", help: "Optional native declared type; older records without type metadata do not match", values: ["string", "boolean", "integer", "double", "array", "object", "bytes"] },
83500
85184
  attribute_op: { kind: "string", help: "Default eq; numeric types also support lt/lte/gt/gte", values: ["eq", "ne", "lt", "lte", "gt", "gte"] },
83501
85185
  trace_id: { kind: "string", help: "Filter by correlated trace ID" },
85186
+ workload_kind: { kind: "string", help: "Only what the platform recorded about one workload of the project (sandbox, deployment, ...); pair with workload_id" },
85187
+ workload_id: { kind: "int", help: "The workload's numeric id; pair with workload_kind" },
83502
85188
  start_time: { kind: "string", help: "Start time (RFC 3339)" },
83503
85189
  end_time: { kind: "string", help: "End time (RFC 3339)" },
83504
85190
  limit: { kind: "int", help: "Max logs to return (default: 100, max: 1000)" },
@@ -84882,6 +86568,20 @@ function registerServicesEndpoints(program) {
84882
86568
  init_sdk_gen();
84883
86569
  function registerSettingsEndpoints(program) {
84884
86570
  const group = topGroup(program, "settings", "settings");
86571
+ endpoint(group, getOnboarding, {
86572
+ name: "onboarding get",
86573
+ description: "Show the install's first-run record: whether the welcome flow is finished, the steps left for later and why, and the default way in"
86574
+ });
86575
+ endpoint(group, updateOnboarding, {
86576
+ name: "onboarding update",
86577
+ description: "Change the install's first-run record",
86578
+ body: {
86579
+ completed: { kind: "bool", help: "Mark the welcome flow finished (true) or reopen it (false)" },
86580
+ default_reach: { kind: "json", help: 'How new apps are reached by default, e.g. {"audience":"public","way":"tunnel","naming":"wildcard","domain":"apps.example.com"}' },
86581
+ done: { kind: "strings", help: "Mark these steps done", values: ["host", "reach", "agents", "app"] },
86582
+ later: { kind: "json", help: 'Leave steps for later with why, e.g. [{"step":"agents","reason":"no provider yet"}]' }
86583
+ }
86584
+ });
84885
86585
  endpoint(group, listOidcProviders, {
84886
86586
  name: "oidc list-providers",
84887
86587
  description: "List oidc providers"
@@ -86327,6 +88027,10 @@ var CREATE_PROJECT_EXTRA = fieldFlags({
86327
88027
  is_public_repo: { kind: "bool", help: "The repository is public (cloned without a git connection)" },
86328
88028
  is_web_app: { kind: "bool", help: "The app serves HTTP (false for a worker with no port)" },
86329
88029
  performance_metrics_enabled: { kind: "bool", help: "Collect web performance metrics" },
88030
+ storage_service_env_aliases: {
88031
+ kind: "json",
88032
+ help: 'Variable aliases per linked storage service, keyed by service id: app name to injected name, e.g. {"12":{"DATABASE_URL":"POSTGRES_URL"}}'
88033
+ },
86330
88034
  use_default_wildcard: { kind: "bool", help: "Give environments a hostname under the instance's wildcard domain" }
86331
88035
  });
86332
88036
  var UPDATE_PROJECT_EXTRA = fieldFlags({
@@ -98779,6 +100483,58 @@ async function ingressSetCmd(environment, options) {
98779
100483
  printIngress(target, settings);
98780
100484
  }
98781
100485
 
100486
+ // src/commands/environments/recording.ts
100487
+ init_sdk_gen();
100488
+ init_spinner();
100489
+ init_output();
100490
+ function registerEnvironmentRecordingCommands(environments) {
100491
+ environments.command("recording <environment>").description("Show or set whether the environment's deployments record their outbound connections (destination, outcome, bytes; never headers or bodies). Takes effect on the next deployment").option("-p, --project <project>", "Project slug").option("--on", "Record outbound connections").option("--off", "Stop recording").option("--json", "Output in JSON format").action(recordingCmd);
100492
+ environments.command("outbound <environment>").description("List the outbound connections a recording environment's deployments made, newest first").option("-p, --project <project>", "Project slug").option("--page <n>", "Page number (default 1)").option("--per-page <n>", "Records per page (default 20, max 100)").option("--outcome <outcome>", "Only allowed, refused or failed connections").option("--json", "Output in JSON format").action(outboundCmd);
100493
+ }
100494
+ async function recordingCmd(environment, options) {
100495
+ const enabled = recordingChange(options);
100496
+ await connect2();
100497
+ const target = await resolveTarget(options.project, environment);
100498
+ const path = { project_id: target.projectId, environment_id: target.environmentId };
100499
+ const status = await withSpinner(enabled === undefined ? "Fetching recording..." : "Updating recording...", async () => {
100500
+ const { data, error } = enabled === undefined ? await getEnvironmentEgressRecording({ client, path }) : await setEnvironmentEgressRecording({ client, path, body: { enabled } });
100501
+ if (error || !data)
100502
+ throw new Error(getErrorMessage(error));
100503
+ return data;
100504
+ });
100505
+ if (options.json) {
100506
+ json(status);
100507
+ return;
100508
+ }
100509
+ const name = `${target.projectSlug}/${target.environmentSlug}`;
100510
+ if (enabled !== undefined) {
100511
+ success2(`Recording ${enabled ? "on" : "off"} for ${name}${enabled ? "; redeploy to start recording" : ""}`);
100512
+ }
100513
+ printRecordingStatus(`Outbound recording of ${name}`, status);
100514
+ }
100515
+ async function outboundCmd(environment, options) {
100516
+ const page = options.page === undefined ? undefined : parseIntegerFlag(options.page, "--page", 1);
100517
+ const perPage = options.perPage === undefined ? undefined : parseIntegerFlag(options.perPage, "--per-page", 1, 100);
100518
+ const outcome = parseOutcomeFilter(options.outcome);
100519
+ await connect2();
100520
+ const target = await resolveTarget(options.project, environment);
100521
+ const result = await withSpinner("Fetching outbound connections...", async () => {
100522
+ const { data, error } = await listEnvironmentEgressRecords({
100523
+ client,
100524
+ path: { project_id: target.projectId, environment_id: target.environmentId },
100525
+ query: { page, per_page: perPage, outcome }
100526
+ });
100527
+ if (error || !data)
100528
+ throw new Error(getErrorMessage(error));
100529
+ return data;
100530
+ });
100531
+ if (options.json) {
100532
+ json(result);
100533
+ return;
100534
+ }
100535
+ printActivity(`Outbound connections of ${target.projectSlug}/${target.environmentSlug}`, result);
100536
+ }
100537
+
98782
100538
  // src/commands/environments/index.ts
98783
100539
  var SET_VAR_EXAMPLES = `
98784
100540
  Examples:
@@ -98794,6 +100550,12 @@ Examples:
98794
100550
 
98795
100551
  # A plain, non-secret value can still be passed inline
98796
100552
  $ temps environments vars set LOG_LEVEL debug --environments production
100553
+
100554
+ # Let the server generate a random secret (32 bytes, hex); it is never shown
100555
+ $ temps environments vars set SESSION_SECRET --generate-secret --environments production
100556
+
100557
+ # Laravel's APP_KEY gets the base64: key its cipher needs
100558
+ $ temps environments vars set APP_KEY --generate-secret --environments production
98797
100559
  `;
98798
100560
  function registerEnvironmentsCommands(program) {
98799
100561
  const environments = program.command("environments").alias("envs").alias("env").description("Manage environments and environment variables");
@@ -98809,7 +100571,7 @@ function registerEnvironmentsCommands(program) {
98809
100571
  const projectSlug = cmd.parent.opts().project;
98810
100572
  return getEnvVar(projectSlug, key, options);
98811
100573
  });
98812
- const setVar = vars.command("set <key> [value]").description("Set an environment variable. For a secret, read the value from a file or stdin (--value-file, --value-stdin) so it stays out of shell history and `ps`; the CLI never prints it").option("-e, --environments <names>", "Comma-separated environment names (interactive if not provided)").option("--preview", "Also include in current and future preview environments").option("--no-preview", "Exclude from preview environments").option("--update", "Update existing variable instead of creating new").option("--secret", "Store as a secret: the value is masked in the UI and never returned by the API. One-way — to make a secret readable again you must delete the variable and create it anew");
100574
+ const setVar = vars.command("set <key> [value]").description("Set an environment variable. For a secret, read the value from a file or stdin (--value-file, --value-stdin) so it stays out of shell history and `ps`; the CLI never prints it").option("-e, --environments <names>", "Comma-separated environment names (interactive if not provided)").option("--preview", "Also include in current and future preview environments").option("--no-preview", "Exclude from preview environments").option("--update", "Update existing variable instead of creating new").option("--secret", "Store as a secret: the value is masked in the UI and never returned by the API. One-way — to make a secret readable again you must delete the variable and create it anew").option("--generate-secret [bytes|laravel]", "Have the server generate a random secret of this many bytes (16 to 64, 32 by default, hex), stored as a secret and never shown; for a new variable, instead of a value. `laravel`, the default for APP_KEY, makes a Laravel application key (base64:, 32 bytes)");
98813
100575
  addValueSourceOptions(setVar, { what: "the value" });
98814
100576
  setVar.addHelpText("after", SET_VAR_EXAMPLES).action(async (key, value, options, cmd) => {
98815
100577
  const projectSlug = cmd.parent.opts().project;
@@ -98832,6 +100594,7 @@ function registerEnvironmentsCommands(program) {
98832
100594
  environments.command("force-https <environment>").description("View or set the HTTP to HTTPS redirect override for an environment").option("-p, --project <project>", "Project slug or ID").option("--enable", "Always redirect plain HTTP to HTTPS, even without a local certificate").option("--disable", "Never redirect: keep serving this environment over plain HTTP").option("--inherit", "Clear the override and follow the proxy default").option("--json", "Output in JSON format").action(forceHttpsCmd);
98833
100595
  environments.command("scale").description("View or set the number of replicas for an environment").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment name or slug", "production").option("-r, --replicas <count>", "Number of replicas to set").option("--load-balancing <json>", "Replica routing policy as JSON; null restores project inheritance").option("--json", "Output in JSON format").action(scaleCmd);
98834
100596
  registerEnvironmentWorkloadCommands(environments);
100597
+ registerEnvironmentRecordingCommands(environments);
98835
100598
  const crons = environments.command("crons").description("Manage cron jobs").option("-p, --project <project>", "Project slug or ID").requiredOption("-e, --environment <env>", "Environment name or slug");
98836
100599
  crons.command("list").alias("ls").description("List cron jobs for an environment").option("--json", "Output in JSON format").action(async (options, cmd) => {
98837
100600
  const parentOpts = cmd.parent.opts();
@@ -99101,6 +100864,21 @@ async function getEnvVar(projectFlag, key, options) {
99101
100864
  newline();
99102
100865
  }
99103
100866
  }
100867
+ var LARAVEL_APP_KEY = "APP_KEY";
100868
+ function generateSecretRequest(option, key = "") {
100869
+ if (option === undefined || option === false)
100870
+ return;
100871
+ if (option === "laravel" || option === true && key === LARAVEL_APP_KEY) {
100872
+ return { kind: "laravel_app_key" };
100873
+ }
100874
+ if (option === true)
100875
+ return { kind: "secret" };
100876
+ const bytes = Number(option);
100877
+ if (!Number.isInteger(bytes) || bytes < 16 || bytes > 64) {
100878
+ throw new Error(`--generate-secret takes a byte count from 16 to 64, or laravel, not "${option}"`);
100879
+ }
100880
+ return { kind: "secret", bytes };
100881
+ }
99104
100882
  async function resolveSetVarValue(key, value, options, io) {
99105
100883
  const resolved = await resolveValueSource(valueSourceInput(value, options), {
99106
100884
  subject: `the value for ${key}`,
@@ -99110,8 +100888,15 @@ async function resolveSetVarValue(key, value, options, io) {
99110
100888
  return resolved?.value;
99111
100889
  }
99112
100890
  async function setEnvVar(projectFlag, key, value, options) {
99113
- const sourcedValue = await resolveSetVarValue(key, value, options);
99114
- if (sourcedValue === undefined && !process.stdin.isTTY) {
100891
+ const generate = generateSecretRequest(options.generateSecret, key);
100892
+ const sourcedValue = generate ? undefined : await resolveSetVarValue(key, value, options);
100893
+ if (generate && (value !== undefined || options.valueFile || options.valueStdin)) {
100894
+ throw new Error(`--generate-secret makes the value for ${key}: do not also pass one`);
100895
+ }
100896
+ if (generate && options.update) {
100897
+ throw new Error(`--generate-secret creates ${key}; to replace an existing variable's value, delete it first or pass the new value with --update`);
100898
+ }
100899
+ if (!generate && sourcedValue === undefined && !process.stdin.isTTY) {
99115
100900
  throw new Error(`Missing the value for ${key}: pass --value-file <path>, --value-stdin, or <value> (stdin is not a terminal, so it cannot be prompted for)`);
99116
100901
  }
99117
100902
  await requireAuth();
@@ -99141,10 +100926,14 @@ async function setEnvVar(projectFlag, key, value, options) {
99141
100926
  });
99142
100927
  if (envs.length === 0) {
99143
100928
  error2("No environments found. Create an environment first.");
100929
+ process.exitCode = 1;
99144
100930
  return;
99145
100931
  }
99146
100932
  const existingVar = existingVars.find((v) => v.key === key);
99147
- const actualValue = sourcedValue ?? (options.secret ? await promptPassword({ message: `Value for ${key} (secret)` }) : await promptText({ message: `Value for ${key}`, required: true }));
100933
+ if (generate && existingVar) {
100934
+ throw new Error(`${key} already exists; --generate-secret only creates a new variable`);
100935
+ }
100936
+ const actualValue = generate ? "" : sourcedValue ?? (options.secret ? await promptPassword({ message: `Value for ${key} (secret)` }) : await promptText({ message: `Value for ${key}`, required: true }));
99148
100937
  let environmentIds;
99149
100938
  if (options.environments) {
99150
100939
  const envNames = options.environments.split(",").map((n) => n.trim().toLowerCase());
@@ -99200,14 +100989,15 @@ async function setEnvVar(projectFlag, key, value, options) {
99200
100989
  value: actualValue,
99201
100990
  environment_ids: environmentIds,
99202
100991
  include_in_preview: includeInPreview,
99203
- ...options.secret ? { is_secret: true } : {}
100992
+ ...options.secret || generate ? { is_secret: true } : {},
100993
+ ...generate ? { generate } : {}
99204
100994
  }
99205
100995
  });
99206
100996
  if (error)
99207
100997
  throw new Error(getErrorMessage(error));
99208
100998
  saved = data;
99209
100999
  });
99210
- success2(`Set ${key}${options.secret ? " (secret)" : ""}`);
101000
+ success2(`Set ${key}${generate ? " (generated secret)" : options.secret ? " (secret)" : ""}`);
99211
101001
  }
99212
101002
  if (saved?.secret_suggestion) {
99213
101003
  warning2(`${saved.secret_suggestion.message}. Consider rotating it and storing it as a secret: ` + `temps environments vars set ${key} --update --secret --value-file <path>`);
@@ -106173,7 +107963,7 @@ function registerServicesCommands(program) {
106173
107963
  services.command("upgrade").description("Upgrade a service to a newer version").requiredOption("--id <id>", "Service ID").option("-v, --version <version>", "Docker image to upgrade to (e.g., postgres:18-alpine)").action(upgradeServiceAction);
106174
107964
  services.command("repoint-continuous-archive-source").description("Repoint a Postgres/MariaDB service's continuous archiving (WAL-G, or MariaDB's binlog " + "shipper) to a different S3 source. Data archived before this call stays under the " + "previous source and will no longer be verifiable or replayable once archiving points " + "at the new one.").requiredOption("--id <id>", "Service ID").requiredOption("--s3-source <id>", "S3 source ID to point continuous archiving at").action(repointContinuousArchiveSourceAction);
106175
107965
  services.command("import").description("Import an existing external service").option("-t, --type <type>", "Service type (postgres, mongodb, redis, s3)").option("-n, --name <name>", "Service name").option("--container-id <id>", "Container ID or name to import").option("-s, --set <key=value>", "Set a parameter (repeatable)", collectSet, []).option("--version <version>", "Optional version override").option("-y, --yes", "Skip confirmation prompts (for automation)").action(importServiceAction);
106176
- services.command("link").description("Link a service to a project").requiredOption("--id <id>", "Service ID").option("-p, --project <slug>", "Project slug (auto-detected from .temps/config.json)").option("--database-mode <mode>", "Which database deployments get: project (one per project), project_environment (one per environment) or custom").option("--database-name <name>", "With --database-mode custom: the exact database name").action(linkServiceAction);
107966
+ services.command("link").description("Link a service to a project").requiredOption("--id <id>", "Service ID").option("-p, --project <slug>", "Project slug (auto-detected from .temps/config.json)").option("--database-mode <mode>", "Which database deployments get: project (one per project), project_environment (one per environment) or custom").option("--database-name <name>", "With --database-mode custom: the exact database name").option("--env-alias <APP_NAME=INJECTED_NAME>", "Also inject a variable under the name the app reads, e.g. DATABASE_URL=POSTGRES_URL (repeatable)", (value, previous = []) => [...previous, value]).action(linkServiceAction);
106177
107967
  services.command("unlink").description("Unlink a service from a project").requiredOption("--id <id>", "Service ID").option("-p, --project <slug>", "Project slug (auto-detected from .temps/config.json)").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation prompts (alias for --force)").action(unlinkServiceAction);
106178
107968
  services.command("connect <name>").description("Get connection info for a service by name or slug").option("-p, --project <slug>", "Project slug (auto-detected from .temps/config.json)").option("--json", "Output in JSON format").action(connectAction);
106179
107969
  services.command("env").description("Show environment variables for a linked service").requiredOption("--id <id>", "Service ID").option("-p, --project <slug>", "Project slug (auto-detected from .temps/config.json)").option("--json", "Output in JSON format").action(envAction);
@@ -106827,8 +108617,27 @@ function linkDatabaseFields(options) {
106827
108617
  ...options.databaseName !== undefined && { custom_database_name: options.databaseName }
106828
108618
  };
106829
108619
  }
108620
+ function linkEnvAliases(values) {
108621
+ if (!values?.length)
108622
+ return;
108623
+ const aliases = {};
108624
+ for (const value of values) {
108625
+ const at = value.indexOf("=");
108626
+ const app = value.slice(0, at).trim();
108627
+ const injected = value.slice(at + 1).trim();
108628
+ if (at <= 0 || !app || !injected) {
108629
+ throw new ValidationError7(`--env-alias takes APP_NAME=INJECTED_NAME, such as DATABASE_URL=POSTGRES_URL, not "${value}"`);
108630
+ }
108631
+ if (app in aliases) {
108632
+ throw new ValidationError7(`--env-alias names ${app} twice`);
108633
+ }
108634
+ aliases[app] = injected;
108635
+ }
108636
+ return aliases;
108637
+ }
106830
108638
  async function linkServiceAction(options) {
106831
108639
  const database = linkDatabaseFields(options);
108640
+ const envAliases = linkEnvAliases(options.envAlias);
106832
108641
  await requireAuth();
106833
108642
  await setupClient();
106834
108643
  const id = parseInt(options.id, 10);
@@ -106843,7 +108652,8 @@ async function linkServiceAction(options) {
106843
108652
  path: { id },
106844
108653
  body: {
106845
108654
  project_id: project.id,
106846
- ...database
108655
+ ...database,
108656
+ ...envAliases && { env_aliases: envAliases }
106847
108657
  }
106848
108658
  });
106849
108659
  if (error) {
@@ -117416,6 +119226,137 @@ async function retryFacetAction(attributeKey, options) {
117416
119226
  info2("Run: temps facets list to check progress");
117417
119227
  }
117418
119228
 
119229
+ // src/commands/ingress/index.ts
119230
+ init_sdk_gen();
119231
+ init_spinner();
119232
+ init_output();
119233
+ function privateIntent(options) {
119234
+ if (options.off) {
119235
+ if (options.listen !== undefined || options.admit?.length) {
119236
+ return {
119237
+ kind: "invalid",
119238
+ error: "--off cannot be combined with --listen or --admit"
119239
+ };
119240
+ }
119241
+ return { kind: "off" };
119242
+ }
119243
+ if (options.listen === undefined) {
119244
+ if (options.admit?.length) {
119245
+ return {
119246
+ kind: "invalid",
119247
+ error: "--admit needs --listen (one of this machine's private addresses, or tailscale)"
119248
+ };
119249
+ }
119250
+ return { kind: "status" };
119251
+ }
119252
+ const listen = options.listen.trim();
119253
+ if (listen === "") {
119254
+ return { kind: "invalid", error: `--listen needs one of this machine's private addresses, or "tailscale"` };
119255
+ }
119256
+ const admit = (options.admit ?? []).map((range) => range.trim());
119257
+ if (admit.some((range) => range === "")) {
119258
+ return {
119259
+ kind: "invalid",
119260
+ error: "--admit was given an empty range. Name a private range (10.8.0.0/24), or leave --admit out to admit the --listen address's own network"
119261
+ };
119262
+ }
119263
+ return {
119264
+ kind: "serve",
119265
+ request: { listen, admit, tailscale_serve: false }
119266
+ };
119267
+ }
119268
+ function describePrivateStatus(status) {
119269
+ if (!status.consent) {
119270
+ return status.error ? `This machine does not serve private addresses: ${status.error}` : "This machine does not serve private addresses.";
119271
+ }
119272
+ if (status.serving) {
119273
+ const admit = status.admit?.length ? `, to ${status.admit.join(", ")} only` : "";
119274
+ return `Serving private addresses on ${status.serving}${admit}.`;
119275
+ }
119276
+ if (status.error) {
119277
+ return `Not serving: ${status.error}`;
119278
+ }
119279
+ return "Waiting for this machine to apply it.";
119280
+ }
119281
+ function networkName(network) {
119282
+ return network.tailscale ? `Tailscale (${network.address})` : `${network.interface} (${network.address})`;
119283
+ }
119284
+ function describeNetwork(network) {
119285
+ if (network.problem)
119286
+ return `Cannot be used: ${network.problem}`;
119287
+ const listen = network.tailscale ? "tailscale" : network.address;
119288
+ return `admits ${network.admit.join(", ")} · --listen ${listen}`;
119289
+ }
119290
+ function registerIngressCommands(program) {
119291
+ const ingress = program.command("ingress").description("How this Temps machine receives traffic for your apps");
119292
+ ingress.command("private").description("Serve private addresses from this machine, only to connections from your private network (Tailscale, WireGuard, NetBird, your LAN…)").option("--listen <address>", `One of this machine's private addresses, or "tailscale" for its Tailscale address`).option("--admit <cidr...>", "Who may connect, as private ranges (default: the network of the --listen address; Tailscale's ranges on Tailscale)").option("--off", "Stop serving private addresses from this machine").option("--json", "Output in JSON format").action(privateAction);
119293
+ }
119294
+ async function privateAction(options) {
119295
+ const intent = privateIntent(options);
119296
+ if (intent.kind === "invalid") {
119297
+ warning2(intent.error);
119298
+ process.exitCode = 1;
119299
+ return;
119300
+ }
119301
+ await requireAuth();
119302
+ await setupClient();
119303
+ if (intent.kind === "off") {
119304
+ await withSpinner("Withdrawing consent...", async () => {
119305
+ const { error } = await deletePrivateIngress({ client });
119306
+ if (error)
119307
+ throw new Error(getErrorMessage(error));
119308
+ });
119309
+ if (options.json) {
119310
+ json({ consent: null });
119311
+ return;
119312
+ }
119313
+ success2("This machine no longer serves private addresses");
119314
+ return;
119315
+ }
119316
+ if (intent.kind === "serve") {
119317
+ const consent = await withSpinner("Storing consent...", async () => {
119318
+ const { data, error } = await putPrivateIngress({ client, body: intent.request });
119319
+ if (error)
119320
+ throw new Error(getErrorMessage(error));
119321
+ return data;
119322
+ });
119323
+ if (options.json) {
119324
+ json({ consent: consent ?? null });
119325
+ return;
119326
+ }
119327
+ const who = intent.request.admit?.length ? intent.request.admit.join(", ") : "its own network";
119328
+ success2(`This machine will serve private addresses on ${intent.request.listen}, to ${who} only`);
119329
+ info2("It applies within a few seconds. Run `ingress private` to see the address it serves on.");
119330
+ return;
119331
+ }
119332
+ const status = await withSpinner("Fetching status...", async () => {
119333
+ const { data, error } = await getPrivateIngress({ client });
119334
+ if (error)
119335
+ throw new Error(getErrorMessage(error));
119336
+ return data;
119337
+ });
119338
+ if (!status) {
119339
+ warning2("No status returned");
119340
+ return;
119341
+ }
119342
+ if (options.json) {
119343
+ json(status);
119344
+ return;
119345
+ }
119346
+ newline();
119347
+ header(`${icons.info} Private addresses on this machine`);
119348
+ keyValue("Listen", status.consent?.listen ?? colors.muted("Not set"));
119349
+ keyValue("Status", describePrivateStatus(status));
119350
+ if (status.networks?.length) {
119351
+ newline();
119352
+ header("Private networks on this machine");
119353
+ for (const network of status.networks) {
119354
+ keyValue(networkName(network), describeNetwork(network));
119355
+ }
119356
+ }
119357
+ newline();
119358
+ }
119359
+
117419
119360
  // src/commands/otel-forward/index.ts
117420
119361
  init_spinner();
117421
119362
  init_prompts();
@@ -130869,6 +132810,10 @@ function staticFilePath(raw) {
130869
132810
  return path;
130870
132811
  }
130871
132812
  function registerPlatformExtraCommands(platform) {
132813
+ endpoint(platform, getHostFacts, {
132814
+ name: "host-facts",
132815
+ description: "What Temps reads about the control plane's machine: processor, memory, swap, disk, Docker, ports 80 and 443, its addresses and Tailscale"
132816
+ });
130872
132817
  platform.command("operations").alias("ops").description("List recent and in-flight operations: deployments, rollbacks, promotions, restores, backups, autofixes").option("--status <status>", `Which ones: ${STATUSES2.join(", ")} (default: the server's)`).option("--kind <kind>", `Only one kind: ${KINDS.join(", ")}`).option("--project <id>", "Only this project ID").option("--page <n>", "Page (default 1)").option("--page-size <n>", "Operations per page (max 100)").option("--json", "Output in JSON format").action(async (options) => {
130873
132818
  const query = operationsQuery(options);
130874
132819
  await connect();
@@ -135527,12 +137472,14 @@ init_spinner();
135527
137472
 
135528
137473
  // src/commands/mcp/clients/claude-code.ts
135529
137474
  import * as fs6 from "node:fs";
135530
- import * as os4 from "node:os";
137475
+ import * as os5 from "node:os";
135531
137476
  import * as path7 from "node:path";
135532
137477
  import { execFileSync as execFileSync3 } from "node:child_process";
135533
137478
 
135534
137479
  // src/commands/mcp/clients/base.ts
137480
+ import { createHash as createHash4 } from "node:crypto";
135535
137481
  import * as fs5 from "node:fs";
137482
+ import * as os4 from "node:os";
135536
137483
  import * as path6 from "node:path";
135537
137484
 
135538
137485
  // node_modules/jsonc-parser/lib/esm/impl/scanner.js
@@ -136859,12 +138806,140 @@ function applyEdits(text, edits) {
136859
138806
  }
136860
138807
 
136861
138808
  // src/commands/mcp/clients/base.ts
138809
+ function localBridgeCommand(entry, bridge, keyFile) {
138810
+ return {
138811
+ command: "npx",
138812
+ args: [
138813
+ "-y",
138814
+ bridge.packageSpec,
138815
+ "mcp",
138816
+ "bridge",
138817
+ "--url",
138818
+ new URL(entry.url).origin,
138819
+ ...bridge.folders.flatMap((folder) => ["--folder", folder])
138820
+ ],
138821
+ env: keyFile ? { TEMPS_API_KEY_FILE: keyFile } : { TEMPS_API_KEY: entry.apiKey, TEMPS_API_KEY_FILE: "" }
138822
+ };
138823
+ }
138824
+ function shortHash(value) {
138825
+ return createHash4("sha256").update(value).digest("hex").slice(0, 16);
138826
+ }
138827
+ function keyFilePrefix(clientId, profile) {
138828
+ return `${clientId}-${shortHash(profile)}-`;
138829
+ }
138830
+ function bridgeKeyFilePath(clientId, url, profile = "", home = os4.homedir()) {
138831
+ const name = `${keyFilePrefix(clientId, profile)}${shortHash(new URL(url).origin)}.key`;
138832
+ return path6.join(home, ".temps", "mcp", name);
138833
+ }
138834
+ async function writeBridgeKeyFile(file, apiKey) {
138835
+ const dir = path6.dirname(file);
138836
+ await fs5.promises.mkdir(dir, { recursive: true, mode: 448 });
138837
+ await fs5.promises.chmod(dir, 448);
138838
+ const previous = await fs5.promises.readFile(file, "utf8").catch((error) => {
138839
+ if (error.code === "ENOENT")
138840
+ return null;
138841
+ throw error;
138842
+ });
138843
+ await replaceKeyFile(file, `${apiKey}
138844
+ `);
138845
+ return previous;
138846
+ }
138847
+ async function restoreBridgeKeyFile(file, previous, written) {
138848
+ if (readKeyFile(file) !== written.trim())
138849
+ return;
138850
+ if (previous === null)
138851
+ await fs5.promises.rm(file, { force: true });
138852
+ else
138853
+ await replaceKeyFile(file, previous);
138854
+ }
138855
+ async function replaceKeyFile(file, content) {
138856
+ const temporary = `${file}.${process.pid}.tmp`;
138857
+ await fs5.promises.rm(temporary, { force: true });
138858
+ await fs5.promises.writeFile(temporary, content, { encoding: "utf8", mode: 384, flag: "wx" });
138859
+ try {
138860
+ await fs5.promises.rename(temporary, file);
138861
+ } catch (error) {
138862
+ await fs5.promises.rm(temporary, { force: true });
138863
+ throw error;
138864
+ }
138865
+ }
138866
+ async function removeBridgeKeyFiles(clientId, profile = "", home = os4.homedir()) {
138867
+ const dir = path6.join(home, ".temps", "mcp");
138868
+ const prefix = keyFilePrefix(clientId, profile);
138869
+ const names = await fs5.promises.readdir(dir).catch((error) => {
138870
+ if (error.code === "ENOENT")
138871
+ return [];
138872
+ throw error;
138873
+ });
138874
+ await Promise.all(names.filter((name) => name.startsWith(prefix) && name.endsWith(".key")).map((name) => fs5.promises.rm(path6.join(dir, name), { force: true })));
138875
+ }
138876
+ function sameOrigin(a, b) {
138877
+ if (!a)
138878
+ return false;
138879
+ try {
138880
+ return new URL(a).origin === new URL(b).origin;
138881
+ } catch {
138882
+ return false;
138883
+ }
138884
+ }
138885
+ function bridgeUrlFromArgs(args) {
138886
+ if (!Array.isArray(args))
138887
+ return null;
138888
+ const bridgeAt = args.findIndex((arg, i) => arg === "bridge" && args[i - 1] === "mcp");
138889
+ const urlAt = args.indexOf("--url");
138890
+ const url = urlAt === -1 ? undefined : args[urlAt + 1];
138891
+ if (bridgeAt === -1 || typeof url !== "string")
138892
+ return null;
138893
+ try {
138894
+ const mcp = new URL("/mcp", new URL(url).origin);
138895
+ mcp.searchParams.set("write", "1");
138896
+ return mcp.toString();
138897
+ } catch {
138898
+ return null;
138899
+ }
138900
+ }
138901
+ function bridgeUrlFromText(text) {
138902
+ const match = text.match(/\bmcp\s+bridge\b[\s\S]*?--url\s+(\S+)/);
138903
+ return match?.[1] ? bridgeUrlFromArgs(["mcp", "bridge", "--url", match[1]]) : null;
138904
+ }
138905
+ var MAX_KEY_FILE_BYTES = 4096;
138906
+ function readKeyFile(file) {
138907
+ let handle;
138908
+ try {
138909
+ handle = fs5.openSync(file, "r");
138910
+ const buffer = Buffer.alloc(MAX_KEY_FILE_BYTES + 1);
138911
+ const read = fs5.readSync(handle, buffer, 0, buffer.length, 0);
138912
+ if (read > MAX_KEY_FILE_BYTES)
138913
+ return;
138914
+ return buffer.subarray(0, read).toString("utf8").trim() || undefined;
138915
+ } catch {
138916
+ return;
138917
+ } finally {
138918
+ if (handle !== undefined)
138919
+ fs5.closeSync(handle);
138920
+ }
138921
+ }
138922
+ function bearerOf(value) {
138923
+ return typeof value === "string" ? /^Bearer\s+(\S+)$/i.exec(value.trim())?.[1] : undefined;
138924
+ }
138925
+ function entryApiKey(entry) {
138926
+ if (!entry || typeof entry !== "object")
138927
+ return;
138928
+ const { headers, env } = entry;
138929
+ const header = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === "authorization")?.[1];
138930
+ const file = typeof env?.TEMPS_API_KEY_FILE === "string" ? env.TEMPS_API_KEY_FILE.trim() : "";
138931
+ const inline = typeof env?.TEMPS_API_KEY === "string" ? env.TEMPS_API_KEY.trim() : "";
138932
+ return bearerOf(header) || bearerOf(env?.AUTH_HEADER) || (file ? readKeyFile(file) : undefined) || inline || undefined;
138933
+ }
136862
138934
  var MCP_SERVER_NAME = "temps";
136863
138935
  function redactSecrets(text) {
136864
138936
  return text.replace(/Bearer\s+\S+/gi, "Bearer ***").replace(/Authorization:\s*\S+(\s+\S+)?/gi, "Authorization: ***");
136865
138937
  }
136866
138938
 
136867
138939
  class JsonConfigMcpClientAdapter {
138940
+ buildBridgeConfig(command) {
138941
+ return { command: command.command, args: command.args, env: command.env };
138942
+ }
136868
138943
  async isClientSupported() {
136869
138944
  return true;
136870
138945
  }
@@ -136884,9 +138959,14 @@ class JsonConfigMcpClientAdapter {
136884
138959
  async isServerInstalled() {
136885
138960
  return await this.readServerConfig() !== null;
136886
138961
  }
138962
+ async installedApiKey() {
138963
+ return entryApiKey(await this.readServerConfig());
138964
+ }
136887
138965
  async getServerUrl() {
136888
138966
  const serverConfig = await this.readServerConfig();
136889
- return serverConfig ? this.extractUrl(serverConfig) : null;
138967
+ if (!serverConfig)
138968
+ return null;
138969
+ return bridgeUrlFromArgs(serverConfig.args) ?? this.extractUrl(serverConfig);
136890
138970
  }
136891
138971
  async addServer(entry) {
136892
138972
  const configPath = this.getConfigPath();
@@ -136899,7 +138979,7 @@ class JsonConfigMcpClientAdapter {
136899
138979
  }
136900
138980
  const prop = this.getServerPropertyName();
136901
138981
  const existing = parse2(content || "{}") ?? {};
136902
- const newEntry = this.buildServerConfig(entry);
138982
+ const newEntry = entry.bridge ? this.buildBridgeConfig(localBridgeCommand(entry, entry.bridge)) : this.buildServerConfig(entry);
136903
138983
  const currentEntry = existing?.[prop]?.[MCP_SERVER_NAME];
136904
138984
  if (currentEntry !== undefined && JSON.stringify(currentEntry) === JSON.stringify(newEntry)) {
136905
138985
  return { success: true, alreadyInstalled: true };
@@ -136966,18 +139046,109 @@ function execErrorMessage(error) {
136966
139046
  // src/commands/mcp/clients/claude-code.ts
136967
139047
  function parseClaudeCodeMcpGetOutput(output) {
136968
139048
  const match = output.match(/^\s*URL:\s*(\S+)/m);
136969
- return match?.[1] ?? null;
139049
+ return match?.[1] ?? bridgeUrlFromText(output);
139050
+ }
139051
+ var CLAUDE_CODE_ID = "claude-code";
139052
+ function bridgeTarget(text) {
139053
+ const match = text.match(/(\S+)\s+mcp\s+bridge\b([^\n]*)/);
139054
+ if (!match)
139055
+ return null;
139056
+ return `${match[1]} mcp bridge ${(match[2] ?? "").trim()}`.trim();
139057
+ }
139058
+ function claudeCodeEntryMatches(installed, entry, installedArgs = null) {
139059
+ const target = bridgeTarget(installed);
139060
+ if (!entry.bridge)
139061
+ return target === null && parseClaudeCodeMcpGetOutput(installed) === entry.url;
139062
+ if (target === null)
139063
+ return false;
139064
+ const command = localBridgeCommand(entry, entry.bridge).args;
139065
+ const wanted = command.slice(command.indexOf(entry.bridge.packageSpec));
139066
+ if (installedArgs) {
139067
+ const at = installedArgs.indexOf("bridge");
139068
+ return at > 1 && JSON.stringify(installedArgs.slice(at - 2)) === JSON.stringify(wanted);
139069
+ }
139070
+ if (wanted.some((arg) => /\s/.test(arg)))
139071
+ return false;
139072
+ return JSON.stringify(target.split(/\s+/).filter(Boolean)) === JSON.stringify(wanted);
139073
+ }
139074
+ function claudeCodeAddArgs(entry, keyFile = bridgeKeyFilePath(CLAUDE_CODE_ID, entry.url)) {
139075
+ if (entry.bridge) {
139076
+ const command = localBridgeCommand(entry, entry.bridge, keyFile);
139077
+ return [
139078
+ "mcp",
139079
+ "add",
139080
+ "--scope",
139081
+ "user",
139082
+ MCP_SERVER_NAME,
139083
+ ...Object.entries(command.env).flatMap(([name, value]) => ["-e", `${name}=${value}`]),
139084
+ "--",
139085
+ command.command,
139086
+ ...command.args
139087
+ ];
139088
+ }
139089
+ return [
139090
+ "mcp",
139091
+ "add",
139092
+ "--transport",
139093
+ "http",
139094
+ "--scope",
139095
+ "user",
139096
+ MCP_SERVER_NAME,
139097
+ entry.url,
139098
+ "--header",
139099
+ `Authorization: Bearer ${entry.apiKey}`
139100
+ ];
136970
139101
  }
136971
139102
 
136972
139103
  class ClaudeCodeAdapter {
136973
- id = "claude-code";
139104
+ options;
139105
+ id = CLAUDE_CODE_ID;
136974
139106
  label = "Claude Code";
136975
139107
  binary;
139108
+ constructor(options = {}) {
139109
+ this.options = options;
139110
+ }
139111
+ get home() {
139112
+ return this.options.home ?? os5.homedir();
139113
+ }
139114
+ get env() {
139115
+ return this.options.env ?? process.env;
139116
+ }
139117
+ profile() {
139118
+ return this.env.CLAUDE_CONFIG_DIR ? path7.resolve(this.env.CLAUDE_CONFIG_DIR) : "";
139119
+ }
139120
+ installedArgs() {
139121
+ const dir = this.profile() || this.home;
139122
+ try {
139123
+ const config = JSON.parse(fs6.readFileSync(path7.join(dir, ".claude.json"), "utf8"));
139124
+ const args = config.mcpServers?.[MCP_SERVER_NAME]?.args;
139125
+ return Array.isArray(args) && args.every((arg) => typeof arg === "string") ? args : null;
139126
+ } catch {
139127
+ return null;
139128
+ }
139129
+ }
139130
+ installedEntry() {
139131
+ const dir = this.profile() || this.home;
139132
+ try {
139133
+ const config = JSON.parse(fs6.readFileSync(path7.join(dir, ".claude.json"), "utf8"));
139134
+ return config.mcpServers?.[MCP_SERVER_NAME] ?? null;
139135
+ } catch {
139136
+ return null;
139137
+ }
139138
+ }
139139
+ async installedApiKey() {
139140
+ return entryApiKey(this.installedEntry());
139141
+ }
139142
+ keyFile(entry) {
139143
+ return bridgeKeyFilePath(CLAUDE_CODE_ID, entry.url, this.profile(), this.home);
139144
+ }
136976
139145
  findBinary() {
139146
+ if (this.options.binary)
139147
+ return this.options.binary;
136977
139148
  if (this.binary !== undefined)
136978
139149
  return this.binary;
136979
139150
  const candidates = [
136980
- path7.join(os4.homedir(), ".claude", "local", "claude"),
139151
+ path7.join(this.home, ".claude", "local", "claude"),
136981
139152
  "/usr/local/bin/claude",
136982
139153
  "/opt/homebrew/bin/claude"
136983
139154
  ];
@@ -136995,7 +139166,10 @@ class ClaudeCodeAdapter {
136995
139166
  }
136996
139167
  getServerEntry(binary) {
136997
139168
  try {
136998
- return execFileSync3(binary, ["mcp", "get", MCP_SERVER_NAME], { stdio: ["ignore", "pipe", "pipe"] }).toString();
139169
+ return execFileSync3(binary, ["mcp", "get", MCP_SERVER_NAME], {
139170
+ stdio: ["ignore", "pipe", "pipe"],
139171
+ env: this.env
139172
+ }).toString();
136999
139173
  } catch {
137000
139174
  return null;
137001
139175
  }
@@ -137019,24 +139193,40 @@ class ClaudeCodeAdapter {
137019
139193
  const binary = this.findBinary();
137020
139194
  if (!binary)
137021
139195
  return { success: false, reason: "The claude CLI was not found on PATH." };
139196
+ const keyFile = entry.bridge ? this.keyFile(entry) : undefined;
139197
+ let previousKey = null;
139198
+ if (keyFile) {
139199
+ try {
139200
+ previousKey = await writeBridgeKeyFile(keyFile, entry.apiKey);
139201
+ } catch (error) {
139202
+ return {
139203
+ success: false,
139204
+ reason: `Could not save the API key to ${keyFile} (${redactSecrets(execErrorMessage(error))}).`
139205
+ };
139206
+ }
139207
+ }
137022
139208
  try {
137023
- execFileSync3(binary, [
137024
- "mcp",
137025
- "add",
137026
- "--transport",
137027
- "http",
137028
- "--scope",
137029
- "user",
137030
- MCP_SERVER_NAME,
137031
- entry.url,
137032
- "--header",
137033
- `Authorization: Bearer ${entry.apiKey}`
137034
- ], { stdio: ["ignore", "pipe", "pipe"] });
139209
+ execFileSync3(binary, claudeCodeAddArgs(entry, keyFile), { stdio: ["ignore", "pipe", "pipe"], env: this.env });
137035
139210
  return { success: true };
137036
139211
  } catch (error) {
137037
139212
  const reason = redactSecrets(execErrorMessage(error));
137038
- if (/already exists/i.test(reason))
137039
- return { success: true, alreadyInstalled: true };
139213
+ if (keyFile)
139214
+ await restoreBridgeKeyFile(keyFile, previousKey, entry.apiKey).catch(() => {
139215
+ return;
139216
+ });
139217
+ if (/already exists/i.test(reason)) {
139218
+ const installedText = this.getServerEntry(binary);
139219
+ const installed = installedText ? parseClaudeCodeMcpGetOutput(installedText) : null;
139220
+ if (installedText && claudeCodeEntryMatches(installedText, entry, this.installedArgs())) {
139221
+ return { success: true, alreadyInstalled: true };
139222
+ }
139223
+ const where = installed ? ` for ${new URL(installed).origin}` : "";
139224
+ const how = sameOrigin(installed, entry.url) ? ", set up differently" : "";
139225
+ return {
139226
+ success: false,
139227
+ reason: `Claude Code already has a ${MCP_SERVER_NAME} server${where}${how}. Run temps mcp remove claude-code, then add it again.`
139228
+ };
139229
+ }
137040
139230
  return { success: false, reason };
137041
139231
  }
137042
139232
  }
@@ -137046,29 +139236,36 @@ class ClaudeCodeAdapter {
137046
139236
  return { success: false, reason: "The claude CLI was not found on PATH." };
137047
139237
  try {
137048
139238
  execFileSync3(binary, ["mcp", "remove", "--scope", "user", MCP_SERVER_NAME], {
137049
- stdio: ["ignore", "pipe", "pipe"]
139239
+ stdio: ["ignore", "pipe", "pipe"],
139240
+ env: this.env
137050
139241
  });
139242
+ await removeBridgeKeyFiles(CLAUDE_CODE_ID, this.profile(), this.home);
137051
139243
  return { success: true };
137052
139244
  } catch (error) {
137053
139245
  const reason = redactSecrets(execErrorMessage(error));
137054
- if (/no such|not found/i.test(reason))
139246
+ if (/no such|not found/i.test(reason)) {
139247
+ await removeBridgeKeyFiles(CLAUDE_CODE_ID, this.profile(), this.home).catch(() => {
139248
+ return;
139249
+ });
137055
139250
  return { success: true, alreadyInstalled: true };
139251
+ }
137056
139252
  return { success: false, reason };
137057
139253
  }
137058
139254
  }
137059
139255
  async describeTarget() {
137060
- return `claude mcp add --transport http --scope user ${MCP_SERVER_NAME} <url>`;
139256
+ const settings = path7.join(this.profile() || this.home, ".claude.json");
139257
+ return `claude mcp add --scope user ${MCP_SERVER_NAME} (Claude Code's user settings in ${settings})`;
137061
139258
  }
137062
139259
  }
137063
139260
 
137064
139261
  // src/commands/mcp/clients/claude-desktop.ts
137065
- import * as os5 from "node:os";
139262
+ import * as os6 from "node:os";
137066
139263
  import * as path8 from "node:path";
137067
139264
  class ClaudeDesktopAdapter extends JsonConfigMcpClientAdapter {
137068
139265
  id = "claude-desktop";
137069
139266
  label = "Claude Desktop";
137070
139267
  getConfigPath() {
137071
- const home = os5.homedir();
139268
+ const home = os6.homedir();
137072
139269
  if (process.platform === "darwin") {
137073
139270
  return path8.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
137074
139271
  }
@@ -137101,17 +139298,115 @@ class ClaudeDesktopAdapter extends JsonConfigMcpClientAdapter {
137101
139298
 
137102
139299
  // src/commands/mcp/clients/codex.ts
137103
139300
  import { execFileSync as execFileSync4 } from "node:child_process";
139301
+ import * as os7 from "node:os";
139302
+ import * as path9 from "node:path";
137104
139303
  var TOKEN_ENV_VAR = "TEMPS_MCP_AUTH_HEADER";
137105
139304
  function parseCodexMcpGetOutput(output) {
137106
139305
  const match = output.match(/^\s*url:\s*(\S+)/m);
137107
- return match?.[1] ?? null;
139306
+ return match?.[1] ?? bridgeUrlFromText(output);
139307
+ }
139308
+ var CODEX_ID = "codex";
139309
+ var CODEX_TIMEOUT_MS = 30000;
139310
+ function parseCodexJsonEntry(text) {
139311
+ if (!text)
139312
+ return null;
139313
+ try {
139314
+ const value = JSON.parse(text);
139315
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
139316
+ } catch {
139317
+ return null;
139318
+ }
139319
+ }
139320
+ function codexBridgeArgs(json) {
139321
+ const args = json.transport?.args;
139322
+ if (!Array.isArray(args) || !args.every((a) => typeof a === "string"))
139323
+ return null;
139324
+ return bridgeUrlFromArgs(args) === null ? null : args;
139325
+ }
139326
+ function codexBridgeKey(json) {
139327
+ if (!codexBridgeArgs(json))
139328
+ return;
139329
+ const env = json.transport?.env ?? {};
139330
+ const file = typeof env.TEMPS_API_KEY_FILE === "string" ? env.TEMPS_API_KEY_FILE.trim() : "";
139331
+ if (file) {
139332
+ if (path9.isAbsolute(file))
139333
+ return readKeyFile(file);
139334
+ const cwd = json.transport?.cwd;
139335
+ return typeof cwd === "string" && path9.isAbsolute(cwd) ? readKeyFile(path9.join(cwd, file)) : undefined;
139336
+ }
139337
+ const inline = env.TEMPS_API_KEY;
139338
+ return typeof inline === "string" && inline.trim() ? inline.trim() : undefined;
139339
+ }
139340
+ function codexEntryMatches(installed, entry, json) {
139341
+ if (json && entry.bridge) {
139342
+ const args = codexBridgeArgs(json);
139343
+ if (!args)
139344
+ return false;
139345
+ const command = localBridgeCommand(entry, entry.bridge).args;
139346
+ const wanted = command.slice(command.indexOf(entry.bridge.packageSpec));
139347
+ const at = args.indexOf(entry.bridge.packageSpec);
139348
+ return at !== -1 && JSON.stringify(args.slice(at)) === JSON.stringify(wanted);
139349
+ }
139350
+ const bridgeUrl = bridgeUrlFromText(installed);
139351
+ if (!entry.bridge)
139352
+ return bridgeUrl === null && parseCodexMcpGetOutput(installed) === entry.url;
139353
+ if (bridgeUrl === null)
139354
+ return false;
139355
+ const command = localBridgeCommand(entry, entry.bridge).args;
139356
+ if (entry.bridge.folders.some((folder) => /(^|\s)--folder(\s|$)/.test(folder)))
139357
+ return false;
139358
+ const wanted = command.slice(command.indexOf(entry.bridge.packageSpec)).join(" ");
139359
+ return installed.split(`
139360
+ `).some((line) => {
139361
+ const at = line.indexOf(entry.bridge?.packageSpec ?? "");
139362
+ return at !== -1 && line.slice(at).trimEnd() === wanted;
139363
+ });
139364
+ }
139365
+ function codexAddArgs(entry, keyFile = bridgeKeyFilePath(CODEX_ID, entry.url, codexHome())) {
139366
+ if (entry.bridge) {
139367
+ const command = localBridgeCommand(entry, entry.bridge, keyFile);
139368
+ return [
139369
+ "mcp",
139370
+ "add",
139371
+ MCP_SERVER_NAME,
139372
+ ...Object.entries(command.env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
139373
+ "--",
139374
+ command.command,
139375
+ ...command.args
139376
+ ];
139377
+ }
139378
+ return ["mcp", "add", MCP_SERVER_NAME, "--url", entry.url, "--bearer-token-env-var", TOKEN_ENV_VAR];
139379
+ }
139380
+ function codexHome(env = process.env, home = os7.homedir()) {
139381
+ return path9.resolve(env.CODEX_HOME || path9.join(home, ".codex"));
139382
+ }
139383
+ function codexConfigPath(env = process.env, home = os7.homedir()) {
139384
+ return path9.join(codexHome(env, home), "config.toml");
137108
139385
  }
137109
139386
 
137110
139387
  class CodexAdapter {
137111
- id = "codex";
139388
+ options;
139389
+ id = CODEX_ID;
137112
139390
  label = "Codex";
137113
139391
  binary;
139392
+ constructor(options = {}) {
139393
+ this.options = options;
139394
+ }
139395
+ get home() {
139396
+ return this.options.home ?? os7.homedir();
139397
+ }
139398
+ get env() {
139399
+ return this.options.env ?? process.env;
139400
+ }
139401
+ profile() {
139402
+ return codexHome(this.env, this.home);
139403
+ }
139404
+ keyFile(entry) {
139405
+ return bridgeKeyFilePath(CODEX_ID, entry.url, this.profile(), this.home);
139406
+ }
137114
139407
  findBinary() {
139408
+ if (this.options.binary)
139409
+ return this.options.binary;
137115
139410
  if (this.binary !== undefined)
137116
139411
  return this.binary;
137117
139412
  this.binary = resolveOnPath("codex");
@@ -137120,9 +139415,24 @@ class CodexAdapter {
137120
139415
  async isClientSupported() {
137121
139416
  return this.findBinary() !== null;
137122
139417
  }
139418
+ getServerJson(binary) {
139419
+ try {
139420
+ return parseCodexJsonEntry(execFileSync4(binary, ["mcp", "get", MCP_SERVER_NAME, "--json"], {
139421
+ stdio: ["ignore", "pipe", "pipe"],
139422
+ env: this.env,
139423
+ timeout: CODEX_TIMEOUT_MS
139424
+ }).toString());
139425
+ } catch {
139426
+ return null;
139427
+ }
139428
+ }
137123
139429
  getServerEntry(binary) {
137124
139430
  try {
137125
- return execFileSync4(binary, ["mcp", "get", MCP_SERVER_NAME], { stdio: ["ignore", "pipe", "pipe"] }).toString();
139431
+ return execFileSync4(binary, ["mcp", "get", MCP_SERVER_NAME], {
139432
+ stdio: ["ignore", "pipe", "pipe"],
139433
+ env: this.env,
139434
+ timeout: CODEX_TIMEOUT_MS
139435
+ }).toString();
137126
139436
  } catch {
137127
139437
  return null;
137128
139438
  }
@@ -137133,6 +139443,11 @@ class CodexAdapter {
137133
139443
  return false;
137134
139444
  return this.getServerEntry(binary) !== null;
137135
139445
  }
139446
+ async installedApiKey() {
139447
+ const binary = this.findBinary();
139448
+ const json = binary ? this.getServerJson(binary) : null;
139449
+ return json ? codexBridgeKey(json) : undefined;
139450
+ }
137136
139451
  async getServerUrl() {
137137
139452
  const binary = this.findBinary();
137138
139453
  if (!binary)
@@ -137146,16 +139461,43 @@ class CodexAdapter {
137146
139461
  const binary = this.findBinary();
137147
139462
  if (!binary)
137148
139463
  return { success: false, reason: "The codex CLI was not found on PATH." };
139464
+ const keyFile = entry.bridge ? this.keyFile(entry) : undefined;
139465
+ let previousKey = null;
139466
+ if (keyFile) {
139467
+ try {
139468
+ previousKey = await writeBridgeKeyFile(keyFile, entry.apiKey);
139469
+ } catch (error) {
139470
+ return {
139471
+ success: false,
139472
+ reason: `Could not save the API key to ${keyFile} (${redactSecrets(execErrorMessage(error))}).`
139473
+ };
139474
+ }
139475
+ }
137149
139476
  try {
137150
- execFileSync4(binary, ["mcp", "add", MCP_SERVER_NAME, "--url", entry.url, "--bearer-token-env-var", TOKEN_ENV_VAR], {
139477
+ execFileSync4(binary, codexAddArgs(entry, keyFile), {
137151
139478
  stdio: ["ignore", "pipe", "pipe"],
137152
- env: { ...process.env, [TOKEN_ENV_VAR]: `Bearer ${entry.apiKey}` }
139479
+ env: { ...this.env, [TOKEN_ENV_VAR]: `Bearer ${entry.apiKey}` },
139480
+ timeout: CODEX_TIMEOUT_MS
137153
139481
  });
137154
139482
  return { success: true };
137155
139483
  } catch (error) {
137156
139484
  const reason = redactSecrets(execErrorMessage(error));
139485
+ if (keyFile)
139486
+ await restoreBridgeKeyFile(keyFile, previousKey, entry.apiKey).catch(() => {
139487
+ return;
139488
+ });
137157
139489
  if (/already (installed|exists|added|registered)/i.test(reason)) {
137158
- return { success: true, alreadyInstalled: true };
139490
+ const text = this.getServerEntry(binary);
139491
+ if (text && codexEntryMatches(text, entry, this.getServerJson(binary))) {
139492
+ return { success: true, alreadyInstalled: true };
139493
+ }
139494
+ const installed = text ? parseCodexMcpGetOutput(text) : null;
139495
+ const where = installed && URL.canParse(installed) ? ` for ${new URL(installed).origin}` : "";
139496
+ const other = sameOrigin(installed, entry.url) ? ", set up differently (other folders or transport)" : "";
139497
+ return {
139498
+ success: false,
139499
+ reason: `Codex already has a ${MCP_SERVER_NAME} server${where}${other}. Run temps mcp remove codex, then add it again.`
139500
+ };
137159
139501
  }
137160
139502
  return { success: false, reason };
137161
139503
  }
@@ -137165,28 +139507,37 @@ class CodexAdapter {
137165
139507
  if (!binary)
137166
139508
  return { success: false, reason: "The codex CLI was not found on PATH." };
137167
139509
  try {
137168
- execFileSync4(binary, ["mcp", "remove", MCP_SERVER_NAME], { stdio: ["ignore", "pipe", "pipe"] });
139510
+ execFileSync4(binary, ["mcp", "remove", MCP_SERVER_NAME], {
139511
+ stdio: ["ignore", "pipe", "pipe"],
139512
+ env: this.env,
139513
+ timeout: CODEX_TIMEOUT_MS
139514
+ });
139515
+ await removeBridgeKeyFiles(CODEX_ID, this.profile(), this.home);
137169
139516
  return { success: true };
137170
139517
  } catch (error) {
137171
139518
  const reason = redactSecrets(execErrorMessage(error));
137172
- if (/not found|no such/i.test(reason))
139519
+ if (/not found|no such/i.test(reason)) {
139520
+ await removeBridgeKeyFiles(CODEX_ID, this.profile(), this.home).catch(() => {
139521
+ return;
139522
+ });
137173
139523
  return { success: true, alreadyInstalled: true };
139524
+ }
137174
139525
  return { success: false, reason };
137175
139526
  }
137176
139527
  }
137177
139528
  async describeTarget() {
137178
- return `codex mcp add ${MCP_SERVER_NAME} --url <url> --bearer-token-env-var ${TOKEN_ENV_VAR}`;
139529
+ return `codex mcp add ${MCP_SERVER_NAME} (${codexConfigPath(this.env, this.home)})`;
137179
139530
  }
137180
139531
  }
137181
139532
 
137182
139533
  // src/commands/mcp/clients/cursor.ts
137183
- import * as os6 from "node:os";
137184
- import * as path9 from "node:path";
139534
+ import * as os8 from "node:os";
139535
+ import * as path10 from "node:path";
137185
139536
  class CursorAdapter extends JsonConfigMcpClientAdapter {
137186
139537
  id = "cursor";
137187
139538
  label = "Cursor";
137188
139539
  getConfigPath() {
137189
- return path9.join(os6.homedir(), ".cursor", "mcp.json");
139540
+ return path10.join(os8.homedir(), ".cursor", "mcp.json");
137190
139541
  }
137191
139542
  getServerPropertyName() {
137192
139543
  return "mcpServers";
@@ -137203,20 +139554,20 @@ class CursorAdapter extends JsonConfigMcpClientAdapter {
137203
139554
  }
137204
139555
 
137205
139556
  // src/commands/mcp/clients/vscode.ts
137206
- import * as os7 from "node:os";
137207
- import * as path10 from "node:path";
139557
+ import * as os9 from "node:os";
139558
+ import * as path11 from "node:path";
137208
139559
  class VsCodeAdapter extends JsonConfigMcpClientAdapter {
137209
139560
  id = "vscode";
137210
139561
  label = "VS Code";
137211
139562
  getConfigPath() {
137212
- const home = os7.homedir();
139563
+ const home = os9.homedir();
137213
139564
  if (process.platform === "darwin") {
137214
- return path10.join(home, "Library", "Application Support", "Code", "User", "mcp.json");
139565
+ return path11.join(home, "Library", "Application Support", "Code", "User", "mcp.json");
137215
139566
  }
137216
139567
  if (process.platform === "win32") {
137217
- return path10.join(process.env.APPDATA || "", "Code", "User", "mcp.json");
139568
+ return path11.join(process.env.APPDATA || "", "Code", "User", "mcp.json");
137218
139569
  }
137219
- return path10.join(home, ".config", "Code", "User", "mcp.json");
139570
+ return path11.join(home, ".config", "Code", "User", "mcp.json");
137220
139571
  }
137221
139572
  getServerPropertyName() {
137222
139573
  return "servers";
@@ -137224,6 +139575,9 @@ class VsCodeAdapter extends JsonConfigMcpClientAdapter {
137224
139575
  buildServerConfig(entry) {
137225
139576
  return { type: "http", url: entry.url, headers: { Authorization: `Bearer ${entry.apiKey}` } };
137226
139577
  }
139578
+ buildBridgeConfig(command) {
139579
+ return { type: "stdio", command: command.command, args: command.args, env: command.env };
139580
+ }
137227
139581
  extractUrl(serverConfig) {
137228
139582
  return typeof serverConfig.url === "string" ? serverConfig.url : null;
137229
139583
  }
@@ -137233,13 +139587,13 @@ class VsCodeAdapter extends JsonConfigMcpClientAdapter {
137233
139587
  }
137234
139588
 
137235
139589
  // src/commands/mcp/clients/windsurf.ts
137236
- import * as os8 from "node:os";
137237
- import * as path11 from "node:path";
139590
+ import * as os10 from "node:os";
139591
+ import * as path12 from "node:path";
137238
139592
  class WindsurfAdapter extends JsonConfigMcpClientAdapter {
137239
139593
  id = "windsurf";
137240
139594
  label = "Windsurf";
137241
139595
  getConfigPath() {
137242
- return path11.join(os8.homedir(), ".codeium", "windsurf", "mcp_config.json");
139596
+ return path12.join(os10.homedir(), ".codeium", "windsurf", "mcp_config.json");
137243
139597
  }
137244
139598
  getServerPropertyName() {
137245
139599
  return "mcpServers";
@@ -137256,18 +139610,18 @@ class WindsurfAdapter extends JsonConfigMcpClientAdapter {
137256
139610
  }
137257
139611
 
137258
139612
  // src/commands/mcp/clients/zed.ts
137259
- import * as os9 from "node:os";
137260
- import * as path12 from "node:path";
139613
+ import * as os11 from "node:os";
139614
+ import * as path13 from "node:path";
137261
139615
  class ZedAdapter extends JsonConfigMcpClientAdapter {
137262
139616
  id = "zed";
137263
139617
  label = "Zed";
137264
139618
  getConfigPath() {
137265
- const home = os9.homedir();
139619
+ const home = os11.homedir();
137266
139620
  const xdgConfigHome = process.env.XDG_CONFIG_HOME;
137267
139621
  if (process.platform === "linux" && xdgConfigHome) {
137268
- return path12.join(xdgConfigHome, "zed", "settings.json");
139622
+ return path13.join(xdgConfigHome, "zed", "settings.json");
137269
139623
  }
137270
- return path12.join(home, ".config", "zed", "settings.json");
139624
+ return path13.join(home, ".config", "zed", "settings.json");
137271
139625
  }
137272
139626
  getServerPropertyName() {
137273
139627
  return "context_servers";
@@ -137387,6 +139741,200 @@ async function probeMcpEndpoint(apiUrl, timeoutMs = 5000) {
137387
139741
  }
137388
139742
  }
137389
139743
 
139744
+ // src/commands/mcp/bridge.ts
139745
+ var import_bridge = __toESM(require_bridge(), 1);
139746
+ import * as fs7 from "node:fs";
139747
+ import * as os12 from "node:os";
139748
+ import * as path14 from "node:path";
139749
+ function bridgePackageSpec(version) {
139750
+ return `@temps-sdk/cli@${version}`;
139751
+ }
139752
+ function resolveFolder(folder) {
139753
+ const trimmed = folder.trim();
139754
+ if (!trimmed) {
139755
+ throw new Error("A deploy folder was left blank. Name the folder that holds your projects.");
139756
+ }
139757
+ const expanded = trimmed === "~" || trimmed.startsWith("~/") ? path14.join(os12.homedir(), trimmed.slice(1)) : trimmed;
139758
+ return path14.resolve(expanded);
139759
+ }
139760
+ function checkBridgeAddress(url) {
139761
+ import_bridge.default.readConfig({ TEMPS_URL: url, TEMPS_API_KEY: "address-check", TEMPS_BRIDGE_HOST: "cli" }, []);
139762
+ }
139763
+ var MAX_KEY_FILE_BYTES2 = 4096;
139764
+ function bridgeApiKey(env) {
139765
+ const file = env.TEMPS_API_KEY_FILE?.trim();
139766
+ if (!file)
139767
+ return env.TEMPS_API_KEY ?? "";
139768
+ let handle;
139769
+ try {
139770
+ handle = fs7.openSync(file, "r");
139771
+ const buffer = Buffer.alloc(MAX_KEY_FILE_BYTES2 + 1);
139772
+ const read = fs7.readSync(handle, buffer, 0, buffer.length, 0);
139773
+ if (read > MAX_KEY_FILE_BYTES2) {
139774
+ throw new Error(`it is larger than ${MAX_KEY_FILE_BYTES2} bytes, so it is not an API key file`);
139775
+ }
139776
+ return buffer.subarray(0, read).toString("utf8").trim();
139777
+ } catch (error) {
139778
+ const reason = error instanceof Error ? error.message : String(error);
139779
+ throw new Error(`Could not read the Temps API key from ${file} (TEMPS_API_KEY_FILE): ${reason}. Run temps mcp add again.`);
139780
+ } finally {
139781
+ if (handle !== undefined)
139782
+ fs7.closeSync(handle);
139783
+ }
139784
+ }
139785
+ function bridgeAction(options) {
139786
+ const folders = (options.folder ?? []).flatMap((folder) => {
139787
+ try {
139788
+ return [resolveFolder(folder)];
139789
+ } catch (error) {
139790
+ process.stderr.write(`temps: ${error instanceof Error ? error.message : String(error)}
139791
+ `);
139792
+ return [];
139793
+ }
139794
+ });
139795
+ let key = "";
139796
+ try {
139797
+ key = bridgeApiKey(process.env);
139798
+ } catch (error) {
139799
+ process.stderr.write(`temps: ${error instanceof Error ? error.message : String(error)}
139800
+ `);
139801
+ }
139802
+ import_bridge.default.main({
139803
+ TEMPS_URL: options.url ?? process.env.TEMPS_URL ?? "",
139804
+ TEMPS_API_KEY: key,
139805
+ TEMPS_BRIDGE_HOST: "cli"
139806
+ }, folders);
139807
+ }
139808
+
139809
+ // src/commands/mcp/index.ts
139810
+ import * as fs9 from "node:fs";
139811
+ import { randomBytes as randomBytes4 } from "node:crypto";
139812
+
139813
+ // src/commands/mcp/minted-keys.ts
139814
+ import { createHash as createHash5, randomBytes as randomBytes3 } from "node:crypto";
139815
+ import * as fs8 from "node:fs";
139816
+ import * as os13 from "node:os";
139817
+ import * as path15 from "node:path";
139818
+ var MAX_ENTRIES = 200;
139819
+ var MAX_RECORD_BYTES = 16 * 1024;
139820
+ function ledgerPath(home = os13.homedir()) {
139821
+ return path15.join(home, ".temps", "mcp", "minted-keys");
139822
+ }
139823
+ function keyDigest(apiKey) {
139824
+ return createHash5("sha256").update(apiKey.trim()).digest("hex");
139825
+ }
139826
+ function installScope(clientId, target) {
139827
+ return `${clientId}
139828
+ ${target}`;
139829
+ }
139830
+ function isMintedKey(value) {
139831
+ if (!value || typeof value !== "object")
139832
+ return false;
139833
+ const { origin, id, name, sha256 } = value;
139834
+ return typeof origin === "string" && Number.isSafeInteger(id) && typeof name === "string" && typeof sha256 === "string" && /^[0-9a-f]{64}$/.test(sha256);
139835
+ }
139836
+ var RECORD_NAME = /^[0-9a-f]{64}-[0-9a-f]{64}\.json$/;
139837
+ function scopeDigest(scope) {
139838
+ return createHash5("sha256").update(scope).digest("hex");
139839
+ }
139840
+ function recordFile(dir, scope, sha256) {
139841
+ return path15.join(dir, `${scopeDigest(scope)}-${sha256}.json`);
139842
+ }
139843
+ async function readRecord(file, scope) {
139844
+ try {
139845
+ const stat = await fs8.promises.stat(file);
139846
+ if (!stat.isFile() || stat.size > MAX_RECORD_BYTES)
139847
+ return;
139848
+ const parsed = JSON.parse(await fs8.promises.readFile(file, "utf8"));
139849
+ if (!parsed || typeof parsed !== "object" || parsed.scope !== scope)
139850
+ return;
139851
+ const { origin, id, name, sha256, settled } = parsed;
139852
+ const key = { origin, id, name, sha256, ...settled === true ? { settled } : {} };
139853
+ return isMintedKey(key) && path15.basename(file) === `${scopeDigest(scope)}-${sha256}.json` ? key : undefined;
139854
+ } catch {
139855
+ return;
139856
+ }
139857
+ }
139858
+ async function ensureDir(dir) {
139859
+ await fs8.promises.mkdir(dir, { recursive: true, mode: 448 });
139860
+ await fs8.promises.chmod(dir, 448);
139861
+ }
139862
+ async function prune(dir, keep) {
139863
+ try {
139864
+ const names = (await fs8.promises.readdir(dir)).filter((name) => RECORD_NAME.test(name));
139865
+ if (names.length <= MAX_ENTRIES)
139866
+ return;
139867
+ const others = names.filter((name) => name !== path15.basename(keep));
139868
+ const dated = await Promise.all(others.map(async (name) => {
139869
+ const stat = await fs8.promises.stat(path15.join(dir, name)).catch(() => null);
139870
+ return { name, at: stat?.mtimeMs ?? 0 };
139871
+ }));
139872
+ dated.sort((a, b) => a.at - b.at);
139873
+ for (const { name } of dated.slice(0, names.length - MAX_ENTRIES)) {
139874
+ await fs8.promises.rm(path15.join(dir, name), { force: true });
139875
+ }
139876
+ } catch {}
139877
+ }
139878
+ async function mintedKeyFor(scope, installed, dir = ledgerPath()) {
139879
+ if (!installed)
139880
+ return;
139881
+ return readRecord(recordFile(dir, scope, keyDigest(installed)), scope);
139882
+ }
139883
+ async function recordedDigests(scope, dir = ledgerPath()) {
139884
+ const prefix = `${scopeDigest(scope)}-`;
139885
+ let names;
139886
+ try {
139887
+ names = await fs8.promises.readdir(dir);
139888
+ } catch (error) {
139889
+ if (error.code === "ENOENT")
139890
+ return new Set;
139891
+ throw error;
139892
+ }
139893
+ return new Set(names.filter((name) => name.startsWith(prefix) && RECORD_NAME.test(name)).map((name) => name.slice(prefix.length, -".json".length)));
139894
+ }
139895
+ async function mintedKeysFor(scope, dir = ledgerPath()) {
139896
+ const prefix = `${scopeDigest(scope)}-`;
139897
+ let names;
139898
+ try {
139899
+ names = (await fs8.promises.readdir(dir)).filter((name) => name.startsWith(prefix) && RECORD_NAME.test(name));
139900
+ } catch {
139901
+ return [];
139902
+ }
139903
+ const records = await Promise.all(names.map((name) => readRecord(path15.join(dir, name), scope)));
139904
+ return records.filter((record) => record !== undefined);
139905
+ }
139906
+ function isRecordedKey(record, installed, origin) {
139907
+ return Boolean(record && installed && origin && record.origin === origin && record.sha256 === keyDigest(installed));
139908
+ }
139909
+ async function recordMintedKey(scope, key, dir = ledgerPath()) {
139910
+ await ensureDir(dir);
139911
+ const file = recordFile(dir, scope, key.sha256);
139912
+ const record = {
139913
+ scope,
139914
+ origin: key.origin,
139915
+ id: key.id,
139916
+ name: key.name,
139917
+ sha256: key.sha256,
139918
+ ...key.settled ? { settled: true } : {}
139919
+ };
139920
+ const temp = `${file}.${process.pid}.${randomBytes3(6).toString("hex")}.tmp`;
139921
+ try {
139922
+ await fs8.promises.writeFile(temp, `${JSON.stringify(record, null, 2)}
139923
+ `, {
139924
+ mode: 384,
139925
+ flag: "wx"
139926
+ });
139927
+ await fs8.promises.rename(temp, file);
139928
+ } catch (error) {
139929
+ await fs8.promises.rm(temp, { force: true });
139930
+ throw error;
139931
+ }
139932
+ await prune(dir, file);
139933
+ }
139934
+ async function forgetMintedKey(scope, sha256, dir = ledgerPath()) {
139935
+ await fs8.promises.rm(recordFile(dir, scope, sha256), { force: true });
139936
+ }
139937
+
137390
139938
  // src/commands/mcp/index.ts
137391
139939
  function originOf(url) {
137392
139940
  try {
@@ -137473,7 +140021,11 @@ async function selectMcpTarget(options) {
137473
140021
  value: c.name,
137474
140022
  description: c.url
137475
140023
  })),
137476
- { name: "Enter a different URL...", value: CUSTOM_TARGET, alwaysShow: true }
140024
+ {
140025
+ name: "Enter a different URL...",
140026
+ value: CUSTOM_TARGET,
140027
+ alwaysShow: true
140028
+ }
137477
140029
  ]
137478
140030
  });
137479
140031
  if (selected === CUSTOM_TARGET) {
@@ -137486,12 +140038,18 @@ async function selectMcpTarget(options) {
137486
140038
  const ctx = await getContext(selected);
137487
140039
  return ctx ? { url: ctx.url, apiKey: ctx.apiKey } : {};
137488
140040
  }
140041
+ function collect11(value, previous = []) {
140042
+ return [...previous, value];
140043
+ }
140044
+ var cliVersion = "latest";
137489
140045
  function registerMcpCommands(program) {
140046
+ cliVersion = program.version() ?? "latest";
137490
140047
  const mcp = program.command("mcp").description("Configure this Temps instance as an MCP server for AI clients (Claude Code, Claude Desktop, Codex, Cursor, VS Code, Windsurf, Zed)");
137491
140048
  mcp.command("enable").description("Enable the Temps MCP server on this instance (admin, one-time per instance)").option("-u, --url <url>", URL_OPTION_DESCRIPTION).action(enableAction3);
137492
140049
  mcp.command("disable").description("Disable the Temps MCP server on this instance (admin)").option("-u, --url <url>", URL_OPTION_DESCRIPTION).action(disableAction3);
137493
- const addCommand = mcp.command("add [client]").description(`Configure an AI client to connect to this Temps instance over MCP. Clients: ${listClientIds().join(", ")}`).option("-g, --groups <groups>", "Legacy tool-group filter (optional; does not restrict temps/temps_write permissions)").option("-w, --write", "Enable write tools (deploy, delete, restart, etc). Default: read-only").option("-k, --api-key <key>", "Use this API key instead of creating or prompting for one").option("-u, --url <url>", URL_OPTION_DESCRIPTION).option("-y, --yes", "Skip prompts and confirmation (uses defaults; requires --api-key or an existing login)").action(addAction2);
140050
+ const addCommand = mcp.command("add [client]").description(`Configure an AI client to connect to this Temps instance over MCP. Clients: ${listClientIds().join(", ")}`).option("-g, --groups <groups>", "Legacy tool-group filter (optional; does not restrict temps/temps_write permissions)").option("-w, --write", "Enable write tools (deploy, delete, restart, etc). Default: read-only").option("-k, --api-key <key>", "Use this API key instead of creating or prompting for one").option("-u, --url <url>", URL_OPTION_DESCRIPTION).option("-y, --yes", "Skip prompts and confirmation (uses defaults; requires --api-key or an existing login; creates a key for the app: read-only, or with --write one that can make changes)").option("-d, --deploy-folder <dir>", "Let the agent deploy project folders from this computer, from inside this folder (repeatable). The app then runs the Temps bridge locally (temps mcp bridge) instead of connecting over HTTP. Implies --write", collect11).action(addAction2);
137494
140051
  addCredentialSources(addCommand, [{ flag: "api-key", what: "the API key" }]);
140052
+ mcp.command("bridge").description("Run the Temps MCP server on this computer over stdio, adding a tool that deploys local folders. AI apps start this themselves (see mcp add --deploy-folder); the API key comes from TEMPS_API_KEY").option("-u, --url <url>", "The address of your Temps console (default: TEMPS_URL)").option("-f, --folder <dir>", "A folder the agent may deploy from, with everything inside it (repeatable)", collect11).action(bridgeAction);
137495
140053
  mcp.command("remove [client]").description("Remove the Temps MCP server from an AI client").action(removeAction6);
137496
140054
  mcp.command("status").description("Show whether this instance has MCP enabled and which AI clients are configured").option("-u, --url <url>", URL_OPTION_DESCRIPTION).action(statusAction6);
137497
140055
  }
@@ -137499,12 +140057,16 @@ async function setMcpServerEnabled(enabled, urlOverride) {
137499
140057
  const apiKey = await ensureMcpAuth({ urlOverride });
137500
140058
  await setupClient(urlOverride, apiKey);
137501
140059
  await withSpinner(enabled ? "Enabling the Temps MCP server..." : "Disabling the Temps MCP server...", async () => {
137502
- const { data: currentSettings, error: getError } = await getSettings({ client });
140060
+ const { data: currentSettings, error: getError } = await getSettings({
140061
+ client
140062
+ });
137503
140063
  if (getError)
137504
140064
  throw new Error(getErrorMessage(getError));
137505
140065
  const { error } = await updateSettings({
137506
140066
  client,
137507
- body: settingsWriteBody(currentSettings, { mcp_server: { enabled } })
140067
+ body: settingsWriteBody(currentSettings, {
140068
+ mcp_server: { enabled }
140069
+ })
137508
140070
  });
137509
140071
  if (error)
137510
140072
  throw new Error(settingsWriteError(error));
@@ -137522,7 +140084,10 @@ async function disableAction3(options) {
137522
140084
  }
137523
140085
  async function addAction2(clientArg, options) {
137524
140086
  const target = await selectMcpTarget({ url: options.url, yes: options.yes });
137525
- const authenticatedApiKey = await ensureMcpAuth({ yes: options.yes, urlOverride: target.url });
140087
+ const authenticatedApiKey = await ensureMcpAuth({
140088
+ yes: options.yes,
140089
+ urlOverride: target.url
140090
+ });
137526
140091
  await setupClient(target.url, target.apiKey ?? authenticatedApiKey);
137527
140092
  const clientId = clientArg || await promptSelect({
137528
140093
  message: "Which AI client do you want to configure?",
@@ -137550,19 +140115,51 @@ async function addAction2(clientArg, options) {
137550
140115
  const invalid = groups.filter((g) => !isValidGroupKey(g));
137551
140116
  if (invalid.length > 0) {
137552
140117
  warning2(`Unknown tool group(s): ${invalid.join(", ")}. Available: ${TOOL_GROUPS.map((g) => g.key).join(", ")}`);
140118
+ process.exitCode = 1;
137553
140119
  return;
137554
140120
  }
137555
140121
  } else {
137556
140122
  groups = [];
137557
140123
  }
137558
- const write = options.write ?? (options.yes ? false : await promptConfirm({
140124
+ let deployFolders;
140125
+ try {
140126
+ deployFolders = (options.deployFolder ?? []).map(resolveFolder);
140127
+ } catch (error) {
140128
+ warning2(error instanceof Error ? error.message : String(error));
140129
+ process.exitCode = 1;
140130
+ return;
140131
+ }
140132
+ if (deployFolders.length > 0 && groups.length > 0) {
140133
+ warning2("--groups cannot be combined with --deploy-folder: the local bridge serves every tool group. Run it again without --groups.");
140134
+ process.exitCode = 1;
140135
+ return;
140136
+ }
140137
+ for (const folder of deployFolders) {
140138
+ if (!fs9.existsSync(folder) || !fs9.statSync(folder).isDirectory()) {
140139
+ warning2(`${folder} is not a folder on this computer. Pass the folder that holds your projects to --deploy-folder.`);
140140
+ process.exitCode = 1;
140141
+ return;
140142
+ }
140143
+ }
140144
+ if (deployFolders.length > 0) {
140145
+ try {
140146
+ checkBridgeAddress(mcpBaseUrl);
140147
+ } catch (error) {
140148
+ warning2(error instanceof Error ? error.message : String(error));
140149
+ process.exitCode = 1;
140150
+ return;
140151
+ }
140152
+ }
140153
+ const write = (deployFolders.length > 0 ? true : undefined) ?? options.write ?? (options.yes ? false : await promptConfirm({
137559
140154
  message: "Enable temps_write? Writes are proposed first and require confirm_action before execution.",
137560
140155
  default: false
137561
140156
  }));
137562
140157
  let apiKey = options.apiKey;
137563
140158
  let mintedKey = false;
140159
+ let mintedKeyId;
140160
+ let mintedKeyNameUsed = "";
137564
140161
  if (!apiKey) {
137565
- const wantsNewKey = options.yes ? false : await promptConfirm({
140162
+ const wantsNewKey = options.yes ? true : await promptConfirm({
137566
140163
  message: "Create a new dedicated API key scoped for MCP access? (recommended over reusing an existing key)",
137567
140164
  default: true
137568
140165
  });
@@ -137571,7 +140168,7 @@ async function addAction2(clientArg, options) {
137571
140168
  const { data, error } = await createApiKey({
137572
140169
  client,
137573
140170
  body: {
137574
- name: `mcp-${adapter.id}-${new Date().toISOString().slice(0, 10)}`,
140171
+ name: mintedKeyName(adapter.id),
137575
140172
  role_type: write ? "user" : "reader",
137576
140173
  expires_at: null,
137577
140174
  permissions: null
@@ -137585,6 +140182,8 @@ async function addAction2(clientArg, options) {
137585
140182
  });
137586
140183
  apiKey = created.api_key;
137587
140184
  mintedKey = true;
140185
+ mintedKeyId = created.id;
140186
+ mintedKeyNameUsed = created.name;
137588
140187
  newline();
137589
140188
  success2(`Created API key "${created.name}" (${created.key_prefix}...)`);
137590
140189
  } else {
@@ -137592,42 +140191,188 @@ async function addAction2(clientArg, options) {
137592
140191
  }
137593
140192
  }
137594
140193
  const url = buildMcpUrl(mcpBaseUrl, groups, write);
140194
+ const bridge = deployFolders.length > 0 ? { folders: deployFolders, packageSpec: bridgePackageSpec(cliVersion) } : undefined;
137595
140195
  newline();
137596
140196
  header(`Configure ${adapter.label}`);
137597
- keyValue("Target", await adapter.describeTarget());
140197
+ const installTarget = await adapter.describeTarget();
140198
+ keyValue("Target", installTarget);
137598
140199
  keyValue("URL", url);
137599
- keyValue("Primary tools", write ? "temps, temps_write, confirm_action" : "temps (read-only)");
140200
+ if (bridge) {
140201
+ keyValue("Runs locally", `npx ${bridge.packageSpec} mcp bridge`);
140202
+ keyValue("Deploys from", bridge.folders.join(", "));
140203
+ }
140204
+ keyValue("Primary tools", bridge ? "temps, temps_write, confirm_action, temps_deploy_folder" : write ? "temps, temps_write, confirm_action" : "temps (read-only)");
137600
140205
  if (options.groups)
137601
140206
  keyValue("Legacy groups", groups.join(", "));
137602
140207
  info2("Start with temps --help. Available operations follow the API key permissions.");
137603
140208
  newline();
137604
140209
  if (!options.yes) {
137605
- const proceed = await promptConfirm({ message: "Apply this configuration?", default: true });
140210
+ const proceed = await promptConfirm({
140211
+ message: "Apply this configuration?",
140212
+ default: true
140213
+ });
137606
140214
  if (!proceed) {
137607
140215
  info2("Cancelled -- no changes made.");
137608
140216
  return;
137609
140217
  }
137610
140218
  }
137611
- const result = await adapter.addServer({ url, apiKey });
140219
+ const scope = installScope(adapter.id, installTarget);
140220
+ const earlier = await recordedDigests(scope).catch(() => null);
140221
+ const before = await adapter.installedApiKey().catch(() => {
140222
+ return;
140223
+ });
140224
+ const recorded = await mintedKeyFor(scope, before);
140225
+ const result = await adapter.addServer({ url, apiKey, bridge });
137612
140226
  if (!result.success) {
137613
140227
  warning2(`Failed to configure ${adapter.label}: ${result.reason}`);
140228
+ if (mintedKeyId !== undefined)
140229
+ await deleteMintedKey(mintedKeyId);
140230
+ process.exitCode = 1;
137614
140231
  return;
137615
140232
  }
137616
140233
  if (result.alreadyInstalled) {
137617
140234
  info2(`${adapter.label} is already configured with this exact setup.`);
140235
+ if (mintedKeyId !== undefined)
140236
+ await deleteMintedKey(mintedKeyId);
140237
+ mintedKey = false;
137618
140238
  } else {
137619
140239
  success2(`${adapter.label} configured.`);
140240
+ const origin = originOf(mcpBaseUrl);
140241
+ const current = { url: target.url, apiKey: target.apiKey ?? authenticatedApiKey, origin };
140242
+ const sent = apiKey ? keyDigest(apiKey) : undefined;
140243
+ const minted = mintedKeyId !== undefined && origin && sent ? { origin, id: mintedKeyId, name: mintedKeyNameUsed, sha256: sent } : undefined;
140244
+ if (minted)
140245
+ await rememberMintedKey(scope, minted);
140246
+ let entry = await entrySends(adapter, sent);
140247
+ if (minted && entry === "sent") {
140248
+ await rememberMintedKey(scope, { ...minted, settled: true });
140249
+ entry = await entrySends(adapter, sent);
140250
+ }
140251
+ if (minted && entry === "replaced") {
140252
+ warning2(`Another temps mcp add changed ${adapter.label} at the same time and its setup is the one kept; the API key created here is unused.`);
140253
+ await deleteMintedKey(minted.id);
140254
+ await forgetRecordedKey(scope, minted.sha256);
140255
+ mintedKey = false;
140256
+ } else if (recorded) {
140257
+ const stillSent = recorded.sha256 === sent;
140258
+ if (!stillSent && isRecordedKey(recorded, before, recorded.origin)) {
140259
+ await retireOnItsInstance(recorded, before, current);
140260
+ await forgetRecordedKey(scope, recorded.sha256);
140261
+ } else if (stillSent && recorded.origin !== origin) {
140262
+ await forgetRecordedKey(scope, recorded.sha256);
140263
+ }
140264
+ } else if (before && before !== apiKey) {
140265
+ info2(`The API key ${adapter.label} used before was not created for it by mcp add on this computer, so it was kept. Delete it under Settings > API keys if nothing else uses it.`);
140266
+ }
140267
+ if (entry === "sent" && earlier)
140268
+ await retireReplaced(adapter, scope, earlier, current);
137620
140269
  }
137621
140270
  info2(`Restart ${adapter.label} to pick up the change.`);
137622
- if (adapter.id === "codex") {
140271
+ if (!bridge) {
140272
+ const first = adapter.id === "claude-code" ? `run temps mcp remove ${adapter.id}, then ` : "";
140273
+ info2(`To let ${adapter.label} deploy project folders from this computer, ${first}run this again with --deploy-folder <folder that holds your projects>.`);
140274
+ }
140275
+ if (adapter.id === "codex" && !bridge) {
137623
140276
  newline();
137624
140277
  warning2(`Codex reads its bearer token from the ${TOKEN_ENV_VAR} environment variable at connect time -- export it in your shell profile, or every codex session will fail to authenticate to Temps:`);
137625
140278
  info2(codexTokenExportLine(apiKey, mintedKey));
140279
+ if (mintedKey) {
140280
+ info2("A key an earlier install of Codex exported stays valid: once your shell exports this one, delete the old one under Settings > API keys.");
140281
+ }
137626
140282
  }
137627
140283
  }
137628
140284
  function codexTokenExportLine(apiKey, minted) {
137629
140285
  return minted ? ` export ${TOKEN_ENV_VAR}='Bearer ${apiKey}'` : ` export ${TOKEN_ENV_VAR}='Bearer <your Temps API key>'`;
137630
140286
  }
140287
+ function mintedKeyName(clientId, now = new Date) {
140288
+ return `mcp-${clientId}-${now.toISOString().slice(0, 10)}-${randomBytes4(3).toString("hex")}`;
140289
+ }
140290
+ async function rememberMintedKey(scope, key) {
140291
+ try {
140292
+ await recordMintedKey(scope, key);
140293
+ } catch (error) {
140294
+ warning2(`Could not record the API key this install uses: ${error instanceof Error ? error.message : String(error)}. A later mcp add or mcp remove will not delete it; delete it under Settings > API keys once it is unused.`);
140295
+ }
140296
+ }
140297
+ async function forgetRecordedKey(scope, sha256) {
140298
+ await forgetMintedKey(scope, sha256).catch(() => {
140299
+ return;
140300
+ });
140301
+ }
140302
+ async function retireOnItsInstance(recorded, installed, current) {
140303
+ if (current?.origin && current.origin === recorded.origin) {
140304
+ await retireRecordedKey(recorded, installed);
140305
+ return;
140306
+ }
140307
+ const context = await findContextByUrl(recorded.origin);
140308
+ if (!context) {
140309
+ warning2(`The API key ${recorded.name} on ${recorded.origin} is unused now. Delete it under Settings > API keys (no login for that instance is saved here).`);
140310
+ return;
140311
+ }
140312
+ await setupClient(context.url, context.apiKey);
140313
+ try {
140314
+ await retireRecordedKey(recorded, installed);
140315
+ } finally {
140316
+ if (current)
140317
+ await setupClient(current.url, current.apiKey);
140318
+ }
140319
+ }
140320
+ async function entrySends(adapter, sent) {
140321
+ const now = await adapter.installedApiKey().catch(() => {
140322
+ return;
140323
+ });
140324
+ if (sent === undefined || now === undefined)
140325
+ return "unknown";
140326
+ return keyDigest(now) === sent ? "sent" : "replaced";
140327
+ }
140328
+ async function retireReplaced(adapter, scope, earlier, current) {
140329
+ for (const other of await mintedKeysFor(scope).catch(() => [])) {
140330
+ if (earlier.has(other.sha256) || !other.settled)
140331
+ continue;
140332
+ const sending = await adapter.installedApiKey().catch(() => {
140333
+ return;
140334
+ });
140335
+ if (sending === undefined)
140336
+ return;
140337
+ if (keyDigest(sending) === other.sha256)
140338
+ continue;
140339
+ await retireOnItsInstance(other, undefined, current);
140340
+ await forgetRecordedKey(scope, other.sha256);
140341
+ }
140342
+ }
140343
+ async function retireRecordedKey(recorded, installed) {
140344
+ try {
140345
+ const { data, error, response } = await getApiKey({
140346
+ client,
140347
+ path: { id: recorded.id }
140348
+ });
140349
+ if (response?.status === 404)
140350
+ return;
140351
+ if (error)
140352
+ throw new Error(getErrorMessage(error));
140353
+ const prefixDiffers = installed !== undefined && (!data?.key_prefix || !installed.startsWith(data.key_prefix));
140354
+ if (!data || data.name !== recorded.name || prefixDiffers) {
140355
+ warning2(`The API key with ID ${recorded.id} is not the ${recorded.name} this computer recorded, so it was kept. Delete ${recorded.name} under Settings > API keys if it still exists.`);
140356
+ return;
140357
+ }
140358
+ const deleted = await deleteApiKey({ client, path: { id: recorded.id } });
140359
+ if (deleted.error)
140360
+ throw new Error(getErrorMessage(deleted.error));
140361
+ info2(`Deleted the API key ${recorded.name}, which nothing uses any more.`);
140362
+ } catch (error) {
140363
+ warning2(`The API key ${recorded.name} (ID ${recorded.id}) was not deleted: ${error instanceof Error ? error.message : String(error)}. Delete it under Settings > API keys.`);
140364
+ }
140365
+ }
140366
+ async function deleteMintedKey(id) {
140367
+ try {
140368
+ const { error } = await deleteApiKey({ client, path: { id } });
140369
+ if (error)
140370
+ throw new Error(getErrorMessage(error));
140371
+ info2("Deleted the API key created for this install.");
140372
+ } catch (error) {
140373
+ warning2(`The API key created for this install (ID ${id}) was not deleted: ${error instanceof Error ? error.message : String(error)}. Delete it under Settings > API keys.`);
140374
+ }
140375
+ }
137631
140376
  async function removeAction6(clientArg) {
137632
140377
  const clientId = clientArg || await promptSelect({
137633
140378
  message: "Which AI client do you want to remove the Temps MCP server from?",
@@ -137638,15 +140383,27 @@ async function removeAction6(clientArg) {
137638
140383
  warning2(`Unknown client "${clientId}". Available: ${listClientIds().join(", ")}`);
137639
140384
  return;
137640
140385
  }
140386
+ const scope = installScope(adapter.id, await adapter.describeTarget());
140387
+ const before = await adapter.installedApiKey().catch(() => {
140388
+ return;
140389
+ });
140390
+ const recorded = await mintedKeyFor(scope, before);
137641
140391
  const result = await adapter.removeServer();
137642
140392
  if (!result.success) {
137643
140393
  warning2(`Failed to remove from ${adapter.label}: ${result.reason}`);
140394
+ process.exitCode = 1;
137644
140395
  return;
137645
140396
  }
137646
140397
  if (result.alreadyInstalled) {
137647
140398
  info2(`${adapter.label} had no Temps MCP server configured.`);
137648
- } else {
137649
- success2(`Removed the Temps MCP server from ${adapter.label}.`);
140399
+ return;
140400
+ }
140401
+ success2(`Removed the Temps MCP server from ${adapter.label}.`);
140402
+ if (recorded && isRecordedKey(recorded, before, recorded.origin)) {
140403
+ await retireOnItsInstance(recorded, before, null);
140404
+ await forgetRecordedKey(scope, recorded.sha256);
140405
+ } else if (before) {
140406
+ info2(`The API key ${adapter.label} used was not created for it by mcp add on this computer, so it was kept. Delete it under Settings > API keys if nothing else uses it.`);
137650
140407
  }
137651
140408
  }
137652
140409
  function formatMcpAccess(url) {
@@ -137914,7 +140671,7 @@ async function deleteAction8(name, options) {
137914
140671
 
137915
140672
  // src/commands/workflows/init.ts
137916
140673
  import { mkdir as mkdir11, writeFile as writeFile8, unlink as unlink6, rmdir, open as open5 } from "node:fs/promises";
137917
- import { resolve as resolve12, join as join22 } from "node:path";
140674
+ import { resolve as resolve15, join as join26 } from "node:path";
137918
140675
  var header2 = `// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
137919
140676
  // SPDX-License-Identifier: MIT OR Apache-2.0
137920
140677
  `;
@@ -137984,7 +140741,7 @@ node_modules/
137984
140741
  async function scaffoldWorker(directory, sdkPackage) {
137985
140742
  let sdk;
137986
140743
  if (sdkPackage) {
137987
- const handle = await open5(resolve12(sdkPackage), "r");
140744
+ const handle = await open5(resolve15(sdkPackage), "r");
137988
140745
  try {
137989
140746
  const stat = await handle.stat();
137990
140747
  if (!stat.isFile() || stat.size > 16 * 1024 * 1024)
@@ -138006,12 +140763,12 @@ async function scaffoldWorker(directory, sdkPackage) {
138006
140763
  await handle.close();
138007
140764
  }
138008
140765
  }
138009
- const target = resolve12(directory);
140766
+ const target = resolve15(directory);
138010
140767
  await mkdir11(target);
138011
140768
  const created = [];
138012
140769
  try {
138013
140770
  if (sdk) {
138014
- await writeFile8(join22(target, "workflows-sdk.tgz"), sdk, { flag: "wx" });
140771
+ await writeFile8(join26(target, "workflows-sdk.tgz"), sdk, { flag: "wx" });
138015
140772
  created.push("workflows-sdk.tgz");
138016
140773
  }
138017
140774
  const files = { ...workerFiles };
@@ -138023,13 +140780,13 @@ async function scaffoldWorker(directory, sdkPackage) {
138023
140780
  files.Dockerfile = files.Dockerfile.replace("COPY package.json ./", "COPY package.json workflows-sdk.tgz ./");
138024
140781
  }
138025
140782
  for (const [name, content] of Object.entries(files)) {
138026
- await writeFile8(join22(target, name), content, { flag: "wx" });
140783
+ await writeFile8(join26(target, name), content, { flag: "wx" });
138027
140784
  created.push(name);
138028
140785
  }
138029
140786
  return target;
138030
140787
  } catch (error) {
138031
140788
  for (const name of created)
138032
- await unlink6(join22(target, name)).catch(() => {});
140789
+ await unlink6(join26(target, name)).catch(() => {});
138033
140790
  await rmdir(target).catch(() => {});
138034
140791
  throw error;
138035
140792
  }
@@ -138279,7 +141036,7 @@ function registerDurableWorkflowCommands(program) {
138279
141036
  }
138280
141037
 
138281
141038
  // src/commands/workflow/index.ts
138282
- import { existsSync as existsSync18 } from "node:fs";
141039
+ import { existsSync as existsSync19 } from "node:fs";
138283
141040
  import { readFile as readFile14 } from "node:fs/promises";
138284
141041
  init_sdk_gen();
138285
141042
  init_spinner();
@@ -138458,7 +141215,7 @@ async function runAction2(slug, options) {
138458
141215
  let run;
138459
141216
  let runLabel;
138460
141217
  if (options.fromFile) {
138461
- if (!existsSync18(options.fromFile)) {
141218
+ if (!existsSync19(options.fromFile)) {
138462
141219
  error2(`File not found: ${options.fromFile}`);
138463
141220
  process.exitCode = 2;
138464
141221
  return;
@@ -138968,7 +141725,7 @@ function printRunSummary(run) {
138968
141725
 
138969
141726
  // src/commands/revenue/index.ts
138970
141727
  import { readFile as readFile15, stat as stat2 } from "node:fs/promises";
138971
- import { basename as basename10 } from "node:path";
141728
+ import { basename as basename11 } from "node:path";
138972
141729
  init_sdk_gen();
138973
141730
  init_spinner();
138974
141731
  init_output();
@@ -139045,7 +141802,7 @@ async function uploadCsv(projectId, integrationId, kind, filePath) {
139045
141802
  const arrayBuffer = new ArrayBuffer(bytes.byteLength);
139046
141803
  new Uint8Array(arrayBuffer).set(bytes);
139047
141804
  const form = new FormData;
139048
- form.append("file", new Blob([arrayBuffer], { type: "text/csv" }), basename10(filePath));
141805
+ form.append("file", new Blob([arrayBuffer], { type: "text/csv" }), basename11(filePath));
139049
141806
  const res = await fetch(url, {
139050
141807
  method: "POST",
139051
141808
  headers: { Authorization: `Bearer ${apiKey}` },
@@ -139479,7 +142236,7 @@ function registerSessionReplayCommands(program) {
139479
142236
  init_sdk_gen();
139480
142237
 
139481
142238
  // src/commands/traefik-discovery/tls.ts
139482
- import { readFileSync as readFileSync8 } from "node:fs";
142239
+ import { readFileSync as readFileSync9 } from "node:fs";
139483
142240
  init_sdk_gen();
139484
142241
  init_spinner();
139485
142242
  init_output();
@@ -139509,7 +142266,7 @@ function isValidRenewalMethod(value) {
139509
142266
  }
139510
142267
  function readAcmeJsonFile(file) {
139511
142268
  try {
139512
- return { ok: true, contents: readFileSync8(file, "utf-8") };
142269
+ return { ok: true, contents: readFileSync9(file, "utf-8") };
139513
142270
  } catch (e) {
139514
142271
  const msg = e instanceof Error ? e.message : String(e);
139515
142272
  return { ok: false, message: `Failed to read '${file}': ${msg}` };
@@ -140067,8 +142824,8 @@ init_prompts();
140067
142824
  init_spinner();
140068
142825
  init_output();
140069
142826
  init_sdk_gen();
140070
- import { existsSync as existsSync19, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2 } from "node:fs";
140071
- import { resolve as resolve13, join as join23 } from "node:path";
142827
+ import { existsSync as existsSync20, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2 } from "node:fs";
142828
+ import { resolve as resolve16, join as join27 } from "node:path";
140072
142829
  import { tmpdir as tmpdir5 } from "node:os";
140073
142830
  async function runSetupWizard(options) {
140074
142831
  newline();
@@ -140171,7 +142928,7 @@ async function runSetupWizard(options) {
140171
142928
  } else {
140172
142929
  staticDir = detectedStaticDir ?? "dist";
140173
142930
  }
140174
- if (!existsSync19(resolve13(staticDir))) {
142931
+ if (!existsSync20(resolve16(staticDir))) {
140175
142932
  warning2(`Folder not found: ${colors.bold(staticDir)}`);
140176
142933
  info2("Build your project first, then re-run, or pass --static-dir <path>.");
140177
142934
  return null;
@@ -140370,7 +143127,7 @@ async function runSetupWizard(options) {
140370
143127
  info2("Building and deploying...");
140371
143128
  newline();
140372
143129
  try {
140373
- const hasDockerfile = existsSync19(resolve13("Dockerfile"));
143130
+ const hasDockerfile = existsSync20(resolve16("Dockerfile"));
140374
143131
  let dockerfilePath;
140375
143132
  let buildArgsList;
140376
143133
  if (!hasDockerfile && presetSlug && presetSlug !== "dockerfile") {
@@ -140398,9 +143155,9 @@ async function runSetupWizard(options) {
140398
143155
  isGitBased
140399
143156
  };
140400
143157
  }
140401
- const tempDir = join23(tmpdir5(), `temps-dockerfile-${Date.now()}`);
143158
+ const tempDir = join27(tmpdir5(), `temps-dockerfile-${Date.now()}`);
140402
143159
  mkdirSync2(tempDir, { recursive: true });
140403
- dockerfilePath = join23(tempDir, "Dockerfile");
143160
+ dockerfilePath = join27(tempDir, "Dockerfile");
140404
143161
  writeFileSync4(dockerfilePath, dockerfileData.dockerfile);
140405
143162
  success2(`Dockerfile generated from ${presetSlug} preset`);
140406
143163
  if (dockerfileData.build_args && Object.keys(dockerfileData.build_args).length > 0) {
@@ -140506,14 +143263,14 @@ async function selectPresetFromAll() {
140506
143263
  });
140507
143264
  }
140508
143265
  function detectPackageManager(dir) {
140509
- const projectDir = dir ? resolve13(dir) : process.cwd();
140510
- if (existsSync19(join23(projectDir, "pnpm-lock.yaml")))
143266
+ const projectDir = dir ? resolve16(dir) : process.cwd();
143267
+ if (existsSync20(join27(projectDir, "pnpm-lock.yaml")))
140511
143268
  return "pnpm";
140512
- if (existsSync19(join23(projectDir, "yarn.lock")))
143269
+ if (existsSync20(join27(projectDir, "yarn.lock")))
140513
143270
  return "yarn";
140514
- if (existsSync19(join23(projectDir, "bun.lockb")) || existsSync19(join23(projectDir, "bun.lock")))
143271
+ if (existsSync20(join27(projectDir, "bun.lockb")) || existsSync20(join27(projectDir, "bun.lock")))
140515
143272
  return "bun";
140516
- if (existsSync19(join23(projectDir, "package-lock.json")))
143273
+ if (existsSync20(join27(projectDir, "package-lock.json")))
140517
143274
  return "npm";
140518
143275
  return "npm";
140519
143276
  }
@@ -140889,7 +143646,7 @@ function registerStatusCommand(program) {
140889
143646
  }
140890
143647
 
140891
143648
  // src/commands/ai/upload.ts
140892
- import { basename as basename11 } from "node:path";
143649
+ import { basename as basename12 } from "node:path";
140893
143650
  init_sdk_gen();
140894
143651
  init_output();
140895
143652
  var DEFAULT_CHUNK_BYTES = 32 * 1024;
@@ -140918,7 +143675,7 @@ async function uploadAction(conversation, file, options) {
140918
143675
  const { data, error } = await startAttachmentUpload({
140919
143676
  client,
140920
143677
  path: { public_id: conversation },
140921
- body: { name: options.name ?? basename11(file), size_bytes: size, mime_type: options.mimeType ?? (source.type || null) }
143678
+ body: { name: options.name ?? basename12(file), size_bytes: size, mime_type: options.mimeType ?? (source.type || null) }
140922
143679
  });
140923
143680
  if (error || !data)
140924
143681
  throw new Error(`Could not start uploading ${file} to conversation ${conversation}: ${getErrorMessage(error)}`);
@@ -140965,7 +143722,7 @@ async function uploadAction(conversation, file, options) {
140965
143722
  const { data, error } = await completeAttachmentUpload({ client, path: { public_id: conversation, upload_id: uploadId } });
140966
143723
  if (error || !data)
140967
143724
  throw new Error(`Could not complete upload ${uploadId} of ${file}: ${getErrorMessage(error)}`);
140968
- output(data, options, `Attached ${basename11(file)}`, `Uploaded ${size} bytes`);
143725
+ output(data, options, `Attached ${basename12(file)}`, `Uploaded ${size} bytes`);
140969
143726
  }
140970
143727
  function registerAiUploadCommand(ai) {
140971
143728
  subgroup(ai, "chat", "AI chat conversations: messages, attachments, sandboxes and workspaces").command("upload <conversation-id> <file>").description("Attach a file to a conversation in chunks; resumable with --resume").option("--name <name>", "File name to show (default: the file name)").option("--mime-type <type>", "Content type (default: guessed from the extension)").option("--resume <upload-id>", "Continue an interrupted upload instead of starting a new one").option("--chunk-bytes <n>", `Bytes per chunk (default ${DEFAULT_CHUNK_BYTES}, the server's limit)`).option("--json", "Output in JSON format").action(uploadAction);
@@ -141229,7 +143986,7 @@ function registerAiCommands(program) {
141229
143986
 
141230
143987
  // src/config/instances.ts
141231
143988
  import { readFile as readFile16, writeFile as writeFile9, mkdir as mkdir12 } from "node:fs/promises";
141232
- import { existsSync as existsSync20 } from "node:fs";
143989
+ import { existsSync as existsSync21 } from "node:fs";
141233
143990
  import { dirname as dirname9 } from "node:path";
141234
143991
  function getInstancesPath() {
141235
143992
  const home = process.env.HOME || process.env.USERPROFILE || "~";
@@ -141238,7 +143995,7 @@ function getInstancesPath() {
141238
143995
  async function loadInstances() {
141239
143996
  const path = getInstancesPath();
141240
143997
  try {
141241
- if (existsSync20(path)) {
143998
+ if (existsSync21(path)) {
141242
143999
  const content = await readFile16(path, "utf-8");
141243
144000
  return JSON.parse(content);
141244
144001
  }
@@ -141429,8 +144186,8 @@ function registerInstancesCommands(program) {
141429
144186
  }
141430
144187
 
141431
144188
  // src/commands/env-sync/index.ts
141432
- import * as fs7 from "node:fs";
141433
- import * as path13 from "node:path";
144189
+ import * as fs10 from "node:fs";
144190
+ import * as path16 from "node:path";
141434
144191
  init_sdk_gen();
141435
144192
  init_spinner();
141436
144193
  init_prompts();
@@ -141529,8 +144286,8 @@ async function pull2(file, options) {
141529
144286
  }
141530
144287
  const envContent = exportableVars.map((v) => formatEnvLine(v.key, resolvedValues.get(v.id) ?? "")).join(`
141531
144288
  `);
141532
- const outputPath = path13.isAbsolute(outputFile) ? outputFile : path13.resolve(process.cwd(), outputFile);
141533
- if (fs7.existsSync(outputPath)) {
144289
+ const outputPath = path16.isAbsolute(outputFile) ? outputFile : path16.resolve(process.cwd(), outputFile);
144290
+ if (fs10.existsSync(outputPath)) {
141534
144291
  const overwrite = await promptConfirm({
141535
144292
  message: `${outputFile} already exists. Overwrite?`,
141536
144293
  default: false
@@ -141540,7 +144297,7 @@ async function pull2(file, options) {
141540
144297
  return;
141541
144298
  }
141542
144299
  }
141543
- fs7.writeFileSync(outputPath, envContent + `
144300
+ fs10.writeFileSync(outputPath, envContent + `
141544
144301
  `);
141545
144302
  success2(`Pulled ${exportableVars.length} variables to ${outputFile}`);
141546
144303
  }
@@ -141549,12 +144306,12 @@ async function push(file, options) {
141549
144306
  await setupClient();
141550
144307
  const resolved = await requireProjectSlug(options.project);
141551
144308
  const inputFile = file ?? ".env";
141552
- const inputPath = path13.isAbsolute(inputFile) ? inputFile : path13.resolve(process.cwd(), inputFile);
141553
- if (!fs7.existsSync(inputPath)) {
144309
+ const inputPath = path16.isAbsolute(inputFile) ? inputFile : path16.resolve(process.cwd(), inputFile);
144310
+ if (!fs10.existsSync(inputPath)) {
141554
144311
  error2(`File not found: ${inputFile}`);
141555
144312
  return;
141556
144313
  }
141557
- const content = fs7.readFileSync(inputPath, "utf-8");
144314
+ const content = fs10.readFileSync(inputPath, "utf-8");
141558
144315
  const variables = parseEnvFile2(content);
141559
144316
  if (Object.keys(variables).length === 0) {
141560
144317
  warning2("No variables found in file");
@@ -143359,6 +146116,7 @@ function createProgram() {
143359
146116
  registerServerCommands(program);
143360
146117
  registerTracesCommands(program);
143361
146118
  registerFacetsCommands(program);
146119
+ registerIngressCommands(program);
143362
146120
  registerOtelForwardCommands(program);
143363
146121
  registerOtelCommands(program);
143364
146122
  registerKvCommands(program);
@@ -143798,6 +146556,7 @@ function createProgram2() {
143798
146556
  registerServerCommands(program);
143799
146557
  registerTracesCommands(program);
143800
146558
  registerFacetsCommands(program);
146559
+ registerIngressCommands(program);
143801
146560
  registerOtelForwardCommands(program);
143802
146561
  registerOtelCommands(program);
143803
146562
  registerKvCommands(program);