@agentic-kit/cli 0.22.1 → 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/esm/auth.js DELETED
@@ -1,114 +0,0 @@
1
- import { auth } from '@constructive-io/sdk';
2
- import { clearSession, loadSession, saveSession } from './account-store';
3
- import { API_KEY_YEARS, buildCreateApiKeyInput, classifyApiKeyError, needsRemint, parseMintedKey, remintApiKey } from './api-key';
4
- import { describeAuthError, withAuthTimeout } from './auth-error';
5
- const SELECT = {
6
- result: {
7
- select: { userId: true, accessToken: true, accessTokenExpiresAt: true }
8
- }
9
- };
10
- const CREATE_KEY_SELECT = {
11
- result: { select: { apiKey: true, keyId: true, expiresAt: true } }
12
- };
13
- const REVOKE_KEY_SELECT = { result: true };
14
- function authedClient(endpoint, bearer) {
15
- return auth.createClient({
16
- endpoint,
17
- headers: { Authorization: `Bearer ${bearer}` }
18
- });
19
- }
20
- async function mint(client) {
21
- const data = (await client.mutation
22
- .createApiKey({ input: buildCreateApiKeyInput({ years: API_KEY_YEARS }) }, { select: CREATE_KEY_SELECT })
23
- .unwrap());
24
- return parseMintedKey(data?.createApiKey?.result);
25
- }
26
- async function revoke(client, keyId) {
27
- await client.mutation.revokeApiKey({ input: { keyId } }, { select: REVOKE_KEY_SELECT }).unwrap();
28
- }
29
- /**
30
- * Ensure the stored session carries a usable, not-about-to-expire API key.
31
- * Never throws: returns a status the caller can surface. A mint/re-mint needs
32
- * the fresh-password step-up window, so it succeeds right after a sign-in and
33
- * degrades to 'reauth-required' when attempted cold.
34
- */
35
- export async function refreshApiKeyIfNeeded({ store, context, authEndpoint }) {
36
- const session = loadSession(store, context);
37
- if (!session)
38
- return 'signed-out';
39
- const hasKey = !!session.apiKey;
40
- const due = needsRemint({
41
- apiKeyExpiresAt: session.apiKeyExpiresAt,
42
- now: Date.now()
43
- });
44
- if (hasKey && !due)
45
- return 'ok';
46
- const client = authedClient(authEndpoint, session.accessToken);
47
- try {
48
- const minted = await remintApiKey({
49
- currentKeyId: session.keyId,
50
- revoke: (keyId) => revoke(client, keyId),
51
- mint: () => mint(client)
52
- });
53
- saveSession(store, {
54
- ...session,
55
- apiKey: minted.apiKey,
56
- keyId: minted.keyId,
57
- apiKeyExpiresAt: minted.apiKeyExpiresAt
58
- }, context);
59
- return 'reminted';
60
- }
61
- catch (err) {
62
- const kind = classifyApiKeyError(err);
63
- if (kind === 'step-up-required' || kind === 'not-authenticated')
64
- return 'reauth-required';
65
- console.warn(`[agent] API key refresh failed (${kind}): ${describeAuthError(err, authEndpoint)}`);
66
- return 'unavailable';
67
- }
68
- }
69
- export async function signIn({ store, context, authEndpoint, email, password }) {
70
- const trimmedEmail = email.trim();
71
- if (!trimmedEmail || !password)
72
- throw new Error('Email and password are required.');
73
- const client = auth.createClient({ endpoint: authEndpoint });
74
- const request = client.mutation
75
- .signIn({ input: { email: trimmedEmail, password } }, { select: SELECT })
76
- .unwrap();
77
- let data;
78
- try {
79
- data = (await withAuthTimeout(request, authEndpoint));
80
- }
81
- catch (err) {
82
- throw new Error(describeAuthError(err, authEndpoint));
83
- }
84
- const record = data?.signIn?.result;
85
- if (!record?.accessToken || !record.userId) {
86
- throw new Error('Authentication returned no access token (MFA may be required).');
87
- }
88
- saveSession(store, {
89
- userId: record.userId,
90
- email: trimmedEmail,
91
- accessToken: record.accessToken,
92
- ...(record.accessTokenExpiresAt ? { accessTokenExpiresAt: record.accessTokenExpiresAt } : {}),
93
- signedInAt: Date.now()
94
- }, context);
95
- // Mint the long-lived API key inside the fresh step-up window. Best-effort: a
96
- // mint failure leaves a valid signed-in session that lacks a key until re-auth.
97
- await refreshApiKeyIfNeeded({ store, context, authEndpoint });
98
- return loadSession(store, context);
99
- }
100
- export async function signOut({ store, context, authEndpoint }) {
101
- const session = loadSession(store, context);
102
- if (!session)
103
- return false;
104
- if (session.keyId) {
105
- try {
106
- await revoke(authedClient(authEndpoint, session.accessToken), session.keyId);
107
- }
108
- catch (err) {
109
- console.warn(`[agent] API key revoke on sign-out failed: ${describeAuthError(err, authEndpoint)}`);
110
- }
111
- }
112
- clearSession(store, context);
113
- return true;
114
- }
@@ -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;
@@ -1,65 +0,0 @@
1
- import { deriveSubdomainEndpoint } from '@agentic-kit/pi';
2
- const PLANES = ['api', 'auth', 'modules', 'agent', 'compute'];
3
- const KEY = {
4
- api: 'apiEndpoint',
5
- auth: 'authEndpoint',
6
- modules: 'modulesEndpoint',
7
- agent: 'agentEndpoint',
8
- compute: 'computeEndpoint'
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 function backendFromApiEndpoint(apiEndpoint) {
16
- const api = apiEndpoint.trim();
17
- const config = { apiEndpoint: api };
18
- for (const plane of PLANES) {
19
- if (plane === 'api')
20
- continue;
21
- const endpoint = api ? deriveSubdomainEndpoint(api, plane) : '';
22
- if (!endpoint)
23
- throw new Error(`Invalid API endpoint URL: ${api || '(empty)'}`);
24
- config[KEY[plane]] = endpoint;
25
- }
26
- return config;
27
- }
28
- /**
29
- * A chosen backend is a named context in the shared store, named after the api
30
- * endpoint's apex (https://api.example.com/graphql -> example.com). Credentials
31
- * hang off the context, so each backend keeps an independent session.
32
- */
33
- export function contextNameFor(config) {
34
- const { host } = new URL(config.apiEndpoint);
35
- const apex = host.includes('.') ? host.slice(host.indexOf('.') + 1) : host;
36
- return apex.toLowerCase().replace(/[^a-z0-9.-]+/g, '-');
37
- }
38
- function toBackendConfig(targets) {
39
- const config = {};
40
- for (const plane of PLANES) {
41
- const endpoint = targets?.[plane]?.endpoint;
42
- if (!endpoint)
43
- return null;
44
- config[KEY[plane]] = endpoint;
45
- }
46
- return config;
47
- }
48
- /**
49
- * Endpoints of the active context, or null when no backend has been chosen or
50
- * the context lacks a plane: callers must fail then, never pick a default.
51
- */
52
- export function loadBackendConfig(store) {
53
- const ctx = store.getCurrentContext();
54
- if (!ctx)
55
- return null;
56
- return toBackendConfig(ctx.targets);
57
- }
58
- /** Persist the endpoints as a context and make it active. */
59
- export function saveBackendConfig(store, config) {
60
- const name = contextNameFor(config);
61
- const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }]));
62
- store.createContext(name, { endpoint: config.apiEndpoint, targets });
63
- store.setCurrentContext(name);
64
- return name;
65
- }
@@ -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;
@@ -1,45 +0,0 @@
1
- import { loadSession } from './account-store';
2
- import { backendFromApiEndpoint, loadBackendConfig } from './backend-store';
3
- import { loadConfig } from './config';
4
- // Both resolvers run on every tool call and re-read the store, so a login or
5
- // logout mid-session is picked up without a restart. CONSTRUCTIVE_* env vars
6
- // win over the store (the CI/headless path); tokens never enter process.env
7
- // from here.
8
- export function resolveAccount() {
9
- const userId = process.env.CONSTRUCTIVE_USER_ID;
10
- const accessToken = process.env.CONSTRUCTIVE_ACCESS_TOKEN;
11
- if (userId && accessToken) {
12
- return { userId, accessToken, apiKey: process.env.CONSTRUCTIVE_API_KEY };
13
- }
14
- const session = loadSession(loadConfig(process.env.AGENT_HOME).store);
15
- if (!session)
16
- return null;
17
- return { userId: session.userId, accessToken: session.accessToken, apiKey: session.apiKey };
18
- }
19
- // CONSTRUCTIVE_API_ENDPOINT picks the whole backend: the other planes derive
20
- // from it unless their own CONSTRUCTIVE_*_ENDPOINT is set. A plane override
21
- // without an api endpoint names no backend, so it is an error, never a partial
22
- // config the tools would complete with a guess.
23
- export function resolveBackendConfig() {
24
- const env = process.env;
25
- const overrides = {
26
- modulesEndpoint: env.CONSTRUCTIVE_MODULES_ENDPOINT,
27
- agentEndpoint: env.CONSTRUCTIVE_AGENT_ENDPOINT,
28
- computeEndpoint: env.CONSTRUCTIVE_COMPUTE_ENDPOINT
29
- };
30
- const backend = env.CONSTRUCTIVE_API_ENDPOINT
31
- ? backendFromApiEndpoint(env.CONSTRUCTIVE_API_ENDPOINT)
32
- : loadBackendConfig(loadConfig(env.AGENT_HOME).store);
33
- if (!backend) {
34
- const stray = Object.entries(overrides).find(([, value]) => value);
35
- if (stray)
36
- throw new Error('CONSTRUCTIVE_API_ENDPOINT is required when any CONSTRUCTIVE_*_ENDPOINT override is set.');
37
- return undefined;
38
- }
39
- return {
40
- apiEndpoint: backend.apiEndpoint,
41
- modulesEndpoint: overrides.modulesEndpoint || backend.modulesEndpoint,
42
- agentEndpoint: overrides.agentEndpoint || backend.agentEndpoint,
43
- computeEndpoint: overrides.computeEndpoint || backend.computeEndpoint
44
- };
45
- }