@pmate/cli 0.45.2 → 0.45.4

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
@@ -8829,8 +8829,10 @@ var import_node_path36 = __toESM(require("path"));
8829
8829
  // src/managedSession.ts
8830
8830
  var import_node_fs = require("fs");
8831
8831
  var import_node_os = require("os");
8832
+ var import_node_crypto = require("crypto");
8832
8833
  var import_node_path = require("path");
8833
8834
  async function ensureManagedSession(env = process.env, fetcher = fetch) {
8835
+ if (env.PMATE_EXPECTED_ACCOUNT_ID && env.HEBO_MEMORY_TOKEN?.trim()) throw Error("Bound Agent CLI cannot use another delegated identity");
8834
8836
  if (env.HEBO_MEMORY_TOKEN?.trim()) {
8835
8837
  const token = env.HEBO_MEMORY_TOKEN.trim(), app = "pmate:factory";
8836
8838
  const base = (env.AUTH_API_BASE_URL ?? "https://auth-api-v2.pmate.chat").replace(/\/+$/, "");
@@ -8852,16 +8854,25 @@ async function ensureManagedSession(env = process.env, fetcher = fetch) {
8852
8854
  }
8853
8855
  if (env.PCS_AGENT_SESSION_MANAGED !== "1") return;
8854
8856
  if (!env.PMATE_SESSION_FILE) throw Error("Managed session file is required");
8855
- const state = JSON.parse((0, import_node_fs.readFileSync)(env.PMATE_SESSION_FILE, "utf8"));
8857
+ const source = env.PCS_AGENT_SESSION_SOURCE_FILE ?? env.PMATE_SESSION_FILE;
8858
+ const state = JSON.parse((0, import_node_fs.readFileSync)(source, "utf8"));
8856
8859
  if (!state.refreshKey) throw Error("Managed session refresh key is missing");
8857
- const port = Number(env.PCS_AGENT_CONTROL_PORT ?? 39399);
8860
+ const port = Number(env.PMATE_SESSION_REFRESH_PORT ?? env.PCS_AGENT_CONTROL_PORT ?? 39399);
8858
8861
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error("Invalid controller port");
8859
- const r = await fetcher(`http://127.0.0.1:${port}/v2/session/refresh`, {
8862
+ const r = await fetcher(`http://127.0.0.1:${port}/${env.PMATE_SESSION_REFRESH_PORT ? "v1" : "v2"}/session/refresh`, {
8860
8863
  method: "POST",
8861
8864
  headers: { "x-agent-session-key": state.refreshKey },
8862
8865
  signal: AbortSignal.timeout(45e3)
8863
8866
  });
8864
8867
  if (!r.ok) throw Error(`Managed session renewal unavailable (${r.status}); retry later`);
8868
+ if (source !== env.PMATE_SESSION_FILE) {
8869
+ const raw = (0, import_node_fs.readFileSync)(source, "utf8"), current = JSON.parse(raw).sessions?.[env.PMATE_SESSION_APP ?? "pmate:factory"];
8870
+ if (env.PMATE_EXPECTED_ACCOUNT_ID && current?.accountId !== env.PMATE_EXPECTED_ACCOUNT_ID) throw Error("Renewed Agent CLI Account mismatch");
8871
+ if (env.PMATE_EXPECTED_PROFILE_ID && current?.profileId !== env.PMATE_EXPECTED_PROFILE_ID) throw Error("Renewed Agent CLI Profile mismatch");
8872
+ const temp = `${env.PMATE_SESSION_FILE}.${(0, import_node_crypto.randomUUID)()}.tmp`;
8873
+ (0, import_node_fs.writeFileSync)(temp, raw, { mode: 384, flag: "wx" });
8874
+ (0, import_node_fs.renameSync)(temp, env.PMATE_SESSION_FILE);
8875
+ }
8865
8876
  }
8866
8877
 
8867
8878
  // src/index.ts
@@ -9865,7 +9876,7 @@ var import_fc20230330 = __toESM(require("@alicloud/fc20230330"));
9865
9876
  var import_openapi_client = require("@alicloud/openapi-client");
9866
9877
  var import_sts20150401 = __toESM(require("@alicloud/sts20150401"));
9867
9878
  var import_ali_oss = __toESM(require("ali-oss"));
9868
- var import_node_crypto = require("crypto");
9879
+ var import_node_crypto2 = require("crypto");
9869
9880
  var import_node_fs5 = require("fs");
9870
9881
  var import_node_path7 = __toESM(require("path"));
9871
9882
 
@@ -10636,7 +10647,7 @@ var AliyunService = class {
10636
10647
  /** Compute MD5 for a file. */
10637
10648
  static getFileMd5(filePath) {
10638
10649
  return new Promise((resolve, reject) => {
10639
- const hash = (0, import_node_crypto.createHash)("md5");
10650
+ const hash = (0, import_node_crypto2.createHash)("md5");
10640
10651
  const stream = (0, import_node_fs5.createReadStream)(filePath);
10641
10652
  stream.on("data", (chunk) => {
10642
10653
  hash.update(chunk);
@@ -14535,7 +14546,7 @@ var QrcodeCommandHandler = class {
14535
14546
  };
14536
14547
 
14537
14548
  // src/commands/RandomCommandHandler.ts
14538
- var import_node_crypto2 = require("crypto");
14549
+ var import_node_crypto3 = require("crypto");
14539
14550
  var DEFAULT_TOKEN_LENGTH = 32;
14540
14551
  var DEFAULT_EASY_WORDS = 3;
14541
14552
  var DEFAULT_EASY_DIGITS = 2;
@@ -14701,7 +14712,7 @@ function randomString(length, charset) {
14701
14712
  const max = Math.floor(256 / charsetLength) * charsetLength;
14702
14713
  let result = "";
14703
14714
  while (result.length < length) {
14704
- const bytes = (0, import_node_crypto2.randomBytes)(Math.max(1, length - result.length));
14715
+ const bytes = (0, import_node_crypto3.randomBytes)(Math.max(1, length - result.length));
14705
14716
  for (const byte of bytes) {
14706
14717
  if (byte >= max) {
14707
14718
  continue;
@@ -14715,12 +14726,12 @@ function randomString(length, charset) {
14715
14726
  return result;
14716
14727
  }
14717
14728
  function randomWord() {
14718
- return EASY_WORDS[(0, import_node_crypto2.randomInt)(0, EASY_WORDS.length)];
14729
+ return EASY_WORDS[(0, import_node_crypto3.randomInt)(0, EASY_WORDS.length)];
14719
14730
  }
14720
14731
  function randomDigits(count) {
14721
14732
  let value = "";
14722
14733
  for (let i = 0; i < count; i += 1) {
14723
- value += (0, import_node_crypto2.randomInt)(0, 10).toString();
14734
+ value += (0, import_node_crypto3.randomInt)(0, 10).toString();
14724
14735
  }
14725
14736
  return value;
14726
14737
  }
@@ -15505,20 +15516,20 @@ var Im1BotClient = class {
15505
15516
  };
15506
15517
 
15507
15518
  // src/collectStore.ts
15508
- var import_node_crypto3 = require("crypto");
15519
+ var import_node_crypto4 = require("crypto");
15509
15520
  var import_node_fs12 = require("fs");
15510
15521
  var import_node_os7 = __toESM(require("os"));
15511
15522
  var import_node_path18 = __toESM(require("path"));
15512
15523
  function resolveCollectTarget(input) {
15513
15524
  const endpoint = input.endpoint ?? (input.source === "cc" ? "http://localhost:9223" : "http://localhost:9222");
15514
- const sourceKey = input.source ?? `endpoint-${(0, import_node_crypto3.createHash)("sha1").update(endpoint).digest("hex").slice(0, 8)}`;
15525
+ const sourceKey = input.source ?? `endpoint-${(0, import_node_crypto4.createHash)("sha1").update(endpoint).digest("hex").slice(0, 8)}`;
15515
15526
  const rootDir = import_node_path18.default.join(import_node_os7.default.homedir(), ".pmate", "collect", sourceKey);
15516
15527
  return { sourceKey, endpoint, rootDir };
15517
15528
  }
15518
15529
  function toThreadKey(name) {
15519
15530
  const normalized = name.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-+|-+$/g, "");
15520
15531
  const base = normalized || "thread";
15521
- const suffix = (0, import_node_crypto3.createHash)("sha1").update(name).digest("hex").slice(0, 8);
15532
+ const suffix = (0, import_node_crypto4.createHash)("sha1").update(name).digest("hex").slice(0, 8);
15522
15533
  return `${base}-${suffix}`;
15523
15534
  }
15524
15535
  async function readStoredThread(rootDir, threadKey) {
@@ -18297,7 +18308,7 @@ var import_sharp2 = __toESM(require("sharp"));
18297
18308
 
18298
18309
  // src/desktopRelease.ts
18299
18310
  init_sessionStore();
18300
- var import_node_crypto4 = require("crypto");
18311
+ var import_node_crypto5 = require("crypto");
18301
18312
  var import_node_fs20 = require("fs");
18302
18313
  var import_node_path25 = __toESM(require("path"));
18303
18314
  async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
@@ -18311,7 +18322,7 @@ async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18311
18322
  const artifacts = (0, import_node_fs20.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && (platform === "mac" ? /(?:\.(dmg|zip|blockmap)$|^latest-mac\.yml$)/i : /(?:\.(exe|zip|blockmap)$|^latest\.yml$)/i).test(entry.name)).sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
18312
18323
  const bytes = (0, import_node_fs20.readFileSync)(import_node_path25.default.join(directory, entry.name));
18313
18324
  const objectKey = prefix + entry.name;
18314
- return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto4.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18325
+ return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto5.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18315
18326
  });
18316
18327
  if (!artifacts.length) throw new Error("No desktop installers found to publish");
18317
18328
  const manifestKey = prefix + "release.json";
@@ -18515,7 +18526,7 @@ function currentRepositoryRoot(repository, cwd = process.cwd()) {
18515
18526
 
18516
18527
  // src/services/AndroidApkReleaseService.ts
18517
18528
  var import_node_child_process11 = require("child_process");
18518
- var import_node_crypto5 = require("crypto");
18529
+ var import_node_crypto6 = require("crypto");
18519
18530
  var import_node_fs22 = require("fs");
18520
18531
  var import_node_os11 = __toESM(require("os"));
18521
18532
  var import_node_path27 = __toESM(require("path"));
@@ -19016,7 +19027,7 @@ function listVersionedToolCandidates(parentDir, relativeToolPath) {
19016
19027
  }
19017
19028
  function sha256File(filePath) {
19018
19029
  return new Promise((resolve, reject) => {
19019
- const hash = (0, import_node_crypto5.createHash)("sha256");
19030
+ const hash = (0, import_node_crypto6.createHash)("sha256");
19020
19031
  const stream = (0, import_node_fs22.createReadStream)(filePath);
19021
19032
  stream.on("data", (chunk) => hash.update(chunk));
19022
19033
  stream.on("error", reject);
@@ -19035,7 +19046,7 @@ function capitalize(value) {
19035
19046
 
19036
19047
  // src/services/HarmonyReleaseService.ts
19037
19048
  var import_node_child_process12 = require("child_process");
19038
- var import_node_crypto6 = require("crypto");
19049
+ var import_node_crypto7 = require("crypto");
19039
19050
  var import_node_fs23 = require("fs");
19040
19051
  var import_node_os12 = __toESM(require("os"));
19041
19052
  var import_node_path28 = __toESM(require("path"));
@@ -19177,7 +19188,7 @@ function signingMaterial(values) {
19177
19188
  return bytes;
19178
19189
  };
19179
19190
  const certificate = decode2("HARMONY_CERTIFICATE_BASE64");
19180
- const fingerprint = new import_node_crypto6.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19191
+ const fingerprint = new import_node_crypto7.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19181
19192
  return { keystore: decode2("HARMONY_KEYSTORE_BASE64"), certificate, profile: decode2("HARMONY_PROFILE_BASE64"), fingerprint };
19182
19193
  }
19183
19194
  function assertHarmonyMetadata(raw, version) {
@@ -19187,7 +19198,7 @@ function assertHarmonyMetadata(raw, version) {
19187
19198
  var withHarmonyPublicationLock = async (bucket2, key, publish) => {
19188
19199
  if (!/^harmony\/[\w-]+\/[\w-]+\/\.publish-lock\.json$/.test(key)) throw new Error("Invalid HarmonyOS publication lock key");
19189
19200
  await AliyunService.assertUnversionedBucket(bucket2);
19190
- const owner = (0, import_node_crypto6.randomUUID)();
19201
+ const owner = (0, import_node_crypto7.randomUUID)();
19191
19202
  try {
19192
19203
  await AliyunService.uploadJsonObject(bucket2, key, { owner, createdAt: (/* @__PURE__ */ new Date()).toISOString() }, { "x-oss-forbid-overwrite": "true" });
19193
19204
  } catch {
@@ -19259,9 +19270,9 @@ var HarmonyReleaseService = class {
19259
19270
  const files = (0, import_node_fs23.readdirSync)(dist, { withFileTypes: true }).filter((e) => e.isFile() && /\.(app|hap)$/.test(e.name)).map((e) => import_node_path28.default.join(dist, e.name));
19260
19271
  if (files.length !== 2 || files.filter((f) => f.endsWith(".app")).length !== 1 || files.filter((f) => f.endsWith(".hap")).length !== 1) throw new Error("HarmonyOS build must produce exactly one signed APP and one signed HAP");
19261
19272
  const check = async (file, inspectMetadata) => {
19262
- const id = (0, import_node_crypto6.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path28.default.join(temp, `${id}.cer`);
19273
+ const id = (0, import_node_crypto7.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path28.default.join(temp, `${id}.cer`);
19263
19274
  await run(tools.java, ["-jar", tools.signer, "verify-app", "-inFile", file, "-outCertChain", cert, "-outProfile", import_node_path28.default.join(temp, `${id}.p7b`)], opts);
19264
- if (new import_node_crypto6.X509Certificate((0, import_node_fs23.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19275
+ if (new import_node_crypto7.X509Certificate((0, import_node_fs23.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19265
19276
  if (inspectMetadata) assertHarmonyMetadata(JSON.parse(await run("unzip", ["-p", file, "module.json"], { ...opts, capture: true })), version);
19266
19277
  };
19267
19278
  for (const file of files) {
@@ -19285,7 +19296,7 @@ var HarmonyReleaseService = class {
19285
19296
  if (!size) throw new Error("Empty HarmonyOS artifact");
19286
19297
  const target = import_node_path28.default.join(output, name);
19287
19298
  (0, import_node_fs23.cpSync)(file, target);
19288
- const hash = (0, import_node_crypto6.createHash)("sha256");
19299
+ const hash = (0, import_node_crypto7.createHash)("sha256");
19289
19300
  for await (const chunk of (0, import_node_fs23.createReadStream)(target)) hash.update(chunk);
19290
19301
  artifacts.push({ name, type: import_node_path28.default.extname(name).slice(1), objectKey: releasePrefix + name, downloadUrl: `${baseUrl}/${releasePrefix}${name}`, sha256: hash.digest("hex"), size });
19291
19302
  }
@@ -19316,7 +19327,7 @@ var HarmonyReleaseService = class {
19316
19327
 
19317
19328
  // src/services/IosBuildService.ts
19318
19329
  var import_node_child_process13 = require("child_process");
19319
- var import_node_crypto7 = require("crypto");
19330
+ var import_node_crypto8 = require("crypto");
19320
19331
  var import_node_fs24 = require("fs");
19321
19332
  var import_node_os13 = __toESM(require("os"));
19322
19333
  var import_node_path29 = __toESM(require("path"));
@@ -19379,7 +19390,7 @@ var IosBuildService = class {
19379
19390
  if (!bundleId || !/^\d+\.\d+(?:\.\d+)?$/.test(version ?? "") || !/^[A-Z0-9]{10}$/.test(team ?? "")) throw new Error("Missing or invalid bundle ID, MARKETING_VERSION or signing team; use --team if needed");
19380
19391
  if (service.mobile && "bundleId" in service.mobile && service.mobile.bundleId !== bundleId) throw new Error("Service bundle ID does not match application target");
19381
19392
  const currentBuild = iosBuildInteger(cfg.CURRENT_PROJECT_VERSION);
19382
- const key = (0, import_node_crypto7.createHash)("sha256").update(bundleId).digest("hex");
19393
+ const key = (0, import_node_crypto8.createHash)("sha256").update(bundleId).digest("hex");
19383
19394
  const statePath = import_node_path29.default.join(root, `${key}.json`);
19384
19395
  const lockPath = import_node_path29.default.join(root, `${key}.lock`);
19385
19396
  let lock;
@@ -22752,7 +22763,7 @@ var RoleCommandHandler = class {
22752
22763
 
22753
22764
  // src/commands/AccountCommandHandler.ts
22754
22765
  var import_node_fs28 = require("fs");
22755
- var import_node_crypto8 = require("crypto");
22766
+ var import_node_crypto9 = require("crypto");
22756
22767
  var import_node_path33 = __toESM(require("path"));
22757
22768
  init_sessionStore();
22758
22769
  var AccountCommandHandler = class {
@@ -23397,7 +23408,7 @@ var AccountCommandHandler = class {
23397
23408
  return process.env.HOME || process.env.USERPROFILE || process.cwd();
23398
23409
  }
23399
23410
  generateBotKeyFile(app, name) {
23400
- const { publicKey, privateKey } = (0, import_node_crypto8.generateKeyPairSync)("ed25519");
23411
+ const { publicKey, privateKey } = (0, import_node_crypto9.generateKeyPairSync)("ed25519");
23401
23412
  return {
23402
23413
  type: "pmate-bot-key",
23403
23414
  version: 1,
@@ -23519,12 +23530,12 @@ var AccountCommandHandler = class {
23519
23530
  });
23520
23531
  }
23521
23532
  signBotChallenge(challenge, privateKey) {
23522
- const key = (0, import_node_crypto8.createPrivateKey)({
23533
+ const key = (0, import_node_crypto9.createPrivateKey)({
23523
23534
  key: Buffer.from(privateKey, "base64url"),
23524
23535
  format: "der",
23525
23536
  type: "pkcs8"
23526
23537
  });
23527
- return (0, import_node_crypto8.sign)(
23538
+ return (0, import_node_crypto9.sign)(
23528
23539
  null,
23529
23540
  Buffer.from(JSON.stringify({
23530
23541
  id: challenge.id,
@@ -3,14 +3,16 @@ const { homedir } = require('node:os')
3
3
  const path = require('node:path')
4
4
  const {modelCatalog}=require('./model-catalog.cjs')
5
5
  const {createLocalExecutor}=require('./local-exec.cjs')
6
+ const {createShellPathResolver}=require('./shell-path.cjs')
6
7
  const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','local.info','local.exec','runtime.inspect','scripts.run']
7
8
  function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch, environment = process.env } = {}) {
9
+ const resolvePath=createShellPathResolver({home,environment,platform})
8
10
  let identityEpoch=0
9
11
  let identity
10
- const run = execute || ((file, args, cwd, timeout = 600000, credentials = {}) => new Promise((resolve, reject) => {
11
- execFile(file, args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024, env: { ...environment, ...credentials, PATH: [path.join(home,'.local/bin'),path.join(home,'.bun/bin'),environment.PNPM_HOME,path.join(home,'Library/pnpm'),path.join(home,'.local/share/pnpm'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':'), GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
12
- }))
13
- const localExec=createLocalExecutor({home,environment})
12
+ const run = execute || (async(file, args, cwd, timeout = 600000, credentials = {}) => {const resolved=await resolvePath();return new Promise((resolve, reject) => {
13
+ execFile(file, args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024, env: { ...environment, ...credentials, PATH: resolved.path, GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
14
+ })})
15
+ const localExec=createLocalExecutor({home,environment,resolvePath})
14
16
  const api = async (route, method='GET', body) => {
15
17
  if (!identity) throw new Error('请先登录梅丽号')
16
18
  const response = await fetcher(`https://issue-api.pmate.chat${route}`, { method, headers: { authorization:`Bearer ${identity.token}`, 'x-pmate-app':identity.appId, 'content-type':'application/json' }, ...(body===undefined?{}:{body:JSON.stringify(body)}), signal:AbortSignal.timeout(30000) })
@@ -28,7 +30,7 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
28
30
  if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新执行')
29
31
  return result
30
32
  }
31
- if(method==='scripts.run'&&input?.id==='runtime.models'&&input.args&&Object.keys(input.args).length===0)return modelCatalog({environment:{...environment,PATH:[path.join(home,'.local/bin'),path.join(home,'.bun/bin'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':')}})
33
+ if(method==='scripts.run'&&input?.id==='runtime.models'&&input.args&&Object.keys(input.args).length===0)return modelCatalog({environment:{...environment,PATH:(await resolvePath()).path}})
32
34
  if(method==='scripts.run')throw new Error('未知脚本操作')
33
35
  if(method==='workspaces.list')return api('/v2/workspaces')
34
36
  const {scope,id,config,expectedRevision}=input||{}
@@ -1,15 +1,16 @@
1
1
  const {execFile}=require('node:child_process')
2
2
  const path=require('node:path')
3
+ const {createShellPathResolver}=require('./shell-path.cjs')
3
4
  /** Stable local process capability. Command selection and business rules belong to Web/bridge. */
4
- function createLocalExecutor({home,environment,execute=execFile}){
5
- const env={...environment,PATH:[path.join(home,'.local/bin'),path.join(home,'.bun/bin'),environment.PNPM_HOME,path.join(home,'Library/pnpm'),path.join(home,'.local/share/pnpm'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':')}
5
+ function createLocalExecutor({home,environment,execute=execFile,resolvePath=createShellPathResolver({home,environment})}){
6
+
6
7
  return input=>{
7
8
  if(!input||typeof input.command!=='string'||!input.command||input.command.includes('\0')||!Array.isArray(input.args)||input.args.some(v=>typeof v!=='string'||v.includes('\0'))||input.args.length>256||input.args.some(v=>v.length>131072))throw Error('Invalid local command')
8
9
  if(input.cwd!==undefined&&(typeof input.cwd!=='string'||!path.isAbsolute(input.cwd)||input.cwd.includes('\0')))throw Error('Invalid working directory')
9
10
  if(input.env!==undefined&&(!input.env||typeof input.env!=='object'||Array.isArray(input.env)||Object.entries(input.env).some(([k,v])=>!k||k.includes('=')||k.includes('\0')||typeof v!=='string'||v.includes('\0'))))throw Error('Invalid process environment')
10
11
  const timeout=input.timeoutMs??10000
11
12
  if(!Number.isSafeInteger(timeout)||timeout<100||timeout>120000)throw Error('Invalid command timeout')
12
- return new Promise(resolve=>execute(input.command,input.args,{cwd:input.cwd,env:{...env,...input.env},shell:false,timeout,maxBuffer:1024*1024,windowsHide:true},(error,stdout,stderr)=>resolve({stdout:String(stdout??''),stderr:String(stderr??''),exitCode:error?(typeof error.code==='number'?error.code:null):0,error:error?(error.code==='ENOENT'?'NOT_FOUND':error.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER'?'OUTPUT_LIMIT':error.killed?'TIMEOUT':'PROCESS_FAILED'):undefined})))
13
+ return resolvePath().then(({path:resolvedPath,warning})=>new Promise(resolve=>execute(input.command,input.args,{cwd:input.cwd,env:{...environment,PATH:resolvedPath,...input.env},shell:false,timeout,maxBuffer:1024*1024,windowsHide:true},(error,stdout,stderr)=>resolve({stdout:String(stdout??''),stderr:(error&&warning?warning+'\n':'')+String(stderr??''),exitCode:error?(typeof error.code==='number'?error.code:null):0,error:error?(error.code==='ENOENT'?'NOT_FOUND':error.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER'?'OUTPUT_LIMIT':error.killed?'TIMEOUT':'PROCESS_FAILED'):undefined}))))
13
14
  }
14
15
  }
15
16
  module.exports={createLocalExecutor}
@@ -0,0 +1,37 @@
1
+ const {execFile}=require('node:child_process')
2
+ const {userInfo}=require('node:os')
3
+ const path=require('node:path')
4
+ const {randomBytes}=require('node:crypto')
5
+ function fallbackPath(home,environment,platform){
6
+ if(platform==='win32')return environment.PATH||''
7
+ return [...new Set([environment.PATH,...[path.join(home,'.local/bin'),path.join(home,'.bun/bin'),environment.PNPM_HOME,path.join(home,'Library/pnpm'),path.join(home,'.local/share/pnpm'),'/opt/homebrew/bin','/usr/local/bin','/usr/bin','/bin'].filter(Boolean)].filter(Boolean).flatMap(value=>value.split(':')).filter(value=>path.isAbsolute(value)))].join(':')
8
+ }
9
+ /** Read only PATH from the user's shell. Never import shell credentials or execute caller arguments through it. */
10
+ function createShellPathResolver({home,environment,platform=process.platform,shell,execute=execFile,timeoutMs=5000}={}){
11
+ let cached
12
+ return()=>cached??(cached=(async()=>{
13
+ const fallback=fallbackPath(home,environment,platform)
14
+ if(platform==='win32')return{path:fallback}
15
+ let selected=shell
16
+ if(!selected)try{selected=userInfo().shell}catch{}
17
+ selected=selected||environment.SHELL||(platform==='darwin'?'/bin/zsh':'/bin/sh')
18
+ if(!path.isAbsolute(selected)||selected.includes('\0'))return{path:fallback,warning:'无法读取用户 shell,已使用桌面默认 PATH'}
19
+ const marker='MERRY_PATH_'+randomBytes(16).toString('hex'),begin=marker+'_BEGIN',end=marker+'_END'
20
+ const command=`printf '\\n${begin}\\n'; /usr/bin/printenv PATH; printf '\\n${end}\\n'`
21
+ return new Promise(resolve=>{
22
+ let done=false,timer,child
23
+ const finish=value=>{if(done)return;done=true;clearTimeout(timer);resolve(value)}
24
+ timer=setTimeout(()=>{child?.kill('SIGKILL');finish({path:fallback,warning:'读取用户 shell PATH 超时,已使用桌面默认 PATH'})},timeoutMs)
25
+ try{child=execute(selected,['-ilc',command],{env:{...environment,HOME:home},cwd:home,shell:false,timeout:timeoutMs,killSignal:'SIGKILL',maxBuffer:1024*1024,windowsHide:true},(error,stdout)=>{
26
+ if(error)return finish({path:fallback,warning:'读取用户 shell PATH 失败,已使用桌面默认 PATH'})
27
+ const output=String(stdout??''),start=output.indexOf('\n'+begin+'\n'),stop=output.indexOf('\n'+end+'\n',start+begin.length+2)
28
+ const value=start<0||stop<0?'':output.slice(start+begin.length+2,stop).trim()
29
+ if(!value||/[\r\n\0]/.test(value))return finish({path:fallback,warning:'用户 shell 未返回有效 PATH,已使用桌面默认 PATH'})
30
+ const entries=value.split(':').filter(entry=>path.isAbsolute(entry))
31
+ if(!entries.length)return finish({path:fallback,warning:'用户 shell PATH 无效,已使用桌面默认 PATH'})
32
+ finish({path:[...new Set([...entries,...fallback.split(':')])].join(':')})
33
+ })}catch{finish({path:fallback,warning:'无法启动用户 shell,已使用桌面默认 PATH'})}
34
+ })
35
+ })())
36
+ }
37
+ module.exports={createShellPathResolver}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.45.2",
3
+ "version": "0.45.4",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {