@parall/cli 1.86.0 → 1.88.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.
@@ -0,0 +1,177 @@
1
+ import { Option } from 'commander';
2
+ import { ApiError, CLIP_CONNECTION_CONNECT_ACTION } from '@parall/sdk';
3
+ import { printFiledApproval } from '../lib/approvers.js';
4
+ import { resolveCredentials, resolveRuntimeContext } from '../lib/client.js';
5
+ import { CLIP_REF_HELP, clipNotFoundError, findConnector } from '../lib/connector-ref.js';
6
+ import { printError, printJson, printProgress, stripPrllScheme } from '../lib/output.js';
7
+ // `parall connector connect` is how an agent that cannot run a connector yet
8
+ // gets an account for it (agent-connector-connect-design.md §4): it files a
9
+ // `clip.connection.connect` approval, and the person taps Connect on the card
10
+ // and signs in. The agent picks the configuration; it never sees a secret.
11
+ const EXAMPLES = `
12
+ Examples:
13
+ parall connector connect google-calendar --reason "Check whether you are free tomorrow afternoon"
14
+ parall connector connect jira --reason "File this bug in the team's Jira" --from org`;
15
+ const USAGE_HINT = '(example: parall connector connect google-calendar --reason "Check whether you are free tomorrow afternoon"; add --help for usage)';
16
+ function shellQuote(value) {
17
+ return `'${value.replaceAll("'", `'\\''`)}'`;
18
+ }
19
+ /** The connector argument: a bare id, name or org_<id>/<name> goes to the
20
+ * registry as is (a name may look like any id); a prll:// reference is always
21
+ * an entity, so anything but a connector is refused before any request. */
22
+ function connectorArg(raw) {
23
+ const ref = raw.trim();
24
+ if (!ref.startsWith('prll://'))
25
+ return ref;
26
+ const id = stripPrllScheme(ref);
27
+ if (id.startsWith('crg_'))
28
+ return id;
29
+ if (id.startsWith('ccn_')) {
30
+ throw new Error(`prll://${id} is a connection, not a connector. If you can already use it, run the connector through it:\n parall connector exec <connector> <command> '<json args>' --connection ${id}`);
31
+ }
32
+ if (id.startsWith('usr_')) {
33
+ throw new Error(`prll://${id} is a person, not a connector. Pass the connector (crg_… or its name); the card goes to the person you are working for:\n parall connector connect <connector> --reason "…"`);
34
+ }
35
+ throw new Error(`prll://${id} is not a connector. Pass the connector's crg_ id or name (find it with \`parall connector search <text>\`).`);
36
+ }
37
+ function detailsOf(err) {
38
+ const details = err.extras?.details;
39
+ return details && typeof details === 'object' ? details : {};
40
+ }
41
+ function text(value) {
42
+ return typeof value === 'string' && value !== '' ? value : undefined;
43
+ }
44
+ function callerNames(value) {
45
+ if (!Array.isArray(value))
46
+ return '';
47
+ const names = value
48
+ .map((c) => (c && typeof c === 'object' ? (text(c.name) ?? text(c.id)) : undefined))
49
+ .filter((n) => n !== undefined);
50
+ return names.length > 0 ? ` (${names.join(', ')})` : '';
51
+ }
52
+ /** The copyable command for a company-shared account: the same request with
53
+ * --from org, keeping every option the agent passed explicitly. */
54
+ function fromOrgCommand(connectorId, opts) {
55
+ const parts = [
56
+ `parall connector connect ${connectorId}`,
57
+ `--reason ${shellQuote(opts.reason.trim())}`,
58
+ '--from org',
59
+ ];
60
+ if (opts.auth)
61
+ parts.push(`--auth ${opts.auth}`);
62
+ if (opts.serverUrl)
63
+ parts.push(`--server-url ${shellQuote(opts.serverUrl)}`);
64
+ if (opts.chat)
65
+ parts.push(`--chat ${opts.chat}`);
66
+ if (opts.threadRootId)
67
+ parts.push(`--thread-root-id ${opts.threadRootId}`);
68
+ return parts.join(' ');
69
+ }
70
+ /** The next step for each refusal of the connect request itself. */
71
+ function refusalStep(err, connectorId, name, opts) {
72
+ if (!(err instanceof ApiError))
73
+ return undefined;
74
+ const details = detailsOf(err);
75
+ switch (err.code) {
76
+ case 'CONNECTION_ALREADY_AVAILABLE': {
77
+ const clip = text(details.clip_id) ?? connectorId;
78
+ const connection = text(details.connection_id) ?? '<ccn_…>';
79
+ return `No card posted: you can already use ${name} through connection ${connection}. Run it directly (commands and their args: \`parall connector info ${clip}\`):\n parall connector exec ${clip} <command> '<json args>' --connection ${connection}`;
80
+ }
81
+ case 'CONNECTION_OWNER_REQUIRED': {
82
+ const why = details.reason === 'multiple_callers'
83
+ ? `you are working for several people at once${callerNames(details.callers)}, so it is not clear whose account to connect. Ask again once you are working for one of them, or ask an admin for a company-shared account`
84
+ : details.reason === 'no_caller'
85
+ ? 'no person is behind this work (for example a message from an external channel), so nobody can connect their own account. The person should message you in Parall directly; or ask an admin for a company-shared account'
86
+ : 'it is not clear whose account to connect. Ask an admin for a company-shared account';
87
+ return `No card posted: ${why}:\n ${fromOrgCommand(connectorId, opts)}`;
88
+ }
89
+ case 'CLIP_NOT_REVIEWED':
90
+ return `No card posted: ${name} was published by an agent and has not been reviewed, so it cannot ask people to connect an account. Tell the person you cannot connect it; do not publish a connector yourself to get around this.`;
91
+ case 'INVALID_ACTION_PAYLOAD':
92
+ return 'No card posted. Fix the option the error names (--auth or --server-url) and run the command again; see `parall connector connect --help`.';
93
+ default:
94
+ return undefined;
95
+ }
96
+ }
97
+ export function registerClipConnectCommand(clip) {
98
+ clip
99
+ .command('connect')
100
+ .description('Ask a person to connect an account for a connector, on a card in the chat — when you cannot run it yet (not installed, no connection, not allowed, or it needs signing in again). The person taps Connect and signs in; the card installs the connector and creates the connection for you. You are woken with the result')
101
+ .argument('<connector>', `${CLIP_REF_HELP}; prll://crg_… works too`)
102
+ .requiredOption('--reason <text>', 'One sentence for the person on what you need it for, in their language')
103
+ .option('--from <owner>', 'Whose account: leave out for the person you are working for (their own account); `org` = a company-shared account an org admin connects')
104
+ .addOption(new Option('--auth <type>', 'How to sign in, only to override the connector (default: what it declares; OAuth when it declares several)').choices(['oauth', 'api_key', 'basic', 'none']))
105
+ .option('--server-url <url>', 'Server address, only for a self-hosted product whose connector has no fixed address')
106
+ .option('--name <name>', 'Name for the connection, with --from org only')
107
+ .option('--chat <chatId>', 'Chat to post the card in (default: the chat you are working in)')
108
+ .option('--thread-root-id <id>', 'Post the card in this thread of the chat (msg_…); pass it when you are working in a thread, it is never inferred')
109
+ .showHelpAfterError(USAGE_HINT)
110
+ .addHelpText('after', EXAMPLES)
111
+ .action(async (raw, opts) => {
112
+ try {
113
+ // Everything that can be refused locally is refused before any request.
114
+ const reason = opts.reason.trim();
115
+ if (!reason) {
116
+ throw new Error('--reason needs one sentence for the person on what you need it for');
117
+ }
118
+ if (opts.from !== undefined && opts.from !== 'org') {
119
+ throw new Error(`--from takes only \`org\` (a company-shared account an org admin connects), not "${opts.from}". Leave --from out to ask the person you are working for to connect their own account.`);
120
+ }
121
+ const fromOrg = opts.from === 'org';
122
+ if (opts.name !== undefined && !fromOrg) {
123
+ throw new Error("--name only applies with --from org: a person's own account has no connection name. Leave --name out.");
124
+ }
125
+ const ref = connectorArg(raw);
126
+ const explicitChat = opts.chat?.trim();
127
+ if (explicitChat && !stripPrllScheme(explicitChat).startsWith('cht_')) {
128
+ throw new Error(`--chat takes a chat (cht_…), not ${explicitChat}. Leave --chat out to post the card in the chat you are working in.`);
129
+ }
130
+ const chatId = stripPrllScheme(explicitChat || resolveRuntimeContext().chatId || '');
131
+ if (!chatId) {
132
+ throw new Error('No chat to post the card in: pass --chat <cht_…>, the chat you are working in.');
133
+ }
134
+ // Placement is the command alone, as in `messages send`: the run's
135
+ // thread is never inferred.
136
+ const threadRootId = opts.threadRootId !== undefined ? stripPrllScheme(opts.threadRootId.trim()) : undefined;
137
+ if (threadRootId !== undefined && !threadRootId.startsWith('msg_')) {
138
+ throw new Error(`--thread-root-id takes the thread's first message (msg_…), not ${opts.threadRootId}.`);
139
+ }
140
+ const { client, orgId } = resolveCredentials();
141
+ const found = await findConnector(client, orgId, ref);
142
+ if (!found)
143
+ throw clipNotFoundError(ref);
144
+ const connectorId = found.entry.id;
145
+ const name = found.entry.name || connectorId;
146
+ let result;
147
+ try {
148
+ result = await client.requestApproval(orgId, {
149
+ action_type: CLIP_CONNECTION_CONNECT_ACTION,
150
+ resource_uri: `prll://${connectorId}`,
151
+ chat_id: chatId,
152
+ ...(threadRootId !== undefined ? { thread_root_id: threadRootId } : {}),
153
+ title: name,
154
+ action_payload: {
155
+ reason,
156
+ owner: fromOrg ? `prll://${orgId}` : 'caller',
157
+ ...(opts.auth !== undefined ? { auth: opts.auth } : {}),
158
+ ...(opts.serverUrl !== undefined ? { server_url: opts.serverUrl } : {}),
159
+ ...(opts.name !== undefined ? { name: opts.name } : {}),
160
+ },
161
+ });
162
+ }
163
+ catch (err) {
164
+ printError(err, undefined, refusalStep(err, connectorId, name, opts));
165
+ }
166
+ printJson(result);
167
+ printProgress(fromOrg
168
+ ? `Tell the person, in their language: "I asked an admin on the card to connect ${name}."`
169
+ : `Tell the person, in their language: "I asked on the card to connect your ${name}: tap 连接 (Connect) and sign in; I'll continue once it is connected."`);
170
+ printFiledApproval(result, result.deduplicated ? 'Already waiting' : 'Created');
171
+ printProgress(`Meanwhile do the parts that do not need ${name}, then end your turn. The result arrives as an approval decision event — do not wait with \`parall approvals wait\`.`);
172
+ }
173
+ catch (err) {
174
+ printError(err);
175
+ }
176
+ });
177
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"clip.d.ts","sourceRoot":"","sources":["../../src/commands/clip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AA0MpC;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,QAUpD"}
1
+ {"version":3,"file":"clip.d.ts","sourceRoot":"","sources":["../../src/commands/clip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AA4GpC;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,QAUpD"}
@@ -1,3 +1,4 @@
1
+ import { registerClipConnectCommand } from './clip-connect.js';
1
2
  import { registerClipConnectionCommands } from './clip-connection.js';
2
3
  import { resolveCredentials } from '../lib/client.js';
3
4
  import { execEdgeClipWithBoundedWait } from '../lib/edge-exec.js';
@@ -5,7 +6,7 @@ import { getClipMCPConfigById, listClipMCPConnectionSummaries } from '../lib/mcp
5
6
  import { printJson, printError, parsePositiveInt } from '../lib/output.js';
6
7
  import { buildPublishedManifest, collectPublishSource } from '../lib/publish-source.js';
7
8
  import { readTextFileArg } from '../lib/text-input.js';
8
- import { CONNECTOR_USAGE_HINT } from '../lib/connector-ref.js';
9
+ import { CLIP_REF_HELP, CONNECTOR_USAGE_HINT, clipNotFoundError, findConnector, resolveRegistryRef, } from '../lib/connector-ref.js';
9
10
  const NO_ALIAS_HINT = 'no alias — reference this connection by its ccn_ id, or ask a human to name it in the Connector Console so callers can tell the accounts apart';
10
11
  function connectionAnnotations(conn, deviceById) {
11
12
  const out = { target: 'orphaned' };
@@ -63,87 +64,6 @@ async function loadDeviceIndex(client, orgId) {
63
64
  return null;
64
65
  }
65
66
  }
66
- const CLIP_REF_HELP = 'Registry connector id (crg_...), an exact connector name (your org first, then a unique public match), or org_<id>/<name> to pin the publisher (discover ids with `parall connector search`)';
67
- /**
68
- * The clip-ref grammar shared with the standalone Solo CLI
69
- * (desktop/edge/cli/parall-clip.mjs, parseClipRef) — the two install surfaces
70
- * must read the same ref the same way. Any slash makes a namespaced ref, and
71
- * only org ids are authoritative namespaces; throws on a malformed ref.
72
- */
73
- function parseClipRef(ref) {
74
- if (ref.startsWith('crg_'))
75
- return { id: ref };
76
- const slash = ref.indexOf('/');
77
- if (slash === -1)
78
- return { name: ref };
79
- const namespace = ref.slice(0, slash);
80
- const name = ref.slice(slash + 1);
81
- if (!namespace || !name || name.includes('/')) {
82
- throw new Error(`Invalid connector reference "${ref}". ${CLIP_REF_HELP}.`);
83
- }
84
- if (!namespace.startsWith('org_')) {
85
- throw new Error(`Publisher namespace "${namespace}" is not authoritative yet. Use an immutable crg_ id or org_<id>/${name}.`);
86
- }
87
- return { namespace, name };
88
- }
89
- /**
90
- * Resolve an install/info argument to a registry entry with per-name queries
91
- * only — never by listing the catalog, which spans every public clip on the
92
- * platform. Bare names resolve in the CALLER'S org first (an authoritative
93
- * point read immune to a third party publishing the same name), then fall
94
- * back to a unique exact match among visible public clips; several publishers
95
- * sharing the name is an explicit ambiguity error, never "first match wins".
96
- * Returns null on a clean not-found; non-404 errors (e.g. 403
97
- * CLIP_NOT_APPROVED) propagate untouched.
98
- */
99
- async function resolveRegistryRef(client, orgId, ref) {
100
- const notFoundToNull = (err) => {
101
- if (err.status === 404)
102
- return null;
103
- throw err;
104
- };
105
- const parsed = parseClipRef(ref);
106
- if ('id' in parsed) {
107
- return client.getRegistryClip(orgId, parsed.id).catch(notFoundToNull);
108
- }
109
- if ('namespace' in parsed) {
110
- return client.resolveRegistryClip(orgId, parsed.namespace, parsed.name).catch(notFoundToNull);
111
- }
112
- const own = await client.resolveRegistryClip(orgId, orgId, parsed.name).catch(notFoundToNull);
113
- if (own)
114
- return own;
115
- // Bare name, not published by the caller's org: accept a UNIQUE exact match
116
- // among visible clips. Search is fuzzy (name+description substrings), so
117
- // exact-filter its max-size page; a page-sized crowd of lookalikes could
118
- // still hide an exact match — the crg_ id and org_<id>/<name> forms stay
119
- // the always-sound addresses. A 404 here is a server without the search
120
- // route, not a lookup miss — degrade to "no matches" so the caller gets
121
- // the guidance error instead of a bare route error.
122
- const page = await client
123
- .searchOrgRegistryClips(orgId, parsed.name, { limit: 100 })
124
- .catch((err) => {
125
- if (err.status === 404)
126
- return [];
127
- throw err;
128
- });
129
- const matches = page.filter((c) => c.name === parsed.name);
130
- if (matches.length > 1) {
131
- const candidates = matches.map((c) => `${c.org_id}/${c.name} (${c.id})`).join(', ');
132
- throw new Error(`Connector name "${parsed.name}" is ambiguous across publishers: ${candidates}. Use the crg_ id or the org_<id>/<name> form.`);
133
- }
134
- // A FULL page proves nothing about uniqueness or absence: rows order by
135
- // (name, id), so the exact-name block can straddle the page boundary and a
136
- // single visible match — or none — may be a truncation artifact. Two exact
137
- // matches on the page prove ambiguity outright (handled above); otherwise
138
- // abstain rather than risk installing the wrong publisher's clip.
139
- if (page.length >= 100) {
140
- throw new Error(`Too many connectors have names or descriptions similar to "${parsed.name}" for a bare name to resolve safely. Pass the crg_ id or the org_<id>/<name> form (find them with \`parall connector search <text>\`).`);
141
- }
142
- return matches[0] ?? null;
143
- }
144
- function clipNotFoundError(ref) {
145
- return new Error(`No registry connector matching "${ref}". Pass a crg_ id, the exact name of a visible connector, or org_<id>/<name> to pin its publisher — discover ids with \`parall connector search <text>\`.`);
146
- }
147
67
  const CONNECTOR_DESCRIPTION = 'Discover, install and execute connectors installed in the organization';
148
68
  /**
149
69
  * `parall connector` is the command; `parall clip` registers the identical
@@ -164,6 +84,7 @@ export function registerClipCommands(program) {
164
84
  }
165
85
  function registerClipTree(clip) {
166
86
  registerClipConnectionCommands(clip);
87
+ registerClipConnectCommand(clip);
167
88
  clip
168
89
  .command('list')
169
90
  .description('List connectors installed in the organization, each with its connections — the --connection refs `connector exec` takes')
@@ -180,28 +101,29 @@ function registerClipTree(clip) {
180
101
  return;
181
102
  }
182
103
  const deviceById = await loadDeviceIndex(client, orgId);
183
- // One list answers both discovery questions — WHICH clip and WHERE it
184
- // can run — so an agent resolves "call <clip> for me" in a single
185
- // command instead of a per-clip connections crawl.
186
- const rows = await Promise.all(clips.map(async (c) => {
187
- const row = {
188
- id: c.id,
189
- name: c.name,
190
- ...(c.description ? { description: c.description } : {}),
191
- version: c.version ?? '-',
192
- visibility: c.visibility,
193
- };
194
- try {
195
- const resp = await client.listClipConnections(orgId, c.id);
196
- row.connections = execTargets(resp.data ?? []).map((conn) => summarizeConnection(conn, deviceById));
197
- }
198
- catch (err) {
199
- // One clip's broken connections read must not take down
200
- // discovery of every other clip — degrade that row, honestly.
201
- row.connections = null;
202
- row.connections_error = err instanceof Error ? err.message : String(err);
104
+ const connections = new Map();
105
+ let connectionsError;
106
+ try {
107
+ const { data } = await client.listAllClipConnections(orgId);
108
+ for (const conn of data ?? []) {
109
+ const group = connections.get(conn.clip_id) ?? [];
110
+ group.push(conn);
111
+ connections.set(conn.clip_id, group);
203
112
  }
204
- return row;
113
+ }
114
+ catch (err) {
115
+ connectionsError = err instanceof Error ? err.message : String(err);
116
+ }
117
+ const rows = clips.map((c) => ({
118
+ id: c.id,
119
+ name: c.name,
120
+ ...(c.description ? { description: c.description } : {}),
121
+ version: c.version ?? '-',
122
+ visibility: c.visibility,
123
+ connections: connectionsError === undefined
124
+ ? execTargets(connections.get(c.id) ?? []).map((conn) => summarizeConnection(conn, deviceById))
125
+ : null,
126
+ ...(connectionsError === undefined ? {} : { connections_error: connectionsError }),
205
127
  }));
206
128
  printJson(rows);
207
129
  }
@@ -290,26 +212,8 @@ function registerClipTree(clip) {
290
212
  .action(async (clip) => {
291
213
  try {
292
214
  const { client, orgId } = resolveCredentials();
293
- // Resolve installed-first (the historical semantic; the installed list
294
- // is org-local and uncapped), then fall back to point-querying the
295
- // registry: an author checking a clip they published but never
296
- // installed — the publish→review→revise loop — must not dead-end here.
297
- // The installed shortcut obeys the SAME bare-name contract as
298
- // resolveRegistryRef: an org can install same-name clips from several
299
- // publishers (installs are keyed by id), so a plain first-match would
300
- // show an arbitrary one — own org wins, and a foreign tie is the same
301
- // explicit ambiguity error, never a silent pick.
302
- const installed = await client.listInstalledRegistryClips(orgId);
303
- const byId = installed.find((c) => c.id === clip);
304
- const byName = byId ? [] : installed.filter((c) => c.name === clip);
305
- let found = byId ?? byName.find((c) => c.org_id === orgId);
306
- if (!found && byName.length > 1) {
307
- const candidates = byName.map((c) => `${c.org_id}/${c.name} (${c.id})`).join(', ');
308
- printError(new Error(`Several installed connectors are named "${clip}": ${candidates}. Use the crg_ id or the org_<id>/<name> form.`));
309
- return;
310
- }
311
- found ??= byName[0];
312
- let entry = found ?? (await resolveRegistryRef(client, orgId, clip));
215
+ const found = await findConnector(client, orgId, clip);
216
+ let entry = found?.entry ?? null;
313
217
  // The detail read is what carries review_status/review_note (server
314
218
  // attaches them only for the owning org; the resolve read does not).
315
219
  // resolveRegistryRef's crg_ branch IS that detail read already. A
@@ -318,7 +222,7 @@ function registerClipTree(clip) {
318
222
  // back to it rather than failing info. Any OTHER failure (auth, 5xx,
319
223
  // network) must surface: silently printing partial data would report
320
224
  // a broken read as success.
321
- const alreadyDetail = !found && clip.startsWith('crg_');
225
+ const alreadyDetail = found?.installed === false && clip.startsWith('crg_');
322
226
  if (entry && !alreadyDetail) {
323
227
  try {
324
228
  entry = await client.getRegistryClip(orgId, entry.id);
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerCloudProfileCommands(program: Command): void;
3
+ //# sourceMappingURL=cloud-profile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-profile.d.ts","sourceRoot":"","sources":["../../src/commands/cloud-profile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAmGpC,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAqGnE"}
@@ -0,0 +1,145 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { ApiError } from '@parall/sdk';
6
+ import { resolveCredentials } from '../lib/client.js';
7
+ import { printError, printJson, printProgress, stripPrllScheme } from '../lib/output.js';
8
+ function agentID(raw) {
9
+ const id = stripPrllScheme(raw);
10
+ if (!/^usr_[A-Za-z0-9_-]+$/.test(id))
11
+ throw new Error('Expected an Agent usr_ ID or prll://usr_ URI. Run: parall cloud-profile access <usr_id>');
12
+ return id;
13
+ }
14
+ async function submit(client, request) {
15
+ return request.action === 'create'
16
+ ? client.createAuthorizedHostedProfile(request.org, request.target, request.key)
17
+ : client.changeHostedProfileCreationGrant(request.org, request.target, request.change, request.key, request.action === 'revoke');
18
+ }
19
+ function saveRequest(request) {
20
+ const directory = join(homedir(), '.parall', 'cloud-profile-requests');
21
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
22
+ const path = join(directory, `${request.key}.json`);
23
+ writeFileSync(path, JSON.stringify(request), { flag: 'wx', mode: 0o600 });
24
+ return path;
25
+ }
26
+ async function mutation(action, target, options) {
27
+ if (action !== 'create')
28
+ target = agentID(target);
29
+ if (!target.trim() || [...target.trim()].length > 128)
30
+ throw new Error('Name must have 1–128 characters. Run: parall cloud-profile create <name>');
31
+ const { client, orgId } = resolveCredentials();
32
+ const me = await client.getMe();
33
+ const request = { org: orgId, actor: me.id, action, target, key: randomUUID() };
34
+ if (action !== 'create') {
35
+ const access = await client.getHostedProfileCreationAccess(orgId, target);
36
+ if (action === 'grant' && access.grant && !access.grant.revoked_at)
37
+ throw new Error(`Authorization already exists. Run: parall cloud-profile update ${target} --max <count> --expires-at <ISO-time>`);
38
+ if (action !== 'grant' && !access.grant)
39
+ throw new Error(`No authorization. Run: parall cloud-profile grant ${target}`);
40
+ const maximum = Number(options.max ?? (action === 'grant' ? 3 : access.grant.max_creations));
41
+ const expiry = options.expiresAt ??
42
+ (action === 'grant'
43
+ ? new Date(Date.now() + 30 * 86400000).toISOString()
44
+ : access.grant.expires_at);
45
+ if (!Number.isInteger(maximum) ||
46
+ maximum < 1 ||
47
+ maximum > 2147483647 ||
48
+ !Number.isFinite(Date.parse(expiry)))
49
+ throw new Error('Use --max <positive count> and --expires-at <ISO-time>. Run: parall cloud-profile grant --help');
50
+ request.change = {
51
+ expected_revision: access.grant?.revision ?? 0,
52
+ max_creations: maximum,
53
+ expires_at: new Date(expiry).toISOString(),
54
+ };
55
+ }
56
+ const file = saveRequest(request);
57
+ // Persist before sending; on failure never generate a second mutation key.
58
+ printProgress(`Recover this exact request if its outcome is unknown: parall cloud-profile recover ${JSON.stringify(file)}`);
59
+ try {
60
+ printJson(await submit(client, request));
61
+ }
62
+ catch (error) {
63
+ printProgress(error instanceof ApiError && error.status >= 400 && error.status < 500
64
+ ? `Authorization or request rejected. Ask a human org administrator to inspect it: parall cloud-profile access ${action === 'create' ? me.id : target}`
65
+ : `Do not create a replacement request. Run: parall cloud-profile recover ${JSON.stringify(file)}`);
66
+ throw error;
67
+ }
68
+ }
69
+ export function registerCloudProfileCommands(program) {
70
+ const cloud = program
71
+ .command('cloud-profile')
72
+ .description('Self-create empty hosted Profiles within a human-granted allowance. Creation is free; execution spending is not limited. Proxy credentials and website login remain human tasks.');
73
+ const run = (fn) => async (...args) => {
74
+ try {
75
+ await fn(...args);
76
+ }
77
+ catch (error) {
78
+ printError(error);
79
+ }
80
+ };
81
+ cloud
82
+ .command('access')
83
+ .argument('[agent]', 'Agent usr_ ID; omitted means yourself')
84
+ .action(run(async (raw) => {
85
+ const { client, orgId } = resolveCredentials();
86
+ const target = raw ? agentID(raw) : (await client.getMe()).id;
87
+ const access = await client.getHostedProfileCreationAccess(orgId, target);
88
+ printJson({
89
+ ...access,
90
+ next_command: access.state === 'active'
91
+ ? 'parall cloud-profile create <name>'
92
+ : `parall cloud-profile access ${target}`,
93
+ hint: access.state === 'active'
94
+ ? 'Creates an empty hosted Profile; execution spending is not limited.'
95
+ : 'Ask a human organization administrator to inspect the grant. Existing Profile access is separate.',
96
+ });
97
+ }));
98
+ for (const action of ['grant', 'update', 'revoke']) {
99
+ cloud
100
+ .command(action)
101
+ .argument('<agent>', 'Agent usr_ ID or prll:// URI')
102
+ .description(action === 'revoke'
103
+ ? 'Stop new creations; retain existing resources and Profile access.'
104
+ : 'Human owner/admin only. Deletion never refunds the cumulative allowance; no execution budget is imposed.')
105
+ .option('--max <count>', 'Cumulative creation maximum (grant default: 3)')
106
+ .option('--expires-at <ISO-time>', 'Absolute expiry (grant default: 30 days)')
107
+ .action(run(async (target, options) => mutation(action, target, options)));
108
+ }
109
+ cloud
110
+ .command('create')
111
+ .argument('<name>', 'Name of the empty hosted Profile')
112
+ .action(run(async (name) => mutation('create', name, {})));
113
+ cloud
114
+ .command('events')
115
+ .argument('[agent]', 'Agent usr_ ID; omitted means yourself')
116
+ .option('--before <event-id>', 'Fetch older events using next_before')
117
+ .action(run(async (raw, options) => {
118
+ const { client, orgId } = resolveCredentials();
119
+ const target = raw ? agentID(raw) : (await client.getMe()).id;
120
+ const before = options.before ? Number(options.before) : undefined;
121
+ if (before !== undefined && (!Number.isSafeInteger(before) || before < 0))
122
+ throw new Error('Use --before <nonnegative event-id>. Run: parall cloud-profile events --help');
123
+ printJson(await client.getHostedProfileCreationEvents(orgId, target, before));
124
+ }));
125
+ cloud
126
+ .command('recover')
127
+ .argument('<file>', 'Saved request path printed by a mutation')
128
+ .action(run(async (file) => {
129
+ const saved = JSON.parse(readFileSync(resolve(file), 'utf8'));
130
+ const { client, orgId } = resolveCredentials();
131
+ const me = await client.getMe();
132
+ if (saved.org !== orgId ||
133
+ saved.actor !== me.id ||
134
+ !['create', 'grant', 'update', 'revoke'].includes(saved.action) ||
135
+ !saved.key ||
136
+ typeof saved.target !== 'string')
137
+ throw new Error('This request does not belong to the current organization and identity. Select its original credentials, then run: parall cloud-profile recover <file>');
138
+ if (saved.action !== 'create') {
139
+ saved.target = agentID(saved.target);
140
+ if (!saved.change)
141
+ throw new Error('Saved authorization request is incomplete. Inspect the current grant with: parall cloud-profile access <usr_id>');
142
+ }
143
+ printJson(await submit(client, saved));
144
+ }));
145
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../../src/commands/secrets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAUpC,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,QA2EtD"}
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../../src/commands/secrets.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAyGpC,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,QA8FtD"}