@agentic-kit/cli 0.22.0 → 0.23.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/README.md +10 -11
- package/commands.d.ts +3 -1
- package/commands.js +80 -47
- package/config.d.ts +2 -9
- package/config.js +5 -12
- package/db-tools.d.ts +0 -5
- package/db-tools.js +10 -24
- package/esm/commands.d.ts +3 -1
- package/esm/commands.js +79 -47
- package/esm/config.d.ts +2 -9
- package/esm/config.js +4 -11
- package/esm/db-tools.d.ts +0 -5
- package/esm/db-tools.js +10 -23
- package/esm/index.d.ts +1 -1
- package/esm/index.js +12 -16
- package/index.d.ts +1 -1
- package/index.js +11 -16
- package/package.json +16 -15
- package/account-store.d.ts +0 -19
- package/account-store.js +0 -61
- package/api-key.d.ts +0 -51
- package/api-key.js +0 -96
- package/auth-error.d.ts +0 -4
- package/auth-error.js +0 -114
- package/auth.d.ts +0 -28
- package/auth.js +0 -119
- package/backend-store.d.ts +0 -28
- package/backend-store.js +0 -71
- package/credentials.d.ts +0 -13
- package/credentials.js +0 -49
- package/esm/account-store.d.ts +0 -19
- package/esm/account-store.js +0 -56
- package/esm/api-key.d.ts +0 -51
- package/esm/api-key.js +0 -88
- package/esm/auth-error.d.ts +0 -4
- package/esm/auth-error.js +0 -108
- package/esm/auth.d.ts +0 -28
- package/esm/auth.js +0 -114
- package/esm/backend-store.d.ts +0 -28
- package/esm/backend-store.js +0 -65
- package/esm/credentials.d.ts +0 -13
- package/esm/credentials.js +0 -45
package/auth.js
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.refreshApiKeyIfNeeded = refreshApiKeyIfNeeded;
|
|
4
|
-
exports.signIn = signIn;
|
|
5
|
-
exports.signOut = signOut;
|
|
6
|
-
const sdk_1 = require("@constructive-io/sdk");
|
|
7
|
-
const account_store_1 = require("./account-store");
|
|
8
|
-
const api_key_1 = require("./api-key");
|
|
9
|
-
const auth_error_1 = require("./auth-error");
|
|
10
|
-
const SELECT = {
|
|
11
|
-
result: {
|
|
12
|
-
select: { userId: true, accessToken: true, accessTokenExpiresAt: true }
|
|
13
|
-
}
|
|
14
|
-
};
|
|
15
|
-
const CREATE_KEY_SELECT = {
|
|
16
|
-
result: { select: { apiKey: true, keyId: true, expiresAt: true } }
|
|
17
|
-
};
|
|
18
|
-
const REVOKE_KEY_SELECT = { result: true };
|
|
19
|
-
function authedClient(endpoint, bearer) {
|
|
20
|
-
return sdk_1.auth.createClient({
|
|
21
|
-
endpoint,
|
|
22
|
-
headers: { Authorization: `Bearer ${bearer}` }
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
async function mint(client) {
|
|
26
|
-
const data = (await client.mutation
|
|
27
|
-
.createApiKey({ input: (0, api_key_1.buildCreateApiKeyInput)({ years: api_key_1.API_KEY_YEARS }) }, { select: CREATE_KEY_SELECT })
|
|
28
|
-
.unwrap());
|
|
29
|
-
return (0, api_key_1.parseMintedKey)(data?.createApiKey?.result);
|
|
30
|
-
}
|
|
31
|
-
async function revoke(client, keyId) {
|
|
32
|
-
await client.mutation.revokeApiKey({ input: { keyId } }, { select: REVOKE_KEY_SELECT }).unwrap();
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Ensure the stored session carries a usable, not-about-to-expire API key.
|
|
36
|
-
* Never throws: returns a status the caller can surface. A mint/re-mint needs
|
|
37
|
-
* the fresh-password step-up window, so it succeeds right after a sign-in and
|
|
38
|
-
* degrades to 'reauth-required' when attempted cold.
|
|
39
|
-
*/
|
|
40
|
-
async function refreshApiKeyIfNeeded({ store, context, authEndpoint }) {
|
|
41
|
-
const session = (0, account_store_1.loadSession)(store, context);
|
|
42
|
-
if (!session)
|
|
43
|
-
return 'signed-out';
|
|
44
|
-
const hasKey = !!session.apiKey;
|
|
45
|
-
const due = (0, api_key_1.needsRemint)({
|
|
46
|
-
apiKeyExpiresAt: session.apiKeyExpiresAt,
|
|
47
|
-
now: Date.now()
|
|
48
|
-
});
|
|
49
|
-
if (hasKey && !due)
|
|
50
|
-
return 'ok';
|
|
51
|
-
const client = authedClient(authEndpoint, session.accessToken);
|
|
52
|
-
try {
|
|
53
|
-
const minted = await (0, api_key_1.remintApiKey)({
|
|
54
|
-
currentKeyId: session.keyId,
|
|
55
|
-
revoke: (keyId) => revoke(client, keyId),
|
|
56
|
-
mint: () => mint(client)
|
|
57
|
-
});
|
|
58
|
-
(0, account_store_1.saveSession)(store, {
|
|
59
|
-
...session,
|
|
60
|
-
apiKey: minted.apiKey,
|
|
61
|
-
keyId: minted.keyId,
|
|
62
|
-
apiKeyExpiresAt: minted.apiKeyExpiresAt
|
|
63
|
-
}, context);
|
|
64
|
-
return 'reminted';
|
|
65
|
-
}
|
|
66
|
-
catch (err) {
|
|
67
|
-
const kind = (0, api_key_1.classifyApiKeyError)(err);
|
|
68
|
-
if (kind === 'step-up-required' || kind === 'not-authenticated')
|
|
69
|
-
return 'reauth-required';
|
|
70
|
-
console.warn(`[agent] API key refresh failed (${kind}): ${(0, auth_error_1.describeAuthError)(err, authEndpoint)}`);
|
|
71
|
-
return 'unavailable';
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
async function signIn({ store, context, authEndpoint, email, password }) {
|
|
75
|
-
const trimmedEmail = email.trim();
|
|
76
|
-
if (!trimmedEmail || !password)
|
|
77
|
-
throw new Error('Email and password are required.');
|
|
78
|
-
const client = sdk_1.auth.createClient({ endpoint: authEndpoint });
|
|
79
|
-
const request = client.mutation
|
|
80
|
-
.signIn({ input: { email: trimmedEmail, password } }, { select: SELECT })
|
|
81
|
-
.unwrap();
|
|
82
|
-
let data;
|
|
83
|
-
try {
|
|
84
|
-
data = (await (0, auth_error_1.withAuthTimeout)(request, authEndpoint));
|
|
85
|
-
}
|
|
86
|
-
catch (err) {
|
|
87
|
-
throw new Error((0, auth_error_1.describeAuthError)(err, authEndpoint));
|
|
88
|
-
}
|
|
89
|
-
const record = data?.signIn?.result;
|
|
90
|
-
if (!record?.accessToken || !record.userId) {
|
|
91
|
-
throw new Error('Authentication returned no access token (MFA may be required).');
|
|
92
|
-
}
|
|
93
|
-
(0, account_store_1.saveSession)(store, {
|
|
94
|
-
userId: record.userId,
|
|
95
|
-
email: trimmedEmail,
|
|
96
|
-
accessToken: record.accessToken,
|
|
97
|
-
...(record.accessTokenExpiresAt ? { accessTokenExpiresAt: record.accessTokenExpiresAt } : {}),
|
|
98
|
-
signedInAt: Date.now()
|
|
99
|
-
}, context);
|
|
100
|
-
// Mint the long-lived API key inside the fresh step-up window. Best-effort: a
|
|
101
|
-
// mint failure leaves a valid signed-in session that lacks a key until re-auth.
|
|
102
|
-
await refreshApiKeyIfNeeded({ store, context, authEndpoint });
|
|
103
|
-
return (0, account_store_1.loadSession)(store, context);
|
|
104
|
-
}
|
|
105
|
-
async function signOut({ store, context, authEndpoint }) {
|
|
106
|
-
const session = (0, account_store_1.loadSession)(store, context);
|
|
107
|
-
if (!session)
|
|
108
|
-
return false;
|
|
109
|
-
if (session.keyId) {
|
|
110
|
-
try {
|
|
111
|
-
await revoke(authedClient(authEndpoint, session.accessToken), session.keyId);
|
|
112
|
-
}
|
|
113
|
-
catch (err) {
|
|
114
|
-
console.warn(`[agent] API key revoke on sign-out failed: ${(0, auth_error_1.describeAuthError)(err, authEndpoint)}`);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
(0, account_store_1.clearSession)(store, context);
|
|
118
|
-
return true;
|
|
119
|
-
}
|
package/backend-store.d.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { ConfigStore } from 'appstash';
|
|
2
|
-
/** Every Constructive plane the agent talks to, one GraphQL endpoint each. */
|
|
3
|
-
export interface BackendConfig {
|
|
4
|
-
apiEndpoint: string;
|
|
5
|
-
authEndpoint: string;
|
|
6
|
-
modulesEndpoint: string;
|
|
7
|
-
agentEndpoint: string;
|
|
8
|
-
computeEndpoint: string;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* The CLI ships no backend URLs: the user names the api endpoint, and the other
|
|
12
|
-
* planes share its host scheme (api.<apex> -> auth.<apex>, modules.<apex>, ...).
|
|
13
|
-
* Throws on anything that is not an absolute URL.
|
|
14
|
-
*/
|
|
15
|
-
export declare function backendFromApiEndpoint(apiEndpoint: string): BackendConfig;
|
|
16
|
-
/**
|
|
17
|
-
* A chosen backend is a named context in the shared store, named after the api
|
|
18
|
-
* endpoint's apex (https://api.example.com/graphql -> example.com). Credentials
|
|
19
|
-
* hang off the context, so each backend keeps an independent session.
|
|
20
|
-
*/
|
|
21
|
-
export declare function contextNameFor(config: BackendConfig): string;
|
|
22
|
-
/**
|
|
23
|
-
* Endpoints of the active context, or null when no backend has been chosen or
|
|
24
|
-
* the context lacks a plane: callers must fail then, never pick a default.
|
|
25
|
-
*/
|
|
26
|
-
export declare function loadBackendConfig(store: ConfigStore): BackendConfig | null;
|
|
27
|
-
/** Persist the endpoints as a context and make it active. */
|
|
28
|
-
export declare function saveBackendConfig(store: ConfigStore, config: BackendConfig): string;
|
package/backend-store.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.backendFromApiEndpoint = backendFromApiEndpoint;
|
|
4
|
-
exports.contextNameFor = contextNameFor;
|
|
5
|
-
exports.loadBackendConfig = loadBackendConfig;
|
|
6
|
-
exports.saveBackendConfig = saveBackendConfig;
|
|
7
|
-
const pi_1 = require("@agentic-kit/pi");
|
|
8
|
-
const PLANES = ['api', 'auth', 'modules', 'agent', 'compute'];
|
|
9
|
-
const KEY = {
|
|
10
|
-
api: 'apiEndpoint',
|
|
11
|
-
auth: 'authEndpoint',
|
|
12
|
-
modules: 'modulesEndpoint',
|
|
13
|
-
agent: 'agentEndpoint',
|
|
14
|
-
compute: 'computeEndpoint'
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* The CLI ships no backend URLs: the user names the api endpoint, and the other
|
|
18
|
-
* planes share its host scheme (api.<apex> -> auth.<apex>, modules.<apex>, ...).
|
|
19
|
-
* Throws on anything that is not an absolute URL.
|
|
20
|
-
*/
|
|
21
|
-
function backendFromApiEndpoint(apiEndpoint) {
|
|
22
|
-
const api = apiEndpoint.trim();
|
|
23
|
-
const config = { apiEndpoint: api };
|
|
24
|
-
for (const plane of PLANES) {
|
|
25
|
-
if (plane === 'api')
|
|
26
|
-
continue;
|
|
27
|
-
const endpoint = api ? (0, pi_1.deriveSubdomainEndpoint)(api, plane) : '';
|
|
28
|
-
if (!endpoint)
|
|
29
|
-
throw new Error(`Invalid API endpoint URL: ${api || '(empty)'}`);
|
|
30
|
-
config[KEY[plane]] = endpoint;
|
|
31
|
-
}
|
|
32
|
-
return config;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* A chosen backend is a named context in the shared store, named after the api
|
|
36
|
-
* endpoint's apex (https://api.example.com/graphql -> example.com). Credentials
|
|
37
|
-
* hang off the context, so each backend keeps an independent session.
|
|
38
|
-
*/
|
|
39
|
-
function contextNameFor(config) {
|
|
40
|
-
const { host } = new URL(config.apiEndpoint);
|
|
41
|
-
const apex = host.includes('.') ? host.slice(host.indexOf('.') + 1) : host;
|
|
42
|
-
return apex.toLowerCase().replace(/[^a-z0-9.-]+/g, '-');
|
|
43
|
-
}
|
|
44
|
-
function toBackendConfig(targets) {
|
|
45
|
-
const config = {};
|
|
46
|
-
for (const plane of PLANES) {
|
|
47
|
-
const endpoint = targets?.[plane]?.endpoint;
|
|
48
|
-
if (!endpoint)
|
|
49
|
-
return null;
|
|
50
|
-
config[KEY[plane]] = endpoint;
|
|
51
|
-
}
|
|
52
|
-
return config;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Endpoints of the active context, or null when no backend has been chosen or
|
|
56
|
-
* the context lacks a plane: callers must fail then, never pick a default.
|
|
57
|
-
*/
|
|
58
|
-
function loadBackendConfig(store) {
|
|
59
|
-
const ctx = store.getCurrentContext();
|
|
60
|
-
if (!ctx)
|
|
61
|
-
return null;
|
|
62
|
-
return toBackendConfig(ctx.targets);
|
|
63
|
-
}
|
|
64
|
-
/** Persist the endpoints as a context and make it active. */
|
|
65
|
-
function saveBackendConfig(store, config) {
|
|
66
|
-
const name = contextNameFor(config);
|
|
67
|
-
const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }]));
|
|
68
|
-
store.createContext(name, { endpoint: config.apiEndpoint, targets });
|
|
69
|
-
store.setCurrentContext(name);
|
|
70
|
-
return name;
|
|
71
|
-
}
|
package/credentials.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export type ResolvedAccount = {
|
|
2
|
-
userId: string;
|
|
3
|
-
accessToken: string;
|
|
4
|
-
apiKey?: string;
|
|
5
|
-
};
|
|
6
|
-
export type ResolvedBackendConfig = {
|
|
7
|
-
apiEndpoint: string;
|
|
8
|
-
modulesEndpoint: string;
|
|
9
|
-
agentEndpoint: string;
|
|
10
|
-
computeEndpoint: string;
|
|
11
|
-
};
|
|
12
|
-
export declare function resolveAccount(): ResolvedAccount | null;
|
|
13
|
-
export declare function resolveBackendConfig(): ResolvedBackendConfig | undefined;
|
package/credentials.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.resolveAccount = resolveAccount;
|
|
4
|
-
exports.resolveBackendConfig = resolveBackendConfig;
|
|
5
|
-
const account_store_1 = require("./account-store");
|
|
6
|
-
const backend_store_1 = require("./backend-store");
|
|
7
|
-
const config_1 = require("./config");
|
|
8
|
-
// Both resolvers run on every tool call and re-read the store, so a login or
|
|
9
|
-
// logout mid-session is picked up without a restart. CONSTRUCTIVE_* env vars
|
|
10
|
-
// win over the store (the CI/headless path); tokens never enter process.env
|
|
11
|
-
// from here.
|
|
12
|
-
function resolveAccount() {
|
|
13
|
-
const userId = process.env.CONSTRUCTIVE_USER_ID;
|
|
14
|
-
const accessToken = process.env.CONSTRUCTIVE_ACCESS_TOKEN;
|
|
15
|
-
if (userId && accessToken) {
|
|
16
|
-
return { userId, accessToken, apiKey: process.env.CONSTRUCTIVE_API_KEY };
|
|
17
|
-
}
|
|
18
|
-
const session = (0, account_store_1.loadSession)((0, config_1.loadConfig)(process.env.AGENT_HOME).store);
|
|
19
|
-
if (!session)
|
|
20
|
-
return null;
|
|
21
|
-
return { userId: session.userId, accessToken: session.accessToken, apiKey: session.apiKey };
|
|
22
|
-
}
|
|
23
|
-
// CONSTRUCTIVE_API_ENDPOINT picks the whole backend: the other planes derive
|
|
24
|
-
// from it unless their own CONSTRUCTIVE_*_ENDPOINT is set. A plane override
|
|
25
|
-
// without an api endpoint names no backend, so it is an error, never a partial
|
|
26
|
-
// config the tools would complete with a guess.
|
|
27
|
-
function resolveBackendConfig() {
|
|
28
|
-
const env = process.env;
|
|
29
|
-
const overrides = {
|
|
30
|
-
modulesEndpoint: env.CONSTRUCTIVE_MODULES_ENDPOINT,
|
|
31
|
-
agentEndpoint: env.CONSTRUCTIVE_AGENT_ENDPOINT,
|
|
32
|
-
computeEndpoint: env.CONSTRUCTIVE_COMPUTE_ENDPOINT
|
|
33
|
-
};
|
|
34
|
-
const backend = env.CONSTRUCTIVE_API_ENDPOINT
|
|
35
|
-
? (0, backend_store_1.backendFromApiEndpoint)(env.CONSTRUCTIVE_API_ENDPOINT)
|
|
36
|
-
: (0, backend_store_1.loadBackendConfig)((0, config_1.loadConfig)(env.AGENT_HOME).store);
|
|
37
|
-
if (!backend) {
|
|
38
|
-
const stray = Object.entries(overrides).find(([, value]) => value);
|
|
39
|
-
if (stray)
|
|
40
|
-
throw new Error('CONSTRUCTIVE_API_ENDPOINT is required when any CONSTRUCTIVE_*_ENDPOINT override is set.');
|
|
41
|
-
return undefined;
|
|
42
|
-
}
|
|
43
|
-
return {
|
|
44
|
-
apiEndpoint: backend.apiEndpoint,
|
|
45
|
-
modulesEndpoint: overrides.modulesEndpoint || backend.modulesEndpoint,
|
|
46
|
-
agentEndpoint: overrides.agentEndpoint || backend.agentEndpoint,
|
|
47
|
-
computeEndpoint: overrides.computeEndpoint || backend.computeEndpoint
|
|
48
|
-
};
|
|
49
|
-
}
|
package/esm/account-store.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { ConfigStore } from 'appstash';
|
|
2
|
-
export interface AccountSession {
|
|
3
|
-
userId: string;
|
|
4
|
-
email: string;
|
|
5
|
-
accessToken: string;
|
|
6
|
-
accessTokenExpiresAt?: string;
|
|
7
|
-
apiKey?: string;
|
|
8
|
-
keyId?: string;
|
|
9
|
-
apiKeyExpiresAt?: string;
|
|
10
|
-
signedInAt: number;
|
|
11
|
-
}
|
|
12
|
-
export declare function loadSession(store: ConfigStore, context?: string): AccountSession | null;
|
|
13
|
-
/**
|
|
14
|
-
* `context` names the backend the session belongs to; it does not have to exist
|
|
15
|
-
* as a context yet, so a sign-in can be filed before the backend is committed
|
|
16
|
-
* and a failed sign-in leaves nothing behind.
|
|
17
|
-
*/
|
|
18
|
-
export declare function saveSession(store: ConfigStore, session: AccountSession, context?: string): void;
|
|
19
|
-
export declare function clearSession(store: ConfigStore, context?: string): void;
|
package/esm/account-store.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sessions live in the shared Constructive stash, as the credentials of the
|
|
3
|
-
* active context (the chosen backend). The store owns the file layout, the
|
|
4
|
-
* atomic 0600 writes and the at-rest encoding; this module only maps between
|
|
5
|
-
* its `ContextCredentials` and the session shape the CLI passes around.
|
|
6
|
-
*/
|
|
7
|
-
function currentContextName(store) {
|
|
8
|
-
return store.getCurrentContext()?.name ?? null;
|
|
9
|
-
}
|
|
10
|
-
/** The active context; a session is never filed under a backend nobody chose. */
|
|
11
|
-
function ensureContextName(store) {
|
|
12
|
-
const name = currentContextName(store);
|
|
13
|
-
if (!name)
|
|
14
|
-
throw new Error('No backend chosen — run `agent login` first.');
|
|
15
|
-
return name;
|
|
16
|
-
}
|
|
17
|
-
export function loadSession(store, context) {
|
|
18
|
-
const contextName = context ?? currentContextName(store);
|
|
19
|
-
if (!contextName)
|
|
20
|
-
return null;
|
|
21
|
-
const creds = store.getCredentials(contextName);
|
|
22
|
-
if (!creds?.token || !creds.userId)
|
|
23
|
-
return null;
|
|
24
|
-
return {
|
|
25
|
-
userId: creds.userId,
|
|
26
|
-
email: creds.email ?? '',
|
|
27
|
-
accessToken: creds.token,
|
|
28
|
-
accessTokenExpiresAt: creds.expiresAt,
|
|
29
|
-
apiKey: creds.apiKey,
|
|
30
|
-
keyId: creds.keyId,
|
|
31
|
-
apiKeyExpiresAt: creds.apiKeyExpiresAt,
|
|
32
|
-
signedInAt: creds.signedInAt ?? 0
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* `context` names the backend the session belongs to; it does not have to exist
|
|
37
|
-
* as a context yet, so a sign-in can be filed before the backend is committed
|
|
38
|
-
* and a failed sign-in leaves nothing behind.
|
|
39
|
-
*/
|
|
40
|
-
export function saveSession(store, session, context) {
|
|
41
|
-
store.setCredentials(context ?? ensureContextName(store), {
|
|
42
|
-
token: session.accessToken,
|
|
43
|
-
expiresAt: session.accessTokenExpiresAt,
|
|
44
|
-
userId: session.userId,
|
|
45
|
-
email: session.email,
|
|
46
|
-
apiKey: session.apiKey,
|
|
47
|
-
keyId: session.keyId,
|
|
48
|
-
apiKeyExpiresAt: session.apiKeyExpiresAt,
|
|
49
|
-
signedInAt: session.signedInAt
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
export function clearSession(store, context) {
|
|
53
|
-
const contextName = context ?? currentContextName(store);
|
|
54
|
-
if (contextName)
|
|
55
|
-
store.removeCredentials(contextName);
|
|
56
|
-
}
|
package/esm/api-key.d.ts
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
export declare const API_KEY_NAME = "agentic-cli";
|
|
2
|
-
export declare const API_KEY_ACCESS_LEVEL = "full_access";
|
|
3
|
-
export declare const API_KEY_MFA_LEVEL = "none";
|
|
4
|
-
export declare const API_KEY_YEARS = 5;
|
|
5
|
-
/**
|
|
6
|
-
* Re-mint once the key is within a week of expiry. The mint needs a
|
|
7
|
-
* fresh-password step-up window, so in practice the refresh succeeds only right
|
|
8
|
-
* after a sign-in; otherwise it surfaces as a re-auth prompt.
|
|
9
|
-
*/
|
|
10
|
-
export declare const REMINT_THRESHOLD_MS: number;
|
|
11
|
-
export interface MintedApiKey {
|
|
12
|
-
apiKey: string;
|
|
13
|
-
keyId: string;
|
|
14
|
-
apiKeyExpiresAt?: string;
|
|
15
|
-
}
|
|
16
|
-
export interface CreateApiKeyInputShape {
|
|
17
|
-
keyName: string;
|
|
18
|
-
accessLevel: string;
|
|
19
|
-
mfaLevel: string;
|
|
20
|
-
expiresIn: {
|
|
21
|
-
years: number;
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
export declare function buildCreateApiKeyInput({ years }: {
|
|
25
|
-
years: number;
|
|
26
|
-
}): CreateApiKeyInputShape;
|
|
27
|
-
interface RawApiKeyRecord {
|
|
28
|
-
apiKey?: string | null;
|
|
29
|
-
keyId?: string | null;
|
|
30
|
-
expiresAt?: string | null;
|
|
31
|
-
}
|
|
32
|
-
export declare function parseMintedKey(record: RawApiKeyRecord | null | undefined): MintedApiKey;
|
|
33
|
-
export type ApiKeyErrorKind = 'step-up-required' | 'disabled' | 'limit-reached' | 'not-authenticated' | 'invalid-access-level' | 'unknown';
|
|
34
|
-
export declare function classifyApiKeyError(err: unknown): ApiKeyErrorKind;
|
|
35
|
-
export declare function needsRemint({ apiKeyExpiresAt, now, thresholdMs }: {
|
|
36
|
-
apiKeyExpiresAt: string | undefined;
|
|
37
|
-
now: number;
|
|
38
|
-
thresholdMs?: number;
|
|
39
|
-
}): boolean;
|
|
40
|
-
/**
|
|
41
|
-
* Mint-first, revoke-on-success: revoking before minting would destroy a
|
|
42
|
-
* still-valid key whenever the mint then fails, leaving no credential at all.
|
|
43
|
-
* The one case that needs the old key gone first is the live-key cap
|
|
44
|
-
* (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once.
|
|
45
|
-
*/
|
|
46
|
-
export declare function remintApiKey({ currentKeyId, revoke, mint }: {
|
|
47
|
-
currentKeyId: string | undefined;
|
|
48
|
-
revoke: (keyId: string) => Promise<void>;
|
|
49
|
-
mint: () => Promise<MintedApiKey>;
|
|
50
|
-
}): Promise<MintedApiKey>;
|
|
51
|
-
export {};
|
package/esm/api-key.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
export const API_KEY_NAME = 'agentic-cli';
|
|
2
|
-
export const API_KEY_ACCESS_LEVEL = 'full_access';
|
|
3
|
-
export const API_KEY_MFA_LEVEL = 'none';
|
|
4
|
-
export const API_KEY_YEARS = 5;
|
|
5
|
-
/**
|
|
6
|
-
* Re-mint once the key is within a week of expiry. The mint needs a
|
|
7
|
-
* fresh-password step-up window, so in practice the refresh succeeds only right
|
|
8
|
-
* after a sign-in; otherwise it surfaces as a re-auth prompt.
|
|
9
|
-
*/
|
|
10
|
-
export const REMINT_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 7;
|
|
11
|
-
export function buildCreateApiKeyInput({ years }) {
|
|
12
|
-
return {
|
|
13
|
-
keyName: API_KEY_NAME,
|
|
14
|
-
accessLevel: API_KEY_ACCESS_LEVEL,
|
|
15
|
-
mfaLevel: API_KEY_MFA_LEVEL,
|
|
16
|
-
expiresIn: { years }
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
export function parseMintedKey(record) {
|
|
20
|
-
if (!record?.apiKey || !record.keyId) {
|
|
21
|
-
throw new Error('createApiKey returned no API key.');
|
|
22
|
-
}
|
|
23
|
-
return {
|
|
24
|
-
apiKey: record.apiKey,
|
|
25
|
-
keyId: record.keyId,
|
|
26
|
-
...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {})
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
const ERROR_CODE_MAP = {
|
|
30
|
-
STEP_UP_REQUIRED: 'step-up-required',
|
|
31
|
-
API_KEYS_DISABLED: 'disabled',
|
|
32
|
-
API_KEY_LIMIT_REACHED: 'limit-reached',
|
|
33
|
-
NOT_AUTHENTICATED: 'not-authenticated',
|
|
34
|
-
INVALID_ACCESS_LEVEL: 'invalid-access-level'
|
|
35
|
-
};
|
|
36
|
-
export function classifyApiKeyError(err) {
|
|
37
|
-
const errors = err?.errors;
|
|
38
|
-
if (Array.isArray(errors)) {
|
|
39
|
-
for (const e of errors) {
|
|
40
|
-
const code = e.extensions?.code;
|
|
41
|
-
if (code && ERROR_CODE_MAP[code])
|
|
42
|
-
return ERROR_CODE_MAP[code];
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';
|
|
46
|
-
for (const code of Object.keys(ERROR_CODE_MAP)) {
|
|
47
|
-
if (message.includes(code))
|
|
48
|
-
return ERROR_CODE_MAP[code];
|
|
49
|
-
}
|
|
50
|
-
return 'unknown';
|
|
51
|
-
}
|
|
52
|
-
export function needsRemint({ apiKeyExpiresAt, now, thresholdMs = REMINT_THRESHOLD_MS }) {
|
|
53
|
-
if (!apiKeyExpiresAt)
|
|
54
|
-
return false;
|
|
55
|
-
const expires = Date.parse(apiKeyExpiresAt);
|
|
56
|
-
if (Number.isNaN(expires))
|
|
57
|
-
return false;
|
|
58
|
-
return expires - now <= thresholdMs;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Mint-first, revoke-on-success: revoking before minting would destroy a
|
|
62
|
-
* still-valid key whenever the mint then fails, leaving no credential at all.
|
|
63
|
-
* The one case that needs the old key gone first is the live-key cap
|
|
64
|
-
* (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once.
|
|
65
|
-
*/
|
|
66
|
-
export async function remintApiKey({ currentKeyId, revoke, mint }) {
|
|
67
|
-
const revokeOld = async () => {
|
|
68
|
-
if (!currentKeyId)
|
|
69
|
-
return;
|
|
70
|
-
try {
|
|
71
|
-
await revoke(currentKeyId);
|
|
72
|
-
}
|
|
73
|
-
catch (err) {
|
|
74
|
-
console.warn(`[agent] failed to revoke superseded API key ${currentKeyId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
try {
|
|
78
|
-
const minted = await mint();
|
|
79
|
-
await revokeOld();
|
|
80
|
-
return minted;
|
|
81
|
-
}
|
|
82
|
-
catch (err) {
|
|
83
|
-
if (classifyApiKeyError(err) !== 'limit-reached')
|
|
84
|
-
throw err;
|
|
85
|
-
await revokeOld();
|
|
86
|
-
return mint();
|
|
87
|
-
}
|
|
88
|
-
}
|
package/esm/auth-error.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
export declare function isNetworkError(err: unknown): boolean;
|
|
2
|
-
export declare function describeAuthError(err: unknown, endpoint: string): string;
|
|
3
|
-
export declare const AUTH_TIMEOUT_MS = 10000;
|
|
4
|
-
export declare function withAuthTimeout<T>(promise: Promise<T>, endpoint: string, ms?: number): Promise<T>;
|
package/esm/auth-error.js
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
const NETWORK_ERROR_CODES = new Set([
|
|
2
|
-
'ECONNREFUSED',
|
|
3
|
-
'ECONNRESET',
|
|
4
|
-
'ENOTFOUND',
|
|
5
|
-
'EAI_AGAIN',
|
|
6
|
-
'EHOSTUNREACH',
|
|
7
|
-
'ENETUNREACH',
|
|
8
|
-
'ETIMEDOUT',
|
|
9
|
-
'UND_ERR_CONNECT_TIMEOUT',
|
|
10
|
-
'UND_ERR_SOCKET'
|
|
11
|
-
]);
|
|
12
|
-
function errorCode(err) {
|
|
13
|
-
if (!err || typeof err !== 'object')
|
|
14
|
-
return undefined;
|
|
15
|
-
const { code, cause } = err;
|
|
16
|
-
if (typeof code === 'string')
|
|
17
|
-
return code;
|
|
18
|
-
if (cause && typeof cause === 'object') {
|
|
19
|
-
const causeCode = cause.code;
|
|
20
|
-
if (typeof causeCode === 'string')
|
|
21
|
-
return causeCode;
|
|
22
|
-
}
|
|
23
|
-
return undefined;
|
|
24
|
-
}
|
|
25
|
-
export function isNetworkError(err) {
|
|
26
|
-
const code = errorCode(err);
|
|
27
|
-
if (code !== undefined)
|
|
28
|
-
return NETWORK_ERROR_CODES.has(code);
|
|
29
|
-
if (err instanceof AggregateError)
|
|
30
|
-
return true;
|
|
31
|
-
return err instanceof TypeError && /fetch failed/i.test(err.message);
|
|
32
|
-
}
|
|
33
|
-
function extractGraphqlMessages(err) {
|
|
34
|
-
const messages = [];
|
|
35
|
-
const codes = [];
|
|
36
|
-
const visited = new Set();
|
|
37
|
-
const visit = (value) => {
|
|
38
|
-
if (!value || typeof value !== 'object' || visited.has(value))
|
|
39
|
-
return;
|
|
40
|
-
visited.add(value);
|
|
41
|
-
const record = value;
|
|
42
|
-
if (typeof record.message === 'string' && record.message.trim() !== '') {
|
|
43
|
-
const message = record.message.trim().replace(/^GraphQL Error:\s*/u, '');
|
|
44
|
-
if (message.length > 0)
|
|
45
|
-
messages.push(message);
|
|
46
|
-
}
|
|
47
|
-
const extensions = record.extensions && typeof record.extensions === 'object'
|
|
48
|
-
? record.extensions
|
|
49
|
-
: undefined;
|
|
50
|
-
if (typeof extensions?.code === 'string')
|
|
51
|
-
codes.push(extensions.code);
|
|
52
|
-
if (Array.isArray(record.errors))
|
|
53
|
-
record.errors.forEach(visit);
|
|
54
|
-
if (record.cause)
|
|
55
|
-
visit(record.cause);
|
|
56
|
-
if (record.extensions)
|
|
57
|
-
visit(record.extensions);
|
|
58
|
-
if (record.detail)
|
|
59
|
-
visit(record.detail);
|
|
60
|
-
if (record.data)
|
|
61
|
-
visit(record.data);
|
|
62
|
-
if (record.response)
|
|
63
|
-
visit(record.response);
|
|
64
|
-
if (record.result)
|
|
65
|
-
visit(record.result);
|
|
66
|
-
if (record.payload)
|
|
67
|
-
visit(record.payload);
|
|
68
|
-
};
|
|
69
|
-
visit(err);
|
|
70
|
-
if (messages.length === 0) {
|
|
71
|
-
for (const code of codes) {
|
|
72
|
-
if (code === 'UNAUTHENTICATED')
|
|
73
|
-
messages.push('Your session has expired. Sign in again.');
|
|
74
|
-
if (code === 'FORBIDDEN') {
|
|
75
|
-
messages.push('The server rejected this request. Check your account permissions.');
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return [...new Set(messages)];
|
|
80
|
-
}
|
|
81
|
-
export function describeAuthError(err, endpoint) {
|
|
82
|
-
if (isNetworkError(err)) {
|
|
83
|
-
return `Could not reach the server at ${endpoint}. Check that it is running, or pick a different backend.`;
|
|
84
|
-
}
|
|
85
|
-
const graphqlMessages = extractGraphqlMessages(err);
|
|
86
|
-
if (graphqlMessages.length > 0)
|
|
87
|
-
return graphqlMessages.join('; ');
|
|
88
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
89
|
-
if (message.trim() !== '' && message !== '[object Object]')
|
|
90
|
-
return message;
|
|
91
|
-
const name = err instanceof Error ? err.name : typeof err;
|
|
92
|
-
return `Authentication failed unexpectedly (${name}).`;
|
|
93
|
-
}
|
|
94
|
-
export const AUTH_TIMEOUT_MS = 10_000;
|
|
95
|
-
export function withAuthTimeout(promise, endpoint, ms = AUTH_TIMEOUT_MS) {
|
|
96
|
-
return new Promise((resolve, reject) => {
|
|
97
|
-
const timer = setTimeout(() => {
|
|
98
|
-
reject(new Error(`The server at ${endpoint} did not respond within ${Math.round(ms / 1000)}s. Check the backend settings and try again.`));
|
|
99
|
-
}, ms);
|
|
100
|
-
promise.then(value => {
|
|
101
|
-
clearTimeout(timer);
|
|
102
|
-
resolve(value);
|
|
103
|
-
}, (err) => {
|
|
104
|
-
clearTimeout(timer);
|
|
105
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
106
|
-
});
|
|
107
|
-
});
|
|
108
|
-
}
|
package/esm/auth.d.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { ConfigStore } from 'appstash';
|
|
2
|
-
import { AccountSession } from './account-store';
|
|
3
|
-
export type ApiKeyRefreshStatus = 'ok' | 'reminted' | 'reauth-required' | 'unavailable' | 'signed-out';
|
|
4
|
-
/**
|
|
5
|
-
* Ensure the stored session carries a usable, not-about-to-expire API key.
|
|
6
|
-
* Never throws: returns a status the caller can surface. A mint/re-mint needs
|
|
7
|
-
* the fresh-password step-up window, so it succeeds right after a sign-in and
|
|
8
|
-
* degrades to 'reauth-required' when attempted cold.
|
|
9
|
-
*/
|
|
10
|
-
export declare function refreshApiKeyIfNeeded({ store, context, authEndpoint }: {
|
|
11
|
-
store: ConfigStore;
|
|
12
|
-
/** Backend context the session is filed under; defaults to the active one. */
|
|
13
|
-
context?: string;
|
|
14
|
-
authEndpoint: string;
|
|
15
|
-
}): Promise<ApiKeyRefreshStatus>;
|
|
16
|
-
export declare function signIn({ store, context, authEndpoint, email, password }: {
|
|
17
|
-
store: ConfigStore;
|
|
18
|
-
context?: string;
|
|
19
|
-
authEndpoint: string;
|
|
20
|
-
email: string;
|
|
21
|
-
password: string;
|
|
22
|
-
}): Promise<AccountSession>;
|
|
23
|
-
export declare function signOut({ store, context, authEndpoint }: {
|
|
24
|
-
store: ConfigStore;
|
|
25
|
-
/** Backend context the session is filed under; defaults to the active one. */
|
|
26
|
-
context?: string;
|
|
27
|
-
authEndpoint: string;
|
|
28
|
-
}): Promise<boolean>;
|