@pmate/cli 0.48.0 → 0.48.2

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.
@@ -0,0 +1,25 @@
1
+ /** Local CLI contract. Credential output is for trusted local consumers, never Web IPC. */
2
+ declare function sessionCommand(args: string[]): {
3
+ version: number;
4
+ loggedIn: boolean;
5
+ accountId?: undefined;
6
+ profileId?: undefined;
7
+ expiresAt?: undefined;
8
+ } | {
9
+ token: string;
10
+ accountId: string;
11
+ profileId: string;
12
+ issuedAt: string;
13
+ expiresAt: string;
14
+ updatedAt: string;
15
+ version: number;
16
+ loggedIn?: undefined;
17
+ } | {
18
+ version: number;
19
+ loggedIn: boolean;
20
+ accountId: string;
21
+ profileId: string;
22
+ expiresAt: string;
23
+ };
24
+
25
+ export { sessionCommand };
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/session-entry.ts
31
+ var session_entry_exports = {};
32
+ __export(session_entry_exports, {
33
+ sessionCommand: () => sessionCommand
34
+ });
35
+ module.exports = __toCommonJS(session_entry_exports);
36
+
37
+ // src/sessionStore.ts
38
+ var import_node_fs = require("fs");
39
+ var import_node_os = __toESM(require("os"));
40
+ var import_node_crypto = require("crypto");
41
+ var import_node_path = __toESM(require("path"));
42
+
43
+ // src/namespacedRef.ts
44
+ function parseNamespacedRef(value, options = {}) {
45
+ const raw = value.trim();
46
+ const entityLabel = options.entityLabel || "ref";
47
+ if (!raw) {
48
+ throw new Error(`Invalid ${entityLabel}.`);
49
+ }
50
+ const colonIndex = raw.indexOf(":");
51
+ if (colonIndex > 0) {
52
+ const namespace2 = raw.slice(0, colonIndex).trim();
53
+ const objectId = raw.slice(colonIndex + 1).trim();
54
+ if (!namespace2 || !objectId) {
55
+ throw new Error(`Invalid ${entityLabel} "${value}". Use <ns:objectId>.`);
56
+ }
57
+ return {
58
+ namespace: namespace2,
59
+ objectId,
60
+ fullId: `${namespace2}:${objectId}`
61
+ };
62
+ }
63
+ const namespace = options.defaultNamespace?.trim();
64
+ if (namespace) {
65
+ return {
66
+ namespace,
67
+ objectId: raw,
68
+ fullId: `${namespace}:${raw}`
69
+ };
70
+ }
71
+ throw new Error(`Invalid ${entityLabel} "${value}". Use <ns:objectId>.`);
72
+ }
73
+
74
+ // src/sessionStore.ts
75
+ var DEFAULT_APP_ID = "pmate:factory";
76
+ var SESSION_STORE_VERSION = 4;
77
+ function buildSessionStorePath() {
78
+ return process.env.PMATE_SESSION_FILE?.trim() || import_node_path.default.join(import_node_os.default.homedir(), ".pmate", "session.json");
79
+ }
80
+ function assertValidAppRef(appRef) {
81
+ return parseNamespacedRef(appRef, { entityLabel: "app ref" }).fullId;
82
+ }
83
+ function readRequiredSession(options) {
84
+ const { sessionPath, store } = loadSessionStoreWithPath();
85
+ const boundApp = process.env.PMATE_SESSION_APP?.trim();
86
+ if (process.env.PMATE_EXPECTED_ACCOUNT_ID && !process.env.PMATE_SESSION_FILE?.trim()) throw new Error("Agent CLI requires a dedicated session file");
87
+ if (boundApp && options?.app && options.app !== boundApp) throw new Error("Agent CLI application differs from its bound session");
88
+ const resolvedApp = boundApp ? assertValidAppRef(boundApp) : resolveReadApp(store, options);
89
+ const session = store.sessions[resolvedApp];
90
+ if (!session) {
91
+ throw new Error(buildMissingSessionMessage(sessionPath, resolvedApp));
92
+ }
93
+ if (process.env.PMATE_EXPECTED_ACCOUNT_ID && session.accountId !== process.env.PMATE_EXPECTED_ACCOUNT_ID) throw new Error("Agent CLI Account mismatch");
94
+ if (process.env.PMATE_EXPECTED_PROFILE_ID && session.profileId !== process.env.PMATE_EXPECTED_PROFILE_ID) throw new Error("Agent CLI Profile mismatch");
95
+ const token = session.token?.trim();
96
+ if (!token) {
97
+ throw new Error(
98
+ `Missing token in ${sessionPath}. Run "pmate login --app ${resolvedApp}" again.`
99
+ );
100
+ }
101
+ return {
102
+ ...session,
103
+ token
104
+ };
105
+ }
106
+ function loadSessionStore() {
107
+ return loadSessionStoreWithPath().store;
108
+ }
109
+ function loadExistingSessionStoreOrEmpty() {
110
+ const sessionPath = buildSessionStorePath();
111
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
112
+ return {
113
+ version: SESSION_STORE_VERSION,
114
+ activeAppRef: DEFAULT_APP_ID,
115
+ sessions: {}
116
+ };
117
+ }
118
+ return loadSessionStore();
119
+ }
120
+ function loadSessionStoreWithPath() {
121
+ const sessionPath = buildSessionStorePath();
122
+ if (!(0, import_node_fs.existsSync)(sessionPath)) {
123
+ throw new Error(`Missing session file at ${sessionPath}. Run "pmate login" first.`);
124
+ }
125
+ const raw = (0, import_node_fs.readFileSync)(sessionPath, "utf8");
126
+ const parsed = JSON.parse(raw);
127
+ const store = normalizeStore(parsed);
128
+ return { sessionPath, store };
129
+ }
130
+ function normalizeStore(value) {
131
+ if (isLegacySessionStoreVersion(value)) {
132
+ throw new Error(
133
+ `Unsupported session store version in ${buildSessionStorePath()}. Run "pmate login" again.`
134
+ );
135
+ }
136
+ if (!isSessionStore(value)) {
137
+ throw new Error(
138
+ `Invalid session store format in ${buildSessionStorePath()}. Run "pmate login" again.`
139
+ );
140
+ }
141
+ return value;
142
+ }
143
+ function isLegacySessionStoreVersion(value) {
144
+ return !!value && typeof value === "object" && "version" in value && value.version !== SESSION_STORE_VERSION;
145
+ }
146
+ function isSessionStore(value) {
147
+ if (!value || typeof value !== "object") {
148
+ return false;
149
+ }
150
+ const candidate = value;
151
+ if (candidate.version !== SESSION_STORE_VERSION) {
152
+ return false;
153
+ }
154
+ if (typeof candidate.activeAppRef !== "string") {
155
+ return false;
156
+ }
157
+ let normalizedActiveApp;
158
+ try {
159
+ normalizedActiveApp = assertValidAppRef(candidate.activeAppRef);
160
+ } catch {
161
+ return false;
162
+ }
163
+ if (normalizedActiveApp !== candidate.activeAppRef) {
164
+ return false;
165
+ }
166
+ if (!candidate.sessions || typeof candidate.sessions !== "object") {
167
+ return false;
168
+ }
169
+ if (!(normalizedActiveApp in candidate.sessions)) {
170
+ return false;
171
+ }
172
+ for (const [appRef, session] of Object.entries(candidate.sessions)) {
173
+ try {
174
+ if (assertValidAppRef(appRef) !== appRef) {
175
+ return false;
176
+ }
177
+ } catch {
178
+ return false;
179
+ }
180
+ if (!isStoredSession(session)) {
181
+ return false;
182
+ }
183
+ }
184
+ return true;
185
+ }
186
+ function isStoredSession(value) {
187
+ if (!value || typeof value !== "object") {
188
+ return false;
189
+ }
190
+ const session = value;
191
+ return typeof session.token === "string" && !!session.token.trim() && typeof session.accountId === "string" && !!session.accountId.trim() && typeof session.profileId === "string" && !!session.profileId.trim() && typeof session.issuedAt === "string" && !!session.issuedAt.trim() && typeof session.expiresAt === "string" && !!session.expiresAt.trim() && typeof session.updatedAt === "string" && !!session.updatedAt.trim();
192
+ }
193
+ function resolveReadApp(store, options) {
194
+ const requestedApp = options?.app?.trim();
195
+ if (requestedApp) {
196
+ return assertValidAppRef(requestedApp);
197
+ }
198
+ const preferredApp = options?.preferredApp?.trim();
199
+ if (preferredApp) {
200
+ const normalizedPreferred = assertValidAppRef(preferredApp);
201
+ if (store.sessions[normalizedPreferred]) {
202
+ return normalizedPreferred;
203
+ }
204
+ }
205
+ if (options?.fallbackToActiveApp && store.sessions[store.activeAppRef]) {
206
+ return store.activeAppRef;
207
+ }
208
+ if (preferredApp) {
209
+ return assertValidAppRef(preferredApp);
210
+ }
211
+ return store.activeAppRef;
212
+ }
213
+ function writeSessionStore(store) {
214
+ const sessionPath = buildSessionStorePath();
215
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(sessionPath), { recursive: true });
216
+ const temporary = sessionPath + "." + (0, import_node_crypto.randomUUID)() + ".tmp";
217
+ try {
218
+ (0, import_node_fs.writeFileSync)(temporary, JSON.stringify(store, null, 2), { mode: 384, flag: "wx" });
219
+ (0, import_node_fs.renameSync)(temporary, sessionPath);
220
+ } finally {
221
+ (0, import_node_fs.rmSync)(temporary, { force: true });
222
+ }
223
+ try {
224
+ (0, import_node_fs.chmodSync)(sessionPath, 384);
225
+ } catch {
226
+ }
227
+ }
228
+ function buildMissingSessionMessage(sessionPath, app) {
229
+ if (app === DEFAULT_APP_ID) {
230
+ return `Missing ${DEFAULT_APP_ID} session in ${sessionPath}. Run "pmate login" first.`;
231
+ }
232
+ return `Missing session for app ${app} in ${sessionPath}. Run "pmate login --app ${app}" first.`;
233
+ }
234
+ function removeStoredSession(appRef) {
235
+ const app = assertValidAppRef(appRef), sessionPath = buildSessionStorePath();
236
+ if (process.env.PMATE_SESSION_APP && process.env.PMATE_SESSION_APP !== app) throw Error("Agent CLI application differs from its bound session");
237
+ if (process.env.PMATE_EXPECTED_ACCOUNT_ID && !process.env.PMATE_SESSION_FILE?.trim()) throw Error("Agent CLI requires a dedicated session file");
238
+ if (!(0, import_node_fs.existsSync)(sessionPath)) return;
239
+ const lock = sessionPath + ".lock";
240
+ try {
241
+ (0, import_node_fs.mkdirSync)(lock);
242
+ } catch {
243
+ throw Error("Session store is busy; retry logout.");
244
+ }
245
+ try {
246
+ const store = loadExistingSessionStoreOrEmpty();
247
+ delete store.sessions[app];
248
+ if (store.activeAppRef === app) store.activeAppRef = Object.keys(store.sessions)[0] || DEFAULT_APP_ID;
249
+ writeSessionStore(store);
250
+ } finally {
251
+ (0, import_node_fs.rmSync)(lock, { recursive: true, force: true });
252
+ }
253
+ }
254
+ function claimSessionLogin(appRef) {
255
+ const app = assertValidAppRef(appRef), file = buildSessionStorePath() + ".login-" + encodeURIComponent(app);
256
+ (0, import_node_fs.mkdirSync)(import_node_path.default.dirname(file), { recursive: true, mode: 448 });
257
+ for (; ; ) {
258
+ try {
259
+ (0, import_node_fs.mkdirSync)(file);
260
+ (0, import_node_fs.writeFileSync)(import_node_path.default.join(file, "pid"), String(process.pid), { mode: 384 });
261
+ return () => (0, import_node_fs.rmSync)(file, { recursive: true, force: true });
262
+ } catch (error) {
263
+ if (error.code !== "EEXIST") throw error;
264
+ let pid;
265
+ try {
266
+ pid = Number((0, import_node_fs.readFileSync)(import_node_path.default.join(file, "pid"), "utf8"));
267
+ } catch {
268
+ throw Error("CLI login is already in progress");
269
+ }
270
+ if (!Number.isSafeInteger(pid) || pid < 1) throw Error("CLI login lock requires inspection");
271
+ try {
272
+ process.kill(pid, 0);
273
+ } catch (error2) {
274
+ if (error2.code === "ESRCH") {
275
+ (0, import_node_fs.rmSync)(file, { recursive: true });
276
+ continue;
277
+ }
278
+ throw error2;
279
+ }
280
+ throw Error("CLI login is already in progress");
281
+ }
282
+ }
283
+ }
284
+
285
+ // src/sessionCommand.ts
286
+ function sessionCommand(args) {
287
+ const [operation, flag, app] = args;
288
+ if (!["status", "read", "logout"].includes(operation) || flag !== "--app" || !app || args.length !== 3) throw Error("Usage: pmate session status|read|logout --app APP");
289
+ if (operation === "logout") {
290
+ const release = claimSessionLogin(app);
291
+ try {
292
+ removeStoredSession(app);
293
+ return { version: 1, loggedIn: false };
294
+ } finally {
295
+ release();
296
+ }
297
+ }
298
+ try {
299
+ const session = readRequiredSession({ app, fallbackToActiveApp: false });
300
+ if (!Number.isFinite(Date.parse(session.expiresAt)) || Date.parse(session.expiresAt) <= Date.now()) throw Error("CLI session expired");
301
+ return operation === "read" ? { version: 1, ...session } : { version: 1, loggedIn: true, accountId: session.accountId, profileId: session.profileId, expiresAt: session.expiresAt };
302
+ } catch (error) {
303
+ if (operation === "read") throw error;
304
+ return { version: 1, loggedIn: false };
305
+ }
306
+ }
307
+ // Annotate the CommonJS export names for ESM import in node:
308
+ 0 && (module.exports = {
309
+ sessionCommand
310
+ });
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.48.0",
3
+ "version": "0.48.2",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {
7
- "pmate": "dist/index.js"
7
+ "pmate": "dist/launcher.js"
8
8
  },
9
9
  "main": "dist/index.js",
10
10
  "types": "dist/index.d.ts",