@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/esm/config.js CHANGED
@@ -1,15 +1,8 @@
1
1
  import { harnessDirs } from '@agentic-kit/harness';
2
- import { createConfigStore } from 'appstash';
2
+ import { openStore, STASH_NAME, stashBaseDir } from '@agentic-kit/session';
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  export const DEFAULT_SKILLS_REPO = 'constructive-io/constructive-skills';
6
- /**
7
- * Directory identity shared with the csdk CLI and the desktop app, so a sign-in
8
- * here is a sign-in there. `agent` is only the tool's own name (env prefixes,
9
- * help text).
10
- */
11
- export const STASH_NAME = 'constructive';
12
- export const TOOL_NAME = 'agent';
13
6
  export const DEFAULT_SKILLS_PIN = 'main';
14
7
  /** Layer names understood by the assembler. */
15
8
  export const BASE_LAYER = 'constructive-skills';
@@ -19,12 +12,12 @@ export function defaultManifest() {
19
12
  sources: [{ name: BASE_LAYER }, { name: OVERLAY_LAYER }]
20
13
  };
21
14
  }
22
- export function loadConfig(baseDir) {
23
- const dirs = harnessDirs('constructive', baseDir);
15
+ export function loadConfig(baseDir = stashBaseDir()) {
16
+ const dirs = harnessDirs(STASH_NAME, baseDir);
24
17
  const agentDir = path.join(dirs.stash.data, 'agent');
25
18
  const overlayDir = path.join(dirs.stash.config, 'skills-overlay');
26
19
  const manifestFile = path.join(dirs.stash.config, 'skills-manifest.json');
27
- const store = createConfigStore(TOOL_NAME, { stashName: STASH_NAME, baseDir });
20
+ const store = openStore(baseDir);
28
21
  fs.mkdirSync(agentDir, { recursive: true });
29
22
  fs.mkdirSync(overlayDir, { recursive: true });
30
23
  let file = {};
package/esm/db-tools.d.ts CHANGED
@@ -1,9 +1,4 @@
1
1
  import { AgentCliConfig } from './config';
2
- /**
3
- * Environment variables that override the stored session at tool-call time.
4
- * Without env vars or a stored session the tools load but report "not signed in".
5
- */
6
- export declare const HOST_ENV_VARS: readonly ["CONSTRUCTIVE_USER_ID", "CONSTRUCTIVE_ACCESS_TOKEN", "CONSTRUCTIVE_API_KEY", "CONSTRUCTIVE_API_ENDPOINT", "CONSTRUCTIVE_MODULES_ENDPOINT", "CONSTRUCTIVE_AGENT_ENDPOINT", "CONSTRUCTIVE_COMPUTE_ENDPOINT"];
7
2
  /**
8
3
  * Write the db-tools extension entry into pi's agent dir. Returns the file
9
4
  * path, or null when @agentic-kit/pi is not installed alongside the CLI.
package/esm/db-tools.js CHANGED
@@ -1,37 +1,24 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
+ import { REPAIR_HINT } from './commands';
3
4
  const EXTENSION_FILE = 'constructive-db-tools.js';
4
- /**
5
- * Environment variables that override the stored session at tool-call time.
6
- * Without env vars or a stored session the tools load but report "not signed in".
7
- */
8
- export const HOST_ENV_VARS = [
9
- 'CONSTRUCTIVE_USER_ID',
10
- 'CONSTRUCTIVE_ACCESS_TOKEN',
11
- 'CONSTRUCTIVE_API_KEY',
12
- 'CONSTRUCTIVE_API_ENDPOINT',
13
- 'CONSTRUCTIVE_MODULES_ENDPOINT',
14
- 'CONSTRUCTIVE_AGENT_ENDPOINT',
15
- 'CONSTRUCTIVE_COMPUTE_ENDPOINT'
16
- ];
17
5
  // pi's TUI loads extensions from files under <agentDir>/extensions (via jiti),
18
6
  // not from factories, so the db tools are wired by materializing a small
19
7
  // generated entry there. Both entry paths are resolved from THIS package at
20
8
  // assembly time and baked in, because node resolution from the appstash agent
21
9
  // dir would not find them.
22
- function extensionSource(pkgEntry, credentialsEntry) {
10
+ function extensionSource(pkgEntry, sessionEntry) {
23
11
  return `// Generated by @agentic-kit/cli — do not edit (rewritten on every \`agent\` run).
24
12
  // Registers the Constructive typed db tools + confirm gate (@agentic-kit/pi)
25
13
  // with credentials resolved on each call: CONSTRUCTIVE_* env vars first, then
26
- // the \`agent login\` session store.
14
+ // the shared session store (@agentic-kit/session).
27
15
  const { createDbTools } = require(${JSON.stringify(pkgEntry)});
28
- const { resolveAccount, resolveBackendConfig } = require(${JSON.stringify(credentialsEntry)});
16
+ const { sessionToolsHost } = require(${JSON.stringify(sessionEntry)});
29
17
 
30
- module.exports = createDbTools({
31
- account: resolveAccount,
32
- backendConfig: resolveBackendConfig,
33
- signInHint: 'Run \`agent login\` to sign in.'
34
- }, { excludeTools: ['add_records', 'update_records', 'delete_records', 'create_api_key'] });
18
+ module.exports = createDbTools(
19
+ sessionToolsHost({ signInHint: 'Run \`agent login\` to sign in.', repairHint: ${JSON.stringify(REPAIR_HINT)} }),
20
+ { excludeTools: ['add_records', 'update_records', 'delete_records', 'create_api_key'] }
21
+ );
35
22
  `;
36
23
  }
37
24
  /**
@@ -47,10 +34,10 @@ export function materializeDbTools(config, log) {
47
34
  log('db tools unavailable (@agentic-kit/pi not installed) — continuing without them');
48
35
  return null;
49
36
  }
50
- const credentialsEntry = require.resolve('./credentials');
37
+ const sessionEntry = require.resolve('@agentic-kit/session');
51
38
  const dir = path.join(config.agentDir, 'extensions');
52
39
  fs.mkdirSync(dir, { recursive: true });
53
40
  const file = path.join(dir, EXTENSION_FILE);
54
- fs.writeFileSync(file, extensionSource(pkgEntry, credentialsEntry));
41
+ fs.writeFileSync(file, extensionSource(pkgEntry, sessionEntry));
55
42
  return file;
56
43
  }
package/esm/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  export { AgentCliConfig, loadConfig } from './config';
3
- export { HOST_ENV_VARS, materializeDbTools } from './db-tools';
3
+ export { materializeDbTools } from './db-tools';
4
4
  export { assembleSkills } from './skills';
package/esm/index.js CHANGED
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { refreshApiKeyIfNeeded } from './auth';
3
- import { loadBackendConfig } from './backend-store';
4
- import { init, login, logout, skillsList, skillsUpdate, usage, whoami } from './commands';
2
+ import { keyEndsSoon, resolveSession, sessionProblem } from '@agentic-kit/session';
3
+ import { init, login, logout, REPAIR_HINT, skillsList, skillsUpdate, usage, whoami } from './commands';
5
4
  import { loadConfig } from './config';
6
5
  import { materializeDbTools } from './db-tools';
7
6
  import { assembleSkills } from './skills';
8
7
  export { loadConfig } from './config';
9
- export { HOST_ENV_VARS, materializeDbTools } from './db-tools';
8
+ export { materializeDbTools } from './db-tools';
10
9
  export { assembleSkills } from './skills';
11
10
  async function run(args) {
12
- const config = loadConfig(process.env.AGENT_HOME);
11
+ const config = loadConfig();
13
12
  // pi resolves its agent dir (skills, sessions, auth) from this env var;
14
13
  // point it at the appstash-owned dir before the SDK loads.
15
14
  process.env.PI_CODING_AGENT_DIR ??= config.agentDir;
@@ -31,7 +30,7 @@ async function run(args) {
31
30
  return;
32
31
  }
33
32
  if (first === 'whoami') {
34
- whoami(config);
33
+ await whoami(config);
35
34
  return;
36
35
  }
37
36
  if (first === 'skills') {
@@ -44,16 +43,13 @@ async function run(args) {
44
43
  const log = (msg) => console.log(`[agent] ${msg}`);
45
44
  await assembleSkills(config, log);
46
45
  materializeDbTools(config, log);
47
- // Fire-and-forget: keep the stored API key fresh (<7 days to expiry re-mints)
48
- // without ever blocking startup. Only an expired login session gets a line.
49
- const backend = loadBackendConfig(config.store);
50
- if (backend) {
51
- void refreshApiKeyIfNeeded({ store: config.store, authEndpoint: backend.authEndpoint })
52
- .then((status) => {
53
- if (status === 'reauth-required')
54
- log('API key expired — run `agent login`');
55
- })
56
- .catch(() => { });
46
+ const session = resolveSession({ store: config.store });
47
+ const problem = sessionProblem(session, REPAIR_HINT);
48
+ if (problem)
49
+ log(`warning: ${problem}`);
50
+ const key = session.kind === 'signed-in' ? session.account.key : null;
51
+ if (key?.kind === 'active' && keyEndsSoon({ expiresAt: key.expiresAt })) {
52
+ log(`warning: the API key ${Date.parse(key.expiresAt) <= Date.now() ? 'ended' : 'ends'} at ${key.expiresAt}. Run \`agent login\` to sign in again and get a new one.`);
57
53
  }
58
54
  // pi is ESM-only; tsc's CJS output would downlevel a plain `await import()`
59
55
  // into `require()`, which cannot load it. Indirect the import so it survives
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  export { AgentCliConfig, loadConfig } from './config';
3
- export { HOST_ENV_VARS, materializeDbTools } from './db-tools';
3
+ export { materializeDbTools } from './db-tools';
4
4
  export { assembleSkills } from './skills';
package/index.js CHANGED
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.assembleSkills = exports.materializeDbTools = exports.HOST_ENV_VARS = exports.loadConfig = void 0;
5
- const auth_1 = require("./auth");
6
- const backend_store_1 = require("./backend-store");
4
+ exports.assembleSkills = exports.materializeDbTools = exports.loadConfig = void 0;
5
+ const session_1 = require("@agentic-kit/session");
7
6
  const commands_1 = require("./commands");
8
7
  const config_1 = require("./config");
9
8
  const db_tools_1 = require("./db-tools");
@@ -11,12 +10,11 @@ const skills_1 = require("./skills");
11
10
  var config_2 = require("./config");
12
11
  Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return config_2.loadConfig; } });
13
12
  var db_tools_2 = require("./db-tools");
14
- Object.defineProperty(exports, "HOST_ENV_VARS", { enumerable: true, get: function () { return db_tools_2.HOST_ENV_VARS; } });
15
13
  Object.defineProperty(exports, "materializeDbTools", { enumerable: true, get: function () { return db_tools_2.materializeDbTools; } });
16
14
  var skills_2 = require("./skills");
17
15
  Object.defineProperty(exports, "assembleSkills", { enumerable: true, get: function () { return skills_2.assembleSkills; } });
18
16
  async function run(args) {
19
- const config = (0, config_1.loadConfig)(process.env.AGENT_HOME);
17
+ const config = (0, config_1.loadConfig)();
20
18
  // pi resolves its agent dir (skills, sessions, auth) from this env var;
21
19
  // point it at the appstash-owned dir before the SDK loads.
22
20
  process.env.PI_CODING_AGENT_DIR ??= config.agentDir;
@@ -38,7 +36,7 @@ async function run(args) {
38
36
  return;
39
37
  }
40
38
  if (first === 'whoami') {
41
- (0, commands_1.whoami)(config);
39
+ await (0, commands_1.whoami)(config);
42
40
  return;
43
41
  }
44
42
  if (first === 'skills') {
@@ -51,16 +49,13 @@ async function run(args) {
51
49
  const log = (msg) => console.log(`[agent] ${msg}`);
52
50
  await (0, skills_1.assembleSkills)(config, log);
53
51
  (0, db_tools_1.materializeDbTools)(config, log);
54
- // Fire-and-forget: keep the stored API key fresh (<7 days to expiry re-mints)
55
- // without ever blocking startup. Only an expired login session gets a line.
56
- const backend = (0, backend_store_1.loadBackendConfig)(config.store);
57
- if (backend) {
58
- void (0, auth_1.refreshApiKeyIfNeeded)({ store: config.store, authEndpoint: backend.authEndpoint })
59
- .then((status) => {
60
- if (status === 'reauth-required')
61
- log('API key expired — run `agent login`');
62
- })
63
- .catch(() => { });
52
+ const session = (0, session_1.resolveSession)({ store: config.store });
53
+ const problem = (0, session_1.sessionProblem)(session, commands_1.REPAIR_HINT);
54
+ if (problem)
55
+ log(`warning: ${problem}`);
56
+ const key = session.kind === 'signed-in' ? session.account.key : null;
57
+ if (key?.kind === 'active' && (0, session_1.keyEndsSoon)({ expiresAt: key.expiresAt })) {
58
+ log(`warning: the API key ${Date.parse(key.expiresAt) <= Date.now() ? 'ended' : 'ends'} at ${key.expiresAt}. Run \`agent login\` to sign in again and get a new one.`);
64
59
  }
65
60
  // pi is ESM-only; tsc's CJS output would downlevel a plain `await import()`
66
61
  // into `require()`, which cannot load it. Indirect the import so it survives
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentic-kit/cli",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "author": "Dan Lynch <pyramation@gmail.com>",
5
5
  "description": "agent — the pi coding agent with the Constructive harness baked in, purely a shell",
6
6
  "main": "index.js",
@@ -22,13 +22,21 @@
22
22
  "bugs": {
23
23
  "url": "https://github.com/constructive-io/constructive/issues"
24
24
  },
25
+ "scripts": {
26
+ "clean": "makage clean",
27
+ "prepack": "npm run build",
28
+ "build": "makage build",
29
+ "build:dev": "makage build --dev",
30
+ "lint": "eslint . --fix",
31
+ "test": "jest",
32
+ "test:watch": "jest --watch"
33
+ },
25
34
  "dependencies": {
35
+ "@agentic-kit/harness": "0.22.0",
36
+ "@agentic-kit/pi": "0.32.0",
37
+ "@agentic-kit/session": "^0.2.0",
26
38
  "@earendil-works/pi-coding-agent": "1.4.0",
27
- "appstash": "^0.8.0",
28
- "inquirerer": "^4.9.8",
29
- "@agentic-kit/harness": "0.21.0",
30
- "@constructive-io/sdk": "^1.22.2",
31
- "@agentic-kit/pi": "0.31.0"
39
+ "inquirerer": "^4.10.1"
32
40
  },
33
41
  "keywords": [
34
42
  "agentic-kit",
@@ -36,12 +44,5 @@
36
44
  "pi",
37
45
  "harness"
38
46
  ],
39
- "scripts": {
40
- "clean": "makage clean",
41
- "build": "makage build",
42
- "build:dev": "makage build --dev",
43
- "lint": "eslint . --fix",
44
- "test": "jest",
45
- "test:watch": "jest --watch"
46
- }
47
- }
47
+ "gitHead": "c1f8c703f57f99d27bc82757283c95e700127761"
48
+ }
@@ -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/account-store.js DELETED
@@ -1,61 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loadSession = loadSession;
4
- exports.saveSession = saveSession;
5
- exports.clearSession = clearSession;
6
- /**
7
- * Sessions live in the shared Constructive stash, as the credentials of the
8
- * active context (the chosen backend). The store owns the file layout, the
9
- * atomic 0600 writes and the at-rest encoding; this module only maps between
10
- * its `ContextCredentials` and the session shape the CLI passes around.
11
- */
12
- function currentContextName(store) {
13
- return store.getCurrentContext()?.name ?? null;
14
- }
15
- /** The active context; a session is never filed under a backend nobody chose. */
16
- function ensureContextName(store) {
17
- const name = currentContextName(store);
18
- if (!name)
19
- throw new Error('No backend chosen — run `agent login` first.');
20
- return name;
21
- }
22
- function loadSession(store, context) {
23
- const contextName = context ?? currentContextName(store);
24
- if (!contextName)
25
- return null;
26
- const creds = store.getCredentials(contextName);
27
- if (!creds?.token || !creds.userId)
28
- return null;
29
- return {
30
- userId: creds.userId,
31
- email: creds.email ?? '',
32
- accessToken: creds.token,
33
- accessTokenExpiresAt: creds.expiresAt,
34
- apiKey: creds.apiKey,
35
- keyId: creds.keyId,
36
- apiKeyExpiresAt: creds.apiKeyExpiresAt,
37
- signedInAt: creds.signedInAt ?? 0
38
- };
39
- }
40
- /**
41
- * `context` names the backend the session belongs to; it does not have to exist
42
- * as a context yet, so a sign-in can be filed before the backend is committed
43
- * and a failed sign-in leaves nothing behind.
44
- */
45
- function saveSession(store, session, context) {
46
- store.setCredentials(context ?? ensureContextName(store), {
47
- token: session.accessToken,
48
- expiresAt: session.accessTokenExpiresAt,
49
- userId: session.userId,
50
- email: session.email,
51
- apiKey: session.apiKey,
52
- keyId: session.keyId,
53
- apiKeyExpiresAt: session.apiKeyExpiresAt,
54
- signedInAt: session.signedInAt
55
- });
56
- }
57
- function clearSession(store, context) {
58
- const contextName = context ?? currentContextName(store);
59
- if (contextName)
60
- store.removeCredentials(contextName);
61
- }
package/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/api-key.js DELETED
@@ -1,96 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REMINT_THRESHOLD_MS = exports.API_KEY_YEARS = exports.API_KEY_MFA_LEVEL = exports.API_KEY_ACCESS_LEVEL = exports.API_KEY_NAME = void 0;
4
- exports.buildCreateApiKeyInput = buildCreateApiKeyInput;
5
- exports.parseMintedKey = parseMintedKey;
6
- exports.classifyApiKeyError = classifyApiKeyError;
7
- exports.needsRemint = needsRemint;
8
- exports.remintApiKey = remintApiKey;
9
- exports.API_KEY_NAME = 'agentic-cli';
10
- exports.API_KEY_ACCESS_LEVEL = 'full_access';
11
- exports.API_KEY_MFA_LEVEL = 'none';
12
- exports.API_KEY_YEARS = 5;
13
- /**
14
- * Re-mint once the key is within a week of expiry. The mint needs a
15
- * fresh-password step-up window, so in practice the refresh succeeds only right
16
- * after a sign-in; otherwise it surfaces as a re-auth prompt.
17
- */
18
- exports.REMINT_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 7;
19
- function buildCreateApiKeyInput({ years }) {
20
- return {
21
- keyName: exports.API_KEY_NAME,
22
- accessLevel: exports.API_KEY_ACCESS_LEVEL,
23
- mfaLevel: exports.API_KEY_MFA_LEVEL,
24
- expiresIn: { years }
25
- };
26
- }
27
- function parseMintedKey(record) {
28
- if (!record?.apiKey || !record.keyId) {
29
- throw new Error('createApiKey returned no API key.');
30
- }
31
- return {
32
- apiKey: record.apiKey,
33
- keyId: record.keyId,
34
- ...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {})
35
- };
36
- }
37
- const ERROR_CODE_MAP = {
38
- STEP_UP_REQUIRED: 'step-up-required',
39
- API_KEYS_DISABLED: 'disabled',
40
- API_KEY_LIMIT_REACHED: 'limit-reached',
41
- NOT_AUTHENTICATED: 'not-authenticated',
42
- INVALID_ACCESS_LEVEL: 'invalid-access-level'
43
- };
44
- function classifyApiKeyError(err) {
45
- const errors = err?.errors;
46
- if (Array.isArray(errors)) {
47
- for (const e of errors) {
48
- const code = e.extensions?.code;
49
- if (code && ERROR_CODE_MAP[code])
50
- return ERROR_CODE_MAP[code];
51
- }
52
- }
53
- const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';
54
- for (const code of Object.keys(ERROR_CODE_MAP)) {
55
- if (message.includes(code))
56
- return ERROR_CODE_MAP[code];
57
- }
58
- return 'unknown';
59
- }
60
- function needsRemint({ apiKeyExpiresAt, now, thresholdMs = exports.REMINT_THRESHOLD_MS }) {
61
- if (!apiKeyExpiresAt)
62
- return false;
63
- const expires = Date.parse(apiKeyExpiresAt);
64
- if (Number.isNaN(expires))
65
- return false;
66
- return expires - now <= thresholdMs;
67
- }
68
- /**
69
- * Mint-first, revoke-on-success: revoking before minting would destroy a
70
- * still-valid key whenever the mint then fails, leaving no credential at all.
71
- * The one case that needs the old key gone first is the live-key cap
72
- * (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once.
73
- */
74
- async function remintApiKey({ currentKeyId, revoke, mint }) {
75
- const revokeOld = async () => {
76
- if (!currentKeyId)
77
- return;
78
- try {
79
- await revoke(currentKeyId);
80
- }
81
- catch (err) {
82
- console.warn(`[agent] failed to revoke superseded API key ${currentKeyId}: ${err instanceof Error ? err.message : String(err)}`);
83
- }
84
- };
85
- try {
86
- const minted = await mint();
87
- await revokeOld();
88
- return minted;
89
- }
90
- catch (err) {
91
- if (classifyApiKeyError(err) !== 'limit-reached')
92
- throw err;
93
- await revokeOld();
94
- return mint();
95
- }
96
- }
package/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/auth-error.js DELETED
@@ -1,114 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AUTH_TIMEOUT_MS = void 0;
4
- exports.isNetworkError = isNetworkError;
5
- exports.describeAuthError = describeAuthError;
6
- exports.withAuthTimeout = withAuthTimeout;
7
- const NETWORK_ERROR_CODES = new Set([
8
- 'ECONNREFUSED',
9
- 'ECONNRESET',
10
- 'ENOTFOUND',
11
- 'EAI_AGAIN',
12
- 'EHOSTUNREACH',
13
- 'ENETUNREACH',
14
- 'ETIMEDOUT',
15
- 'UND_ERR_CONNECT_TIMEOUT',
16
- 'UND_ERR_SOCKET'
17
- ]);
18
- function errorCode(err) {
19
- if (!err || typeof err !== 'object')
20
- return undefined;
21
- const { code, cause } = err;
22
- if (typeof code === 'string')
23
- return code;
24
- if (cause && typeof cause === 'object') {
25
- const causeCode = cause.code;
26
- if (typeof causeCode === 'string')
27
- return causeCode;
28
- }
29
- return undefined;
30
- }
31
- function isNetworkError(err) {
32
- const code = errorCode(err);
33
- if (code !== undefined)
34
- return NETWORK_ERROR_CODES.has(code);
35
- if (err instanceof AggregateError)
36
- return true;
37
- return err instanceof TypeError && /fetch failed/i.test(err.message);
38
- }
39
- function extractGraphqlMessages(err) {
40
- const messages = [];
41
- const codes = [];
42
- const visited = new Set();
43
- const visit = (value) => {
44
- if (!value || typeof value !== 'object' || visited.has(value))
45
- return;
46
- visited.add(value);
47
- const record = value;
48
- if (typeof record.message === 'string' && record.message.trim() !== '') {
49
- const message = record.message.trim().replace(/^GraphQL Error:\s*/u, '');
50
- if (message.length > 0)
51
- messages.push(message);
52
- }
53
- const extensions = record.extensions && typeof record.extensions === 'object'
54
- ? record.extensions
55
- : undefined;
56
- if (typeof extensions?.code === 'string')
57
- codes.push(extensions.code);
58
- if (Array.isArray(record.errors))
59
- record.errors.forEach(visit);
60
- if (record.cause)
61
- visit(record.cause);
62
- if (record.extensions)
63
- visit(record.extensions);
64
- if (record.detail)
65
- visit(record.detail);
66
- if (record.data)
67
- visit(record.data);
68
- if (record.response)
69
- visit(record.response);
70
- if (record.result)
71
- visit(record.result);
72
- if (record.payload)
73
- visit(record.payload);
74
- };
75
- visit(err);
76
- if (messages.length === 0) {
77
- for (const code of codes) {
78
- if (code === 'UNAUTHENTICATED')
79
- messages.push('Your session has expired. Sign in again.');
80
- if (code === 'FORBIDDEN') {
81
- messages.push('The server rejected this request. Check your account permissions.');
82
- }
83
- }
84
- }
85
- return [...new Set(messages)];
86
- }
87
- function describeAuthError(err, endpoint) {
88
- if (isNetworkError(err)) {
89
- return `Could not reach the server at ${endpoint}. Check that it is running, or pick a different backend.`;
90
- }
91
- const graphqlMessages = extractGraphqlMessages(err);
92
- if (graphqlMessages.length > 0)
93
- return graphqlMessages.join('; ');
94
- const message = err instanceof Error ? err.message : String(err);
95
- if (message.trim() !== '' && message !== '[object Object]')
96
- return message;
97
- const name = err instanceof Error ? err.name : typeof err;
98
- return `Authentication failed unexpectedly (${name}).`;
99
- }
100
- exports.AUTH_TIMEOUT_MS = 10_000;
101
- function withAuthTimeout(promise, endpoint, ms = exports.AUTH_TIMEOUT_MS) {
102
- return new Promise((resolve, reject) => {
103
- const timer = setTimeout(() => {
104
- reject(new Error(`The server at ${endpoint} did not respond within ${Math.round(ms / 1000)}s. Check the backend settings and try again.`));
105
- }, ms);
106
- promise.then(value => {
107
- clearTimeout(timer);
108
- resolve(value);
109
- }, (err) => {
110
- clearTimeout(timer);
111
- reject(err instanceof Error ? err : new Error(String(err)));
112
- });
113
- });
114
- }
package/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>;