@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/config.ts CHANGED
@@ -16,9 +16,16 @@ import { dirname, join } from 'node:path';
16
16
  * └── <tool>.json 0600 every other tool's profiles
17
17
  * (e.g. tools/slideless.json)
18
18
  *
19
- * Each file holds one tool's `{ activeProfile?, profiles }`: multiple named
20
- * profiles per tool, one active profile per tool. Hub profiles additionally
21
- * carry the active org (`workspaceId`) their credential is bound to.
19
+ * Each file holds one tool's `{ activeProfile?, profiles }`. A PROFILE IS AN
20
+ * INSTANCE: it names the tool instance it talks to (`baseUrl`; absent = the
21
+ * tool's cloud URL) and carries the credentials for that instance, either
22
+ * the tool's own key (`apiKey`, the tool's login) or the keys the hub
23
+ * exchange minted (`connectKeys`, one per hub profile). Profiles are named
24
+ * for their host by default (`cloud` for the cloud instance,
25
+ * `share.antasphere.com`, `localhost:3400`); the person may rename them and
26
+ * chooses the active one with `<tool> use`. The hub profile additionally
27
+ * carries `workspaceId`, the default organization at login (informational;
28
+ * the hub's server-side default is what applies).
22
29
  *
23
30
  * Files store API keys, so directories are created 0700 and files kept 0600
24
31
  * on every write. All I/O is synchronous and env-injected (no process.env
@@ -30,14 +37,15 @@ export type CliEnv = Record<string, string | undefined>;
30
37
 
31
38
  /**
32
39
  * A tool-local key minted by the cross-tool connect exchange (binding
33
- * patterns §7), cached in the tool's profile under the HUB org it was
34
- * exchanged for. Every field beyond the key itself is informational.
40
+ * patterns §7), cached on the profile of the instance it was minted for,
41
+ * under the HUB PROFILE whose `antasphere login` credential minted it. The
42
+ * key is USER-scoped (hub ADR 014): one key serves every org — the org is a
43
+ * per-request parameter, never part of the credential or of this cache's
44
+ * slot. Every field beyond the key itself is informational.
35
45
  */
36
- export interface CliWorkspaceKey {
46
+ export interface CliConnectKey {
37
47
  /** Full tool-local API key (`slk_`-style) — shown once at mint, cached here. */
38
48
  apiKey: string;
39
- /** The tool-local workspace the key is bound to (the hub org's projection). */
40
- toolWorkspaceId?: string;
41
49
  /** The signed-in account's email at mint. */
42
50
  email?: string;
43
51
  /** ISO timestamp of the exchange that minted the key. */
@@ -45,20 +53,21 @@ export interface CliWorkspaceKey {
45
53
  }
46
54
 
47
55
  export interface CliProfile {
48
- /** `<prefix>_...` API key for this profile. */
56
+ /** `<prefix>_...` API key for this profile (the tool's own login). */
49
57
  apiKey?: string;
50
- /** Instance origin; absent = the tool's default instance, when it has one. */
58
+ /** The instance this profile IS: its origin. Absent = the tool's cloud URL. */
51
59
  baseUrl?: string;
52
60
  /** The signed-in account's email (informational, set by login). */
53
61
  email?: string;
54
- /** The org/workspace the key is bound to (one workspace per credential). */
62
+ /** Hub profile: the default organization at login (informational; the
63
+ * hub's server-side default is what applies, `--org` overrides per
64
+ * command). Tool profiles from a tool's own login may carry the
65
+ * workspace that login bound. */
55
66
  workspaceId?: string;
56
- /** Hub profiles only: the org selected via `antasphere org use` (overrides
57
- * the key's bound `workspaceId` as the default exchange target). */
58
- activeWorkspaceId?: string;
59
- /** Tool profiles only: exchange-minted keys, one per HUB org — the
60
- * per-(tool, org) cache of the cross-tool connect flow. */
61
- workspaceKeys?: Record<string, CliWorkspaceKey>;
67
+ /** Tool profiles only: exchange-minted USER-scoped keys, ONE per hub
68
+ * profile — the (tool profile, hub profile) cache of the cross-tool
69
+ * connect flow. Org-independent: a cached key serves every org. */
70
+ connectKeys?: Record<string, CliConnectKey>;
62
71
  }
63
72
 
64
73
  export interface CliConfig {
@@ -147,62 +156,99 @@ export function redactKey(key: string): string {
147
156
  }
148
157
 
149
158
  /**
150
- * The cached tool-local key for a HUB org, if any. Strictly org-matched:
151
- * the per-org cache first, then the legacy single `apiKey` — but ONLY when
152
- * the profile's `workspaceId` says it is bound to exactly this workspace.
153
- * A key whose binding is unknown is never returned for an org lookup.
159
+ * The cached user-scoped connect key a HUB PROFILE minted for this tool
160
+ * profile, if any. The slot is the hub profile NAME — stable across runs
161
+ * and orgs (the key identifies the user; selecting a different org between
162
+ * runs never misses the cache).
154
163
  */
155
- export function lookupWorkspaceKey(profile: CliProfile | undefined, workspaceId: string): string | undefined {
156
- if (!profile) return undefined;
157
- const entry = profile.workspaceKeys?.[workspaceId];
158
- if (entry?.apiKey) return entry.apiKey;
159
- if (profile.apiKey && profile.workspaceId === workspaceId) return profile.apiKey;
160
- return undefined;
164
+ export function lookupConnectKey(
165
+ profile: CliProfile | undefined,
166
+ hubProfileName: string
167
+ ): string | undefined {
168
+ return profile?.connectKeys?.[hubProfileName]?.apiKey;
169
+ }
170
+
171
+ /** How a profile signs in, for a `profiles`-style listing. */
172
+ export type ProfileCredential = 'key' | 'hub' | 'none';
173
+
174
+ /**
175
+ * What a profile signs in with, in the order the tool resolves it: its own
176
+ * `apiKey` (`key`, the tool's login), else a key the hub exchange minted
177
+ * (`hub`: under the named hub profile, or under any when none is named),
178
+ * else `none`. A listing can then say which profiles ride the hub login.
179
+ */
180
+ export function profileCredential(
181
+ profile: CliProfile | undefined,
182
+ hubProfileName?: string
183
+ ): ProfileCredential {
184
+ if (!profile) return 'none';
185
+ if (profile.apiKey) return 'key';
186
+ const slots = profile.connectKeys ?? {};
187
+ const connected = hubProfileName
188
+ ? Boolean(slots[hubProfileName]?.apiKey)
189
+ : Object.values(slots).some((k) => k.apiKey);
190
+ return connected ? 'hub' : 'none';
191
+ }
192
+
193
+ export interface StoreConnectKeyOptions {
194
+ /**
195
+ * The instance the key was minted for. Written on the profile when it is
196
+ * created here or has no `baseUrl` of its own (a blank one counts as
197
+ * none); a `baseUrl` that is there is never overwritten (a profile is
198
+ * never repointed).
199
+ */
200
+ baseUrl?: string;
161
201
  }
162
202
 
163
203
  /**
164
- * Cache an exchange-minted tool key under (profile, hub org), creating the
165
- * profile on first contact (and making it active when no profile is active
166
- * yet — first cloud connect on a fresh machine). Every other profile field
167
- * is preserved untouched. Returns the file written.
204
+ * Cache an exchange-minted tool key on the SELECTED profile under the hub
205
+ * profile's name. A profile not on disk yet is created (with `baseUrl` when
206
+ * given) and made active only when the tool had NO profile at all: the
207
+ * first cloud connect on a fresh machine. An existing profile is never
208
+ * renamed, repointed or made active; every other field is preserved.
209
+ * Returns the file written.
168
210
  */
169
- export function storeWorkspaceKey(
211
+ export function storeConnectKey(
170
212
  env: CliEnv,
171
213
  tool: string,
172
214
  profileName: string,
173
- workspaceId: string,
174
- entry: CliWorkspaceKey
215
+ hubProfileName: string,
216
+ entry: CliConnectKey,
217
+ opts: StoreConnectKeyOptions = {}
175
218
  ): string {
176
219
  const config = loadConfig(env, tool);
220
+ const first = Object.keys(config.profiles).length === 0;
177
221
  const profile = config.profiles[profileName] ?? {};
178
222
  config.profiles[profileName] = {
179
223
  ...profile,
180
- workspaceKeys: { ...profile.workspaceKeys, [workspaceId]: entry }
224
+ ...(!profile.baseUrl?.trim() && opts.baseUrl ? { baseUrl: opts.baseUrl } : {}),
225
+ connectKeys: { ...profile.connectKeys, [hubProfileName]: entry }
181
226
  };
182
- if (!config.activeProfile) config.activeProfile = profileName;
227
+ if (first) config.activeProfile = profileName;
183
228
  return saveConfig(env, tool, config);
184
229
  }
185
230
 
186
231
  /**
187
- * Drop one org's cached key from a profile (tool logout for that org).
188
- * Returns whether anything was removed; the legacy single `apiKey` is never
189
- * touched — it belongs to the tool's own login flow.
232
+ * Drop one hub profile's cached connect key from a profile (disconnect this
233
+ * tool from the hub account, or evict a key the hub revoked). Returns
234
+ * whether anything was removed; the tool's own `apiKey` is never touched —
235
+ * it belongs to the tool's own login flow.
190
236
  */
191
- export function removeWorkspaceKey(
237
+ export function removeConnectKey(
192
238
  env: CliEnv,
193
239
  tool: string,
194
240
  profileName: string,
195
- workspaceId: string
241
+ hubProfileName: string
196
242
  ): boolean {
197
243
  const config = loadConfig(env, tool);
198
244
  const profile = config.profiles[profileName];
199
- if (!profile?.workspaceKeys || !(workspaceId in profile.workspaceKeys)) return false;
200
- const { [workspaceId]: _dropped, ...rest } = profile.workspaceKeys;
245
+ if (!profile?.connectKeys || !(hubProfileName in profile.connectKeys)) return false;
246
+ const { [hubProfileName]: _dropped, ...rest } = profile.connectKeys;
201
247
  if (Object.keys(rest).length === 0) {
202
- const { workspaceKeys: _empty, ...bare } = profile;
248
+ const { connectKeys: _empty, ...bare } = profile;
203
249
  config.profiles[profileName] = bare;
204
250
  } else {
205
- config.profiles[profileName] = { ...profile, workspaceKeys: rest };
251
+ config.profiles[profileName] = { ...profile, connectKeys: rest };
206
252
  }
207
253
  saveConfig(env, tool, config);
208
254
  return true;
@@ -1,31 +1,64 @@
1
- import { assertToolNamespace, HUB_TOOL, loadConfig, saveConfig, storeWorkspaceKey } from './config.js';
2
- import type { CliEnv } from './config.js';
1
+ import {
2
+ assertToolNamespace,
3
+ HUB_TOOL,
4
+ loadConfig,
5
+ lookupConnectKey,
6
+ removeConnectKey,
7
+ storeConnectKey
8
+ } from './config.js';
9
+ import type { CliEnv, CliProfile } from './config.js';
3
10
  import { CliConnectClient, CliConnectError } from './connect.js';
4
11
  import type { CliConnectResult } from './connect.js';
5
- import { CliUsageError, DEFAULT_PROFILE, resolveProfile } from './resolve.js';
12
+ import {
13
+ CliUsageError,
14
+ firstSet,
15
+ normalizeUrl,
16
+ profileUrl,
17
+ resolveProfile,
18
+ sameInstance
19
+ } from './resolve.js';
20
+ import type { ResolvedProfile } from './resolve.js';
6
21
 
7
22
  /**
8
23
  * Connect-on-demand (binding patterns §7, gcloud model), extracted from the
9
24
  * Slideless CLI so every Antasphere tool CLI inherits "one `antasphere login`
10
25
  * serves every federated tool". When a tool CLI resolves NO credential of its
11
- * own, it calls `connectOnDemand`:
26
+ * own, it calls `connectOnDemand` with the profile it selected
27
+ * (`selectProfile`: the profile IS the instance):
12
28
  *
13
- * 1. Discovery gates the flow: only an Antasphere-CLOUD instance can mint
14
- * keys through the hub (unauthenticated GET /instance — never guess).
15
- * Unreachable, foreign, or self-hosted instances answer `not_cloud`
16
- * and the tool raises its classic no-key error unchanged.
29
+ * 0. The cache is consulted FIRST: a key minted earlier for THIS instance
30
+ * under the active hub profile is USER-scoped (hub ADR 014) — it serves
31
+ * every subsequent run and every org, with zero network (no probe, no
32
+ * hub round-trip, no fresh mint). It is read on the selected profile
33
+ * only when that profile is at the resolved instance (its `baseUrl`,
34
+ * else the tool's `cloudUrl` when the profile has none), so a cached
35
+ * key never travels to another origin. `cached: false` skips this step.
36
+ * 1. On a miss, discovery gates the flow: only an Antasphere-CLOUD
37
+ * instance can mint keys through the hub (unauthenticated GET
38
+ * /instance — never guess). Unreachable, foreign, or self-hosted
39
+ * instances answer `not_cloud` and the tool raises its classic no-key
40
+ * error unchanged.
17
41
  * 2. The hub credential is what `antasphere login` stored on the hub
18
42
  * profile (the config home's HUB_TOOL namespace) — hub URL included,
19
43
  * never a hardcoded constant here.
20
44
  * 3. `CliConnectClient.exchange` trades it for a tool-local key (one
21
45
  * re-exchange retry when the 120 s JWT dies in transit; a rejected hub
22
- * credential maps to guided `antasphere login` advice).
23
- * 4. The minted key is cached per (tool, HUB org) — but only onto a
24
- * profile that names THIS instance (a fresh profile gets pinned to it);
25
- * a profile pointing elsewhere never receives it.
46
+ * credential maps to guided `antasphere login` advice on either
47
+ * attempt; a hub REFUSAL, a 403 that is not the scope case, propagates
48
+ * as its `CliConnectError` with the hub's own sentence and `exitCode`
49
+ * 3).
50
+ * 4. The minted key is cached on the SELECTED profile under the hub
51
+ * profile's name. A profile not on disk yet is created with this
52
+ * instance's URL, and made active only when the tool had no profile at
53
+ * all; an existing profile is never renamed or repointed, and one that
54
+ * is at another instance never receives the key.
26
55
  *
27
- * A new tool needs only its namespace, base URL, and copy — the flow itself
28
- * is tool-agnostic.
56
+ * A stranded key recovers: on a 401 with a key that came from the cache,
57
+ * the tool CLI calls `refreshConnectKey` once (evict, exchange again with
58
+ * `cached: false`) and retries its request once; a second 401 fails.
59
+ *
60
+ * A new tool needs only its namespace, its cloud URL, and copy — the flow
61
+ * itself is tool-agnostic.
29
62
  */
30
63
 
31
64
  /** What the unauthenticated discovery probe learned about a tool instance. */
@@ -72,19 +105,29 @@ export async function probeToolInstance(
72
105
  }
73
106
  }
74
107
 
75
- /** The facts the connected notice is rendered from. */
108
+ /**
109
+ * The ACTIVE hub profile — what `antasphere login` stored. Its NAME is the
110
+ * connect cache's slot (config.ts `connectKeys`): stable per hub account on
111
+ * this machine, independent of any org selection.
112
+ */
113
+ export function activeHubProfile(env: CliEnv): ResolvedProfile {
114
+ return resolveProfile(loadConfig(env, HUB_TOOL), undefined);
115
+ }
116
+
117
+ /** The facts the connected notice is rendered from (fresh exchanges only —
118
+ * cache hits are silent). */
76
119
  export interface ConnectNoticeFacts {
77
120
  /** The tool instance the exchange connected to (origin-normalized). */
78
121
  toolBaseUrl: string;
79
122
  /** The signed-in account's email at mint. */
80
123
  email: string;
81
- /** The HUB org the exchange resolved to. */
82
- hubWorkspaceId: string;
83
- /** Whether the minted key was cached (per (tool, hub org)). */
84
- cached: boolean;
124
+ /** Whether the minted key was persisted for the next run (on the
125
+ * selected profile, under the hub profile's name); false = the profile
126
+ * is at another instance. */
127
+ stored: boolean;
85
128
  /** The tool profile the cache targeted. */
86
129
  profileName: string;
87
- /** When NOT cached: the other instance the profile points at. */
130
+ /** When NOT stored: the other instance the profile is at. */
88
131
  profileBaseUrl?: string;
89
132
  }
90
133
 
@@ -116,8 +159,8 @@ const DEFAULT_HUB_LOGIN_REJECTED =
116
159
 
117
160
  function defaultConnected(facts: ConnectNoticeFacts): string {
118
161
  return (
119
- `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere (org ${facts.hubWorkspaceId})` +
120
- (facts.cached
162
+ `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere` +
163
+ (facts.stored
121
164
  ? ''
122
165
  : ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
123
166
  '.\n'
@@ -129,32 +172,44 @@ export interface ConnectOnDemandOptions {
129
172
  tool: string;
130
173
  /** The resolved tool instance origin the CLI is talking to. */
131
174
  toolBaseUrl: string;
175
+ /** The tool's cloud URL, the same value `selectProfile` got: what a
176
+ * profile with no `baseUrl` of its own is at. Omit only for a tool with
177
+ * no cloud instance. */
178
+ cloudUrl?: string | undefined;
132
179
  /** The exchange resource URL; default = this instance's MCP endpoint,
133
180
  * `${toolBaseUrl}/mcp` (the tool's registered resource URL). */
134
181
  resource?: string;
135
- /** Target hub org for the exchange (`--org` → `antasphere org use` → the
136
- * hub key's bound org — resolve via `resolveTargetWorkspace`); omit =
137
- * the hub defaults to the key's bound org server-side. */
138
- org?: string;
139
- /** The tool profile the minted key is cached on; default `DEFAULT_PROFILE`. */
140
- profileName?: string;
182
+ /** The tool profile the CLI selected for this run (`selectProfile`), the
183
+ * one the minted key is cached on. Not on disk yet → created with
184
+ * `toolBaseUrl` on first contact; at another instance → the key is
185
+ * returned but never stored. cli-core never guesses it. */
186
+ profileName: string;
141
187
  env: CliEnv;
142
188
  fetch?: typeof globalThis.fetch;
143
189
  /** Receives the human "Connected to …" notice (tools wire their stderr);
144
- * omitted = silent. Machine output stays untouched either way. */
190
+ * omitted = silent. Cache hits are always silent either way. */
145
191
  notify?: (line: string) => void;
146
192
  messages?: ConnectOnDemandMessages;
193
+ /** false = do not read the cache: run the exchange even when a key is
194
+ * cached (the one re-exchange after a 401 on a cached key;
195
+ * `refreshConnectKey` sets it). Default true. */
196
+ cached?: boolean;
147
197
  }
148
198
 
149
199
  export type ConnectOnDemandOutcome =
150
200
  | {
151
201
  outcome: 'connected';
152
- /** The minted tool-local key — this invocation's credential. */
202
+ /** The tool-local key — this invocation's credential. */
153
203
  key: string;
154
- /** The full exchange result (user, hub org, tool workspace, key meta). */
155
- result: CliConnectResult;
156
- /** Whether the key was cached per (tool, hub org) for the next run. */
204
+ /** true = served from the (tool profile, hub profile) config cache:
205
+ * zero network, nothing minted. false = a fresh exchange ran. A 401
206
+ * on a `cached: true` key is what warrants `refreshConnectKey`. */
157
207
  cached: boolean;
208
+ /** Fresh exchanges only: the full result (user, key meta). */
209
+ result?: CliConnectResult;
210
+ /** Fresh exchanges only: whether the minted key was persisted for
211
+ * the next run (false = the profile is at another instance). */
212
+ stored?: boolean;
158
213
  }
159
214
  | {
160
215
  /** Not an Antasphere-cloud instance (or unreachable): the caller
@@ -162,17 +217,53 @@ export type ConnectOnDemandOutcome =
162
217
  outcome: 'not_cloud';
163
218
  };
164
219
 
220
+ /**
221
+ * Where the selected profile stands with respect to the resolved instance:
222
+ * `here` (its `baseUrl`, else the tool's cloud URL, is this instance),
223
+ * `elsewhere` (it is at another instance), or `free` (absent, or with no
224
+ * instance at all: no `baseUrl` and no cloud URL known). The cache is read
225
+ * only when `here`; a key is stored unless `elsewhere`; a key is evicted
226
+ * only when `here`.
227
+ */
228
+ function placeOf(
229
+ existing: CliProfile | undefined,
230
+ toolBaseUrl: string,
231
+ cloudUrl: string | undefined
232
+ ): { place: 'here' | 'elsewhere' | 'free'; at?: string } {
233
+ const at = existing ? profileUrl(existing, cloudUrl) : undefined;
234
+ if (!existing || at === undefined) return { place: 'free' };
235
+ return sameInstance(at, toolBaseUrl) ? { place: 'here', at } : { place: 'elsewhere', at };
236
+ }
237
+
165
238
  /**
166
239
  * The hub → tool exchange fallback a tool CLI runs when no direct credential
167
- * resolved. Returns `not_cloud` when the instance is not an Antasphere-cloud
168
- * one (or unreachable). Throws a guided `CliUsageError` when the instance IS
169
- * cloud but the hub login is missing or rejected; every other exchange
170
- * failure propagates as its `CliConnectError`.
240
+ * resolved. Serves the cached user-scoped key when one exists for this
241
+ * (instance, hub profile) on the selected profile; otherwise returns
242
+ * `not_cloud` when the instance is not an Antasphere-cloud one (or
243
+ * unreachable). Throws a guided `CliUsageError` when the instance IS cloud
244
+ * but the hub login is missing or rejected; a refusal and every other
245
+ * exchange failure propagate as their `CliConnectError` (`exitCode` says 3
246
+ * for the refusal, `message` is the server's own sentence).
171
247
  */
172
248
  export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
173
249
  assertToolNamespace(opts.tool);
174
- const toolBaseUrl = opts.toolBaseUrl.replace(/\/+$/, '');
250
+ const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
175
251
  const messages = opts.messages ?? {};
252
+ const { profileName } = opts;
253
+
254
+ // 0. The cache: a key minted earlier by the active hub profile is
255
+ // user-scoped — it serves every run and every org (hub ADR 014; the
256
+ // org is a per-request parameter, never part of the credential). Only
257
+ // the selected profile is read, and only when it is at THIS instance:
258
+ // a cached key never travels to a different instance. A hit costs zero
259
+ // network. `cached: false` (the re-exchange after a 401) skips it.
260
+ const hub = activeHubProfile(opts.env);
261
+ const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
262
+ const { place, at } = placeOf(existing, toolBaseUrl, opts.cloudUrl);
263
+ if (opts.cached !== false && place === 'here' && hub.name) {
264
+ const cachedKey = lookupConnectKey(existing, hub.name);
265
+ if (cachedKey) return { outcome: 'connected', key: cachedKey, cached: true };
266
+ }
176
267
 
177
268
  // 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
178
269
  // never guess. An unreachable or foreign instance is `not_cloud`.
@@ -182,69 +273,92 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
182
273
  // 2. The hub credential is what `antasphere login` stored on the hub
183
274
  // profile (HUB_TOOL namespace) — one login for the whole tool family.
184
275
  // The hub URL comes from that same profile, never from a constant here.
185
- const { profile: hubProfile } = resolveProfile(loadConfig(opts.env, HUB_TOOL), undefined);
186
- const hubKey = hubProfile?.apiKey;
187
- const hubBaseUrl = hubProfile?.baseUrl;
188
- if (!hubKey || !hubBaseUrl) {
276
+ // A blank field is no field (the package's one blank rule, firstSet).
277
+ const hubKey = firstSet(hub.profile?.apiKey);
278
+ const hubBaseUrl = firstSet(hub.profile?.baseUrl);
279
+ if (!hubKey || !hubBaseUrl || !hub.name) {
189
280
  throw new CliUsageError(messages.missingHubLogin ?? defaultMissingHubLogin(opts.tool));
190
281
  }
191
282
 
192
283
  // 3. The exchange resource defaults to THIS instance's registered resource
193
284
  // URL — its MCP endpoint, derived from the resolved instance origin.
285
+ // The body names NO org: the exchange is user-scoped end to end.
194
286
  const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
195
287
  const connect = new CliConnectClient({
196
288
  hubBaseUrl,
197
289
  toolBaseUrl,
198
290
  ...(opts.fetch ? { fetch: opts.fetch } : {})
199
291
  });
200
- const body = { resource, ...(opts.org ? { workspaceId: opts.org } : {}) };
292
+ const body = { resource };
293
+ // One attempt, with the hub's verdict on the KEY mapped to the guided
294
+ // login error whichever attempt it comes on. A refusal (403 that is not
295
+ // the scope case) and every wire error propagate as they are: the error
296
+ // carries the server's own sentence and its exit code.
297
+ const attempt = async (): Promise<CliConnectResult> => {
298
+ try {
299
+ return await connect.exchange(hubKey, body);
300
+ } catch (e) {
301
+ if (e instanceof CliConnectError && e.needsHubLogin) {
302
+ throw new CliUsageError(messages.hubLoginRejected ?? DEFAULT_HUB_LOGIN_REJECTED);
303
+ }
304
+ throw e;
305
+ }
306
+ };
201
307
  let result: CliConnectResult;
202
308
  try {
203
- result = await connect.exchange(hubKey, body);
309
+ result = await attempt();
204
310
  } catch (e) {
205
- if (e instanceof CliConnectError && e.needsReExchange) {
206
- // The 120 s JWT died in transit (expired/replayed) — one fresh
207
- // exchange; a second rejection propagates.
208
- result = await connect.exchange(hubKey, body);
209
- } else if (e instanceof CliConnectError && e.needsHubLogin) {
210
- throw new CliUsageError(messages.hubLoginRejected ?? DEFAULT_HUB_LOGIN_REJECTED);
211
- } else {
212
- throw e;
213
- }
311
+ if (!(e instanceof CliConnectError && e.needsReExchange)) throw e;
312
+ // The 120 s JWT died in transit (expired/replayed) — one fresh
313
+ // exchange; a second rejection propagates.
314
+ result = await attempt();
214
315
  }
215
316
 
216
- // 4. Cache the minted key per (tool, hub org) — but only onto a profile
217
- // that names THIS instance (or a fresh one, which gets pinned to it),
218
- // never onto a profile pointing somewhere else.
219
- const profileName = opts.profileName ?? DEFAULT_PROFILE;
220
- const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
221
- const cached = !existing?.baseUrl || existing.baseUrl.replace(/\/+$/, '') === toolBaseUrl;
222
- if (cached) {
223
- storeWorkspaceKey(opts.env, opts.tool, profileName, result.hubWorkspaceId, {
224
- apiKey: result.key,
225
- toolWorkspaceId: result.toolWorkspaceId,
226
- email: result.user.email,
227
- mintedAt: new Date().toISOString()
228
- });
229
- if (!existing?.baseUrl) {
230
- // First contact: pin the profile to this instance so the next
231
- // invocation resolves the URL and the cached key with no flags.
232
- const cfg = loadConfig(opts.env, opts.tool);
233
- cfg.profiles[profileName] = { ...cfg.profiles[profileName], baseUrl: toolBaseUrl };
234
- saveConfig(opts.env, opts.tool, cfg);
235
- }
317
+ // 4. Cache the minted key on the SELECTED profile under the hub profile's
318
+ // name. A profile not on disk yet, or one with no instance of its own,
319
+ // takes this instance's URL; a profile at another instance never
320
+ // receives the key and is never repointed.
321
+ const stored = place !== 'elsewhere';
322
+ if (stored) {
323
+ storeConnectKey(
324
+ opts.env,
325
+ opts.tool,
326
+ profileName,
327
+ hub.name,
328
+ { apiKey: result.key, email: result.user.email, mintedAt: new Date().toISOString() },
329
+ { baseUrl: toolBaseUrl }
330
+ );
236
331
  }
237
332
 
238
333
  const facts: ConnectNoticeFacts = {
239
334
  toolBaseUrl,
240
335
  email: result.user.email,
241
- hubWorkspaceId: result.hubWorkspaceId,
242
- cached,
336
+ stored,
243
337
  profileName,
244
- // `cached` is false only when the profile names another instance.
245
- ...(cached ? {} : { profileBaseUrl: existing?.baseUrl })
338
+ // `stored` is false only when the profile is at another instance.
339
+ ...(stored ? {} : { profileBaseUrl: at })
246
340
  };
247
341
  opts.notify?.((messages.connected ?? defaultConnected)(facts));
248
342
 
249
- return { outcome: 'connected', key: result.key, result, cached };
343
+ return { outcome: 'connected', key: result.key, result, cached: false, stored };
344
+ }
345
+
346
+ /**
347
+ * The stranded-key recovery: what a tool CLI calls once when a request
348
+ * answered 401 with a key that `connectOnDemand` served from the cache
349
+ * (`cached: true`). Evicts that key from the selected profile (the hub
350
+ * revoked it, or a membership was swept), only when that profile is at
351
+ * this instance (a key of another instance is never touched), and runs the
352
+ * exchange again with the cache skipped. The caller retries its request
353
+ * once with the new key and fails on a second 401; `not_cloud` means there
354
+ * is nothing to recover with, and the caller fails with its 401 as it
355
+ * stands.
356
+ */
357
+ export async function refreshConnectKey(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
358
+ assertToolNamespace(opts.tool);
359
+ const hub = activeHubProfile(opts.env);
360
+ const existing = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
361
+ const { place } = placeOf(existing, normalizeUrl(opts.toolBaseUrl), opts.cloudUrl);
362
+ if (hub.name && place === 'here') removeConnectKey(opts.env, opts.tool, opts.profileName, hub.name);
363
+ return connectOnDemand({ ...opts, cached: false });
250
364
  }