@antasphere/cli-core 0.3.0 → 0.4.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.
@@ -1,8 +1,16 @@
1
- import { assertToolNamespace, HUB_TOOL, loadConfig, saveConfig, storeWorkspaceKey } from './config.js';
1
+ import {
2
+ assertToolNamespace,
3
+ HUB_TOOL,
4
+ loadConfig,
5
+ lookupConnectKey,
6
+ saveConfig,
7
+ storeConnectKey
8
+ } from './config.js';
2
9
  import type { CliEnv } from './config.js';
3
10
  import { CliConnectClient, CliConnectError } from './connect.js';
4
11
  import type { CliConnectResult } from './connect.js';
5
12
  import { CliUsageError, DEFAULT_PROFILE, resolveProfile } from './resolve.js';
13
+ import type { ResolvedProfile } from './resolve.js';
6
14
 
7
15
  /**
8
16
  * Connect-on-demand (binding patterns §7, gcloud model), extracted from the
@@ -10,17 +18,22 @@ import { CliUsageError, DEFAULT_PROFILE, resolveProfile } from './resolve.js';
10
18
  * serves every federated tool". When a tool CLI resolves NO credential of its
11
19
  * own, it calls `connectOnDemand`:
12
20
  *
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.
21
+ * 0. The cache is consulted FIRST: a key minted earlier for THIS instance
22
+ * under the active hub profile is USER-scoped (hub ADR 014) — it serves
23
+ * every subsequent run and every org, with zero network (no probe, no
24
+ * hub round-trip, no fresh mint).
25
+ * 1. On a miss, discovery gates the flow: only an Antasphere-CLOUD
26
+ * instance can mint keys through the hub (unauthenticated GET
27
+ * /instance — never guess). Unreachable, foreign, or self-hosted
28
+ * instances answer `not_cloud` and the tool raises its classic no-key
29
+ * error unchanged.
17
30
  * 2. The hub credential is what `antasphere login` stored on the hub
18
31
  * profile (the config home's HUB_TOOL namespace) — hub URL included,
19
32
  * never a hardcoded constant here.
20
33
  * 3. `CliConnectClient.exchange` trades it for a tool-local key (one
21
34
  * re-exchange retry when the 120 s JWT dies in transit; a rejected hub
22
35
  * credential maps to guided `antasphere login` advice).
23
- * 4. The minted key is cached per (tool, HUB org) — but only onto a
36
+ * 4. The minted key is cached per (tool, HUB PROFILE) — but only onto a
24
37
  * profile that names THIS instance (a fresh profile gets pinned to it);
25
38
  * a profile pointing elsewhere never receives it.
26
39
  *
@@ -72,19 +85,28 @@ export async function probeToolInstance(
72
85
  }
73
86
  }
74
87
 
75
- /** The facts the connected notice is rendered from. */
88
+ /**
89
+ * The ACTIVE hub profile — what `antasphere login` stored. Its NAME is the
90
+ * connect cache's slot (config.ts `connectKeys`): stable per hub account on
91
+ * this machine, independent of any org selection.
92
+ */
93
+ export function activeHubProfile(env: CliEnv): ResolvedProfile {
94
+ return resolveProfile(loadConfig(env, HUB_TOOL), undefined);
95
+ }
96
+
97
+ /** The facts the connected notice is rendered from (fresh exchanges only —
98
+ * cache hits are silent). */
76
99
  export interface ConnectNoticeFacts {
77
100
  /** The tool instance the exchange connected to (origin-normalized). */
78
101
  toolBaseUrl: string;
79
102
  /** The signed-in account's email at mint. */
80
103
  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;
104
+ /** Whether the minted key was persisted for the next run (per
105
+ * (tool, hub profile)); false = the profile names another instance. */
106
+ stored: boolean;
85
107
  /** The tool profile the cache targeted. */
86
108
  profileName: string;
87
- /** When NOT cached: the other instance the profile points at. */
109
+ /** When NOT stored: the other instance the profile points at. */
88
110
  profileBaseUrl?: string;
89
111
  }
90
112
 
@@ -116,8 +138,8 @@ const DEFAULT_HUB_LOGIN_REJECTED =
116
138
 
117
139
  function defaultConnected(facts: ConnectNoticeFacts): string {
118
140
  return (
119
- `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere (org ${facts.hubWorkspaceId})` +
120
- (facts.cached
141
+ `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere` +
142
+ (facts.stored
121
143
  ? ''
122
144
  : ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
123
145
  '.\n'
@@ -132,16 +154,12 @@ export interface ConnectOnDemandOptions {
132
154
  /** The exchange resource URL; default = this instance's MCP endpoint,
133
155
  * `${toolBaseUrl}/mcp` (the tool's registered resource URL). */
134
156
  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
157
  /** The tool profile the minted key is cached on; default `DEFAULT_PROFILE`. */
140
158
  profileName?: string;
141
159
  env: CliEnv;
142
160
  fetch?: typeof globalThis.fetch;
143
161
  /** Receives the human "Connected to …" notice (tools wire their stderr);
144
- * omitted = silent. Machine output stays untouched either way. */
162
+ * omitted = silent. Cache hits are always silent either way. */
145
163
  notify?: (line: string) => void;
146
164
  messages?: ConnectOnDemandMessages;
147
165
  }
@@ -149,12 +167,16 @@ export interface ConnectOnDemandOptions {
149
167
  export type ConnectOnDemandOutcome =
150
168
  | {
151
169
  outcome: 'connected';
152
- /** The minted tool-local key — this invocation's credential. */
170
+ /** The tool-local key — this invocation's credential. */
153
171
  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. */
172
+ /** true = served from the (tool, hub profile) config cache: zero
173
+ * network, nothing minted. false = a fresh exchange ran. */
157
174
  cached: boolean;
175
+ /** Fresh exchanges only: the full result (user, key meta). */
176
+ result?: CliConnectResult;
177
+ /** Fresh exchanges only: whether the minted key was persisted for
178
+ * the next run (false = the profile names another instance). */
179
+ stored?: boolean;
158
180
  }
159
181
  | {
160
182
  /** Not an Antasphere-cloud instance (or unreachable): the caller
@@ -164,15 +186,30 @@ export type ConnectOnDemandOutcome =
164
186
 
165
187
  /**
166
188
  * 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`.
189
+ * resolved. Serves the cached user-scoped key when one exists for this
190
+ * (instance, hub profile); otherwise returns `not_cloud` when the instance
191
+ * is not an Antasphere-cloud one (or unreachable). Throws a guided
192
+ * `CliUsageError` when the instance IS cloud but the hub login is missing or
193
+ * rejected; every other exchange failure propagates as its `CliConnectError`.
171
194
  */
172
195
  export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
173
196
  assertToolNamespace(opts.tool);
174
197
  const toolBaseUrl = opts.toolBaseUrl.replace(/\/+$/, '');
175
198
  const messages = opts.messages ?? {};
199
+ const profileName = opts.profileName ?? DEFAULT_PROFILE;
200
+
201
+ // 0. The cache: a key minted earlier by the active hub profile is
202
+ // user-scoped — it serves every run and every org (hub ADR 014; the
203
+ // org is a per-request parameter, never part of the credential). Only
204
+ // a profile that names THIS instance is trusted: a cached key never
205
+ // travels to a different instance. A hit costs zero network.
206
+ const hub = activeHubProfile(opts.env);
207
+ const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
208
+ const pinnedHere = existing?.baseUrl?.replace(/\/+$/, '') === toolBaseUrl;
209
+ if (pinnedHere && hub.name) {
210
+ const cachedKey = lookupConnectKey(existing, hub.name);
211
+ if (cachedKey) return { outcome: 'connected', key: cachedKey, cached: true };
212
+ }
176
213
 
177
214
  // 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
178
215
  // never guess. An unreachable or foreign instance is `not_cloud`.
@@ -182,22 +219,22 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
182
219
  // 2. The hub credential is what `antasphere login` stored on the hub
183
220
  // profile (HUB_TOOL namespace) — one login for the whole tool family.
184
221
  // 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) {
222
+ const hubKey = hub.profile?.apiKey;
223
+ const hubBaseUrl = hub.profile?.baseUrl;
224
+ if (!hubKey || !hubBaseUrl || !hub.name) {
189
225
  throw new CliUsageError(messages.missingHubLogin ?? defaultMissingHubLogin(opts.tool));
190
226
  }
191
227
 
192
228
  // 3. The exchange resource defaults to THIS instance's registered resource
193
229
  // URL — its MCP endpoint, derived from the resolved instance origin.
230
+ // The body names NO org: the exchange is user-scoped end to end.
194
231
  const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
195
232
  const connect = new CliConnectClient({
196
233
  hubBaseUrl,
197
234
  toolBaseUrl,
198
235
  ...(opts.fetch ? { fetch: opts.fetch } : {})
199
236
  });
200
- const body = { resource, ...(opts.org ? { workspaceId: opts.org } : {}) };
237
+ const body = { resource };
201
238
  let result: CliConnectResult;
202
239
  try {
203
240
  result = await connect.exchange(hubKey, body);
@@ -213,16 +250,13 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
213
250
  }
214
251
  }
215
252
 
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, {
253
+ // 4. Cache the minted key per (tool, hub profile) — but only onto a
254
+ // profile that names THIS instance (or a fresh one, which gets pinned
255
+ // to it), never onto a profile pointing somewhere else.
256
+ const stored = !existing?.baseUrl || pinnedHere;
257
+ if (stored) {
258
+ storeConnectKey(opts.env, opts.tool, profileName, hub.name, {
224
259
  apiKey: result.key,
225
- toolWorkspaceId: result.toolWorkspaceId,
226
260
  email: result.user.email,
227
261
  mintedAt: new Date().toISOString()
228
262
  });
@@ -238,13 +272,12 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
238
272
  const facts: ConnectNoticeFacts = {
239
273
  toolBaseUrl,
240
274
  email: result.user.email,
241
- hubWorkspaceId: result.hubWorkspaceId,
242
- cached,
275
+ stored,
243
276
  profileName,
244
- // `cached` is false only when the profile names another instance.
245
- ...(cached ? {} : { profileBaseUrl: existing?.baseUrl })
277
+ // `stored` is false only when the profile names another instance.
278
+ ...(stored ? {} : { profileBaseUrl: existing?.baseUrl })
246
279
  };
247
280
  opts.notify?.((messages.connected ?? defaultConnected)(facts));
248
281
 
249
- return { outcome: 'connected', key: result.key, result, cached };
282
+ return { outcome: 'connected', key: result.key, result, cached: false, stored };
250
283
  }
package/src/connect.ts CHANGED
@@ -6,17 +6,23 @@ 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; any org is a per-request selection tool-side.
12
15
  * 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.
16
+ * the credential), body `{ token, hubRefreshToken }` → the tool
17
+ * verifies, JIT-provisions, stores the grant, and mints an ordinary
18
+ * USER-scoped tool-local API key, returned exactly once.
15
19
  *
16
20
  * 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
19
- * ordinary local API-key path with the hub out of the loop.
21
+ * hubRefreshToken is sent to the TOOL only (it is that tool's own grant;
22
+ * redeeming it needs the tool client's credentials) and never persisted by
23
+ * the CLI. The minted key is cached per (tool, hub profile) in the tool's
24
+ * config namespace (config.ts `connectKeys`); day-to-day tool CLI calls
25
+ * then take the ordinary local API-key path with the hub out of the loop.
20
26
  */
21
27
 
22
28
  export type CliConnectStage = 'hub' | 'tool';
@@ -26,8 +32,6 @@ export type CliConnectStage = 'hub' | 'tool';
26
32
  * pick the remedy without string-matching:
27
33
  *
28
34
  * - 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
35
  * - `needsHubLogin` — the hub rejected the KEY itself; re-run
32
36
  * `antasphere login`.
33
37
  * - `needsReExchange` — the tool rejected the 120 s JWT (expired/replayed
@@ -65,20 +69,24 @@ export class CliConnectError extends CliAuthError {
65
69
  }
66
70
 
67
71
  export interface CliToolTokenBody {
68
- /** The tool's registry resource URL (e.g. `https://app.slideless.ai/mcp`). */
72
+ /** The tool's registry resource URL (e.g. `https://app.slideless.ai/mcp`).
73
+ * The ONLY field — the exchange is user-scoped and names no org
74
+ * (hub contract `ssoToolTokenRequestSchema`, ADR 014). */
69
75
  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
76
  }
74
77
 
78
+ /** The hub's tool-token response (hub contract `ssoToolTokenSchema`). */
75
79
  export interface CliToolTokenMinted {
76
- /** The single-org exchange JWT — opaque, ~120 s; relay it, never keep it. */
80
+ /** The user-scoped exchange JWT — opaque, ~120 s; relay it, never keep it. */
77
81
  token: string;
78
82
  /** ISO expiry of the JWT (informational; the minted key outlives it). */
79
83
  expiresAt: string;
80
- /** The hub org the token was minted for (explicit target or the key's bound org). */
81
- workspaceId: string;
84
+ /** The raw one-time offline-grant refresh token for the TARGET TOOL —
85
+ * relayed to that tool's /sso/cli-connect exactly once (it stores it as
86
+ * the standing grant for live as-the-user hub reads) and NEVER persisted
87
+ * or logged by the CLI. Without it, a fresh CLI user's connect is
88
+ * refused tool-side (`hub_grant_missing` — no key is minted born-dead). */
89
+ hubRefreshToken: string;
82
90
  }
83
91
 
84
92
  export interface CliConnected {
@@ -86,20 +94,21 @@ export interface CliConnected {
86
94
  key: string;
87
95
  apiKey: CliAuthMintedKey;
88
96
  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;
97
+ /** The tool workspace the key is PINNED to — null on the live contract
98
+ * (user-scoped, unpinned; the org is a per-request parameter). */
99
+ workspaceId: string | null;
91
100
  }
92
101
 
93
- /** The flattened outcome of a full exchange — everything a CLI caches. */
102
+ /** The flattened outcome of a full exchange. */
94
103
  export interface CliConnectResult {
95
- /** Full tool-local key — cache it per (tool, `hubWorkspaceId`). */
104
+ /** Full tool-local key — user-scoped: ONE per (tool, hub profile),
105
+ * valid for every org the user can select per request (config.ts). */
96
106
  key: string;
97
107
  apiKey: CliAuthMintedKey;
98
108
  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;
109
+ /** The tool workspace the key is pinned to — null = unpinned (the live
110
+ * contract always answers null; informational). */
111
+ toolWorkspaceId: string | null;
103
112
  }
104
113
 
105
114
  export interface CliConnectClientOptions {
@@ -126,20 +135,28 @@ export class CliConnectClient {
126
135
  return this.call('hub', `${this.hubBaseUrl}/api/v1/sso/tool-token`, body, hubApiKey);
127
136
  }
128
137
 
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 });
138
+ /**
139
+ * Step 2 — the tool verifies the JWT (its only credential) and mints its
140
+ * key. `hubRefreshToken` is the SAME response's offline grant, relayed so
141
+ * the tool can store it (a grant-less connect is refused for users with
142
+ * none already stored — `hub_grant_missing`).
143
+ */
144
+ cliConnect(token: string, hubRefreshToken?: string): Promise<CliConnected> {
145
+ return this.call('tool', `${this.toolBaseUrl}/api/v1/sso/cli-connect`, {
146
+ token,
147
+ ...(hubRefreshToken ? { hubRefreshToken } : {})
148
+ });
132
149
  }
133
150
 
134
- /** The full two-call exchange. The hub key goes to the hub ONLY. */
151
+ /** The full two-call exchange. The hub key goes to the hub ONLY; the
152
+ * offline grant goes to the TOOL only — neither is ever persisted here. */
135
153
  async exchange(hubApiKey: string, body: CliToolTokenBody): Promise<CliConnectResult> {
136
154
  const minted = await this.toolToken(hubApiKey, body);
137
- const connected = await this.cliConnect(minted.token);
155
+ const connected = await this.cliConnect(minted.token, minted.hubRefreshToken);
138
156
  return {
139
157
  key: connected.key,
140
158
  apiKey: connected.apiKey,
141
159
  user: connected.user,
142
- hubWorkspaceId: minted.workspaceId,
143
160
  toolWorkspaceId: connected.workspaceId
144
161
  };
145
162
  }
package/src/index.ts CHANGED
@@ -3,9 +3,10 @@
3
3
  * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
4
  * with tool-namespaced profiles, the flag → env → profile → default URL
5
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
6
+ * cross-tool connect exchange (+ its per-(tool, hub profile) user-scoped
7
+ * key cache, the hub-profile org context, and the connect-on-demand seam a
8
+ * tool CLI runs when no direct credential resolved), and the CliIo prompt
9
+ * seam. Tool
9
10
  * commands, wire types, and API surfaces live in the tools; this package
10
11
  * carries only config/login plumbing, never secrets.
11
12
  */
@@ -16,14 +17,14 @@ export {
16
17
  configPath,
17
18
  HUB_TOOL,
18
19
  loadConfig,
19
- lookupWorkspaceKey,
20
+ lookupConnectKey,
20
21
  parseConfig,
21
22
  redactKey,
22
- removeWorkspaceKey,
23
+ removeConnectKey,
23
24
  saveConfig,
24
- storeWorkspaceKey
25
+ storeConnectKey
25
26
  } from './config.js';
26
- export type { CliConfig, CliEnv, CliProfile, CliWorkspaceKey } from './config.js';
27
+ export type { CliConfig, CliConnectKey, CliEnv, CliProfile } from './config.js';
27
28
 
28
29
  export { ask, printJson } from './io.js';
29
30
  export type { CliIo } from './io.js';
@@ -52,7 +53,7 @@ export type {
52
53
  CliToolTokenMinted
53
54
  } from './connect.js';
54
55
 
55
- export { connectOnDemand, probeToolInstance } from './connect-on-demand.js';
56
+ export { activeHubProfile, connectOnDemand, probeToolInstance } from './connect-on-demand.js';
56
57
  export type {
57
58
  ConnectNoticeFacts,
58
59
  ConnectOnDemandMessages,