@antasphere/cli-core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/connect.ts CHANGED
@@ -6,16 +6,25 @@ import { CliAuthError, type CliAuthMintedKey } from './auth.js';
6
6
  * API key is traded for a tool-local key in two calls:
7
7
  *
8
8
  * 1. POST {hub}/api/v1/sso/tool-token — auth = hub API key (Bearer),
9
- * body `{ resource, workspaceId? }` → a single-org, 120-second JWT
10
- * for the tool's resource URL. The token is OPAQUE to this client:
11
- * it is relayed hub → tool, never inspected or stored.
9
+ * body `{ resource }` → a USER-scoped, 120-second JWT for the tool's
10
+ * resource URL plus a one-time `hubRefreshToken` (the tool's standing
11
+ * offline grant for live as-the-user hub reads). Both are OPAQUE to
12
+ * this client: relayed hub → tool, never inspected or stored. The
13
+ * exchange names NO organization (hub ADR 014): the credential
14
+ * identifies the user; the organization is a per-request parameter
15
+ * tool-side, the hub's server-side default unless `--org` says
16
+ * otherwise.
12
17
  * 2. POST {tool}/api/v1/sso/cli-connect — NO auth header (the JWT is
13
- * the credential), body `{ token }` → the tool verifies, JIT-provisions,
14
- * and mints an ordinary tool-local API key, returned exactly once.
18
+ * the credential), body `{ token, hubRefreshToken }` → the tool
19
+ * verifies, JIT-provisions, stores the grant, and mints an ordinary
20
+ * USER-scoped tool-local API key, returned exactly once.
15
21
  *
16
22
  * The hub key is sent to the HUB only — it never reaches the tool. The
17
- * minted key is cached per (tool, hub org) in the tool's config namespace
18
- * (config.ts `workspaceKeys`); day-to-day tool CLI calls then take the
23
+ * hubRefreshToken is sent to the TOOL only (it is that tool's own grant;
24
+ * redeeming it needs the tool client's credentials) and never persisted by
25
+ * the CLI. The minted key is cached per (tool profile, hub profile) in the
26
+ * tool's config namespace (config.ts `connectKeys`), on the profile of the
27
+ * instance it was minted for; day-to-day tool CLI calls then take the
19
28
  * ordinary local API-key path with the hub out of the loop.
20
29
  */
21
30
 
@@ -26,10 +35,10 @@ export type CliConnectStage = 'hub' | 'tool';
26
35
  * pick the remedy without string-matching:
27
36
  *
28
37
  * - hub 400 `unknown_resource` — the resource URL is not in the registry.
29
- * - hub 403 `no_membership` / `workspace_suspended` — the target org is
30
- * not exchangeable for this user; pick another org.
31
38
  * - `needsHubLogin` — the hub rejected the KEY itself; re-run
32
39
  * `antasphere login`.
40
+ * - `refusal` — the account was refused (403), not the key: print the
41
+ * server's own sentence and exit 3. No login fixes it.
33
42
  * - `needsReExchange` — the tool rejected the 120 s JWT (expired/replayed
34
43
  * in transit); run the exchange again.
35
44
  * - tool 429 `rate_limited` — back off and retry.
@@ -62,23 +71,43 @@ export class CliConnectError extends CliAuthError {
62
71
  get needsReExchange(): boolean {
63
72
  return this.stage === 'tool' && this.status === 401;
64
73
  }
74
+
75
+ /**
76
+ * The person was refused, not the credential: a 403 that is not the
77
+ * scope case, from either side (`tool_access_denied` on a restricted
78
+ * tool, `unverified_email`, a grant the tool will not take). `message`
79
+ * is the server's own sentence; a runner prints it as is and exits
80
+ * `exitCode`, 3, the code the tool docs promise for a refusal.
81
+ */
82
+ get refusal(): boolean {
83
+ return this.status === 403 && !this.needsHubLogin;
84
+ }
85
+
86
+ /** The exit code a runner uses for this error: 3 for a refusal, 1 otherwise. */
87
+ get exitCode(): number {
88
+ return this.refusal ? 3 : 1;
89
+ }
65
90
  }
66
91
 
67
92
  export interface CliToolTokenBody {
68
- /** The tool's registry resource URL (e.g. `https://app.slideless.ai/mcp`). */
93
+ /** The tool's registry resource URL (e.g. `https://app.slideless.ai/mcp`).
94
+ * The ONLY field — the exchange is user-scoped and names no org
95
+ * (hub contract `ssoToolTokenRequestSchema`, ADR 014). */
69
96
  resource: string;
70
- /** Target hub org — any live ACTIVE membership of the user (gcloud
71
- * model); omit = the hub key's bound workspace. */
72
- workspaceId?: string;
73
97
  }
74
98
 
99
+ /** The hub's tool-token response (hub contract `ssoToolTokenSchema`). */
75
100
  export interface CliToolTokenMinted {
76
- /** The single-org exchange JWT — opaque, ~120 s; relay it, never keep it. */
101
+ /** The user-scoped exchange JWT — opaque, ~120 s; relay it, never keep it. */
77
102
  token: string;
78
103
  /** ISO expiry of the JWT (informational; the minted key outlives it). */
79
104
  expiresAt: string;
80
- /** The hub org the token was minted for (explicit target or the key's bound org). */
81
- workspaceId: string;
105
+ /** The raw one-time offline-grant refresh token for the TARGET TOOL —
106
+ * relayed to that tool's /sso/cli-connect exactly once (it stores it as
107
+ * the standing grant for live as-the-user hub reads) and NEVER persisted
108
+ * or logged by the CLI. Without it, a fresh CLI user's connect is
109
+ * refused tool-side (`hub_grant_missing` — no key is minted born-dead). */
110
+ hubRefreshToken: string;
82
111
  }
83
112
 
84
113
  export interface CliConnected {
@@ -86,20 +115,21 @@ export interface CliConnected {
86
115
  key: string;
87
116
  apiKey: CliAuthMintedKey;
88
117
  user: { id: string; email: string; name: string };
89
- /** The tool-local workspace the key is bound to (the hub org's projection). */
90
- workspaceId: string;
118
+ /** The tool workspace the key is PINNED to — null on the live contract
119
+ * (user-scoped, unpinned; the org is a per-request parameter). */
120
+ workspaceId: string | null;
91
121
  }
92
122
 
93
- /** The flattened outcome of a full exchange — everything a CLI caches. */
123
+ /** The flattened outcome of a full exchange. */
94
124
  export interface CliConnectResult {
95
- /** Full tool-local key — cache it per (tool, `hubWorkspaceId`). */
125
+ /** Full tool-local key — user-scoped: ONE per (tool profile, hub profile),
126
+ * valid for every org the user can select per request (config.ts). */
96
127
  key: string;
97
128
  apiKey: CliAuthMintedKey;
98
129
  user: { id: string; email: string; name: string };
99
- /** The HUB org the exchange resolved to — the cache key (config.ts). */
100
- hubWorkspaceId: string;
101
- /** The tool-local workspace the minted key is bound to (informational). */
102
- toolWorkspaceId: string;
130
+ /** The tool workspace the key is pinned to — null = unpinned (the live
131
+ * contract always answers null; informational). */
132
+ toolWorkspaceId: string | null;
103
133
  }
104
134
 
105
135
  export interface CliConnectClientOptions {
@@ -121,25 +151,33 @@ export class CliConnectClient {
121
151
  this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
122
152
  }
123
153
 
124
- /** Step 1 — the hub mints the 120 s single-org JWT for the tool's resource. */
154
+ /** Step 1 — the hub mints the 120 s user-scoped JWT for the tool's resource. */
125
155
  toolToken(hubApiKey: string, body: CliToolTokenBody): Promise<CliToolTokenMinted> {
126
156
  return this.call('hub', `${this.hubBaseUrl}/api/v1/sso/tool-token`, body, hubApiKey);
127
157
  }
128
158
 
129
- /** Step 2 — the tool verifies the JWT (its only credential) and mints its key. */
130
- cliConnect(token: string): Promise<CliConnected> {
131
- return this.call('tool', `${this.toolBaseUrl}/api/v1/sso/cli-connect`, { token });
159
+ /**
160
+ * Step 2 — the tool verifies the JWT (its only credential) and mints its
161
+ * key. `hubRefreshToken` is the SAME response's offline grant, relayed so
162
+ * the tool can store it (a grant-less connect is refused for users with
163
+ * none already stored — `hub_grant_missing`).
164
+ */
165
+ cliConnect(token: string, hubRefreshToken?: string): Promise<CliConnected> {
166
+ return this.call('tool', `${this.toolBaseUrl}/api/v1/sso/cli-connect`, {
167
+ token,
168
+ ...(hubRefreshToken ? { hubRefreshToken } : {})
169
+ });
132
170
  }
133
171
 
134
- /** The full two-call exchange. The hub key goes to the hub ONLY. */
172
+ /** The full two-call exchange. The hub key goes to the hub ONLY; the
173
+ * offline grant goes to the TOOL only — neither is ever persisted here. */
135
174
  async exchange(hubApiKey: string, body: CliToolTokenBody): Promise<CliConnectResult> {
136
175
  const minted = await this.toolToken(hubApiKey, body);
137
- const connected = await this.cliConnect(minted.token);
176
+ const connected = await this.cliConnect(minted.token, minted.hubRefreshToken);
138
177
  return {
139
178
  key: connected.key,
140
179
  apiKey: connected.apiKey,
141
180
  user: connected.user,
142
- hubWorkspaceId: minted.workspaceId,
143
181
  toolWorkspaceId: connected.workspaceId
144
182
  };
145
183
  }
package/src/index.ts CHANGED
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * @antasphere/cli-core — the shared foundation every Antasphere tool CLI
3
3
  * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
- * with tool-namespaced profiles, the flag → env → profile → default URL
5
- * resolution order, the instance email-OTP auth client, the hub→tool
6
- * cross-tool connect exchange (+ its per-(tool, org) key cache, the
7
- * hub-profile org context, and the connect-on-demand seam a tool CLI runs
8
- * when no direct credential resolved), and the CliIo prompt seam. Tool
4
+ * with tool-namespaced profiles where A PROFILE IS AN INSTANCE (named for
5
+ * its host, the implicit `cloud` profile at the tool's cloud URL), the
6
+ * profile selection rule (--profile → instance URL → active → cloud), the
7
+ * flag → env → profile → cloud URL resolution order, the per-command
8
+ * organization override (`resolveOrg`; the hub's server-side default
9
+ * organization applies otherwise), the instance email-OTP auth client, the
10
+ * hub→tool cross-tool connect exchange (user-scoped, no org in the
11
+ * exchange) with its per-(tool profile, hub profile) key cache, the
12
+ * connect-on-demand seam a tool CLI runs when no direct credential
13
+ * resolved, the stranded-key recovery, and the CliIo prompt seam. Tool
9
14
  * commands, wire types, and API surfaces live in the tools; this package
10
15
  * carries only config/login plumbing, never secrets.
11
16
  */
@@ -16,20 +21,49 @@ export {
16
21
  configPath,
17
22
  HUB_TOOL,
18
23
  loadConfig,
19
- lookupWorkspaceKey,
24
+ lookupConnectKey,
20
25
  parseConfig,
26
+ profileCredential,
21
27
  redactKey,
22
- removeWorkspaceKey,
28
+ removeConnectKey,
23
29
  saveConfig,
24
- storeWorkspaceKey
30
+ storeConnectKey
31
+ } from './config.js';
32
+ export type {
33
+ CliConfig,
34
+ CliConnectKey,
35
+ CliEnv,
36
+ CliProfile,
37
+ ProfileCredential,
38
+ StoreConnectKeyOptions
25
39
  } from './config.js';
26
- export type { CliConfig, CliEnv, CliProfile, CliWorkspaceKey } from './config.js';
27
40
 
28
41
  export { ask, printJson } from './io.js';
29
42
  export type { CliIo } from './io.js';
30
43
 
31
- export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
32
- export type { ResolveApiKeyOptions, ResolveBaseUrlOptions, ResolvedProfile } from './resolve.js';
44
+ export {
45
+ CLOUD_PROFILE,
46
+ CliUsageError,
47
+ firstSet,
48
+ normalizeUrl,
49
+ profileNameFor,
50
+ profileUrl,
51
+ resolveApiKey,
52
+ resolveBaseUrl,
53
+ resolveOrg,
54
+ resolveProfile,
55
+ sameInstance,
56
+ selectProfile
57
+ } from './resolve.js';
58
+ export type {
59
+ ProfileSource,
60
+ ResolveApiKeyOptions,
61
+ ResolveBaseUrlOptions,
62
+ ResolveOrgOptions,
63
+ ResolvedProfile,
64
+ SelectProfileOptions,
65
+ SelectedProfile
66
+ } from './resolve.js';
33
67
 
34
68
  export { CliAuthClient, CliAuthError } from './auth.js';
35
69
  export type {
@@ -52,7 +86,12 @@ export type {
52
86
  CliToolTokenMinted
53
87
  } from './connect.js';
54
88
 
55
- export { connectOnDemand, probeToolInstance } from './connect-on-demand.js';
89
+ export {
90
+ activeHubProfile,
91
+ connectOnDemand,
92
+ probeToolInstance,
93
+ refreshConnectKey
94
+ } from './connect-on-demand.js';
56
95
  export type {
57
96
  ConnectNoticeFacts,
58
97
  ConnectOnDemandMessages,
@@ -61,8 +100,5 @@ export type {
61
100
  ToolInstanceProbe
62
101
  } from './connect-on-demand.js';
63
102
 
64
- export { getActiveWorkspace, resolveTargetWorkspace, setActiveWorkspace } from './org.js';
65
- export type { OrgContextOptions, ResolveTargetWorkspaceOptions } from './org.js';
66
-
67
103
  export { migrateLegacyConfig } from './migrate.js';
68
104
  export type { LegacyMigrationSpec, MigrationResult } from './migrate.js';
package/src/resolve.ts CHANGED
@@ -1,10 +1,28 @@
1
1
  import type { CliConfig, CliEnv, CliProfile } from './config.js';
2
2
 
3
- /** A usage-level error: runners print `Error: <message>` and exit 1. */
4
- export class CliUsageError extends Error {}
3
+ /**
4
+ * A usage-level error: runners print `Error: <message>` and exit with
5
+ * `exitCode`. 1 is a usage or wire error; 3 is a refusal, the code the tool
6
+ * docs promise when the account may not do what it asked (the thrower says
7
+ * so, nothing else does).
8
+ */
9
+ export class CliUsageError extends Error {
10
+ readonly exitCode: number;
11
+
12
+ constructor(message: string, opts: { exitCode?: number } = {}) {
13
+ super(message);
14
+ this.name = 'CliUsageError';
15
+ this.exitCode = opts.exitCode ?? 1;
16
+ }
17
+ }
5
18
 
6
- /** The profile name tools fall back to when none is named or active. */
7
- export const DEFAULT_PROFILE = 'default';
19
+ /**
20
+ * The implicit profile every tool CLI has at its cloud URL. It exists before
21
+ * anything is written to disk: a clean machine with an `antasphere login`
22
+ * runs the tool on it. `default` is not a magic name any more, just a
23
+ * profile a person may have.
24
+ */
25
+ export const CLOUD_PROFILE = 'cloud';
8
26
 
9
27
  export interface ResolvedProfile {
10
28
  /** The resolved profile name (undefined = flags/env only, nothing stored). */
@@ -20,7 +38,7 @@ export interface ResolvedProfile {
20
38
  export function resolveProfile(
21
39
  config: CliConfig,
22
40
  requested: string | undefined,
23
- opts: { unknownHint?: string } = {}
41
+ opts: { unknownHint?: string | undefined } = {}
24
42
  ): ResolvedProfile {
25
43
  if (requested) {
26
44
  const profile = config.profiles[requested];
@@ -36,6 +54,181 @@ export function resolveProfile(
36
54
  return { name: profile ? name : undefined, profile };
37
55
  }
38
56
 
57
+ /**
58
+ * The comparable form of an instance URL: the scheme, the host (case-folded,
59
+ * port kept) and the path without trailing slashes; query and fragment
60
+ * dropped. Two URLs name the same instance when their normalized forms are
61
+ * equal. A string the URL parser refuses is only stripped of its trailing
62
+ * slashes.
63
+ */
64
+ export function normalizeUrl(url: string): string {
65
+ try {
66
+ const u = new URL(url);
67
+ return `${u.protocol}//${u.host}${u.pathname}`.replace(/\/+$/, '');
68
+ } catch {
69
+ return url.replace(/\/+$/, '');
70
+ }
71
+ }
72
+
73
+ /** Whether two URLs name the same instance (`normalizeUrl` equality). */
74
+ export function sameInstance(a: string, b: string): boolean {
75
+ return normalizeUrl(a) === normalizeUrl(b);
76
+ }
77
+
78
+ /**
79
+ * The name an instance URL's profile gets when nothing named it: `cloud`
80
+ * for the tool's cloud URL, else the host with its port
81
+ * (`share.antasphere.com`, `localhost:3400`). The person may rename it.
82
+ */
83
+ export function profileNameFor(url: string, cloudUrl?: string | undefined): string {
84
+ if (cloudUrl && sameInstance(url, cloudUrl)) return CLOUD_PROFILE;
85
+ try {
86
+ return new URL(url).host;
87
+ } catch {
88
+ return normalizeUrl(url).replace(/^[a-z][a-z0-9+.-]*:\/\//i, '');
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The first value that is set, trimmed. An empty or whitespace-only flag,
94
+ * env var or profile field counts as unset and the next source applies (a
95
+ * `.env` leftover such as `SLIDELESS_URL=""` never hides the cloud URL).
96
+ */
97
+ export function firstSet(...values: Array<string | undefined>): string | undefined {
98
+ for (const v of values) {
99
+ const t = v?.trim();
100
+ if (t) return t;
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ /** The instance a profile is at: its `baseUrl`, else the tool's cloud URL.
106
+ * A blank `baseUrl` is no `baseUrl`. */
107
+ export function profileUrl(profile: CliProfile, cloudUrl: string | undefined): string | undefined {
108
+ return firstSet(profile.baseUrl, cloudUrl);
109
+ }
110
+
111
+ /**
112
+ * The profile on disk at an instance, if any. When several name it: the
113
+ * active one, then the one named `cloud`, then the first declared.
114
+ */
115
+ function profileAt(
116
+ config: CliConfig,
117
+ url: string,
118
+ cloudUrl: string | undefined
119
+ ): { name: string; profile: CliProfile } | undefined {
120
+ const at = Object.entries(config.profiles).filter(([, p]) => {
121
+ const u = profileUrl(p, cloudUrl);
122
+ return u !== undefined && sameInstance(u, url);
123
+ });
124
+ const pick =
125
+ at.find(([name]) => name === config.activeProfile) ??
126
+ at.find(([name]) => name === CLOUD_PROFILE) ??
127
+ at[0];
128
+ return pick ? { name: pick[0], profile: pick[1] } : undefined;
129
+ }
130
+
131
+ /**
132
+ * A profile made in memory for an instance nothing on disk names, under a
133
+ * name nothing on disk has: `cloud` for the cloud URL, else the host; when
134
+ * that name belongs to a profile at ANOTHER instance, the host, then
135
+ * `<host>-2`, `<host>-3`, … so `storeConnectKey` never writes onto a
136
+ * profile that is not this instance's.
137
+ */
138
+ function freshProfileAt(
139
+ config: CliConfig,
140
+ url: string,
141
+ cloudUrl: string | undefined
142
+ ): { name: string; profile: CliProfile } {
143
+ const host = profileNameFor(url);
144
+ let name = [profileNameFor(url, cloudUrl), host].find((c) => !(c in config.profiles));
145
+ for (let n = 2; name === undefined; n += 1) {
146
+ if (!(`${host}-${n}` in config.profiles)) name = `${host}-${n}`;
147
+ }
148
+ return { name, profile: { baseUrl: normalizeUrl(url) } };
149
+ }
150
+
151
+ /** The rule that picked the profile. */
152
+ export type ProfileSource = 'flag' | 'url' | 'active' | 'cloud';
153
+
154
+ export interface SelectedProfile extends ResolvedProfile {
155
+ /** Which rule chose it; undefined when nothing could be selected. */
156
+ source: ProfileSource | undefined;
157
+ /**
158
+ * true = the profile is not on disk yet: it was made in memory for the
159
+ * instance URL given, or it is the implicit cloud profile, under a name
160
+ * no profile on disk has. `storeConnectKey` writes it on first contact,
161
+ * nothing else does.
162
+ */
163
+ created: boolean;
164
+ }
165
+
166
+ export interface SelectProfileOptions {
167
+ config: CliConfig;
168
+ /** Value of --profile when given: wins over everything, must exist. */
169
+ requested?: string | undefined;
170
+ /**
171
+ * The instance URL the run was pointed at, when one was: --api-url, else
172
+ * the tool's URL env var (the caller applies that order; a blank value
173
+ * counts as none). It selects the profile of that instance, or makes one
174
+ * in memory named for its host.
175
+ */
176
+ apiUrl?: string | undefined;
177
+ /** The tool's cloud home; the implicit `cloud` profile lives there. */
178
+ cloudUrl?: string | undefined;
179
+ /** Appended to the unknown-profile error, e.g. 'run `slideless profiles`'. */
180
+ unknownHint?: string;
181
+ }
182
+
183
+ /**
184
+ * A profile is an instance. The selection rule every tool CLI applies, in
185
+ * this order:
186
+ *
187
+ * 1. --profile <name>: that profile, which must exist.
188
+ * 2. --api-url / the URL env var: the profile whose instance that is (the
189
+ * active one first when several name it, then `cloud`, then the first
190
+ * declared); none → a profile made in memory, named for the host under
191
+ * a free name (`created: true`), so a cached key never travels to
192
+ * another origin and nothing is ever written onto another instance's
193
+ * profile.
194
+ * 3. The active profile, the choice the person made with `<tool> use`.
195
+ * 4. The profile at `cloudUrl`, `cloud` by default: the one on disk at
196
+ * that instance whatever its name (a `cloud` profile that lives
197
+ * elsewhere is not it), else made in memory under a free name
198
+ * (`created: true`).
199
+ *
200
+ * A profile with no `baseUrl` is at the cloud URL. Nothing here writes to
201
+ * disk, and no profile is ever repointed. A tool without a cloud URL and
202
+ * without a profile selects nothing (both fields undefined), and its URL
203
+ * resolution errors with the tool's own message.
204
+ */
205
+ export function selectProfile(opts: SelectProfileOptions): SelectedProfile {
206
+ const { config, cloudUrl } = opts;
207
+
208
+ if (opts.requested) {
209
+ const { name, profile } = resolveProfile(config, opts.requested, { unknownHint: opts.unknownHint });
210
+ return { name, profile, source: 'flag', created: false };
211
+ }
212
+
213
+ const apiUrl = firstSet(opts.apiUrl);
214
+ if (apiUrl) {
215
+ const found = profileAt(config, apiUrl, cloudUrl);
216
+ if (found) return { ...found, source: 'url', created: false };
217
+ return { ...freshProfileAt(config, apiUrl, cloudUrl), source: 'url', created: true };
218
+ }
219
+
220
+ const active = resolveProfile(config, undefined);
221
+ if (active.name && active.profile) return { ...active, source: 'active', created: false };
222
+
223
+ if (cloudUrl) {
224
+ const found = profileAt(config, cloudUrl, cloudUrl);
225
+ if (found) return { ...found, source: 'cloud', created: false };
226
+ return { ...freshProfileAt(config, cloudUrl, cloudUrl), source: 'cloud', created: true };
227
+ }
228
+
229
+ return { name: undefined, profile: undefined, source: undefined, created: false };
230
+ }
231
+
39
232
  export interface ResolveBaseUrlOptions {
40
233
  /** Value of --api-url (or an alias) when given. */
41
234
  flag?: string | undefined;
@@ -43,19 +236,25 @@ export interface ResolveBaseUrlOptions {
43
236
  /** The tool's URL env var, e.g. 'ANTASPHERE_URL' / 'SLIDELESS_URL'. */
44
237
  envVar: string;
45
238
  profile?: CliProfile | undefined;
46
- /** Optional tool default (the hub has one; self-hosted tools error instead). */
47
- defaultUrl?: string;
48
- /** Error text when nothing resolves and there is no default. */
239
+ /**
240
+ * The tool's cloud home, the last fallback: every CLI that has a cloud
241
+ * instance ships it (`https://slideless.antasphere.com`), so a clean
242
+ * machine with an `antasphere login` needs no flag. A tool with none (a
243
+ * template placeholder) errors with `missingMessage` as before.
244
+ */
245
+ cloudUrl?: string | undefined;
246
+ /** Error text when nothing resolves and there is no cloud URL. */
49
247
  missingMessage?: string;
50
248
  }
51
249
 
52
250
  /**
53
251
  * Base-URL resolution in the ecosystem-wide order:
54
- * flag → tool env var → profile → optional default → CliUsageError.
55
- * The result is origin-normalized (trailing slashes stripped).
252
+ * flag → tool env var → profile → cloud URL → CliUsageError.
253
+ * A blank value counts as unset (the next source applies). The result is
254
+ * origin-normalized (trailing slashes stripped).
56
255
  */
57
256
  export function resolveBaseUrl(opts: ResolveBaseUrlOptions): string {
58
- const raw = opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.baseUrl ?? opts.defaultUrl;
257
+ const raw = firstSet(opts.flag, opts.env[opts.envVar], opts.profile?.baseUrl, opts.cloudUrl);
59
258
  if (!raw) {
60
259
  throw new CliUsageError(
61
260
  opts.missingMessage ?? `No instance configured — pass --api-url <url> or set ${opts.envVar}.`
@@ -73,7 +272,29 @@ export interface ResolveApiKeyOptions {
73
272
  profile?: CliProfile | undefined;
74
273
  }
75
274
 
76
- /** API-key resolution: flag → tool env var → profile (undefined = public only). */
275
+ /** API-key resolution: flag → tool env var → profile (undefined = public
276
+ * only); a blank value counts as unset. */
77
277
  export function resolveApiKey(opts: ResolveApiKeyOptions): string | undefined {
78
- return opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.apiKey;
278
+ return firstSet(opts.flag, opts.env[opts.envVar], opts.profile?.apiKey);
279
+ }
280
+
281
+ export interface ResolveOrgOptions {
282
+ /** Value of --org when given: a hub organization id or name. */
283
+ flag?: string | undefined;
284
+ env: CliEnv;
285
+ /** The tool's org env var, e.g. 'ANTASPHERE_ORG' / 'SLIDELESS_ORG'. */
286
+ envVar: string;
287
+ }
288
+
289
+ /**
290
+ * The organization override for one command: --org, else the tool's org
291
+ * env var, else undefined. There is one organization notion in the family:
292
+ * the hub's server-side default organization applies when this answers
293
+ * undefined, and the override names a hub organization (id or name) that
294
+ * the tool maps to its own workspace through `central_account_id`. An empty
295
+ * or blank value counts as unset and the next source applies. Nothing is
296
+ * stored on this machine; nothing here ever reaches the exchange.
297
+ */
298
+ export function resolveOrg(opts: ResolveOrgOptions): string | undefined {
299
+ return firstSet(opts.flag, opts.env[opts.envVar]);
79
300
  }
package/dist/org.d.ts DELETED
@@ -1,42 +0,0 @@
1
- import { type CliEnv } from './config.js';
2
- /**
3
- * Org context for the cross-tool connect flow (binding patterns §7). Orgs
4
- * are HUB-level entities and the hub login is the one credential shared
5
- * across the tool family, so the active org lives on the HUB profile:
6
- * `antasphere org use` sets it, every tool CLI reads it when picking the
7
- * org to exchange for.
8
- *
9
- * The effective target org for an exchange resolves in this order:
10
- *
11
- * explicit per-invocation override (--org)
12
- * → the hub profile's active org (`org use`)
13
- * → the hub key's bound workspace (set at login)
14
- * → undefined — the exchange then omits `workspaceId` and the hub
15
- * defaults to the key's bound org server-side.
16
- */
17
- export interface OrgContextOptions {
18
- /** Hub profile name; default = the hub config's active profile. */
19
- profile?: string;
20
- }
21
- /**
22
- * The hub profile's effective active org: the `org use` choice when one is
23
- * set, else the org the hub key was bound to at login. Undefined when not
24
- * logged in (or an explicitly named profile is missing → CliUsageError).
25
- */
26
- export declare function getActiveWorkspace(env: CliEnv, opts?: OrgContextOptions): string | undefined;
27
- /**
28
- * What `antasphere org use` calls: persist the org choice on the hub
29
- * profile (`null` clears it, falling back to the key's bound workspace).
30
- * Every other profile field is preserved. Returns the file written.
31
- */
32
- export declare function setActiveWorkspace(env: CliEnv, workspaceId: string | null, opts?: OrgContextOptions): string;
33
- export interface ResolveTargetWorkspaceOptions extends OrgContextOptions {
34
- /** Per-invocation override (--org). */
35
- override?: string;
36
- }
37
- /**
38
- * The org a cross-tool exchange should target: explicit override → active
39
- * org → the hub key's bound workspace → undefined (hub decides).
40
- */
41
- export declare function resolveTargetWorkspace(env: CliEnv, opts?: ResolveTargetWorkspaceOptions): string | undefined;
42
- //# sourceMappingURL=org.d.ts.map
package/dist/org.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"org.d.ts","sourceRoot":"","sources":["../src/org.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAG5E;;;;;;;;;;;;;;GAcG;AAEH,MAAM,WAAW,iBAAiB;IAChC,mEAAmE;IACnE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,iBAAsB,GAAG,MAAM,GAAG,SAAS,CAGhG;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,GAAG,IAAI,EAC1B,IAAI,GAAE,iBAAsB,GAC3B,MAAM,CAaR;AAED,MAAM,WAAW,6BAA8B,SAAQ,iBAAiB;IACtE,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,MAAM,EACX,IAAI,GAAE,6BAAkC,GACvC,MAAM,GAAG,SAAS,CAEpB"}
package/dist/org.js DELETED
@@ -1,39 +0,0 @@
1
- import { HUB_TOOL, loadConfig, saveConfig } from './config.js';
2
- import { CliUsageError, resolveProfile } from './resolve.js';
3
- /**
4
- * The hub profile's effective active org: the `org use` choice when one is
5
- * set, else the org the hub key was bound to at login. Undefined when not
6
- * logged in (or an explicitly named profile is missing → CliUsageError).
7
- */
8
- export function getActiveWorkspace(env, opts = {}) {
9
- const { profile } = resolveProfile(loadConfig(env, HUB_TOOL), opts.profile);
10
- return profile?.activeWorkspaceId ?? profile?.workspaceId;
11
- }
12
- /**
13
- * What `antasphere org use` calls: persist the org choice on the hub
14
- * profile (`null` clears it, falling back to the key's bound workspace).
15
- * Every other profile field is preserved. Returns the file written.
16
- */
17
- export function setActiveWorkspace(env, workspaceId, opts = {}) {
18
- const config = loadConfig(env, HUB_TOOL);
19
- const { name, profile } = resolveProfile(config, opts.profile);
20
- if (!name || !profile) {
21
- throw new CliUsageError('No hub profile to set the org on — run `antasphere login` first.');
22
- }
23
- if (workspaceId === null) {
24
- const { activeWorkspaceId: _cleared, ...rest } = profile;
25
- config.profiles[name] = rest;
26
- }
27
- else {
28
- config.profiles[name] = { ...profile, activeWorkspaceId: workspaceId };
29
- }
30
- return saveConfig(env, HUB_TOOL, config);
31
- }
32
- /**
33
- * The org a cross-tool exchange should target: explicit override → active
34
- * org → the hub key's bound workspace → undefined (hub decides).
35
- */
36
- export function resolveTargetWorkspace(env, opts = {}) {
37
- return opts.override ?? getActiveWorkspace(env, opts);
38
- }
39
- //# sourceMappingURL=org.js.map
package/dist/org.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"org.js","sourceRoot":"","sources":["../src/org.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAe,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAuB7D;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAW,EAAE,OAA0B,EAAE;IAC1E,MAAM,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5E,OAAO,OAAO,EAAE,iBAAiB,IAAI,OAAO,EAAE,WAAW,CAAC;AAC5D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,GAAW,EACX,WAA0B,EAC1B,OAA0B,EAAE;IAE5B,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACzC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;QACtB,MAAM,IAAI,aAAa,CAAC,kEAAkE,CAAC,CAAC;IAC9F,CAAC;IACD,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;QACzB,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;QACzD,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC/B,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,CAAC;IACzE,CAAC;IACD,OAAO,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC;AAOD;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,GAAW,EACX,OAAsC,EAAE;IAExC,OAAO,IAAI,CAAC,QAAQ,IAAI,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACxD,CAAC"}