@pmate/cli 0.46.2 → 0.48.0

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.d.ts CHANGED
@@ -62,6 +62,8 @@ type LoginCommandArgs = {
62
62
  accessKeyFile?: string;
63
63
  accessKeyScan?: boolean;
64
64
  selectProfile?: boolean;
65
+ tokenStdin?: boolean;
66
+ expectedAccount?: string;
65
67
  };
66
68
  type AddDnsCommandArgs = {
67
69
  type: Command.AddDns;
package/dist/index.js CHANGED
@@ -88,47 +88,59 @@ var init_namespacedRef = __esm({
88
88
 
89
89
  // src/sessionStore.ts
90
90
  function buildSessionStorePath() {
91
- return process.env.PMATE_SESSION_FILE?.trim() || import_node_path6.default.join(import_node_os5.default.homedir(), ".pmate", "session.json");
91
+ return process.env.PMATE_SESSION_FILE?.trim() || import_node_path.default.join(import_node_os.default.homedir(), ".pmate", "session.json");
92
92
  }
93
93
  function assertValidAppRef(appRef2) {
94
94
  return parseNamespacedRef(appRef2, { entityLabel: "app ref" }).fullId;
95
95
  }
96
96
  function saveLoginSession(session, requestedApp = DEFAULT_APP_ID) {
97
- const store = loadExistingSessionStoreOrEmpty();
98
- const app = assertValidAppRef(requestedApp);
99
- const sessionApp = session.session?.identity?.app?.trim();
100
- if (!sessionApp) {
101
- throw new Error("Missing app in login session payload.");
102
- }
103
- const normalizedSessionApp = assertValidAppRef(sessionApp);
104
- if (normalizedSessionApp !== app) {
105
- throw new Error(
106
- `Session app mismatch. requested=${app}, received=${normalizedSessionApp}`
107
- );
97
+ const sessionPath = buildSessionStorePath();
98
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(sessionPath), { recursive: true, mode: 448 });
99
+ const lock = sessionPath + ".lock";
100
+ try {
101
+ (0, import_node_fs.mkdirSync)(lock);
102
+ } catch {
103
+ throw new Error("Session store is busy; retry login.");
104
+ }
105
+ try {
106
+ const store = loadExistingSessionStoreOrEmpty();
107
+ const app = assertValidAppRef(requestedApp);
108
+ const sessionApp = session.session?.identity?.app?.trim();
109
+ if (!sessionApp) {
110
+ throw new Error("Missing app in login session payload.");
111
+ }
112
+ const normalizedSessionApp = assertValidAppRef(sessionApp);
113
+ if (normalizedSessionApp !== app) {
114
+ throw new Error(
115
+ `Session app mismatch. requested=${app}, received=${normalizedSessionApp}`
116
+ );
117
+ }
118
+ const accountId = session.session.identity?.accountId?.trim();
119
+ const profileId = session.profileId?.trim();
120
+ const token = session.token?.trim();
121
+ const issuedAt = session.session.issuedAt?.trim();
122
+ const expiresAt = session.session.expiresAt?.trim();
123
+ if (!accountId || !profileId || !token || !issuedAt || !expiresAt) {
124
+ throw new Error("Invalid login session payload.");
125
+ }
126
+ const nextSession = {
127
+ token,
128
+ accountId,
129
+ profileId,
130
+ issuedAt,
131
+ expiresAt,
132
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
133
+ };
134
+ store.sessions[app] = nextSession;
135
+ store.activeAppRef = app;
136
+ writeSessionStore(store);
137
+ return {
138
+ app,
139
+ sessionPath: buildSessionStorePath()
140
+ };
141
+ } finally {
142
+ (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
108
143
  }
109
- const accountId = session.session.identity?.accountId?.trim();
110
- const profileId = session.profileId?.trim();
111
- const token = session.token?.trim();
112
- const issuedAt = session.session.issuedAt?.trim();
113
- const expiresAt = session.session.expiresAt?.trim();
114
- if (!accountId || !profileId || !token || !issuedAt || !expiresAt) {
115
- throw new Error("Invalid login session payload.");
116
- }
117
- const nextSession = {
118
- token,
119
- accountId,
120
- profileId,
121
- issuedAt,
122
- expiresAt,
123
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
124
- };
125
- store.sessions[app] = nextSession;
126
- store.activeAppRef = app;
127
- writeSessionStore(store);
128
- return {
129
- app,
130
- sessionPath: buildSessionStorePath()
131
- };
132
144
  }
133
145
  function readRequiredSession(options) {
134
146
  const { sessionPath, store } = loadSessionStoreWithPath();
@@ -158,29 +170,21 @@ function loadSessionStore() {
158
170
  }
159
171
  function loadExistingSessionStoreOrEmpty() {
160
172
  const sessionPath = buildSessionStorePath();
161
- if (!(0, import_node_fs5.existsSync)(sessionPath)) {
162
- return {
163
- version: SESSION_STORE_VERSION,
164
- activeAppRef: DEFAULT_APP_ID,
165
- sessions: {}
166
- };
167
- }
168
- try {
169
- return loadSessionStore();
170
- } catch {
173
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
171
174
  return {
172
175
  version: SESSION_STORE_VERSION,
173
176
  activeAppRef: DEFAULT_APP_ID,
174
177
  sessions: {}
175
178
  };
176
179
  }
180
+ return loadSessionStore();
177
181
  }
178
182
  function loadSessionStoreWithPath() {
179
183
  const sessionPath = buildSessionStorePath();
180
- if (!(0, import_node_fs5.existsSync)(sessionPath)) {
184
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
181
185
  throw new Error(`Missing session file at ${sessionPath}. Run "pmate login" first.`);
182
186
  }
183
- const raw = (0, import_node_fs5.readFileSync)(sessionPath, "utf8");
187
+ const raw = (0, import_node_fs.readFileSync)(sessionPath, "utf8");
184
188
  const parsed = JSON.parse(raw);
185
189
  const store = normalizeStore(parsed);
186
190
  return { sessionPath, store };
@@ -270,12 +274,16 @@ function resolveReadApp(store, options) {
270
274
  }
271
275
  function writeSessionStore(store) {
272
276
  const sessionPath = buildSessionStorePath();
273
- (0, import_node_fs5.mkdirSync)(import_node_path6.default.dirname(sessionPath), { recursive: true });
274
- (0, import_node_fs5.writeFileSync)(sessionPath, JSON.stringify(store, null, 2), {
275
- mode: 384
276
- });
277
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(sessionPath), { recursive: true });
278
+ const temporary = sessionPath + "." + (0, import_node_crypto.randomUUID)() + ".tmp";
277
279
  try {
278
- (0, import_node_fs5.chmodSync)(sessionPath, 384);
280
+ (0, import_node_fs.writeFileSync)(temporary, JSON.stringify(store, null, 2), { mode: 384, flag: "wx" });
281
+ (0, import_node_fs.renameSync)(temporary, sessionPath);
282
+ } finally {
283
+ (0, import_node_fs.rmSync)(temporary, { force: true });
284
+ }
285
+ try {
286
+ (0, import_node_fs.chmodSync)(sessionPath, 384);
279
287
  } catch {
280
288
  }
281
289
  }
@@ -285,13 +293,64 @@ function buildMissingSessionMessage(sessionPath, app) {
285
293
  }
286
294
  return `Missing session for app ${app} in ${sessionPath}. Run "pmate login --app ${app}" first.`;
287
295
  }
288
- var import_node_fs5, import_node_os5, import_node_path6, DEFAULT_APP_ID, SESSION_STORE_VERSION;
296
+ function removeStoredSession(appRef2) {
297
+ const app = assertValidAppRef(appRef2), sessionPath = buildSessionStorePath();
298
+ if (process.env.PMATE_SESSION_APP && process.env.PMATE_SESSION_APP !== app) throw Error("Agent CLI application differs from its bound session");
299
+ if (process.env.PMATE_EXPECTED_ACCOUNT_ID && !process.env.PMATE_SESSION_FILE?.trim()) throw Error("Agent CLI requires a dedicated session file");
300
+ if (!(0, import_node_fs.existsSync)(sessionPath)) return;
301
+ const lock = sessionPath + ".lock";
302
+ try {
303
+ (0, import_node_fs.mkdirSync)(lock);
304
+ } catch {
305
+ throw Error("Session store is busy; retry logout.");
306
+ }
307
+ try {
308
+ const store = loadExistingSessionStoreOrEmpty();
309
+ delete store.sessions[app];
310
+ if (store.activeAppRef === app) store.activeAppRef = Object.keys(store.sessions)[0] || DEFAULT_APP_ID;
311
+ writeSessionStore(store);
312
+ } finally {
313
+ (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
314
+ }
315
+ }
316
+ function claimSessionLogin(appRef2) {
317
+ const app = assertValidAppRef(appRef2), file = buildSessionStorePath() + ".login-" + encodeURIComponent(app);
318
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(file), { recursive: true, mode: 448 });
319
+ for (; ; ) {
320
+ try {
321
+ (0, import_node_fs.mkdirSync)(file);
322
+ (0, import_node_fs.writeFileSync)(import_node_path.default.join(file, "pid"), String(process.pid), { mode: 384 });
323
+ return () => (0, import_node_fs.rmSync)(file, { recursive: true, force: true });
324
+ } catch (error) {
325
+ if (error.code !== "EEXIST") throw error;
326
+ let pid;
327
+ try {
328
+ pid = Number((0, import_node_fs.readFileSync)(import_node_path.default.join(file, "pid"), "utf8"));
329
+ } catch {
330
+ throw Error("CLI login is already in progress");
331
+ }
332
+ if (!Number.isSafeInteger(pid) || pid < 1) throw Error("CLI login lock requires inspection");
333
+ try {
334
+ process.kill(pid, 0);
335
+ } catch (error2) {
336
+ if (error2.code === "ESRCH") {
337
+ (0, import_node_fs.rmSync)(file, { recursive: true });
338
+ continue;
339
+ }
340
+ throw error2;
341
+ }
342
+ throw Error("CLI login is already in progress");
343
+ }
344
+ }
345
+ }
346
+ var import_node_fs, import_node_os, import_node_crypto, import_node_path, DEFAULT_APP_ID, SESSION_STORE_VERSION;
289
347
  var init_sessionStore = __esm({
290
348
  "src/sessionStore.ts"() {
291
349
  "use strict";
292
- import_node_fs5 = require("fs");
293
- import_node_os5 = __toESM(require("os"));
294
- import_node_path6 = __toESM(require("path"));
350
+ import_node_fs = require("fs");
351
+ import_node_os = __toESM(require("os"));
352
+ import_node_crypto = require("crypto");
353
+ import_node_path = __toESM(require("path"));
295
354
  init_namespacedRef();
296
355
  DEFAULT_APP_ID = "pmate:factory";
297
356
  SESSION_STORE_VERSION = 4;
@@ -8823,22 +8882,48 @@ __export(index_exports, {
8823
8882
  parseCommandArgs: () => parseCommandArgs
8824
8883
  });
8825
8884
  module.exports = __toCommonJS(index_exports);
8885
+
8886
+ // src/sessionCommand.ts
8887
+ init_sessionStore();
8888
+ function sessionCommand(args) {
8889
+ const [operation, flag, app] = args;
8890
+ if (!["status", "read", "logout"].includes(operation) || flag !== "--app" || !app || args.length !== 3) throw Error("Usage: pmate session status|read|logout --app APP");
8891
+ if (operation === "logout") {
8892
+ const release = claimSessionLogin(app);
8893
+ try {
8894
+ removeStoredSession(app);
8895
+ return { version: 1, loggedIn: false };
8896
+ } finally {
8897
+ release();
8898
+ }
8899
+ }
8900
+ try {
8901
+ const session = readRequiredSession({ app, fallbackToActiveApp: false });
8902
+ if (!Number.isFinite(Date.parse(session.expiresAt)) || Date.parse(session.expiresAt) <= Date.now()) throw Error("CLI session expired");
8903
+ return operation === "read" ? { version: 1, ...session } : { version: 1, loggedIn: true, accountId: session.accountId, profileId: session.profileId, expiresAt: session.expiresAt };
8904
+ } catch (error) {
8905
+ if (operation === "read") throw error;
8906
+ return { version: 1, loggedIn: false };
8907
+ }
8908
+ }
8909
+
8910
+ // src/index.ts
8826
8911
  var import_node_fs32 = require("fs");
8827
8912
  var import_node_path37 = __toESM(require("path"));
8828
8913
 
8829
8914
  // src/services/PackageInstaller.ts
8830
8915
  var import_node_child_process = require("child_process");
8831
8916
  var import_node_util = require("util");
8832
- var import_node_fs = require("fs");
8833
- var import_node_os = require("os");
8834
- var import_node_path = __toESM(require("path"));
8917
+ var import_node_fs2 = require("fs");
8918
+ var import_node_os2 = require("os");
8919
+ var import_node_path2 = __toESM(require("path"));
8835
8920
  var run = async (file, args, cwd) => {
8836
8921
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process.execFile)(file, args, { cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, timeout: 6e5, maxBuffer: 8 * 1024 * 1024 });
8837
8922
  return stdout.trim();
8838
8923
  };
8839
8924
  var semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
8840
8925
  var segment = /^[a-z][a-z0-9-]{0,62}$/;
8841
- var relative = (p) => typeof p === "string" && !!p && !import_node_path.default.isAbsolute(p) && !p.includes("\\") && !p.includes("\0") && !p.split("/").some((x) => !x || x === "..");
8926
+ var relative = (p) => typeof p === "string" && !!p && !import_node_path2.default.isAbsolute(p) && !p.includes("\\") && !p.includes("\0") && !p.split("/").some((x) => !x || x === "..");
8842
8927
  function packageRef(value) {
8843
8928
  const parts = value.includes(":") ? value.split(":") : ["pmate", value];
8844
8929
  if (parts.length !== 2 || parts.some((p) => !segment.test(p))) throw Error("Use a package name or namespace:name");
@@ -8855,8 +8940,8 @@ function validateInstallMetadata(value, id) {
8855
8940
  var PackageInstaller = class {
8856
8941
  constructor(ports = {}) {
8857
8942
  this.ports = ports;
8858
- this.directory = import_node_path.default.join(ports.home ?? (0, import_node_os.homedir)(), ".pmate/packages");
8859
- this.binDirectory = import_node_path.default.join(ports.home ?? (0, import_node_os.homedir)(), ".local/bin");
8943
+ this.directory = import_node_path2.default.join(ports.home ?? (0, import_node_os2.homedir)(), ".pmate/packages");
8944
+ this.binDirectory = import_node_path2.default.join(ports.home ?? (0, import_node_os2.homedir)(), ".local/bin");
8860
8945
  }
8861
8946
  execute(file, args, cwd) {
8862
8947
  return (this.ports.run ?? run)(file, args, cwd);
@@ -8865,21 +8950,21 @@ var PackageInstaller = class {
8865
8950
  this.ports.progress?.(message);
8866
8951
  }
8867
8952
  records() {
8868
- const file = import_node_path.default.join(this.directory, "installed.json");
8869
- if (!(0, import_node_fs.existsSync)(file)) return {};
8870
- const value = JSON.parse((0, import_node_fs.readFileSync)(file, "utf8"));
8953
+ const file = import_node_path2.default.join(this.directory, "installed.json");
8954
+ if (!(0, import_node_fs2.existsSync)(file)) return {};
8955
+ const value = JSON.parse((0, import_node_fs2.readFileSync)(file, "utf8"));
8871
8956
  if (value.schemaVersion !== 1 || !value.packages || typeof value.packages !== "object") throw Error("Invalid installed package registry");
8872
8957
  return value.packages;
8873
8958
  }
8874
8959
  save(packages) {
8875
- const file = import_node_path.default.join(this.directory, "installed.json"), temporary = file + ".tmp-" + process.pid;
8876
- (0, import_node_fs.writeFileSync)(temporary, JSON.stringify({ schemaVersion: 1, packages }, null, 2) + "\n", { mode: 384 });
8877
- (0, import_node_fs.renameSync)(temporary, file);
8960
+ const file = import_node_path2.default.join(this.directory, "installed.json"), temporary = file + ".tmp-" + process.pid;
8961
+ (0, import_node_fs2.writeFileSync)(temporary, JSON.stringify({ schemaVersion: 1, packages }, null, 2) + "\n", { mode: 384 });
8962
+ (0, import_node_fs2.renameSync)(temporary, file);
8878
8963
  }
8879
8964
  local(root, relativePath) {
8880
8965
  if (!relative(relativePath)) throw Error("Invalid package path");
8881
- const file = import_node_path.default.resolve(root, relativePath), base = (0, import_node_fs.realpathSync)(root);
8882
- if ((0, import_node_fs.realpathSync)(file) !== base && !(0, import_node_fs.realpathSync)(file).startsWith(base + import_node_path.default.sep)) throw Error("Package path escapes repository");
8966
+ const file = import_node_path2.default.resolve(root, relativePath), base = (0, import_node_fs2.realpathSync)(root);
8967
+ if ((0, import_node_fs2.realpathSync)(file) !== base && !(0, import_node_fs2.realpathSync)(file).startsWith(base + import_node_path2.default.sep)) throw Error("Package path escapes repository");
8883
8968
  return file;
8884
8969
  }
8885
8970
  async step(root, step) {
@@ -8907,40 +8992,40 @@ var PackageInstaller = class {
8907
8992
  async install(name) {
8908
8993
  const metadata = await this.metadata(name);
8909
8994
  if (!metadata.platforms.includes(this.ports.platform ?? process.platform)) throw Error("Package is not supported on this platform");
8910
- (0, import_node_fs.mkdirSync)(this.directory, { recursive: true, mode: 448 });
8911
- if ((0, import_node_fs.lstatSync)(this.directory).isSymbolicLink()) throw Error("Package directory must not be a symlink");
8912
- const lock = import_node_path.default.join(this.directory, "install.lock");
8995
+ (0, import_node_fs2.mkdirSync)(this.directory, { recursive: true, mode: 448 });
8996
+ if ((0, import_node_fs2.lstatSync)(this.directory).isSymbolicLink()) throw Error("Package directory must not be a symlink");
8997
+ const lock = import_node_path2.default.join(this.directory, "install.lock");
8913
8998
  try {
8914
- (0, import_node_fs.mkdirSync)(lock);
8915
- (0, import_node_fs.writeFileSync)(import_node_path.default.join(lock, "pid"), String(process.pid));
8999
+ (0, import_node_fs2.mkdirSync)(lock);
9000
+ (0, import_node_fs2.writeFileSync)(import_node_path2.default.join(lock, "pid"), String(process.pid));
8916
9001
  } catch {
8917
9002
  throw Error("Another package installation is running; inspect ~/.pmate/packages/install.lock");
8918
9003
  }
8919
9004
  try {
8920
9005
  return await this.installLocked(metadata);
8921
9006
  } finally {
8922
- (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
9007
+ (0, import_node_fs2.rmSync)(lock, { recursive: true, force: true });
8923
9008
  }
8924
9009
  }
8925
9010
  async installLocked(metadata) {
8926
- const records = this.records(), old = records[metadata.id], root = import_node_path.default.join(this.directory, "repos", ...metadata.repository.split("/"));
8927
- (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(root), { recursive: true, mode: 448 });
9011
+ const records = this.records(), old = records[metadata.id], root = import_node_path2.default.join(this.directory, "repos", ...metadata.repository.split("/"));
9012
+ (0, import_node_fs2.mkdirSync)(import_node_path2.default.dirname(root), { recursive: true, mode: 448 });
8928
9013
  if (old && old.root !== root) throw Error("Installed repository location differs; migration required");
8929
- if ((0, import_node_fs.existsSync)(root)) {
8930
- if ((0, import_node_fs.lstatSync)(root).isSymbolicLink()) throw Error("Repository directory must not be a symlink");
9014
+ if ((0, import_node_fs2.existsSync)(root)) {
9015
+ if ((0, import_node_fs2.lstatSync)(root).isSymbolicLink()) throw Error("Repository directory must not be a symlink");
8931
9016
  const remote = (await this.execute("git", ["remote", "get-url", "origin"], root)).replace(/\.git$/, "");
8932
9017
  if (!remote.endsWith("/" + metadata.repository) && !remote.endsWith(":" + metadata.repository)) throw Error("Installed repository origin differs");
8933
9018
  if (await this.execute("git", ["status", "--porcelain"], root)) throw Error("Installed repository contains local changes; preserve them before updating");
8934
9019
  }
8935
- (0, import_node_fs.mkdirSync)(this.binDirectory, { recursive: true });
9020
+ (0, import_node_fs2.mkdirSync)(this.binDirectory, { recursive: true });
8936
9021
  for (const name of Object.keys(metadata.bins)) {
8937
- const file = import_node_path.default.join(this.binDirectory, name), stat = (0, import_node_fs.lstatSync)(file, { throwIfNoEntry: false });
8938
- if (stat && (!old?.bins[name] || !stat.isSymbolicLink() || (0, import_node_fs.realpathSync)(file) !== (0, import_node_fs.realpathSync)(old.bins[name]))) throw Error("Refusing to replace unmanaged command: " + name);
9022
+ const file = import_node_path2.default.join(this.binDirectory, name), stat = (0, import_node_fs2.lstatSync)(file, { throwIfNoEntry: false });
9023
+ if (stat && (!old?.bins[name] || !stat.isSymbolicLink() || (0, import_node_fs2.realpathSync)(file) !== (0, import_node_fs2.realpathSync)(old.bins[name]))) throw Error("Refusing to replace unmanaged command: " + name);
8939
9024
  }
8940
- if (old?.version === metadata.version && (0, import_node_fs.existsSync)(root)) {
8941
- const manifest = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9025
+ if (old?.version === metadata.version && (0, import_node_fs2.existsSync)(root)) {
9026
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
8942
9027
  if (manifest.version !== old.version) throw Error("Installed manifest does not match the recorded version");
8943
- for (const [name, file] of Object.entries(old.bins)) if (!(0, import_node_fs.existsSync)(import_node_path.default.join(this.binDirectory, name)) || (0, import_node_fs.realpathSync)(import_node_path.default.join(this.binDirectory, name)) !== (0, import_node_fs.realpathSync)(file)) throw Error("Installed bin is missing or changed: " + name);
9028
+ for (const [name, file] of Object.entries(old.bins)) if (!(0, import_node_fs2.existsSync)(import_node_path2.default.join(this.binDirectory, name)) || (0, import_node_fs2.realpathSync)(import_node_path2.default.join(this.binDirectory, name)) !== (0, import_node_fs2.realpathSync)(file)) throw Error("Installed bin is missing or changed: " + name);
8944
9029
  this.say(metadata.id + " is already installed (" + metadata.version + ")");
8945
9030
  return { ...old, changed: false };
8946
9031
  }
@@ -8972,19 +9057,19 @@ var PackageInstaller = class {
8972
9057
  throw error;
8973
9058
  }
8974
9059
  }
8975
- const previousCommit = (0, import_node_fs.existsSync)(root) ? await this.execute("git", ["rev-parse", "HEAD"], root) : void 0;
9060
+ const previousCommit = (0, import_node_fs2.existsSync)(root) ? await this.execute("git", ["rev-parse", "HEAD"], root) : void 0;
8976
9061
  try {
8977
- if (!(0, import_node_fs.existsSync)(root)) {
9062
+ if (!(0, import_node_fs2.existsSync)(root)) {
8978
9063
  this.say("Cloning " + metadata.repository);
8979
- await this.execute("git", ["clone", "--branch", "main", "https://github.com/" + metadata.repository + ".git", root], import_node_path.default.dirname(root));
9064
+ await this.execute("git", ["clone", "--branch", "main", "https://github.com/" + metadata.repository + ".git", root], import_node_path2.default.dirname(root));
8980
9065
  } else {
8981
9066
  this.say("Updating " + metadata.repository);
8982
9067
  await this.execute("git", ["pull", "--ff-only", "origin", "main"], root);
8983
9068
  }
8984
- const manifest = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9069
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
8985
9070
  if (manifest.version !== metadata.version) throw Error("Repository component version does not match the published package version");
8986
9071
  for (const sibling of Object.values(records).filter((p) => p.root === root && p.id !== metadata.id)) {
8987
- const manifest2 = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(sibling.directory, sibling.manifest)), "utf8"));
9072
+ const manifest2 = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(sibling.directory, sibling.manifest)), "utf8"));
8988
9073
  if (manifest2.version !== sibling.version) throw Error("Shared repository also requires an update to " + sibling.id);
8989
9074
  }
8990
9075
  for (const step of metadata.prepare) {
@@ -8994,8 +9079,8 @@ var PackageInstaller = class {
8994
9079
  const bins = {};
8995
9080
  for (const [name, file] of Object.entries(metadata.bins)) {
8996
9081
  const target = this.local(root, file);
8997
- if (!(0, import_node_fs.lstatSync)(target).isFile()) throw Error("Package bin is not a regular file");
8998
- (0, import_node_fs.chmodSync)(target, 493);
9082
+ if (!(0, import_node_fs2.lstatSync)(target).isFile()) throw Error("Package bin is not a regular file");
9083
+ (0, import_node_fs2.chmodSync)(target, 493);
8999
9084
  bins[name] = target;
9000
9085
  }
9001
9086
  const commit = await this.execute("git", ["rev-parse", "HEAD"], root);
@@ -9004,9 +9089,9 @@ var PackageInstaller = class {
9004
9089
  await this.healthy(root, metadata.lifecycle.health);
9005
9090
  }
9006
9091
  for (const [name, target] of Object.entries(bins)) {
9007
- const link = import_node_path.default.join(this.binDirectory, name), temporary = link + ".install-" + process.pid;
9008
- (0, import_node_fs.symlinkSync)(target, temporary);
9009
- (0, import_node_fs.renameSync)(temporary, link);
9092
+ const link = import_node_path2.default.join(this.binDirectory, name), temporary = link + ".install-" + process.pid;
9093
+ (0, import_node_fs2.symlinkSync)(target, temporary);
9094
+ (0, import_node_fs2.renameSync)(temporary, link);
9010
9095
  }
9011
9096
  const record = { id: metadata.id, version: metadata.version, root, directory: metadata.directory, manifest: metadata.manifest, bins, metadataRevision: metadata.revision, commit, installedAt: (/* @__PURE__ */ new Date()).toISOString(), definition: metadata };
9012
9097
  records[metadata.id] = record;
@@ -9038,10 +9123,10 @@ function parseInstallArgs(args) {
9038
9123
  }
9039
9124
 
9040
9125
  // src/managedSession.ts
9041
- var import_node_fs2 = require("fs");
9042
- var import_node_os2 = require("os");
9043
- var import_node_crypto = require("crypto");
9044
- var import_node_path2 = require("path");
9126
+ var import_node_fs3 = require("fs");
9127
+ var import_node_os3 = require("os");
9128
+ var import_node_crypto2 = require("crypto");
9129
+ var import_node_path3 = require("path");
9045
9130
  async function ensureManagedSession(env = process.env, fetcher = fetch) {
9046
9131
  if (env.PMATE_EXPECTED_ACCOUNT_ID && env.HEBO_MEMORY_TOKEN?.trim()) throw Error("Bound Agent CLI cannot use another delegated identity");
9047
9132
  if (env.HEBO_MEMORY_TOKEN?.trim()) {
@@ -9054,19 +9139,19 @@ async function ensureManagedSession(env = process.env, fetcher = fetch) {
9054
9139
  const pr = await fetcher(`${base}/profiles?app=${encodeURIComponent(app)}&account=${encodeURIComponent(session.identity.accountId)}`, { headers, signal: AbortSignal.timeout(15e3) });
9055
9140
  const profiles = await pr.json(), profileId = profiles.data?.[0]?.id;
9056
9141
  if (!pr.ok || !profiles.success || !profileId) throw Error("Delegated user profile unavailable");
9057
- const dir = (0, import_node_fs2.mkdtempSync)((0, import_node_path2.join)((0, import_node_os2.tmpdir)(), "pmate-delegated-")), file = (0, import_node_path2.join)(dir, "session.json");
9058
- (0, import_node_fs2.writeFileSync)(file, JSON.stringify({ version: 4, activeAppRef: app, sessions: { [app]: { token, accountId: session.identity.accountId, profileId, issuedAt: session.issuedAt, expiresAt: session.expiresAt, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } } }), { mode: 384 });
9142
+ const dir = (0, import_node_fs3.mkdtempSync)((0, import_node_path3.join)((0, import_node_os3.tmpdir)(), "pmate-delegated-")), file = (0, import_node_path3.join)(dir, "session.json");
9143
+ (0, import_node_fs3.writeFileSync)(file, JSON.stringify({ version: 4, activeAppRef: app, sessions: { [app]: { token, accountId: session.identity.accountId, profileId, issuedAt: session.issuedAt, expiresAt: session.expiresAt, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } } }), { mode: 384 });
9059
9144
  env.PMATE_SESSION_FILE = file;
9060
9145
  env.PCS_AGENT_SESSION_MANAGED = "0";
9061
9146
  process.once("exit", () => {
9062
- (0, import_node_fs2.rmSync)(dir, { recursive: true, force: true });
9147
+ (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
9063
9148
  });
9064
9149
  return;
9065
9150
  }
9066
9151
  if (env.PCS_AGENT_SESSION_MANAGED !== "1") return;
9067
9152
  if (!env.PMATE_SESSION_FILE) throw Error("Managed session file is required");
9068
9153
  const source = env.PCS_AGENT_SESSION_SOURCE_FILE ?? env.PMATE_SESSION_FILE;
9069
- const state = JSON.parse((0, import_node_fs2.readFileSync)(source, "utf8"));
9154
+ const state = JSON.parse((0, import_node_fs3.readFileSync)(source, "utf8"));
9070
9155
  if (!state.refreshKey) throw Error("Managed session refresh key is missing");
9071
9156
  const port = Number(env.PMATE_SESSION_REFRESH_PORT ?? env.PCS_AGENT_CONTROL_PORT ?? 39399);
9072
9157
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error("Invalid controller port");
@@ -9077,12 +9162,12 @@ async function ensureManagedSession(env = process.env, fetcher = fetch) {
9077
9162
  });
9078
9163
  if (!r.ok) throw Error(`Managed session renewal unavailable (${r.status}); retry later`);
9079
9164
  if (source !== env.PMATE_SESSION_FILE) {
9080
- const raw = (0, import_node_fs2.readFileSync)(source, "utf8"), current = JSON.parse(raw).sessions?.[env.PMATE_SESSION_APP ?? "pmate:factory"];
9165
+ const raw = (0, import_node_fs3.readFileSync)(source, "utf8"), current = JSON.parse(raw).sessions?.[env.PMATE_SESSION_APP ?? "pmate:factory"];
9081
9166
  if (env.PMATE_EXPECTED_ACCOUNT_ID && current?.accountId !== env.PMATE_EXPECTED_ACCOUNT_ID) throw Error("Renewed Agent CLI Account mismatch");
9082
9167
  if (env.PMATE_EXPECTED_PROFILE_ID && current?.profileId !== env.PMATE_EXPECTED_PROFILE_ID) throw Error("Renewed Agent CLI Profile mismatch");
9083
- const temp = `${env.PMATE_SESSION_FILE}.${(0, import_node_crypto.randomUUID)()}.tmp`;
9084
- (0, import_node_fs2.writeFileSync)(temp, raw, { mode: 384, flag: "wx" });
9085
- (0, import_node_fs2.renameSync)(temp, env.PMATE_SESSION_FILE);
9168
+ const temp = `${env.PMATE_SESSION_FILE}.${(0, import_node_crypto2.randomUUID)()}.tmp`;
9169
+ (0, import_node_fs3.writeFileSync)(temp, raw, { mode: 384, flag: "wx" });
9170
+ (0, import_node_fs3.renameSync)(temp, env.PMATE_SESSION_FILE);
9086
9171
  }
9087
9172
  }
9088
9173
 
@@ -9129,12 +9214,12 @@ var ui = {
9129
9214
  };
9130
9215
 
9131
9216
  // src/commands/ListCommandHandler.ts
9132
- var import_node_path4 = __toESM(require("path"));
9217
+ var import_node_path5 = __toESM(require("path"));
9133
9218
 
9134
9219
  // src/config.ts
9135
- var import_node_fs3 = require("fs");
9136
- var import_node_os3 = __toESM(require("os"));
9137
- var import_node_path3 = __toESM(require("path"));
9220
+ var import_node_fs4 = require("fs");
9221
+ var import_node_os4 = __toESM(require("os"));
9222
+ var import_node_path4 = __toESM(require("path"));
9138
9223
  var import_ajv = __toESM(require("ajv"));
9139
9224
  var import_yaml = __toESM(require("yaml"));
9140
9225
  var cachedConfig;
@@ -9258,11 +9343,11 @@ function loadPmateConfig() {
9258
9343
  if (cachedConfig !== void 0) {
9259
9344
  return cachedConfig ?? {};
9260
9345
  }
9261
- const pmateDir = import_node_path3.default.join(import_node_os3.default.homedir(), ".pmate");
9262
- const yamlPath = import_node_path3.default.join(pmateDir, "config.yaml");
9346
+ const pmateDir = import_node_path4.default.join(import_node_os4.default.homedir(), ".pmate");
9347
+ const yamlPath = import_node_path4.default.join(pmateDir, "config.yaml");
9263
9348
  let yamlConfig = null;
9264
- if ((0, import_node_fs3.existsSync)(yamlPath)) {
9265
- const raw = (0, import_node_fs3.readFileSync)(yamlPath, "utf8");
9349
+ if ((0, import_node_fs4.existsSync)(yamlPath)) {
9350
+ const raw = (0, import_node_fs4.readFileSync)(yamlPath, "utf8");
9266
9351
  try {
9267
9352
  const parsed = import_yaml.default.parse(raw);
9268
9353
  yamlConfig = validateParsedConfig(parsed, yamlPath);
@@ -9324,21 +9409,21 @@ ${detail}`);
9324
9409
  return value;
9325
9410
  }
9326
9411
  function findRepoConfigPaths(cwd, searchParents) {
9327
- let current = import_node_path3.default.resolve(cwd);
9412
+ let current = import_node_path4.default.resolve(cwd);
9328
9413
  while (true) {
9329
- const candidate = import_node_path3.default.join(current, ".pmate.yaml");
9330
- if ((0, import_node_fs3.existsSync)(candidate)) {
9331
- const localCandidate = import_node_path3.default.join(current, ".pmate.local.yaml");
9414
+ const candidate = import_node_path4.default.join(current, ".pmate.yaml");
9415
+ if ((0, import_node_fs4.existsSync)(candidate)) {
9416
+ const localCandidate = import_node_path4.default.join(current, ".pmate.local.yaml");
9332
9417
  return {
9333
9418
  rootDir: current,
9334
9419
  configPath: candidate,
9335
- localConfigPath: (0, import_node_fs3.existsSync)(localCandidate) ? localCandidate : void 0
9420
+ localConfigPath: (0, import_node_fs4.existsSync)(localCandidate) ? localCandidate : void 0
9336
9421
  };
9337
9422
  }
9338
9423
  if (!searchParents) {
9339
9424
  return null;
9340
9425
  }
9341
- const parent = import_node_path3.default.dirname(current);
9426
+ const parent = import_node_path4.default.dirname(current);
9342
9427
  if (parent === current) {
9343
9428
  return null;
9344
9429
  }
@@ -9354,7 +9439,7 @@ function loadMergedRepoYaml(paths) {
9354
9439
  return mergeRepoConfigValues(base, local);
9355
9440
  }
9356
9441
  function parseYamlFile(configPath) {
9357
- const raw = (0, import_node_fs3.readFileSync)(configPath, "utf8");
9442
+ const raw = (0, import_node_fs4.readFileSync)(configPath, "utf8");
9358
9443
  try {
9359
9444
  return import_yaml.default.parse(raw);
9360
9445
  } catch (error) {
@@ -9509,7 +9594,7 @@ var ListCommandHandler = class {
9509
9594
  }
9510
9595
  }
9511
9596
  resolveTargetDir(targetPath) {
9512
- return targetPath ? import_node_path4.default.resolve(process.cwd(), targetPath) : process.cwd();
9597
+ return targetPath ? import_node_path5.default.resolve(process.cwd(), targetPath) : process.cwd();
9513
9598
  }
9514
9599
  loadConfig(targetDir) {
9515
9600
  return loadAppConfig(targetDir).config;
@@ -9523,17 +9608,17 @@ var import_node_http = require("http");
9523
9608
  var import_promises = require("readline/promises");
9524
9609
 
9525
9610
  // src/accessKeyFile.ts
9526
- var import_node_fs4 = require("fs");
9527
- var import_node_os4 = __toESM(require("os"));
9528
- var import_node_path5 = __toESM(require("path"));
9611
+ var import_node_fs5 = require("fs");
9612
+ var import_node_os5 = __toESM(require("os"));
9613
+ var import_node_path6 = __toESM(require("path"));
9529
9614
  function readAccessKeyFile(filePath, options = {}) {
9530
9615
  const absolutePath = resolveFilePath(filePath, options.cwd);
9531
- if (!(0, import_node_fs4.existsSync)(absolutePath)) {
9616
+ if (!(0, import_node_fs5.existsSync)(absolutePath)) {
9532
9617
  throw new Error(`Access key file not found: ${absolutePath}`);
9533
9618
  }
9534
9619
  let parsed;
9535
9620
  try {
9536
- parsed = JSON.parse((0, import_node_fs4.readFileSync)(absolutePath, "utf8"));
9621
+ parsed = JSON.parse((0, import_node_fs5.readFileSync)(absolutePath, "utf8"));
9537
9622
  } catch (error) {
9538
9623
  const message = error instanceof Error ? error.message : String(error);
9539
9624
  throw new Error(`Invalid JSON in ${absolutePath}: ${message}`);
@@ -9550,10 +9635,10 @@ function readAccessKeyFile(filePath, options = {}) {
9550
9635
  }
9551
9636
  function scanAccessKeyFiles(app) {
9552
9637
  const dir = resolveAccessKeyDir(app);
9553
- if (!(0, import_node_fs4.existsSync)(dir)) {
9638
+ if (!(0, import_node_fs5.existsSync)(dir)) {
9554
9639
  return [];
9555
9640
  }
9556
- return (0, import_node_fs4.readdirSync)(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".access-key.json")).map((entry) => import_node_path5.default.join(dir, entry.name)).flatMap((filePath) => {
9641
+ return (0, import_node_fs5.readdirSync)(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".access-key.json")).map((entry) => import_node_path6.default.join(dir, entry.name)).flatMap((filePath) => {
9557
9642
  try {
9558
9643
  return [{ filePath, key: readAccessKeyFile(filePath, { expectedApp: app }) }];
9559
9644
  } catch {
@@ -9562,13 +9647,13 @@ function scanAccessKeyFiles(app) {
9562
9647
  }).sort((a, b) => a.key.name.localeCompare(b.key.name) || a.filePath.localeCompare(b.filePath));
9563
9648
  }
9564
9649
  function resolveAccessKeyDir(app) {
9565
- return import_node_path5.default.join(homeDir(), ".pmate", "access-keys", app);
9650
+ return import_node_path6.default.join(homeDir(), ".pmate", "access-keys", app);
9566
9651
  }
9567
9652
  function resolveFilePath(filePath, cwd = process.cwd()) {
9568
- return import_node_path5.default.isAbsolute(filePath) ? filePath : import_node_path5.default.resolve(cwd, filePath);
9653
+ return import_node_path6.default.isAbsolute(filePath) ? filePath : import_node_path6.default.resolve(cwd, filePath);
9569
9654
  }
9570
9655
  function homeDir() {
9571
- return process.env.HOME || process.env.USERPROFILE || import_node_os4.default.homedir() || process.cwd();
9656
+ return process.env.HOME || process.env.USERPROFILE || import_node_os5.default.homedir() || process.cwd();
9572
9657
  }
9573
9658
  function isAccessKeyFile(value) {
9574
9659
  if (!value || typeof value !== "object") {
@@ -9637,6 +9722,8 @@ async function fetchBotProfileId(options) {
9637
9722
  }
9638
9723
 
9639
9724
  // src/commands/LoginCommandHandler.ts
9725
+ var ExpiredLoginTokenError = class extends Error {
9726
+ };
9640
9727
  var AUTH_UI_BASE_URL = "https://auth.pmate.chat";
9641
9728
  var CALLBACK_PATH = "/pmate-login-callback";
9642
9729
  var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
@@ -9649,12 +9736,56 @@ function buildHostedLoginUrl(redirectUrl, appId = DEFAULT_APP_ID) {
9649
9736
  }
9650
9737
  var LoginCommandHandler = class {
9651
9738
  async handle(args) {
9739
+ const release = claimSessionLogin(args.app?.trim() || DEFAULT_APP_ID);
9740
+ try {
9741
+ await this.execute(args);
9742
+ } finally {
9743
+ release();
9744
+ }
9745
+ }
9746
+ async execute(args) {
9747
+ if (args.tokenStdin) {
9748
+ if (!args.app?.trim()) throw new Error("--token-stdin requires --app");
9749
+ if (args.accessKey || args.accessKeyFile || args.accessKeyScan) throw new Error("Token and access-key login cannot be combined");
9750
+ const token = await this.readTokenInput();
9751
+ const appId = assertValidAppRef(args.app);
9752
+ let loginResponse;
9753
+ try {
9754
+ loginResponse = await this.exchangeSession(token, appId);
9755
+ } catch (error) {
9756
+ if (!(error instanceof ExpiredLoginTokenError)) throw error;
9757
+ await this.handleHostedLogin(args);
9758
+ return;
9759
+ }
9760
+ this.assertExpectedAccount(loginResponse, args);
9761
+ const profiles = await fetchProfiles({ token: loginResponse.token, app: appId, accountId: loginResponse.session.identity.accountId });
9762
+ const profileId = await this.resolveProfileId({ appId, requestedProfileId: args.profileId, selectProfile: args.selectProfile, profiles });
9763
+ const saved = saveLoginSession({ ...loginResponse, profileId }, appId);
9764
+ ui.success(`Logged in to ${saved.app}. Session saved to ${saved.sessionPath}`);
9765
+ return;
9766
+ }
9652
9767
  if (args.accessKey || args.accessKeyFile || args.accessKeyScan) {
9653
9768
  await this.handleAccessKeyLogin(args);
9654
9769
  return;
9655
9770
  }
9656
9771
  await this.handleHostedLogin(args);
9657
9772
  }
9773
+ assertExpectedAccount(session, args) {
9774
+ if (args.expectedAccount && session.session.identity.accountId !== args.expectedAccount) {
9775
+ throw new Error("Login Account differs from the expected Runtime Owner; session was not saved.");
9776
+ }
9777
+ }
9778
+ async readTokenInput() {
9779
+ if (process.stdin.isTTY) throw new Error("--token-stdin requires piped input");
9780
+ let input = "";
9781
+ for await (const chunk of process.stdin) {
9782
+ input += chunk.toString();
9783
+ if (Buffer.byteLength(input) > 16384) throw new Error("Token input is too large");
9784
+ }
9785
+ const token = input.trim();
9786
+ if (!token || /\s/.test(token)) throw new Error("Expected one non-empty token on stdin");
9787
+ return token;
9788
+ }
9658
9789
  async handleHostedLogin(args) {
9659
9790
  const callback = await this.startCallbackServer();
9660
9791
  const appId = assertValidAppRef(args.app?.trim() || DEFAULT_APP_ID);
@@ -9675,6 +9806,7 @@ var LoginCommandHandler = class {
9675
9806
  try {
9676
9807
  const token = await callback.waitForToken;
9677
9808
  const loginResponse = await this.exchangeSession(token, appId);
9809
+ this.assertExpectedAccount(loginResponse, args);
9678
9810
  const profiles = await fetchProfiles({
9679
9811
  token: loginResponse.token,
9680
9812
  app: appId,
@@ -9700,6 +9832,7 @@ var LoginCommandHandler = class {
9700
9832
  const resolved = await this.resolveAccessKeyInput(args);
9701
9833
  const appId = assertValidAppRef(resolved.app);
9702
9834
  const loginResponse = await this.exchangeAccessKeySession(resolved.secret, appId);
9835
+ this.assertExpectedAccount(loginResponse, args);
9703
9836
  const profiles = await fetchProfiles({
9704
9837
  token: loginResponse.token,
9705
9838
  app: appId,
@@ -9726,10 +9859,8 @@ var LoginCommandHandler = class {
9726
9859
  body: JSON.stringify({ app: appId })
9727
9860
  });
9728
9861
  if (!response.ok) {
9729
- const detail = await response.text();
9730
- throw new Error(
9731
- `Failed to exchange app session (${response.status}): ${detail || response.statusText}`
9732
- );
9862
+ if (response.status === 401) throw new ExpiredLoginTokenError("Login token is expired or invalid");
9863
+ throw new Error(`Failed to exchange app session (${response.status})`);
9733
9864
  }
9734
9865
  const resp = await response.json();
9735
9866
  const returnedApp = resp?.data?.session?.identity?.app?.trim();
@@ -10087,7 +10218,7 @@ var import_fc20230330 = __toESM(require("@alicloud/fc20230330"));
10087
10218
  var import_openapi_client = require("@alicloud/openapi-client");
10088
10219
  var import_sts20150401 = __toESM(require("@alicloud/sts20150401"));
10089
10220
  var import_ali_oss = __toESM(require("ali-oss"));
10090
- var import_node_crypto2 = require("crypto");
10221
+ var import_node_crypto3 = require("crypto");
10091
10222
  var import_node_fs6 = require("fs");
10092
10223
  var import_node_path8 = __toESM(require("path"));
10093
10224
 
@@ -10858,7 +10989,7 @@ var AliyunService = class {
10858
10989
  /** Compute MD5 for a file. */
10859
10990
  static getFileMd5(filePath) {
10860
10991
  return new Promise((resolve, reject) => {
10861
- const hash = (0, import_node_crypto2.createHash)("md5");
10992
+ const hash = (0, import_node_crypto3.createHash)("md5");
10862
10993
  const stream = (0, import_node_fs6.createReadStream)(filePath);
10863
10994
  stream.on("data", (chunk) => {
10864
10995
  hash.update(chunk);
@@ -14757,7 +14888,7 @@ var QrcodeCommandHandler = class {
14757
14888
  };
14758
14889
 
14759
14890
  // src/commands/RandomCommandHandler.ts
14760
- var import_node_crypto3 = require("crypto");
14891
+ var import_node_crypto4 = require("crypto");
14761
14892
  var DEFAULT_TOKEN_LENGTH = 32;
14762
14893
  var DEFAULT_EASY_WORDS = 3;
14763
14894
  var DEFAULT_EASY_DIGITS = 2;
@@ -14923,7 +15054,7 @@ function randomString(length, charset) {
14923
15054
  const max = Math.floor(256 / charsetLength) * charsetLength;
14924
15055
  let result = "";
14925
15056
  while (result.length < length) {
14926
- const bytes = (0, import_node_crypto3.randomBytes)(Math.max(1, length - result.length));
15057
+ const bytes = (0, import_node_crypto4.randomBytes)(Math.max(1, length - result.length));
14927
15058
  for (const byte of bytes) {
14928
15059
  if (byte >= max) {
14929
15060
  continue;
@@ -14937,12 +15068,12 @@ function randomString(length, charset) {
14937
15068
  return result;
14938
15069
  }
14939
15070
  function randomWord() {
14940
- return EASY_WORDS[(0, import_node_crypto3.randomInt)(0, EASY_WORDS.length)];
15071
+ return EASY_WORDS[(0, import_node_crypto4.randomInt)(0, EASY_WORDS.length)];
14941
15072
  }
14942
15073
  function randomDigits(count) {
14943
15074
  let value = "";
14944
15075
  for (let i = 0; i < count; i += 1) {
14945
- value += (0, import_node_crypto3.randomInt)(0, 10).toString();
15076
+ value += (0, import_node_crypto4.randomInt)(0, 10).toString();
14946
15077
  }
14947
15078
  return value;
14948
15079
  }
@@ -15727,20 +15858,20 @@ var Im1BotClient = class {
15727
15858
  };
15728
15859
 
15729
15860
  // src/collectStore.ts
15730
- var import_node_crypto4 = require("crypto");
15861
+ var import_node_crypto5 = require("crypto");
15731
15862
  var import_node_fs13 = require("fs");
15732
15863
  var import_node_os8 = __toESM(require("os"));
15733
15864
  var import_node_path19 = __toESM(require("path"));
15734
15865
  function resolveCollectTarget(input) {
15735
15866
  const endpoint = input.endpoint ?? (input.source === "cc" ? "http://localhost:9223" : "http://localhost:9222");
15736
- const sourceKey = input.source ?? `endpoint-${(0, import_node_crypto4.createHash)("sha1").update(endpoint).digest("hex").slice(0, 8)}`;
15867
+ const sourceKey = input.source ?? `endpoint-${(0, import_node_crypto5.createHash)("sha1").update(endpoint).digest("hex").slice(0, 8)}`;
15737
15868
  const rootDir = import_node_path19.default.join(import_node_os8.default.homedir(), ".pmate", "collect", sourceKey);
15738
15869
  return { sourceKey, endpoint, rootDir };
15739
15870
  }
15740
15871
  function toThreadKey(name) {
15741
15872
  const normalized = name.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-+|-+$/g, "");
15742
15873
  const base = normalized || "thread";
15743
- const suffix = (0, import_node_crypto4.createHash)("sha1").update(name).digest("hex").slice(0, 8);
15874
+ const suffix = (0, import_node_crypto5.createHash)("sha1").update(name).digest("hex").slice(0, 8);
15744
15875
  return `${base}-${suffix}`;
15745
15876
  }
15746
15877
  async function readStoredThread(rootDir, threadKey) {
@@ -18519,7 +18650,7 @@ var import_sharp2 = __toESM(require("sharp"));
18519
18650
 
18520
18651
  // src/desktopRelease.ts
18521
18652
  init_sessionStore();
18522
- var import_node_crypto5 = require("crypto");
18653
+ var import_node_crypto6 = require("crypto");
18523
18654
  var import_node_fs21 = require("fs");
18524
18655
  var import_node_path26 = __toESM(require("path"));
18525
18656
  async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
@@ -18533,7 +18664,7 @@ async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18533
18664
  const artifacts = (0, import_node_fs21.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) => {
18534
18665
  const bytes = (0, import_node_fs21.readFileSync)(import_node_path26.default.join(directory, entry.name));
18535
18666
  const objectKey = prefix + entry.name;
18536
- return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto5.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18667
+ return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto6.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18537
18668
  });
18538
18669
  if (!artifacts.length) throw new Error("No desktop installers found to publish");
18539
18670
  const manifestKey = prefix + "release.json";
@@ -18737,7 +18868,7 @@ function currentRepositoryRoot(repository, cwd = process.cwd()) {
18737
18868
 
18738
18869
  // src/services/AndroidApkReleaseService.ts
18739
18870
  var import_node_child_process12 = require("child_process");
18740
- var import_node_crypto6 = require("crypto");
18871
+ var import_node_crypto7 = require("crypto");
18741
18872
  var import_node_fs23 = require("fs");
18742
18873
  var import_node_os12 = __toESM(require("os"));
18743
18874
  var import_node_path28 = __toESM(require("path"));
@@ -19238,7 +19369,7 @@ function listVersionedToolCandidates(parentDir, relativeToolPath) {
19238
19369
  }
19239
19370
  function sha256File(filePath) {
19240
19371
  return new Promise((resolve, reject) => {
19241
- const hash = (0, import_node_crypto6.createHash)("sha256");
19372
+ const hash = (0, import_node_crypto7.createHash)("sha256");
19242
19373
  const stream = (0, import_node_fs23.createReadStream)(filePath);
19243
19374
  stream.on("data", (chunk) => hash.update(chunk));
19244
19375
  stream.on("error", reject);
@@ -19257,7 +19388,7 @@ function capitalize(value) {
19257
19388
 
19258
19389
  // src/services/HarmonyReleaseService.ts
19259
19390
  var import_node_child_process13 = require("child_process");
19260
- var import_node_crypto7 = require("crypto");
19391
+ var import_node_crypto8 = require("crypto");
19261
19392
  var import_node_fs24 = require("fs");
19262
19393
  var import_node_os13 = __toESM(require("os"));
19263
19394
  var import_node_path29 = __toESM(require("path"));
@@ -19399,7 +19530,7 @@ function signingMaterial(values) {
19399
19530
  return bytes;
19400
19531
  };
19401
19532
  const certificate = decode2("HARMONY_CERTIFICATE_BASE64");
19402
- const fingerprint = new import_node_crypto7.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19533
+ const fingerprint = new import_node_crypto8.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19403
19534
  return { keystore: decode2("HARMONY_KEYSTORE_BASE64"), certificate, profile: decode2("HARMONY_PROFILE_BASE64"), fingerprint };
19404
19535
  }
19405
19536
  function assertHarmonyMetadata(raw, version) {
@@ -19409,7 +19540,7 @@ function assertHarmonyMetadata(raw, version) {
19409
19540
  var withHarmonyPublicationLock = async (bucket2, key, publish) => {
19410
19541
  if (!/^harmony\/[\w-]+\/[\w-]+\/\.publish-lock\.json$/.test(key)) throw new Error("Invalid HarmonyOS publication lock key");
19411
19542
  await AliyunService.assertUnversionedBucket(bucket2);
19412
- const owner = (0, import_node_crypto7.randomUUID)();
19543
+ const owner = (0, import_node_crypto8.randomUUID)();
19413
19544
  try {
19414
19545
  await AliyunService.uploadJsonObject(bucket2, key, { owner, createdAt: (/* @__PURE__ */ new Date()).toISOString() }, { "x-oss-forbid-overwrite": "true" });
19415
19546
  } catch {
@@ -19481,9 +19612,9 @@ var HarmonyReleaseService = class {
19481
19612
  const files = (0, import_node_fs24.readdirSync)(dist, { withFileTypes: true }).filter((e) => e.isFile() && /\.(app|hap)$/.test(e.name)).map((e) => import_node_path29.default.join(dist, e.name));
19482
19613
  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");
19483
19614
  const check = async (file, inspectMetadata) => {
19484
- const id = (0, import_node_crypto7.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path29.default.join(temp, `${id}.cer`);
19615
+ const id = (0, import_node_crypto8.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path29.default.join(temp, `${id}.cer`);
19485
19616
  await run2(tools.java, ["-jar", tools.signer, "verify-app", "-inFile", file, "-outCertChain", cert, "-outProfile", import_node_path29.default.join(temp, `${id}.p7b`)], opts);
19486
- if (new import_node_crypto7.X509Certificate((0, import_node_fs24.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19617
+ if (new import_node_crypto8.X509Certificate((0, import_node_fs24.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19487
19618
  if (inspectMetadata) assertHarmonyMetadata(JSON.parse(await run2("unzip", ["-p", file, "module.json"], { ...opts, capture: true })), version);
19488
19619
  };
19489
19620
  for (const file of files) {
@@ -19507,7 +19638,7 @@ var HarmonyReleaseService = class {
19507
19638
  if (!size) throw new Error("Empty HarmonyOS artifact");
19508
19639
  const target = import_node_path29.default.join(output, name);
19509
19640
  (0, import_node_fs24.cpSync)(file, target);
19510
- const hash = (0, import_node_crypto7.createHash)("sha256");
19641
+ const hash = (0, import_node_crypto8.createHash)("sha256");
19511
19642
  for await (const chunk of (0, import_node_fs24.createReadStream)(target)) hash.update(chunk);
19512
19643
  artifacts.push({ name, type: import_node_path29.default.extname(name).slice(1), objectKey: releasePrefix + name, downloadUrl: `${baseUrl}/${releasePrefix}${name}`, sha256: hash.digest("hex"), size });
19513
19644
  }
@@ -19538,7 +19669,7 @@ var HarmonyReleaseService = class {
19538
19669
 
19539
19670
  // src/services/IosBuildService.ts
19540
19671
  var import_node_child_process14 = require("child_process");
19541
- var import_node_crypto8 = require("crypto");
19672
+ var import_node_crypto9 = require("crypto");
19542
19673
  var import_node_fs25 = require("fs");
19543
19674
  var import_node_os14 = __toESM(require("os"));
19544
19675
  var import_node_path30 = __toESM(require("path"));
@@ -19601,7 +19732,7 @@ var IosBuildService = class {
19601
19732
  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");
19602
19733
  if (service.mobile && "bundleId" in service.mobile && service.mobile.bundleId !== bundleId) throw new Error("Service bundle ID does not match application target");
19603
19734
  const currentBuild = iosBuildInteger(cfg.CURRENT_PROJECT_VERSION);
19604
- const key = (0, import_node_crypto8.createHash)("sha256").update(bundleId).digest("hex");
19735
+ const key = (0, import_node_crypto9.createHash)("sha256").update(bundleId).digest("hex");
19605
19736
  const statePath = import_node_path30.default.join(root, `${key}.json`);
19606
19737
  const lockPath = import_node_path30.default.join(root, `${key}.lock`);
19607
19738
  let lock;
@@ -22980,7 +23111,7 @@ var RoleCommandHandler = class {
22980
23111
 
22981
23112
  // src/commands/AccountCommandHandler.ts
22982
23113
  var import_node_fs29 = require("fs");
22983
- var import_node_crypto9 = require("crypto");
23114
+ var import_node_crypto10 = require("crypto");
22984
23115
  var import_node_path34 = __toESM(require("path"));
22985
23116
  init_sessionStore();
22986
23117
  var AccountCommandHandler = class {
@@ -23625,7 +23756,7 @@ var AccountCommandHandler = class {
23625
23756
  return process.env.HOME || process.env.USERPROFILE || process.cwd();
23626
23757
  }
23627
23758
  generateBotKeyFile(app, name) {
23628
- const { publicKey, privateKey } = (0, import_node_crypto9.generateKeyPairSync)("ed25519");
23759
+ const { publicKey, privateKey } = (0, import_node_crypto10.generateKeyPairSync)("ed25519");
23629
23760
  return {
23630
23761
  type: "pmate-bot-key",
23631
23762
  version: 1,
@@ -23747,12 +23878,12 @@ var AccountCommandHandler = class {
23747
23878
  });
23748
23879
  }
23749
23880
  signBotChallenge(challenge, privateKey) {
23750
- const key = (0, import_node_crypto9.createPrivateKey)({
23881
+ const key = (0, import_node_crypto10.createPrivateKey)({
23751
23882
  key: Buffer.from(privateKey, "base64url"),
23752
23883
  format: "der",
23753
23884
  type: "pkcs8"
23754
23885
  });
23755
- return (0, import_node_crypto9.sign)(
23886
+ return (0, import_node_crypto10.sign)(
23756
23887
  null,
23757
23888
  Buffer.from(JSON.stringify({
23758
23889
  id: challenge.id,
@@ -27273,7 +27404,7 @@ var HELP_TEXT = [
27273
27404
  import_chalk4.default.bold("Commands:"),
27274
27405
  ` ${import_chalk4.default.cyan("list [path]")} List apps from .pmate.yaml in the target folder`,
27275
27406
  ` ${import_chalk4.default.cyan("login")} Log in and store a session in ~/.pmate/session.json`,
27276
- ` ${import_chalk4.default.gray(" [--app <app-id>] [--profile-id <id>] [--select-profile]")}`,
27407
+ ` ${import_chalk4.default.gray(" [--app <app-id>] [--profile-id <id>] [--select-profile] [--token-stdin]")}`,
27277
27408
  ` ${import_chalk4.default.gray(" [--access-key [secret] | --access-key-file <path>]")}`,
27278
27409
  ` ${import_chalk4.default.cyan("add-dns")} Add a DNS record via Aliyun DNS`,
27279
27410
  ` ${import_chalk4.default.gray(" --type <t> --value <v> --rr <rr> [--ttl <n>] [--domain <name>]")}`,
@@ -27512,6 +27643,8 @@ function parseCommandArgs(args) {
27512
27643
  let accessKeyFile;
27513
27644
  let accessKeyScan = false;
27514
27645
  let selectProfile = false;
27646
+ let tokenStdin = false;
27647
+ let expectedAccount;
27515
27648
  while (rest.length > 0) {
27516
27649
  const token = rest.shift();
27517
27650
  switch (token) {
@@ -27531,6 +27664,12 @@ function parseCommandArgs(args) {
27531
27664
  case "--access-key-file":
27532
27665
  accessKeyFile = requireValue11(rest, token);
27533
27666
  break;
27667
+ case "--expected-account":
27668
+ expectedAccount = requireValue11(rest, token);
27669
+ break;
27670
+ case "--token-stdin":
27671
+ tokenStdin = true;
27672
+ break;
27534
27673
  case "--select-profile":
27535
27674
  selectProfile = true;
27536
27675
  break;
@@ -27544,7 +27683,9 @@ function parseCommandArgs(args) {
27544
27683
  if (accessKeyScan && accessKeyFile) {
27545
27684
  throw new Error("--access-key and --access-key-file are mutually exclusive");
27546
27685
  }
27547
- return { type: "login" /* Login */, app, profileId, accessKey, accessKeyFile, accessKeyScan, selectProfile };
27686
+ if (tokenStdin && !app?.trim()) throw new Error("--token-stdin requires --app");
27687
+ if (tokenStdin && (accessKey || accessKeyFile || accessKeyScan)) throw new Error("--token-stdin cannot be combined with access-key login");
27688
+ return { type: "login" /* Login */, app, profileId, accessKey, accessKeyFile, accessKeyScan, selectProfile, ...tokenStdin ? { tokenStdin: true } : {}, ...expectedAccount ? { expectedAccount } : {} };
27548
27689
  }
27549
27690
  if (args.rest[0] === "add-dns") {
27550
27691
  return parseAddDnsArgs(args.rest.slice(1));
@@ -29177,6 +29318,10 @@ function parseNonNegativeInt(value, optionName) {
29177
29318
  }
29178
29319
  async function main() {
29179
29320
  try {
29321
+ if (process.argv[2] === "session") {
29322
+ process.stdout.write(JSON.stringify(sessionCommand(process.argv.slice(3))) + "\n");
29323
+ return;
29324
+ }
29180
29325
  await ensureManagedSession();
29181
29326
  const args = parseArgs(process.argv.slice(2));
29182
29327
  if (args.help) {
@@ -7,62 +7,46 @@ const {createShellPathResolver}=require('./shell-path.cjs')
7
7
  const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','local.info','local.exec','runtime.inspect','scripts.run']
8
8
  function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch, environment = process.env } = {}) {
9
9
  const resolvePath=createShellPathResolver({home,environment,platform})
10
- let identityEpoch=0
11
- let identity
12
10
  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()))
11
+ execFile(file, args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024, env: { ...environment, ...credentials, PATH: resolved.path, GIT_TERMINAL_PROMPT: '0' } }, (error, stdout, stderr) => error ? reject(new Error(`${path.basename(file)} 执行失败:${String(stderr||'').trim().slice(0,2000)||error.code||'未知错误'}`)) : resolve(stdout.trim()))
14
12
  })})
15
13
  const localExec=createLocalExecutor({home,environment,resolvePath})
16
- const api = async (route, method='GET', body) => {
17
- if (!identity) throw new Error('请先登录梅丽号')
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) })
19
- const value=await response.json()
20
- if(!response.ok||!value.success)throw new Error(value.message||`Issues API 请求失败 (${response.status})`)
21
- return value.data
14
+ const ownerEnvironment=()=>({MERRY_RUNTIME_EXPECTED_USER:undefined,PCS_AGENT_API_TOKEN:undefined,HEBO_MEMORY_TOKEN:undefined,PCS_AGENT_SESSION_SOURCE_FILE:undefined,PCS_AGENT_SESSION_MANAGED:'0',PCS_ISSUES_API_URL:'https://issue-api.pmate.chat',PCS_AGENT_ID:undefined,PCS_AGENT_RUN_ID:undefined,VEGA_RUN_TOKEN:undefined,VEGA_INPUT_ID:undefined})
15
+ const runtimeApi=async(method,input)=>{
16
+ const output=await run('merry-runtime',['api',method,'--request',JSON.stringify(input??{})],undefined,600000,ownerEnvironment())
17
+ return JSON.parse(output)
22
18
  }
23
19
  const invoke = async (method,input) => {
24
20
  if(!methods.includes(method))throw new Error('ELECTRON_METHOD_UNAVAILABLE')
25
21
  if(method==='capabilities')return methods
26
- if(method==='local.info')return {platform,arch:process.arch,home}
22
+ if(method==='local.info')return {platform,arch:process.arch,home,stdin:true,agentsAuth:'cli-v1',requestCancellation:true}
27
23
  if(method==='local.exec'){
28
- if(!identity)throw new Error('请先登录梅丽号')
29
- const epoch=identityEpoch,result=await localExec(input)
30
- if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新执行')
31
- return result
24
+ return localExec(input)
32
25
  }
33
26
  if(method==='scripts.run'&&input?.id==='runtime.models'&&input.args&&Object.keys(input.args).length===0)return modelCatalog({environment:{...environment,PATH:(await resolvePath()).path}})
34
27
  if(method==='scripts.run')throw new Error('未知脚本操作')
35
- if(method==='workspaces.list')return api('/v2/workspaces')
28
+ if(method==='workspaces.list')return runtimeApi(method,input)
36
29
  const {scope,id,config,expectedRevision}=input||{}
37
30
  if(!scope||!['namespace','topic'].every(k=>typeof scope[k]==='string'&&/^[a-z0-9][a-z0-9_-]{0,127}$/.test(scope[k])))throw new Error('无效工作区')
38
31
  const base=`/v2/topics/${encodeURIComponent(scope.namespace)}/${encodeURIComponent(scope.topic)}`
39
32
  if(method==='runtime.inspect'){
40
- if(!identity)throw new Error('请先登录梅丽号')
41
33
  if(!['runs','run','run-logs'].includes(input.kind)||Object.keys(input).some(k=>!['scope','kind','agentId','runId','status'].includes(k)))throw new Error('无效的 Run 查询')
42
- const epoch=identityEpoch
43
- const output=await run('merry-runtime',['inspect','--request',JSON.stringify(input)],undefined,600000,{PCS_AGENT_API_TOKEN:identity.token,PCS_ISSUES_API_URL:'https://issue-api.pmate.chat',PCS_AGENT_ID:undefined,PCS_AGENT_RUN_ID:undefined,VEGA_RUN_TOKEN:undefined,VEGA_INPUT_ID:undefined})
44
- if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新打开页面')
34
+ const output=await run('merry-runtime',['inspect','--request',JSON.stringify(input)],undefined,600000,ownerEnvironment())
45
35
  return JSON.parse(output)
46
36
  }
47
- if(method==='agents.list')return api(base+'/vega-agents')
48
- if(method==='plugins.list')return api(base+'/runtime-plugins')
37
+ if(method==='agents.list')return runtimeApi(method,input)
38
+ if(method==='plugins.list')return runtimeApi(method,input)
49
39
  if(typeof id!=='string'||!(method==='plugins.configure'?/^(?:[a-z][a-z0-9-]*:)?[a-z][a-z0-9-]*$/:/^0x[a-f0-9]{64}$/).test(id)||!config||typeof config!=='object'||Array.isArray(config))throw new Error('无效配置')
50
40
  if(Object.hasOwn(config,'expectedRevision'))throw new Error('revision 必须单独指定')
51
41
  if(method!=='agents.create'&&(!Number.isSafeInteger(expectedRevision)||expectedRevision<1))throw new Error('更新需要 revision')
52
42
  if(method==='agents.create'&&expectedRevision!==undefined)throw new Error('创建不能指定 revision')
53
- return api(base+(method==='plugins.configure'?'/runtime-plugins/':'/vega-agents/')+encodeURIComponent(id),'PUT',{...config,...(expectedRevision===undefined?{}:{expectedRevision})})
54
- }
55
- return { invoke,
56
- async configureIdentity(value, configure) {
57
- const epoch=++identityEpoch;identity=undefined
58
- const result=await configure(value)
59
- if(epoch===identityEpoch)identity={appId:value.appId,token:value.token}
60
- return result
61
- },
62
- setIdentity(value) { identityEpoch++;identity=value ? {appId:value.appId,token:value.token} : undefined }
43
+ return runtimeApi(method,input)
63
44
  }
45
+ // Website reach identity is deliberately unrelated to local Agents authority.
46
+ return {invoke, configureIdentity(value, configure) {return configure(value)}, setIdentity() {}}
47
+
64
48
  }
65
- function installAgentRuntime({ ipcMain, trusted, runtime }) {
66
- ipcMain.handle('pmate:electron:invoke',(event,method,input)=>{if(!trusted(event))throw new Error('Untrusted Electron sender');return runtime.invoke(method,input)})
49
+ function installAgentRuntime({ ipcMain, trusted, runtime, activateWindow }) {
50
+ ipcMain.handle('pmate:electron:invoke',(event,method,input)=>{if(!trusted(event))throw new Error('Untrusted Electron sender');return runtime.invoke(method,input).then(result=>{if(method==='local.exec'&&input?.activateOnSuccess===true&&result.exitCode===0)activateWindow?.();return result})})
67
51
  }
68
52
  module.exports={createAgentRuntime,installAgentRuntime}
@@ -4,13 +4,22 @@ const {createShellPathResolver}=require('./shell-path.cjs')
4
4
  /** Stable local process capability. Command selection and business rules belong to Web/bridge. */
5
5
  function createLocalExecutor({home,environment,execute=execFile,resolvePath=createShellPathResolver({home,environment})}){
6
6
 
7
+ const active=new Map()
7
8
  return input=>{
9
+ if(input?.cancelRequestId!==undefined){
10
+ if(typeof input.cancelRequestId!=='string'||!/^[a-zA-Z0-9-]{16,80}$/.test(input.cancelRequestId))throw Error('Invalid cancellation ID')
11
+ const operation=active.get(input.cancelRequestId);if(operation){operation.canceled=true;operation.child?.kill()}
12
+ return Promise.resolve({stdout:'',stderr:'',exitCode:0})
13
+ }
14
+ if(input?.requestId!==undefined&&(typeof input.requestId!=='string'||!/^[a-zA-Z0-9-]{16,80}$/.test(input.requestId)||active.has(input.requestId)))throw Error('Invalid or duplicate request ID')
8
15
  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')
9
16
  if(input.cwd!==undefined&&(typeof input.cwd!=='string'||!path.isAbsolute(input.cwd)||input.cwd.includes('\0')))throw Error('Invalid working directory')
10
17
  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')
18
+ if(input.stdin!==undefined&&(typeof input.stdin!=='string'||Buffer.byteLength(input.stdin)>16384))throw Error('Invalid standard input')
11
19
  const timeout=input.timeoutMs??10000
12
- if(!Number.isSafeInteger(timeout)||timeout<100||timeout>120000)throw Error('Invalid command timeout')
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}))))
20
+ if(!Number.isSafeInteger(timeout)||timeout<100||timeout>360000)throw Error('Invalid command timeout')
21
+ const operation={child:undefined,canceled:false};if(input.requestId)active.set(input.requestId,operation)
22
+ return resolvePath().then(({path:resolvedPath,warning})=>new Promise(resolve=>{if(operation.canceled){resolve({stdout:'',stderr:'Operation canceled',exitCode:null,error:'CANCELED'});return}const child=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)=>{if(input.requestId)active.delete(input.requestId);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})});operation.child=child;if(input.stdin!==undefined){child.stdin?.on('error',()=>{});child.stdin?.end(input.stdin)}else child.stdin?.end()})).finally(()=>{if(input.requestId)active.delete(input.requestId)})
14
23
  }
15
24
  }
16
25
  module.exports={createLocalExecutor}
@@ -71,7 +71,7 @@ else {
71
71
  })
72
72
  desktopApps = installDesktopApps({ ipcMain, BrowserWindow, session: desktopSession, config, installNavigationRestrictions,
73
73
  openExternal: url => shell.openExternal(url), trusted: event => desktopNotifications.trusted(event) })
74
- if (config.app === 'pmate:merry') installAgentRuntime({ ipcMain, trusted: event => desktopNotifications.trusted(event), runtime: agentRuntime })
74
+ if (config.app === 'pmate:merry') installAgentRuntime({ ipcMain, trusted: event => desktopNotifications.trusted(event), runtime: agentRuntime, activateWindow: showMainWindow })
75
75
  updateController = installUpdateHandlers({ ipcMain, app, shell, appId: config.app, trusted: event => desktopNotifications.trusted(event), updater: require('electron-updater').autoUpdater, getWindow: () => mainWindow })
76
76
  const instanceId = desktopInstanceId(app.getPath('userData'))
77
77
  const rendererReach = createRendererReach({ ipcMain, getWindow: () => mainWindow, trusted: event => desktopNotifications.trusted(event) })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.46.2",
3
+ "version": "0.48.0",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {