@pmate/cli 0.47.0 → 0.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1163,6 +1163,7 @@ type LogsCommandArgs = {
1163
1163
  type InstallCommandArgs = {
1164
1164
  type: Command.Install;
1165
1165
  package: string;
1166
+ staged?: boolean;
1166
1167
  };
1167
1168
  type CommandArgs = InstallCommandArgs | LogsCommandArgs | NoneCommandArgs | ListCommandArgs | LoginCommandArgs | AddDnsCommandArgs | StsCommandArgs | BucketCommandArgs | DeployCommandArgs | LogCommandArgs | InitCommandArgs | DeleteCommandArgs | DevCommandArgs | EnvCommandArgs | CommitCommandArgs | SummaryCommandArgs | QuizCommandArgs | ServiceCommandArgs | LinearCommandArgs | NotionCommandArgs | OssCommandArgs | QrcodeCommandArgs | RandomCommandArgs | CollectCommandArgs | ChatRoomCommandArgs | FunctionCommandArgs | WorkerCommandArgs | CallCommandArgs | NsCommandArgs | RoleCommandArgs | AccountCommandArgs | OrgCommandArgs | StoreCommandArgs | AppCommandArgs | VercelCommandArgs | HostCommandArgs;
1168
1169
 
package/dist/index.js CHANGED
@@ -88,17 +88,17 @@ 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
97
  const sessionPath = buildSessionStorePath();
98
- (0, import_node_fs5.mkdirSync)(import_node_path6.default.dirname(sessionPath), { recursive: true, mode: 448 });
98
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(sessionPath), { recursive: true, mode: 448 });
99
99
  const lock = sessionPath + ".lock";
100
100
  try {
101
- (0, import_node_fs5.mkdirSync)(lock);
101
+ (0, import_node_fs.mkdirSync)(lock);
102
102
  } catch {
103
103
  throw new Error("Session store is busy; retry login.");
104
104
  }
@@ -139,7 +139,7 @@ function saveLoginSession(session, requestedApp = DEFAULT_APP_ID) {
139
139
  sessionPath: buildSessionStorePath()
140
140
  };
141
141
  } finally {
142
- (0, import_node_fs5.rmSync)(lock, { recursive: true, force: true });
142
+ (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
143
143
  }
144
144
  }
145
145
  function readRequiredSession(options) {
@@ -170,7 +170,7 @@ function loadSessionStore() {
170
170
  }
171
171
  function loadExistingSessionStoreOrEmpty() {
172
172
  const sessionPath = buildSessionStorePath();
173
- if (!(0, import_node_fs5.existsSync)(sessionPath)) {
173
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
174
174
  return {
175
175
  version: SESSION_STORE_VERSION,
176
176
  activeAppRef: DEFAULT_APP_ID,
@@ -181,10 +181,10 @@ function loadExistingSessionStoreOrEmpty() {
181
181
  }
182
182
  function loadSessionStoreWithPath() {
183
183
  const sessionPath = buildSessionStorePath();
184
- if (!(0, import_node_fs5.existsSync)(sessionPath)) {
184
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
185
185
  throw new Error(`Missing session file at ${sessionPath}. Run "pmate login" first.`);
186
186
  }
187
- const raw = (0, import_node_fs5.readFileSync)(sessionPath, "utf8");
187
+ const raw = (0, import_node_fs.readFileSync)(sessionPath, "utf8");
188
188
  const parsed = JSON.parse(raw);
189
189
  const store = normalizeStore(parsed);
190
190
  return { sessionPath, store };
@@ -274,16 +274,16 @@ function resolveReadApp(store, options) {
274
274
  }
275
275
  function writeSessionStore(store) {
276
276
  const sessionPath = buildSessionStorePath();
277
- (0, import_node_fs5.mkdirSync)(import_node_path6.default.dirname(sessionPath), { recursive: true });
278
- const temporary = sessionPath + "." + (0, import_node_crypto2.randomUUID)() + ".tmp";
277
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(sessionPath), { recursive: true });
278
+ const temporary = sessionPath + "." + (0, import_node_crypto.randomUUID)() + ".tmp";
279
279
  try {
280
- (0, import_node_fs5.writeFileSync)(temporary, JSON.stringify(store, null, 2), { mode: 384, flag: "wx" });
281
- (0, import_node_fs5.renameSync)(temporary, sessionPath);
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
282
  } finally {
283
- (0, import_node_fs5.rmSync)(temporary, { force: true });
283
+ (0, import_node_fs.rmSync)(temporary, { force: true });
284
284
  }
285
285
  try {
286
- (0, import_node_fs5.chmodSync)(sessionPath, 384);
286
+ (0, import_node_fs.chmodSync)(sessionPath, 384);
287
287
  } catch {
288
288
  }
289
289
  }
@@ -293,14 +293,64 @@ function buildMissingSessionMessage(sessionPath, app) {
293
293
  }
294
294
  return `Missing session for app ${app} in ${sessionPath}. Run "pmate login --app ${app}" first.`;
295
295
  }
296
- var import_node_fs5, import_node_os5, import_node_crypto2, 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;
297
347
  var init_sessionStore = __esm({
298
348
  "src/sessionStore.ts"() {
299
349
  "use strict";
300
- import_node_fs5 = require("fs");
301
- import_node_os5 = __toESM(require("os"));
302
- import_node_crypto2 = require("crypto");
303
- 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"));
304
354
  init_namespacedRef();
305
355
  DEFAULT_APP_ID = "pmate:factory";
306
356
  SESSION_STORE_VERSION = 4;
@@ -8832,22 +8882,48 @@ __export(index_exports, {
8832
8882
  parseCommandArgs: () => parseCommandArgs
8833
8883
  });
8834
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
8835
8911
  var import_node_fs32 = require("fs");
8836
8912
  var import_node_path37 = __toESM(require("path"));
8837
8913
 
8838
8914
  // src/services/PackageInstaller.ts
8839
8915
  var import_node_child_process = require("child_process");
8840
8916
  var import_node_util = require("util");
8841
- var import_node_fs = require("fs");
8842
- var import_node_os = require("os");
8843
- 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"));
8844
8920
  var run = async (file, args, cwd) => {
8845
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 });
8846
8922
  return stdout.trim();
8847
8923
  };
8848
8924
  var semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
8849
8925
  var segment = /^[a-z][a-z0-9-]{0,62}$/;
8850
- 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 === "..");
8851
8927
  function packageRef(value) {
8852
8928
  const parts = value.includes(":") ? value.split(":") : ["pmate", value];
8853
8929
  if (parts.length !== 2 || parts.some((p) => !segment.test(p))) throw Error("Use a package name or namespace:name");
@@ -8864,8 +8940,8 @@ function validateInstallMetadata(value, id) {
8864
8940
  var PackageInstaller = class {
8865
8941
  constructor(ports = {}) {
8866
8942
  this.ports = ports;
8867
- this.directory = import_node_path.default.join(ports.home ?? (0, import_node_os.homedir)(), ".pmate/packages");
8868
- 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");
8869
8945
  }
8870
8946
  execute(file, args, cwd) {
8871
8947
  return (this.ports.run ?? run)(file, args, cwd);
@@ -8874,21 +8950,21 @@ var PackageInstaller = class {
8874
8950
  this.ports.progress?.(message);
8875
8951
  }
8876
8952
  records() {
8877
- const file = import_node_path.default.join(this.directory, "installed.json");
8878
- if (!(0, import_node_fs.existsSync)(file)) return {};
8879
- 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"));
8880
8956
  if (value.schemaVersion !== 1 || !value.packages || typeof value.packages !== "object") throw Error("Invalid installed package registry");
8881
8957
  return value.packages;
8882
8958
  }
8883
8959
  save(packages) {
8884
- const file = import_node_path.default.join(this.directory, "installed.json"), temporary = file + ".tmp-" + process.pid;
8885
- (0, import_node_fs.writeFileSync)(temporary, JSON.stringify({ schemaVersion: 1, packages }, null, 2) + "\n", { mode: 384 });
8886
- (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);
8887
8963
  }
8888
8964
  local(root, relativePath) {
8889
8965
  if (!relative(relativePath)) throw Error("Invalid package path");
8890
- const file = import_node_path.default.resolve(root, relativePath), base = (0, import_node_fs.realpathSync)(root);
8891
- 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");
8892
8968
  return file;
8893
8969
  }
8894
8970
  async step(root, step) {
@@ -8913,43 +8989,86 @@ var PackageInstaller = class {
8913
8989
  if (!response.ok || !body.success) throw Error(body.message ?? "Package registry unavailable");
8914
8990
  return validateInstallMetadata(body.data, ref.id);
8915
8991
  }
8916
- async install(name) {
8992
+ async install(name, options = {}) {
8917
8993
  const metadata = await this.metadata(name);
8918
8994
  if (!metadata.platforms.includes(this.ports.platform ?? process.platform)) throw Error("Package is not supported on this platform");
8919
- (0, import_node_fs.mkdirSync)(this.directory, { recursive: true, mode: 448 });
8920
- if ((0, import_node_fs.lstatSync)(this.directory).isSymbolicLink()) throw Error("Package directory must not be a symlink");
8921
- 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");
8922
8998
  try {
8923
- (0, import_node_fs.mkdirSync)(lock);
8924
- (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));
8925
9001
  } catch {
8926
9002
  throw Error("Another package installation is running; inspect ~/.pmate/packages/install.lock");
8927
9003
  }
8928
9004
  try {
8929
- return await this.installLocked(metadata);
9005
+ const old = this.records()[metadata.id];
9006
+ return options.staged || old?.root.startsWith(import_node_path2.default.join(this.directory, "releases") + import_node_path2.default.sep) ? await this.installStaged(metadata) : await this.installLocked(metadata);
8930
9007
  } finally {
8931
- (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
9008
+ (0, import_node_fs2.rmSync)(lock, { recursive: true, force: true });
8932
9009
  }
8933
9010
  }
9011
+ /** Prepare a separate source tree, then switch command links. Never touch running processes. */
9012
+ async installStaged(metadata) {
9013
+ const records = this.records(), old = records[metadata.id];
9014
+ const root = import_node_path2.default.join(this.directory, "releases", ...metadata.repository.split("/"), metadata.name + "-" + metadata.version);
9015
+ (0, import_node_fs2.mkdirSync)(this.binDirectory, { recursive: true });
9016
+ for (const name of Object.keys(metadata.bins)) {
9017
+ const link = import_node_path2.default.join(this.binDirectory, name), stat = (0, import_node_fs2.lstatSync)(link, { throwIfNoEntry: false });
9018
+ if (stat && (!old?.bins[name] || !stat.isSymbolicLink() || (0, import_node_fs2.realpathSync)(link) !== (0, import_node_fs2.realpathSync)(old.bins[name]))) throw Error("Refusing to replace unmanaged command: " + name);
9019
+ }
9020
+ if (old?.version === metadata.version) {
9021
+ const manifest2 = JSON.parse((0, import_node_fs2.readFileSync)(this.local(old.root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9022
+ if (manifest2.version !== old.version) throw Error("Installed manifest does not match the recorded version");
9023
+ 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);
9024
+ return { ...old, changed: false };
9025
+ }
9026
+ if (old && old.version.split(".").map(BigInt).some((part, i, parts) => part > BigInt(metadata.version.split(".")[i]) && parts.slice(0, i).every((p, j) => p === BigInt(metadata.version.split(".")[j])))) throw Error("Published package version is older than the installed version");
9027
+ if ((0, import_node_fs2.existsSync)(root)) throw Error("Staged release directory already exists; inspect it before retrying");
9028
+ (0, import_node_fs2.mkdirSync)(import_node_path2.default.dirname(root), { recursive: true, mode: 448 });
9029
+ this.say("Preparing isolated release " + metadata.id + " " + metadata.version + "; running processes are unchanged");
9030
+ await this.execute("git", ["clone", "--branch", "main", "https://github.com/" + metadata.repository + ".git", root], import_node_path2.default.dirname(root));
9031
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9032
+ if (manifest.version !== metadata.version) throw Error("Repository component version does not match the published package version");
9033
+ for (const step of metadata.prepare) await this.step(root, step);
9034
+ const bins = {};
9035
+ for (const [name, file] of Object.entries(metadata.bins)) {
9036
+ const target = this.local(root, file);
9037
+ if (!(0, import_node_fs2.lstatSync)(target).isFile()) throw Error("Package bin is not a regular file");
9038
+ (0, import_node_fs2.chmodSync)(target, 493);
9039
+ bins[name] = target;
9040
+ }
9041
+ const commit = await this.execute("git", ["rev-parse", "HEAD"], root);
9042
+ for (const [name, target] of Object.entries(bins)) {
9043
+ const link = import_node_path2.default.join(this.binDirectory, name), temporary = link + ".install-" + process.pid;
9044
+ (0, import_node_fs2.symlinkSync)(target, temporary);
9045
+ (0, import_node_fs2.renameSync)(temporary, link);
9046
+ }
9047
+ 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 };
9048
+ records[metadata.id] = record;
9049
+ this.save(records);
9050
+ this.say("Installed " + metadata.id + " " + metadata.version + "; restart selected processes separately");
9051
+ return { ...record, changed: true };
9052
+ }
8934
9053
  async installLocked(metadata) {
8935
- const records = this.records(), old = records[metadata.id], root = import_node_path.default.join(this.directory, "repos", ...metadata.repository.split("/"));
8936
- (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(root), { recursive: true, mode: 448 });
9054
+ const records = this.records(), old = records[metadata.id], root = import_node_path2.default.join(this.directory, "repos", ...metadata.repository.split("/"));
9055
+ (0, import_node_fs2.mkdirSync)(import_node_path2.default.dirname(root), { recursive: true, mode: 448 });
8937
9056
  if (old && old.root !== root) throw Error("Installed repository location differs; migration required");
8938
- if ((0, import_node_fs.existsSync)(root)) {
8939
- if ((0, import_node_fs.lstatSync)(root).isSymbolicLink()) throw Error("Repository directory must not be a symlink");
9057
+ if ((0, import_node_fs2.existsSync)(root)) {
9058
+ if ((0, import_node_fs2.lstatSync)(root).isSymbolicLink()) throw Error("Repository directory must not be a symlink");
8940
9059
  const remote = (await this.execute("git", ["remote", "get-url", "origin"], root)).replace(/\.git$/, "");
8941
9060
  if (!remote.endsWith("/" + metadata.repository) && !remote.endsWith(":" + metadata.repository)) throw Error("Installed repository origin differs");
8942
9061
  if (await this.execute("git", ["status", "--porcelain"], root)) throw Error("Installed repository contains local changes; preserve them before updating");
8943
9062
  }
8944
- (0, import_node_fs.mkdirSync)(this.binDirectory, { recursive: true });
9063
+ (0, import_node_fs2.mkdirSync)(this.binDirectory, { recursive: true });
8945
9064
  for (const name of Object.keys(metadata.bins)) {
8946
- const file = import_node_path.default.join(this.binDirectory, name), stat = (0, import_node_fs.lstatSync)(file, { throwIfNoEntry: false });
8947
- 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);
9065
+ const file = import_node_path2.default.join(this.binDirectory, name), stat = (0, import_node_fs2.lstatSync)(file, { throwIfNoEntry: false });
9066
+ 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);
8948
9067
  }
8949
- if (old?.version === metadata.version && (0, import_node_fs.existsSync)(root)) {
8950
- const manifest = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9068
+ if (old?.version === metadata.version && (0, import_node_fs2.existsSync)(root)) {
9069
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
8951
9070
  if (manifest.version !== old.version) throw Error("Installed manifest does not match the recorded version");
8952
- 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);
9071
+ 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);
8953
9072
  this.say(metadata.id + " is already installed (" + metadata.version + ")");
8954
9073
  return { ...old, changed: false };
8955
9074
  }
@@ -8981,19 +9100,19 @@ var PackageInstaller = class {
8981
9100
  throw error;
8982
9101
  }
8983
9102
  }
8984
- const previousCommit = (0, import_node_fs.existsSync)(root) ? await this.execute("git", ["rev-parse", "HEAD"], root) : void 0;
9103
+ const previousCommit = (0, import_node_fs2.existsSync)(root) ? await this.execute("git", ["rev-parse", "HEAD"], root) : void 0;
8985
9104
  try {
8986
- if (!(0, import_node_fs.existsSync)(root)) {
9105
+ if (!(0, import_node_fs2.existsSync)(root)) {
8987
9106
  this.say("Cloning " + metadata.repository);
8988
- await this.execute("git", ["clone", "--branch", "main", "https://github.com/" + metadata.repository + ".git", root], import_node_path.default.dirname(root));
9107
+ await this.execute("git", ["clone", "--branch", "main", "https://github.com/" + metadata.repository + ".git", root], import_node_path2.default.dirname(root));
8989
9108
  } else {
8990
9109
  this.say("Updating " + metadata.repository);
8991
9110
  await this.execute("git", ["pull", "--ff-only", "origin", "main"], root);
8992
9111
  }
8993
- const manifest = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
9112
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(metadata.directory, metadata.manifest)), "utf8"));
8994
9113
  if (manifest.version !== metadata.version) throw Error("Repository component version does not match the published package version");
8995
9114
  for (const sibling of Object.values(records).filter((p) => p.root === root && p.id !== metadata.id)) {
8996
- const manifest2 = JSON.parse((0, import_node_fs.readFileSync)(this.local(root, import_node_path.default.posix.join(sibling.directory, sibling.manifest)), "utf8"));
9115
+ const manifest2 = JSON.parse((0, import_node_fs2.readFileSync)(this.local(root, import_node_path2.default.posix.join(sibling.directory, sibling.manifest)), "utf8"));
8997
9116
  if (manifest2.version !== sibling.version) throw Error("Shared repository also requires an update to " + sibling.id);
8998
9117
  }
8999
9118
  for (const step of metadata.prepare) {
@@ -9003,8 +9122,8 @@ var PackageInstaller = class {
9003
9122
  const bins = {};
9004
9123
  for (const [name, file] of Object.entries(metadata.bins)) {
9005
9124
  const target = this.local(root, file);
9006
- if (!(0, import_node_fs.lstatSync)(target).isFile()) throw Error("Package bin is not a regular file");
9007
- (0, import_node_fs.chmodSync)(target, 493);
9125
+ if (!(0, import_node_fs2.lstatSync)(target).isFile()) throw Error("Package bin is not a regular file");
9126
+ (0, import_node_fs2.chmodSync)(target, 493);
9008
9127
  bins[name] = target;
9009
9128
  }
9010
9129
  const commit = await this.execute("git", ["rev-parse", "HEAD"], root);
@@ -9013,9 +9132,9 @@ var PackageInstaller = class {
9013
9132
  await this.healthy(root, metadata.lifecycle.health);
9014
9133
  }
9015
9134
  for (const [name, target] of Object.entries(bins)) {
9016
- const link = import_node_path.default.join(this.binDirectory, name), temporary = link + ".install-" + process.pid;
9017
- (0, import_node_fs.symlinkSync)(target, temporary);
9018
- (0, import_node_fs.renameSync)(temporary, link);
9135
+ const link = import_node_path2.default.join(this.binDirectory, name), temporary = link + ".install-" + process.pid;
9136
+ (0, import_node_fs2.symlinkSync)(target, temporary);
9137
+ (0, import_node_fs2.renameSync)(temporary, link);
9019
9138
  }
9020
9139
  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 };
9021
9140
  records[metadata.id] = record;
@@ -9042,15 +9161,16 @@ var PackageInstaller = class {
9042
9161
 
9043
9162
  // src/installCommandParser.ts
9044
9163
  function parseInstallArgs(args) {
9045
- if (args.length !== 1 || !args[0] || args[0].startsWith("-")) throw Error("Usage: pmate install <package>");
9046
- return { type: "install" /* Install */, package: args[0] };
9164
+ const staged = args.length === 2 && args[1] === "--staged";
9165
+ if (args.length !== 1 && !staged || !args[0] || args[0].startsWith("-")) throw Error("Usage: pmate install <package> [--staged]");
9166
+ return { type: "install" /* Install */, package: args[0], ...staged ? { staged: true } : {} };
9047
9167
  }
9048
9168
 
9049
9169
  // src/managedSession.ts
9050
- var import_node_fs2 = require("fs");
9051
- var import_node_os2 = require("os");
9052
- var import_node_crypto = require("crypto");
9053
- var import_node_path2 = require("path");
9170
+ var import_node_fs3 = require("fs");
9171
+ var import_node_os3 = require("os");
9172
+ var import_node_crypto2 = require("crypto");
9173
+ var import_node_path3 = require("path");
9054
9174
  async function ensureManagedSession(env = process.env, fetcher = fetch) {
9055
9175
  if (env.PMATE_EXPECTED_ACCOUNT_ID && env.HEBO_MEMORY_TOKEN?.trim()) throw Error("Bound Agent CLI cannot use another delegated identity");
9056
9176
  if (env.HEBO_MEMORY_TOKEN?.trim()) {
@@ -9063,19 +9183,19 @@ async function ensureManagedSession(env = process.env, fetcher = fetch) {
9063
9183
  const pr = await fetcher(`${base}/profiles?app=${encodeURIComponent(app)}&account=${encodeURIComponent(session.identity.accountId)}`, { headers, signal: AbortSignal.timeout(15e3) });
9064
9184
  const profiles = await pr.json(), profileId = profiles.data?.[0]?.id;
9065
9185
  if (!pr.ok || !profiles.success || !profileId) throw Error("Delegated user profile unavailable");
9066
- 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");
9067
- (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 });
9186
+ 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");
9187
+ (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 });
9068
9188
  env.PMATE_SESSION_FILE = file;
9069
9189
  env.PCS_AGENT_SESSION_MANAGED = "0";
9070
9190
  process.once("exit", () => {
9071
- (0, import_node_fs2.rmSync)(dir, { recursive: true, force: true });
9191
+ (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
9072
9192
  });
9073
9193
  return;
9074
9194
  }
9075
9195
  if (env.PCS_AGENT_SESSION_MANAGED !== "1") return;
9076
9196
  if (!env.PMATE_SESSION_FILE) throw Error("Managed session file is required");
9077
9197
  const source = env.PCS_AGENT_SESSION_SOURCE_FILE ?? env.PMATE_SESSION_FILE;
9078
- const state = JSON.parse((0, import_node_fs2.readFileSync)(source, "utf8"));
9198
+ const state = JSON.parse((0, import_node_fs3.readFileSync)(source, "utf8"));
9079
9199
  if (!state.refreshKey) throw Error("Managed session refresh key is missing");
9080
9200
  const port = Number(env.PMATE_SESSION_REFRESH_PORT ?? env.PCS_AGENT_CONTROL_PORT ?? 39399);
9081
9201
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error("Invalid controller port");
@@ -9086,12 +9206,12 @@ async function ensureManagedSession(env = process.env, fetcher = fetch) {
9086
9206
  });
9087
9207
  if (!r.ok) throw Error(`Managed session renewal unavailable (${r.status}); retry later`);
9088
9208
  if (source !== env.PMATE_SESSION_FILE) {
9089
- const raw = (0, import_node_fs2.readFileSync)(source, "utf8"), current = JSON.parse(raw).sessions?.[env.PMATE_SESSION_APP ?? "pmate:factory"];
9209
+ const raw = (0, import_node_fs3.readFileSync)(source, "utf8"), current = JSON.parse(raw).sessions?.[env.PMATE_SESSION_APP ?? "pmate:factory"];
9090
9210
  if (env.PMATE_EXPECTED_ACCOUNT_ID && current?.accountId !== env.PMATE_EXPECTED_ACCOUNT_ID) throw Error("Renewed Agent CLI Account mismatch");
9091
9211
  if (env.PMATE_EXPECTED_PROFILE_ID && current?.profileId !== env.PMATE_EXPECTED_PROFILE_ID) throw Error("Renewed Agent CLI Profile mismatch");
9092
- const temp = `${env.PMATE_SESSION_FILE}.${(0, import_node_crypto.randomUUID)()}.tmp`;
9093
- (0, import_node_fs2.writeFileSync)(temp, raw, { mode: 384, flag: "wx" });
9094
- (0, import_node_fs2.renameSync)(temp, env.PMATE_SESSION_FILE);
9212
+ const temp = `${env.PMATE_SESSION_FILE}.${(0, import_node_crypto2.randomUUID)()}.tmp`;
9213
+ (0, import_node_fs3.writeFileSync)(temp, raw, { mode: 384, flag: "wx" });
9214
+ (0, import_node_fs3.renameSync)(temp, env.PMATE_SESSION_FILE);
9095
9215
  }
9096
9216
  }
9097
9217
 
@@ -9138,12 +9258,12 @@ var ui = {
9138
9258
  };
9139
9259
 
9140
9260
  // src/commands/ListCommandHandler.ts
9141
- var import_node_path4 = __toESM(require("path"));
9261
+ var import_node_path5 = __toESM(require("path"));
9142
9262
 
9143
9263
  // src/config.ts
9144
- var import_node_fs3 = require("fs");
9145
- var import_node_os3 = __toESM(require("os"));
9146
- var import_node_path3 = __toESM(require("path"));
9264
+ var import_node_fs4 = require("fs");
9265
+ var import_node_os4 = __toESM(require("os"));
9266
+ var import_node_path4 = __toESM(require("path"));
9147
9267
  var import_ajv = __toESM(require("ajv"));
9148
9268
  var import_yaml = __toESM(require("yaml"));
9149
9269
  var cachedConfig;
@@ -9267,11 +9387,11 @@ function loadPmateConfig() {
9267
9387
  if (cachedConfig !== void 0) {
9268
9388
  return cachedConfig ?? {};
9269
9389
  }
9270
- const pmateDir = import_node_path3.default.join(import_node_os3.default.homedir(), ".pmate");
9271
- const yamlPath = import_node_path3.default.join(pmateDir, "config.yaml");
9390
+ const pmateDir = import_node_path4.default.join(import_node_os4.default.homedir(), ".pmate");
9391
+ const yamlPath = import_node_path4.default.join(pmateDir, "config.yaml");
9272
9392
  let yamlConfig = null;
9273
- if ((0, import_node_fs3.existsSync)(yamlPath)) {
9274
- const raw = (0, import_node_fs3.readFileSync)(yamlPath, "utf8");
9393
+ if ((0, import_node_fs4.existsSync)(yamlPath)) {
9394
+ const raw = (0, import_node_fs4.readFileSync)(yamlPath, "utf8");
9275
9395
  try {
9276
9396
  const parsed = import_yaml.default.parse(raw);
9277
9397
  yamlConfig = validateParsedConfig(parsed, yamlPath);
@@ -9333,21 +9453,21 @@ ${detail}`);
9333
9453
  return value;
9334
9454
  }
9335
9455
  function findRepoConfigPaths(cwd, searchParents) {
9336
- let current = import_node_path3.default.resolve(cwd);
9456
+ let current = import_node_path4.default.resolve(cwd);
9337
9457
  while (true) {
9338
- const candidate = import_node_path3.default.join(current, ".pmate.yaml");
9339
- if ((0, import_node_fs3.existsSync)(candidate)) {
9340
- const localCandidate = import_node_path3.default.join(current, ".pmate.local.yaml");
9458
+ const candidate = import_node_path4.default.join(current, ".pmate.yaml");
9459
+ if ((0, import_node_fs4.existsSync)(candidate)) {
9460
+ const localCandidate = import_node_path4.default.join(current, ".pmate.local.yaml");
9341
9461
  return {
9342
9462
  rootDir: current,
9343
9463
  configPath: candidate,
9344
- localConfigPath: (0, import_node_fs3.existsSync)(localCandidate) ? localCandidate : void 0
9464
+ localConfigPath: (0, import_node_fs4.existsSync)(localCandidate) ? localCandidate : void 0
9345
9465
  };
9346
9466
  }
9347
9467
  if (!searchParents) {
9348
9468
  return null;
9349
9469
  }
9350
- const parent = import_node_path3.default.dirname(current);
9470
+ const parent = import_node_path4.default.dirname(current);
9351
9471
  if (parent === current) {
9352
9472
  return null;
9353
9473
  }
@@ -9363,7 +9483,7 @@ function loadMergedRepoYaml(paths) {
9363
9483
  return mergeRepoConfigValues(base, local);
9364
9484
  }
9365
9485
  function parseYamlFile(configPath) {
9366
- const raw = (0, import_node_fs3.readFileSync)(configPath, "utf8");
9486
+ const raw = (0, import_node_fs4.readFileSync)(configPath, "utf8");
9367
9487
  try {
9368
9488
  return import_yaml.default.parse(raw);
9369
9489
  } catch (error) {
@@ -9518,7 +9638,7 @@ var ListCommandHandler = class {
9518
9638
  }
9519
9639
  }
9520
9640
  resolveTargetDir(targetPath) {
9521
- return targetPath ? import_node_path4.default.resolve(process.cwd(), targetPath) : process.cwd();
9641
+ return targetPath ? import_node_path5.default.resolve(process.cwd(), targetPath) : process.cwd();
9522
9642
  }
9523
9643
  loadConfig(targetDir) {
9524
9644
  return loadAppConfig(targetDir).config;
@@ -9532,17 +9652,17 @@ var import_node_http = require("http");
9532
9652
  var import_promises = require("readline/promises");
9533
9653
 
9534
9654
  // src/accessKeyFile.ts
9535
- var import_node_fs4 = require("fs");
9536
- var import_node_os4 = __toESM(require("os"));
9537
- var import_node_path5 = __toESM(require("path"));
9655
+ var import_node_fs5 = require("fs");
9656
+ var import_node_os5 = __toESM(require("os"));
9657
+ var import_node_path6 = __toESM(require("path"));
9538
9658
  function readAccessKeyFile(filePath, options = {}) {
9539
9659
  const absolutePath = resolveFilePath(filePath, options.cwd);
9540
- if (!(0, import_node_fs4.existsSync)(absolutePath)) {
9660
+ if (!(0, import_node_fs5.existsSync)(absolutePath)) {
9541
9661
  throw new Error(`Access key file not found: ${absolutePath}`);
9542
9662
  }
9543
9663
  let parsed;
9544
9664
  try {
9545
- parsed = JSON.parse((0, import_node_fs4.readFileSync)(absolutePath, "utf8"));
9665
+ parsed = JSON.parse((0, import_node_fs5.readFileSync)(absolutePath, "utf8"));
9546
9666
  } catch (error) {
9547
9667
  const message = error instanceof Error ? error.message : String(error);
9548
9668
  throw new Error(`Invalid JSON in ${absolutePath}: ${message}`);
@@ -9559,10 +9679,10 @@ function readAccessKeyFile(filePath, options = {}) {
9559
9679
  }
9560
9680
  function scanAccessKeyFiles(app) {
9561
9681
  const dir = resolveAccessKeyDir(app);
9562
- if (!(0, import_node_fs4.existsSync)(dir)) {
9682
+ if (!(0, import_node_fs5.existsSync)(dir)) {
9563
9683
  return [];
9564
9684
  }
9565
- 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) => {
9685
+ 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) => {
9566
9686
  try {
9567
9687
  return [{ filePath, key: readAccessKeyFile(filePath, { expectedApp: app }) }];
9568
9688
  } catch {
@@ -9571,13 +9691,13 @@ function scanAccessKeyFiles(app) {
9571
9691
  }).sort((a, b) => a.key.name.localeCompare(b.key.name) || a.filePath.localeCompare(b.filePath));
9572
9692
  }
9573
9693
  function resolveAccessKeyDir(app) {
9574
- return import_node_path5.default.join(homeDir(), ".pmate", "access-keys", app);
9694
+ return import_node_path6.default.join(homeDir(), ".pmate", "access-keys", app);
9575
9695
  }
9576
9696
  function resolveFilePath(filePath, cwd = process.cwd()) {
9577
- return import_node_path5.default.isAbsolute(filePath) ? filePath : import_node_path5.default.resolve(cwd, filePath);
9697
+ return import_node_path6.default.isAbsolute(filePath) ? filePath : import_node_path6.default.resolve(cwd, filePath);
9578
9698
  }
9579
9699
  function homeDir() {
9580
- return process.env.HOME || process.env.USERPROFILE || import_node_os4.default.homedir() || process.cwd();
9700
+ return process.env.HOME || process.env.USERPROFILE || import_node_os5.default.homedir() || process.cwd();
9581
9701
  }
9582
9702
  function isAccessKeyFile(value) {
9583
9703
  if (!value || typeof value !== "object") {
@@ -9660,6 +9780,14 @@ function buildHostedLoginUrl(redirectUrl, appId = DEFAULT_APP_ID) {
9660
9780
  }
9661
9781
  var LoginCommandHandler = class {
9662
9782
  async handle(args) {
9783
+ const release = claimSessionLogin(args.app?.trim() || DEFAULT_APP_ID);
9784
+ try {
9785
+ await this.execute(args);
9786
+ } finally {
9787
+ release();
9788
+ }
9789
+ }
9790
+ async execute(args) {
9663
9791
  if (args.tokenStdin) {
9664
9792
  if (!args.app?.trim()) throw new Error("--token-stdin requires --app");
9665
9793
  if (args.accessKey || args.accessKeyFile || args.accessKeyScan) throw new Error("Token and access-key login cannot be combined");
@@ -27475,7 +27603,7 @@ var HELP_TEXT = [
27475
27603
  ` ${import_chalk4.default.gray(" icon add <ns:objectId> <name> (--size <w>x<h>|--<w>x<h>) [--format <png|webp|svg|ico>] [--output <path>] [--force] [--base-url <url>] [--json]")}`,
27476
27604
  ` ${import_chalk4.default.gray(" delete <ns:objectId> [--base-url <url>] [--json]")}`,
27477
27605
  ` ${import_chalk4.default.gray(" default base URL: https://apps-api.pmate.chat")}`,
27478
- ` ${import_chalk4.default.cyan("install")} Install or update a managed source package: pmate install <package>`,
27606
+ ` ${import_chalk4.default.cyan("install")} Install or update a managed source package: pmate install <package> [--staged]`,
27479
27607
  ` ${import_chalk4.default.cyan("service")} Manage service registry entries via apps-api`,
27480
27608
  " deploy <ns:service> [--env prod] [--cwd <repo>] [--dry-run] [--local] [--unsigned] [--platform mac|win] [--arch arm64|x64] [--config <file>] [--out-dir <dir>] [--scheme <name>] [--team <id>] [--variant release|debug] [--bump patch|minor|major]",
27481
27609
  ` ${import_chalk4.default.gray(" list [--namespace <ns>] [--repo <owner/name|https://github.com/owner/name>] [--server <name>] [--base-url <url>] [--json]")}`,
@@ -29234,6 +29362,10 @@ function parseNonNegativeInt(value, optionName) {
29234
29362
  }
29235
29363
  async function main() {
29236
29364
  try {
29365
+ if (process.argv[2] === "session") {
29366
+ process.stdout.write(JSON.stringify(sessionCommand(process.argv.slice(3))) + "\n");
29367
+ return;
29368
+ }
29237
29369
  await ensureManagedSession();
29238
29370
  const args = parseArgs(process.argv.slice(2));
29239
29371
  if (args.help) {
@@ -29251,7 +29383,7 @@ async function main() {
29251
29383
  const commandArgs = parseCommandArgs(args);
29252
29384
  switch (commandArgs.type) {
29253
29385
  case "install" /* Install */: {
29254
- await new PackageInstaller({ progress: (message) => ui.plain(message) }).install(commandArgs.package);
29386
+ await new PackageInstaller({ progress: (message) => ui.plain(message) }).install(commandArgs.package, { staged: commandArgs.staged });
29255
29387
  return;
29256
29388
  }
29257
29389
  case "list" /* List */: {
@@ -7,28 +7,21 @@ 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
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 ownerEnvironment=()=>({MERRY_RUNTIME_EXPECTED_USER:identity.accountId,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})
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})
17
15
  const runtimeApi=async(method,input)=>{
18
- if(!identity?.accountId)throw Error('请重新登录梅丽号以确认 Runtime Owner')
19
- const epoch=identityEpoch,output=await run('merry-runtime',['api',method,'--request',JSON.stringify(input??{})],undefined,600000,ownerEnvironment())
20
- if(epoch!==identityEpoch||!identity)throw Error('登录身份已改变,请重新打开页面')
16
+ const output=await run('merry-runtime',['api',method,'--request',JSON.stringify(input??{})],undefined,600000,ownerEnvironment())
21
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,stdin:true}
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('未知脚本操作')
@@ -37,11 +30,8 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
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?.accountId)throw new Error('请重新登录梅丽号以确认 Runtime Owner')
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
34
  const output=await run('merry-runtime',['inspect','--request',JSON.stringify(input)],undefined,600000,ownerEnvironment())
44
- if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新打开页面')
45
35
  return JSON.parse(output)
46
36
  }
47
37
  if(method==='agents.list')return runtimeApi(method,input)
@@ -52,17 +42,11 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
52
42
  if(method==='agents.create'&&expectedRevision!==undefined)throw new Error('创建不能指定 revision')
53
43
  return runtimeApi(method,input)
54
44
  }
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,accountId:value.accountId}
60
- return result
61
- },
62
- setIdentity(value) { identityEpoch++;identity=value ? {appId:value.appId,accountId:value.accountId} : undefined }
63
- }
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,14 +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')
11
18
  if(input.stdin!==undefined&&(typeof input.stdin!=='string'||Buffer.byteLength(input.stdin)>16384))throw Error('Invalid standard input')
12
19
  const timeout=input.timeoutMs??10000
13
20
  if(!Number.isSafeInteger(timeout)||timeout<100||timeout>360000)throw Error('Invalid command timeout')
14
- return resolvePath().then(({path:resolvedPath,warning})=>new Promise(resolve=>{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)=>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}));if(input.stdin!==undefined){child.stdin?.on('error',()=>{});child.stdin?.end(input.stdin)}else child.stdin?.end()}))
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)})
15
23
  }
16
24
  }
17
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.47.0",
3
+ "version": "0.48.1",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {