diff --git a/.github/workflows/run-tests.yaml b/.github/workflows/run-tests.yaml index 45e2f83ef8..5b339e29fb 100644 --- a/.github/workflows/run-tests.yaml +++ b/.github/workflows/run-tests.yaml @@ -118,7 +118,7 @@ jobs: - batch: graphile-unit packages: 'graphile/graphile-plugin-utils graphile/graphile-realtime-subscriptions graphile/graphile-sql-expression-validator graphile/graphile-storage-registry' - batch: agentic - packages: 'agentic/protocol agentic/agentic-kit agentic/agent agentic/harness agentic/permissions agentic/chat agentic/cli agentic/db-tools agentic/pi agentic/dsh agentic/react agentic/agentic-server agentic/anthropic agentic/openai agentic/ollama agentic/run-log agentic/metering agentic/agent-conversation agentic/pi-host agentic/run-log-client agentic/run-log-gate agentic/machine-protocol agentic/machine-runner agentic/agent-cli' + packages: 'agentic/protocol agentic/agentic-kit agentic/agent agentic/harness agentic/permissions agentic/chat agentic/cli agentic/db-tools agentic/pi agentic/dsh agentic/react agentic/agentic-server agentic/anthropic agentic/openai agentic/ollama agentic/run-log agentic/metering agentic/agent-conversation agentic/pi-host agentic/run-log-client agentic/run-log-gate agentic/machine-protocol agentic/machine-runner agentic/agent-cli agentic/command agentic/mcp agentic/session' - batch: pgpm-unit packages: 'pgpm/types pgpm/naming-spec pgpm/diff pgpm/import pgpm/slice pgpm/transform' - batch: pglite diff --git a/agentic/cli/README.md b/agentic/cli/README.md index 1ceb6c8d8e..3bea58a5a4 100644 --- a/agentic/cli/README.md +++ b/agentic/cli/README.md @@ -26,7 +26,7 @@ On startup, `agent` assembles the harness skill tree and drops you into an inter 1. **Base layer** — [`constructive-io/constructive-skills`](https://github.com/constructive-io/constructive-skills), fetched as a git tag/branch/SHA tarball into `~/.constructive/data/skills//` (default ref: `main`; offline fallback: newest cached release). 2. **Local overlay** — `~/.constructive/config/skills-overlay//SKILL.md` (agentskills.io layout), highest precedence: a same-name skill replaces the base skill wholesale. -3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, and `run_codegen`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools. +3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, `run_codegen`, and the access tools `describe_policy_type`, `explain_access` and `set_access`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools. The merged tree is materialized into the appstash-owned agent dir, so the session picks the skills up natively. All harness state lives in the [appstash](https://github.com/constructive-io/appstash) `~/.constructive/` layout; project directories are untouched. @@ -35,16 +35,16 @@ The merged tree is materialized into the appstash-owned agent dir, so the sessio | Command | Description | |---------|-------------| | `agent [options...]` | Start an interactive session with the harness skills | -| `agent -p "prompt"` | One-shot print mode; gated tools are refused | +| `agent -p "prompt"` | One-shot print mode; every database tool that changes something is refused, and pi's own tools still run | | `agent init` | Configure the skills source (repo + pin) interactively | | `agent login` | Sign in to the Constructive platform (interactive) | -| `agent logout` | Revoke the API key and clear the stored session | -| `agent whoami` | Show the signed-in account, backend, and masked API key | +| `agent logout` | Revoke the API key at the backend that issued it and clear the stored session; a session from the environment is not stored, so there is nothing to remove | +| `agent whoami` | Show the signed-in account, backend, and masked API key, and ask the backend whether it still accepts the credential | | `agent skills list` | Resolve and list the effective skill set per layer | | `agent skills update` | Re-fetch the base release and re-materialize | | `agent help` | Usage | -Print mode has no confirmation UI, so it refuses gated database changes and `run_codegen`. Setting a credential does not bypass confirmation. Use the interactive TUI or `agent --mode rpc` with a client that handles pi's approval requests for gated operations. Ungated tools, such as `describe_schema`, can still run in print mode. +Print mode has no confirmation UI, so it refuses every database tool whose effect is a write or a destructive change, `run_codegen` included. Setting a credential does not bypass confirmation. Use the interactive TUI or `agent --mode rpc` with a client that handles pi's approval requests for gated operations. Database tools that only read, such as `describe_schema`, still run in print mode, and so do pi's own tools (`bash`, `edit`, `write`): the gate covers the database tools only. ## Configuration @@ -63,22 +63,21 @@ Print mode has no confirmation UI, so it refuses gated database changes and `run } ``` -Env overrides: `AGENT_SKILLS_REPO`, `AGENT_SKILLS_PIN`, `AGENT_HOME` (appstash base dir), `GITHUB_TOKEN` (private skills repos). +Env overrides: `AGENT_SKILLS_REPO`, `AGENT_SKILLS_PIN`, `CONSTRUCTIVE_STASH_DIR` (base directory that replaces `~` for `~/.constructive/`, shared with the session store and Constructive Desktop), `GITHUB_TOKEN` (private skills repos). ## Authentication -`agent login` signs in to the Constructive platform with email and password. The CLI ships no backend URLs: the flow asks for the backend's API GraphQL endpoint (e.g. `https://api.example.com/graphql`, defaulting to the last one used or `CONSTRUCTIVE_API_ENDPOINT`) and derives the auth, modules, agent and compute endpoints from its host. With no backend chosen the db tools fail and say so; they never fall back to a default host. After sign-in, the CLI mints a 5-year API key for the db tools and checks it on each startup. `agent logout` revokes the key and deletes the session. +`agent login` signs in to the Constructive platform with email and password, through [`@agentic-kit/session`](https://www.npmjs.com/package/@agentic-kit/session), the sign-in every Constructive binary shares. The CLI ships no backend URLs: the flow asks for the backend's API GraphQL endpoint (e.g. `https://api.example.com/graphql`, defaulting to the last one used or `CONSTRUCTIVE_API_ENDPOINT`) and derives the auth, modules, agent and compute endpoints from its host. With no backend chosen the db tools fail and say so; they never fall back to a default host. After sign-in, the CLI asks for a 30-day API key for the db tools, then ends the password sign-in on the backend, so the key is the only credential it keeps. If no key can be made, the sign-in fails and nothing is stored. When the key is within 7 days of its end, each startup asks you to run `agent login` again, which signs you in and mints a new key; nothing renews it on its own. `agent logout` revokes the key and deletes the session. -Shared appstash files: +Shared appstash files (with `CONSTRUCTIVE_STASH_DIR` set, each `~/.constructive/` below is `$CONSTRUCTIVE_STASH_DIR/.constructive/`): -- `~/.constructive/config/credentials.json` — the signed-in session (user, access token, API key; mode `0600`, plaintext) +- `~/.constructive/config/credentials.json` — the signed-in session (user and API key; mode `0600`, plaintext) - `~/.constructive/config/contexts/.json` — endpoints for each backend context - `~/.constructive/config/settings.json` — shared settings, including the active context The db tools read these files on each tool call, so a login mid-session is picked up without a restart. The CLI does not export stored credentials to child processes. -Env overrides for CI and headless use (these win over the stored session; read per tool call): -`CONSTRUCTIVE_USER_ID`, `CONSTRUCTIVE_ACCESS_TOKEN`, `CONSTRUCTIVE_API_KEY` (optional), `CONSTRUCTIVE_API_ENDPOINT` (picks the backend; the other planes derive from it), and `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT`, `CONSTRUCTIVE_COMPUTE_ENDPOINT` to override one plane (only together with `CONSTRUCTIVE_API_ENDPOINT`). +Env overrides for CI and headless use (read per tool call): `CONSTRUCTIVE_USER_ID`, `CONSTRUCTIVE_ACCESS_TOKEN` and `CONSTRUCTIVE_API_KEY` (optional) give the credential, and need `CONSTRUCTIVE_API_ENDPOINT` to name its backend. `CONSTRUCTIVE_API_ENDPOINT` alone picks a backend; the stored session is used with it only when it names the backend of the active context. `CONSTRUCTIVE_AUTH_ENDPOINT`, `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT` and `CONSTRUCTIVE_COMPUTE_ENDPOINT` give one plane each (only together with `CONSTRUCTIVE_API_ENDPOINT`); the planes are derived only from an api host that starts with `api.`. An incomplete or wrong set is reported at startup, and every db tool call fails with that cause (for example `no-backend` naming `CONSTRUCTIVE_API_ENDPOINT`) in place of a sign-in prompt. See [`@agentic-kit/session`](https://www.npmjs.com/package/@agentic-kit/session) for the rules. ## Roadmap diff --git a/agentic/cli/__tests__/auth.test.ts b/agentic/cli/__tests__/auth.test.ts deleted file mode 100644 index 6cd2a7cd9c..0000000000 --- a/agentic/cli/__tests__/auth.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { ConfigStore } from 'appstash'; -import * as fs from 'fs'; -import * as os from 'os'; -import * as path from 'path'; - -const createClient = jest.fn(); - -jest.mock('@constructive-io/sdk', () => ({ - auth: { createClient: (...args: any[]) => createClient(...args) } -})); - -import { loadSession, saveSession } from '../src/account-store'; -import { refreshApiKeyIfNeeded, signIn, signOut } from '../src/auth'; -import { backendFromApiEndpoint, saveBackendConfig } from '../src/backend-store'; -import { loadConfig } from '../src/config'; - -const AUTH_ENDPOINT = 'http://auth.localhost:3000/graphql'; - -const unwrappable = (value: unknown) => ({ unwrap: () => Promise.resolve(value) }); -const failing = (err: unknown) => ({ unwrap: () => Promise.reject(err) }); - -let home: string; -let store: ConfigStore; - -beforeEach(() => { - home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-auth-')); - store = loadConfig(home).store; - saveBackendConfig(store, backendFromApiEndpoint('http://api.localhost:3000/graphql')); - createClient.mockReset(); -}); - -afterEach(() => { - fs.rmSync(home, { recursive: true, force: true }); -}); - -function mockClient(mutation: Record) { - createClient.mockImplementation(() => ({ mutation })); - return mutation; -} - -const signInResult = { - signIn: { - result: { - userId: 'user-1', - accessToken: 'access-token', - accessTokenExpiresAt: '2026-08-04T00:00:00Z' - } - } -}; - -const mintedResult = { - createApiKey: { - result: { apiKey: 'cnc_live_sk_new', keyId: 'key-new', expiresAt: '2031-08-03T00:00:00Z' } - } -}; - -describe('signIn', () => { - it('persists the session and mints an API key in the step-up window', async () => { - const mutation = mockClient({ - signIn: jest.fn(() => unwrappable(signInResult)), - createApiKey: jest.fn(() => unwrappable(mintedResult)), - revokeApiKey: jest.fn() - }); - - const session = await signIn({ - store, - authEndpoint: AUTH_ENDPOINT, - email: ' dev@example.com ', - password: 'pw' - }); - - expect(mutation.signIn).toHaveBeenCalledWith( - { input: { email: 'dev@example.com', password: 'pw' } }, - expect.anything() - ); - expect(session.userId).toBe('user-1'); - expect(session.apiKey).toBe('cnc_live_sk_new'); - expect(session.keyId).toBe('key-new'); - expect(loadSession(store)).toEqual(session); - expect(createClient).toHaveBeenCalledWith({ endpoint: AUTH_ENDPOINT }); - expect(createClient).toHaveBeenCalledWith({ - endpoint: AUTH_ENDPOINT, - headers: { Authorization: 'Bearer access-token' } - }); - }); - - it('keeps the session when the mint fails', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); - mockClient({ - signIn: jest.fn(() => unwrappable(signInResult)), - createApiKey: jest.fn(() => failing(new Error('API_KEYS_DISABLED'))), - revokeApiKey: jest.fn() - }); - - const session = await signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'pw' }); - expect(session.apiKey).toBeUndefined(); - expect(loadSession(store)?.accessToken).toBe('access-token'); - warn.mockRestore(); - }); - - it('rejects when no access token comes back (MFA)', async () => { - mockClient({ signIn: jest.fn(() => unwrappable({ signIn: { result: {} } })) }); - await expect( - signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'pw' }) - ).rejects.toThrow('Authentication returned no access token (MFA may be required).'); - expect(loadSession(store)).toBeNull(); - }); - - it('rejects empty credentials without a network call', async () => { - await expect( - signIn({ store, authEndpoint: AUTH_ENDPOINT, email: ' ', password: 'pw' }) - ).rejects.toThrow('Email and password are required.'); - expect(createClient).not.toHaveBeenCalled(); - }); - - it('maps sign-in errors through describeAuthError', async () => { - const gqlError = Object.assign(new Error('request failed'), { - errors: [{ message: 'GraphQL Error: Invalid credentials' }] - }); - mockClient({ signIn: jest.fn(() => failing(gqlError)) }); - await expect( - signIn({ store, authEndpoint: AUTH_ENDPOINT, email: 'dev@example.com', password: 'nope' }) - ).rejects.toThrow('Invalid credentials'); - }); -}); - -describe('refreshApiKeyIfNeeded', () => { - const baseSession = { - userId: 'user-1', - email: 'dev@example.com', - accessToken: 'access-token', - signedInAt: 1754000000000 - }; - - it('returns signed-out without a session', async () => { - await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('signed-out'); - }); - - it('returns ok for a fresh key without a network call', async () => { - saveSession(store, { - ...baseSession, - apiKey: 'k', - keyId: 'id', - apiKeyExpiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365).toISOString() - }); - await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('ok'); - expect(createClient).not.toHaveBeenCalled(); - }); - - it('re-mints an expiring key and persists it', async () => { - saveSession(store, { - ...baseSession, - apiKey: 'old', - keyId: 'old-id', - apiKeyExpiresAt: new Date(Date.now() + 1000).toISOString() - }); - const mutation = mockClient({ - createApiKey: jest.fn(() => unwrappable(mintedResult)), - revokeApiKey: jest.fn(() => unwrappable({ revokeApiKey: { result: true } })) - }); - - await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('reminted'); - expect(mutation.revokeApiKey).toHaveBeenCalledWith({ input: { keyId: 'old-id' } }, expect.anything()); - expect(loadSession(store)?.apiKey).toBe('cnc_live_sk_new'); - }); - - it('returns reauth-required on a step-up error', async () => { - saveSession(store, baseSession); - mockClient({ - createApiKey: jest.fn(() => failing({ errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] })), - revokeApiKey: jest.fn() - }); - await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('reauth-required'); - }); - - it('returns unavailable on other errors', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); - saveSession(store, baseSession); - mockClient({ - createApiKey: jest.fn(() => failing(new Error('boom'))), - revokeApiKey: jest.fn() - }); - await expect(refreshApiKeyIfNeeded({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe('unavailable'); - warn.mockRestore(); - }); -}); - -describe('signOut', () => { - it('revokes the key and clears the session', async () => { - saveSession(store, { - userId: 'user-1', - email: 'dev@example.com', - accessToken: 'access-token', - apiKey: 'k', - keyId: 'key-1', - signedInAt: 1754000000000 - }); - const mutation = mockClient({ - revokeApiKey: jest.fn(() => unwrappable({ revokeApiKey: { result: true } })) - }); - - await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(true); - expect(mutation.revokeApiKey).toHaveBeenCalledWith({ input: { keyId: 'key-1' } }, expect.anything()); - expect(loadSession(store)).toBeNull(); - }); - - it('clears the session even when the revoke fails', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); - saveSession(store, { - userId: 'user-1', - email: 'dev@example.com', - accessToken: 'access-token', - keyId: 'key-1', - signedInAt: 1754000000000 - }); - mockClient({ revokeApiKey: jest.fn(() => failing(new Error('offline'))) }); - - await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(true); - expect(loadSession(store)).toBeNull(); - warn.mockRestore(); - }); - - it('is a no-op when signed out', async () => { - await expect(signOut({ store, authEndpoint: AUTH_ENDPOINT })).resolves.toBe(false); - expect(createClient).not.toHaveBeenCalled(); - }); -}); diff --git a/agentic/cli/__tests__/commands.test.ts b/agentic/cli/__tests__/commands.test.ts index 45a5781c4c..ae3bb6bb4a 100644 --- a/agentic/cli/__tests__/commands.test.ts +++ b/agentic/cli/__tests__/commands.test.ts @@ -2,23 +2,35 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -jest.mock('../src/auth', () => ({ +jest.mock('@agentic-kit/session', () => ({ + ...jest.requireActual('@agentic-kit/session'), signIn: jest.fn(), signOut: jest.fn(), - refreshApiKeyIfNeeded: jest.fn() + verifySession: jest.fn() })); -import { AccountSession, saveSession } from '../src/account-store'; -import { signIn, signOut } from '../src/auth'; -import { backendFromApiEndpoint, loadBackendConfig, saveBackendConfig } from '../src/backend-store'; +import { + AccountSession, + addBackend, + backendFromEndpoints, + saveSession, + selectBackend, + signIn, + signOut, + verifySession +} from '@agentic-kit/session'; + import { login, logout, whoami } from '../src/commands'; import { AgentCliConfig, loadConfig } from '../src/config'; -const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql'); -const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql'); +const LOCAL = backendFromEndpoints({ api: 'http://api.localhost:3000/graphql' }); +const REMOTE = backendFromEndpoints({ api: 'https://api.example.com/graphql' }); + +const useBackend = (config: AgentCliConfig) => selectBackend(config.store, addBackend(config.store, LOCAL).name); const signInMock = signIn as jest.Mock; const signOutMock = signOut as jest.Mock; +const verifyMock = verifySession as jest.Mock; let home: string; let config: AgentCliConfig; @@ -44,6 +56,8 @@ beforeEach(() => { }); signInMock.mockReset(); signOutMock.mockReset(); + verifyMock.mockReset(); + verifyMock.mockResolvedValue({ kind: 'accepted' }); process.exitCode = undefined; }); @@ -56,47 +70,25 @@ afterEach(() => { const output = () => logs.join('\n'); describe('login', () => { - it('signs in against the named API endpoint and persists all five planes', async () => { - signInMock.mockResolvedValue(session); + it('signs in against the backend derived from the named API endpoint', async () => { + signInMock.mockResolvedValue({ session, context: 'example.com', apiKey: { kind: 'minted' }, previousKey: { kind: 'absent' } }); - await login(config, { apiUrl: LOCAL.apiEndpoint, email: 'dev@example.com', password: 'pw' }); + await login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'pw' }); expect(signInMock).toHaveBeenCalledWith({ store: config.store, - context: 'localhost-3000', - authEndpoint: LOCAL.authEndpoint, + backend: REMOTE, email: 'dev@example.com', password: 'pw' }); - expect(loadBackendConfig(config.store)).toEqual(LOCAL); expect(output()).toContain('signed in as dev@example.com'); expect(output()).toContain('cnc_li...abcd'); - }); - - it('derives auth and modules endpoints from a custom API URL', async () => { - signInMock.mockResolvedValue(session); - - await login(config, { - apiUrl: 'https://api.example.com/graphql', - email: 'dev@example.com', - password: 'pw' - }); - - expect(signInMock).toHaveBeenCalledWith( - expect.objectContaining({ authEndpoint: 'https://auth.example.com/graphql' }) - ); - expect(loadBackendConfig(config.store)).toEqual({ - apiEndpoint: 'https://api.example.com/graphql', - authEndpoint: 'https://auth.example.com/graphql', - modulesEndpoint: 'https://modules.example.com/graphql', - agentEndpoint: 'https://agent.example.com/graphql', - computeEndpoint: 'https://compute.example.com/graphql' - }); + expect(output()).toContain('session stored in context example.com'); }); it('ships no backend: with no API endpoint named it refuses before any network call', async () => { await expect(login(config, { email: 'dev@example.com', password: 'pw' })).rejects.toThrow( - 'Invalid API endpoint URL: (empty)' + 'is not an absolute URL' ); expect(signInMock).not.toHaveBeenCalled(); }); @@ -104,62 +96,67 @@ describe('login', () => { it('rejects an invalid custom URL before any network call', async () => { await expect( login(config, { apiUrl: 'not a url', email: 'dev@example.com', password: 'pw' }) - ).rejects.toThrow('Invalid API endpoint URL'); + ).rejects.toThrow('is not an absolute URL'); expect(signInMock).not.toHaveBeenCalled(); }); - it('warns when the session lacks an API key after sign-in', async () => { - signInMock.mockResolvedValue({ ...session, apiKey: undefined, keyId: undefined }); + it('warns when no API key was minted, and when the replaced key could not be revoked', async () => { + signInMock.mockResolvedValue({ + session, + context: 'localhost-3000', + apiKey: { kind: 'not-minted', reason: 'API keys are disabled' }, + previousKey: { kind: 'failed', keyId: 'key-0', reason: 'offline' } + }); await login(config, { apiUrl: LOCAL.apiEndpoint, email: 'dev@example.com', password: 'pw' }); - expect(output()).toContain('API key mint failed'); - }); - - it('does not persist the backend config when sign-in fails', async () => { - signInMock.mockRejectedValue(new Error('Invalid credentials')); - - await expect( - login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'bad' }) - ).rejects.toThrow('Invalid credentials'); - expect(loadBackendConfig(config.store)).toBeNull(); + expect(output()).toContain('no new API key was minted (API keys are disabled); the previous key stays in use'); + expect(output()).toContain('key-0 of the replaced session could not be revoked (offline)'); }); }); describe('logout', () => { - it('signs out against the stored backend', async () => { - saveBackendConfig(config.store, REMOTE); - signOutMock.mockResolvedValue(true); + it('signs out of the active backend', async () => { + signOutMock.mockResolvedValue({ kind: 'cleared', context: 'localhost-3000', key: { kind: 'revoked', keyId: 'key-1' } }); await logout(config); - expect(signOutMock).toHaveBeenCalledWith({ - store: config.store, - authEndpoint: REMOTE.authEndpoint - }); + expect(signOutMock).toHaveBeenCalledWith({ store: config.store, session: expect.objectContaining({ kind: 'no-backend' }) }); expect(output()).toContain('signed out'); }); + it('signs out of the session the environment gives, and says nothing stored was removed', async () => { + const saved = { ...process.env }; + Object.assign(process.env, { CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint }); + try { + signOutMock.mockResolvedValue({ kind: 'from-environment' }); + await logout(config); + expect(signOutMock).toHaveBeenCalledWith({ store: config.store, session: expect.objectContaining({ kind: 'signed-in', source: 'env' }) }); + expect(output()).toContain('the session comes from the environment'); + } finally { + process.env = saved; + } + }); + it('reports when there is no session', async () => { - saveBackendConfig(config.store, LOCAL); - signOutMock.mockResolvedValue(false); + signOutMock.mockResolvedValue({ kind: 'not-signed-in', context: null }); await logout(config); expect(output()).toContain('not signed in'); }); - it('never signs out against a guessed backend when none was chosen', async () => { + it('says the session was cleared but the key stays valid when the revoke failed', async () => { + signOutMock.mockResolvedValue({ kind: 'cleared', context: 'localhost-3000', key: { kind: 'failed', keyId: 'key-1', reason: 'offline' } }); await logout(config); - expect(signOutMock).not.toHaveBeenCalled(); - expect(output()).toContain('not signed in'); + expect(output()).toContain('session cleared, but the API key key-1 could not be revoked (offline)'); }); }); describe('whoami', () => { - it('prints the session details with a masked API key', () => { - saveBackendConfig(config.store, LOCAL); - saveSession(config.store, session); + it('prints the session details with a masked API key', async () => { + useBackend(config); + saveSession(config.store, { ...session, issuedFor: LOCAL }); - whoami(config); + await whoami(config); expect(process.exitCode).toBeUndefined(); expect(output()).toContain('signed in as dev@example.com'); @@ -170,8 +167,46 @@ describe('whoami', () => { expect(output()).not.toContain('access-token'); }); - it('exits 1 with a sign-in hint when signed out', () => { - whoami(config); + it('says the backend rejected the credential, and exits 1', async () => { + useBackend(config); + saveSession(config.store, { ...session, issuedFor: LOCAL }); + verifyMock.mockResolvedValue({ kind: 'rejected', reason: 'The server rejected the credential (UNAUTHENTICATED).', code: 'UNAUTHENTICATED' }); + + await whoami(config); + + expect(process.exitCode).toBe(1); + expect(output()).toContain('credential: rejected'); + expect(output()).toContain('Run `agent login` to sign in again'); + }); + + it('names a stored session that another backend issued, and does not use it', async () => { + useBackend(config); + saveSession(config.store, { ...session, issuedFor: { ...LOCAL, authEndpoint: 'http://auth.elsewhere.localhost/graphql' } }); + + await whoami(config); + + expect(process.exitCode).toBe(1); + expect(output()).toContain('but the session was issued for http://auth.elsewhere.localhost/graphql'); + expect(verifyMock).not.toHaveBeenCalled(); + }); + + it('names the missing plane of a context another app wrote instead of reporting a backend', async () => { + const four = LOCAL; + config.store.createContext('localnet', { + endpoint: four.apiEndpoint, + targets: { api: { endpoint: four.apiEndpoint }, auth: { endpoint: four.authEndpoint }, modules: { endpoint: four.modulesEndpoint }, agent: { endpoint: four.agentEndpoint } } + }); + config.store.setCurrentContext('localnet'); + saveSession(config.store, session); + + await whoami(config); + + expect(process.exitCode).toBe(1); + expect(output()).toContain('"localnet" lacks the compute endpoint'); + }); + + it('exits 1 with a sign-in hint when signed out', async () => { + await whoami(config); expect(process.exitCode).toBe(1); expect(output()).toContain('run `agent login`'); }); diff --git a/agentic/cli/__tests__/db-tools.test.ts b/agentic/cli/__tests__/db-tools.test.ts index 9ff651acb3..a2ee494a05 100644 --- a/agentic/cli/__tests__/db-tools.test.ts +++ b/agentic/cli/__tests__/db-tools.test.ts @@ -1,26 +1,18 @@ import { constructiveDbTools } from '@agentic-kit/pi'; +import { + addBackend, + backendFromEndpoints, + OVERRIDE_ENV_VARS, + saveSession, + selectBackend +} from '@agentic-kit/session'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { saveSession } from '../src/account-store'; -import { backendFromApiEndpoint, saveBackendConfig } from '../src/backend-store'; import { loadConfig } from '../src/config'; import { materializeDbTools } from '../src/db-tools'; -const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql'); -const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql'); - -const CONSTRUCTIVE_VARS = [ - 'CONSTRUCTIVE_USER_ID', - 'CONSTRUCTIVE_ACCESS_TOKEN', - 'CONSTRUCTIVE_API_KEY', - 'CONSTRUCTIVE_API_ENDPOINT', - 'CONSTRUCTIVE_MODULES_ENDPOINT', - 'CONSTRUCTIVE_AGENT_ENDPOINT', - 'CONSTRUCTIVE_COMPUTE_ENDPOINT' -]; - describe('materializeDbTools', () => { let home: string; let prevEnv: NodeJS.ProcessEnv; @@ -28,8 +20,8 @@ describe('materializeDbTools', () => { beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-dbtools-')); prevEnv = { ...process.env }; - process.env.AGENT_HOME = home; - for (const name of CONSTRUCTIVE_VARS) delete process.env[name]; + process.env.CONSTRUCTIVE_STASH_DIR = home; + for (const name of OVERRIDE_ENV_VARS) delete process.env[name]; }); afterEach(() => { @@ -37,7 +29,7 @@ describe('materializeDbTools', () => { fs.rmSync(home, { recursive: true, force: true }); }); - it('writes a loadable extension entry into /extensions', () => { + function registeredTools(): string[] { const config = loadConfig(home); const file = materializeDbTools(config, () => {}); expect(file).toBe(path.join(config.agentDir, 'extensions', 'constructive-db-tools.js')); @@ -54,11 +46,12 @@ describe('materializeDbTools', () => { registerTool: (tool: { name: string }) => registered.push(tool.name), on: () => {} }); - expect(registered).toContain('provision_database'); - expect(registered).not.toContain('add_records'); - expect(registered).not.toContain('create_api_key'); + return registered; + } + + it('registers every db tool except add_records (row data needs a tenant sign-in the CLI lacks) and create_api_key (a minted key needs secret delivery the CLI lacks)', () => { const expected = constructiveDbTools.map((tool) => tool.name).filter((name) => name !== 'add_records' && name !== 'create_api_key'); - expect(registered.sort()).toEqual(expected.sort()); + expect(registeredTools().sort()).toEqual(expected.sort()); }); function loadHost() { @@ -68,82 +61,23 @@ describe('materializeDbTools', () => { require(file!); // eslint-disable-next-line @typescript-eslint/no-var-requires const { getHost } = require('@agentic-kit/pi'); - return { config, host: getHost() }; + return getHost(); } - it('signals a signed-out host until env vars or a stored session exist', () => { - const { host } = loadHost(); + it('reads the session stored under CONSTRUCTIVE_STASH_DIR per call', () => { + const host = loadHost(); expect(host.account()).toBeNull(); - expect(host.backendConfig()).toBeUndefined(); - - process.env.CONSTRUCTIVE_USER_ID = 'u1'; - process.env.CONSTRUCTIVE_ACCESS_TOKEN = 't1'; - process.env.CONSTRUCTIVE_API_ENDPOINT = 'http://api.localhost:3000/graphql'; - expect(host.account()).toMatchObject({ userId: 'u1', accessToken: 't1' }); - expect(host.backendConfig()).toEqual({ - apiEndpoint: 'http://api.localhost:3000/graphql', - modulesEndpoint: 'http://modules.localhost:3000/graphql', - agentEndpoint: 'http://agent.localhost:3000/graphql', - computeEndpoint: 'http://compute.localhost:3000/graphql' - }); - process.env.CONSTRUCTIVE_MODULES_ENDPOINT = 'http://modules.other.test/graphql'; - expect(host.backendConfig()).toMatchObject({ - apiEndpoint: 'http://api.localhost:3000/graphql', - modulesEndpoint: 'http://modules.other.test/graphql' - }); - }); + const { store } = loadConfig(home); + selectBackend(store, addBackend(store, backendFromEndpoints({ api: 'https://api.example.com/graphql' })).name); + saveSession(store, { userId: 'stored-user', email: 'dev@example.com', accessToken: 'stored-token', signedInAt: 1, issuedFor: backendFromEndpoints({ api: 'https://api.example.com/graphql' }) }); - it('rejects a plane override that names no api endpoint instead of completing it with a guess', () => { - const { host } = loadHost(); - process.env.CONSTRUCTIVE_MODULES_ENDPOINT = 'https://modules.example.com/graphql'; - expect(() => host.backendConfig()).toThrow('CONSTRUCTIVE_API_ENDPOINT is required'); - }); - - it('reads the stored session and backend per call when env vars are absent', () => { - const { config, host } = loadHost(); - expect(host.account()).toBeNull(); - - saveBackendConfig(config.store, REMOTE); - saveSession(config.store, { - userId: 'stored-user', - email: 'dev@example.com', - accessToken: 'stored-token', - apiKey: 'stored-key', - signedInAt: 1 - }); - - expect(host.account()).toEqual({ - userId: 'stored-user', - accessToken: 'stored-token', - apiKey: 'stored-key' - }); - expect(host.backendConfig()).toEqual({ - apiEndpoint: REMOTE.apiEndpoint, - modulesEndpoint: REMOTE.modulesEndpoint, - agentEndpoint: REMOTE.agentEndpoint, - computeEndpoint: REMOTE.computeEndpoint - }); - }); - - it('lets env vars beat the stored session', () => { - const { config, host } = loadHost(); - saveBackendConfig(config.store, LOCAL); - saveSession(config.store, { - userId: 'stored-user', - email: 'dev@example.com', - accessToken: 'stored-token', - signedInAt: 1 - }); - - process.env.CONSTRUCTIVE_USER_ID = 'env-user'; - process.env.CONSTRUCTIVE_ACCESS_TOKEN = 'env-token'; - expect(host.account()).toMatchObject({ userId: 'env-user', accessToken: 'env-token' }); + expect(host.account()).toMatchObject({ userId: 'stored-user', accessToken: 'stored-token' }); + expect(host.backendConfig()).toMatchObject({ apiEndpoint: 'https://api.example.com/graphql' }); }); it('bakes the sign-in hint for pi failure reasons', () => { - const { host } = loadHost(); - expect(host.signInHint).toBe('Run `agent login` to sign in.'); + expect(loadHost().signInHint).toBe('Run `agent login` to sign in.'); }); it('surfaces `agent login` in the signed-out pi context reason', async () => { @@ -153,11 +87,66 @@ describe('materializeDbTools', () => { const project = path.join(home, 'project'); fs.mkdirSync(project); - fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=00000000-0000-4000-8000-000000000001\n'); + fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=0190f1a0-0000-7000-8000-000000000001\n'); const result = await resolveProjectContext(project); expect(result.context).toBeNull(); expect(result.code).toBe('missing-credentials'); expect(result.reason).toContain('Run `agent login` to sign in.'); }); + + const boundProject = () => { + const project = path.join(home, 'project'); + fs.mkdirSync(project); + fs.writeFileSync(path.join(project, '.env'), 'DATABASE_ID=0190f1a0-0000-7000-8000-000000000001\n'); + return project; + }; + + it.each([ + ['a credential without an api endpoint', { CONSTRUCTIVE_USER_ID: 'u1', CONSTRUCTIVE_ACCESS_TOKEN: 'secret-token' }], + ['a plane variable alone', { CONSTRUCTIVE_MODULES_ENDPOINT: 'https://modules.example.com/graphql' }] + ])('reports no-backend naming CONSTRUCTIVE_API_ENDPOINT for %s, not a missing sign-in', async (_name, env) => { + loadHost(); + Object.assign(process.env, env); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { resolveProjectContext } = require('@agentic-kit/pi'); + + const result = await resolveProjectContext(boundProject()); + expect(result.context).toBeNull(); + expect(result.code).toBe('no-backend'); + expect(result.reason).toContain('CONSTRUCTIVE_API_ENDPOINT'); + expect(result.reason).not.toContain('secret-token'); + }); + + it('names the missing plane and `agent login` for a context another app wrote', async () => { + loadHost(); + const { store } = loadConfig(home); + const api = 'http://api.localhost/graphql'; + store.createContext('localnet', { + endpoint: api, + targets: { api: { endpoint: api }, auth: { endpoint: 'http://auth.localhost/graphql' }, modules: { endpoint: 'http://modules.localhost/graphql' }, agent: { endpoint: 'http://agent.localhost/graphql' } } + }); + store.setCurrentContext('localnet'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { resolveProjectContext } = require('@agentic-kit/pi'); + + const result = await resolveProjectContext(boundProject()); + expect(result.code).toBe('no-backend'); + expect(result.reason).toMatch(/"localnet" lacks the compute endpoint.*`agent login`/); + }); + + it('says a stored session was issued by another backend instead of only asking to sign in', async () => { + loadHost(); + const { store } = loadConfig(home); + selectBackend(store, addBackend(store, backendFromEndpoints({ api: 'https://api.example.com/graphql' })).name); + saveSession(store, { userId: 'u', email: 'e', accessToken: 'secret-token', signedInAt: 1, issuedFor: backendFromEndpoints({ api: 'http://api.a.localhost/graphql' }) }); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { resolveProjectContext } = require('@agentic-kit/pi'); + + const result = await resolveProjectContext(boundProject()); + expect(result.context).toBeNull(); + expect(result.reason).toContain('was issued for another backend'); + expect(result.reason).toContain('the session was issued for http://api.a.localhost/graphql'); + expect(result.reason).not.toContain('secret-token'); + }); }); diff --git a/agentic/cli/__tests__/stores.test.ts b/agentic/cli/__tests__/stores.test.ts deleted file mode 100644 index 08002815ec..0000000000 --- a/agentic/cli/__tests__/stores.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { ConfigStore } from 'appstash'; -import * as fs from 'fs'; -import * as os from 'os'; -import * as path from 'path'; - -import { AccountSession, clearSession, loadSession, saveSession } from '../src/account-store'; -import { backendFromApiEndpoint, loadBackendConfig, saveBackendConfig } from '../src/backend-store'; -import { loadConfig } from '../src/config'; - -const LOCAL = backendFromApiEndpoint('http://api.localhost:3000/graphql'); -const REMOTE = backendFromApiEndpoint('https://api.example.com/graphql'); - -let home: string; - -beforeEach(() => { - home = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-cli-store-')); -}); - -afterEach(() => { - fs.rmSync(home, { recursive: true, force: true }); -}); - -const session: AccountSession = { - userId: 'user-1', - email: 'dev@example.com', - accessToken: 'access-token', - accessTokenExpiresAt: '2026-08-04T00:00:00Z', - apiKey: 'cnc_live_sk_abc', - keyId: 'key-1', - apiKeyExpiresAt: '2031-08-03T00:00:00Z', - signedInAt: 1754000000000 -}; - -const store = (): ConfigStore => { - const s = loadConfig(home).store; - if (!s.getCurrentContext()) saveBackendConfig(s, LOCAL); - return s; -}; -const bareStore = (): ConfigStore => loadConfig(home).store; - -describe('config', () => { - it('shares the constructive stash rather than an agent-specific directory', () => { - const config = loadConfig(home); - saveBackendConfig(config.store, LOCAL); - expect(fs.existsSync(path.join(config.dirs.stash.config, 'agent', 'account.json'))).toBe(false); - saveSession(config.store, session); - // credentials land in the shared stash root, not an agent-only subdirectory - expect(fs.existsSync(path.join(config.dirs.stash.config, 'credentials.json'))).toBe(true); - }); -}); - -describe('account-store', () => { - it('round-trips a session through the shared store', () => { - const s = store(); - saveSession(s, session); - expect(loadSession(s)).toEqual(session); - }); - - it('files the session under the active backend context, keeping backends independent', () => { - const s = store(); - saveBackendConfig(s, REMOTE); - saveSession(s, session); - saveBackendConfig(s, LOCAL); - expect(loadSession(s)).toBeNull(); - saveBackendConfig(s, REMOTE); - expect(loadSession(s)).toEqual(session); - }); - - it('refuses to file a session before a backend is chosen', () => { - const s = bareStore(); - expect(() => saveSession(s, session)).toThrow('No backend chosen'); - expect(s.getCurrentContext()).toBeNull(); - }); - - it('writes credentials with mode 0600', () => { - const s = store(); - saveSession(s, session); - const file = path.join(loadConfig(home).dirs.stash.config, 'credentials.json'); - expect(fs.statSync(file).mode & 0o777).toBe(0o600); - }); - - it('returns null when nothing is stored', () => { - expect(loadSession(store())).toBeNull(); - }); - - it('clearSession removes the credentials and tolerates a signed-out store', () => { - const s = store(); - saveSession(s, session); - clearSession(s); - expect(loadSession(s)).toBeNull(); - expect(() => clearSession(s)).not.toThrow(); - }); -}); - -describe('backend-store', () => { - it('derives all five planes from the api endpoint the user names', () => { - expect(REMOTE).toEqual({ - apiEndpoint: 'https://api.example.com/graphql', - authEndpoint: 'https://auth.example.com/graphql', - modulesEndpoint: 'https://modules.example.com/graphql', - agentEndpoint: 'https://agent.example.com/graphql', - computeEndpoint: 'https://compute.example.com/graphql' - }); - expect(() => backendFromApiEndpoint('not a url')).toThrow('Invalid API endpoint URL'); - }); - - it('round-trips all five planes and returns null before one is chosen', () => { - const s = bareStore(); - expect(loadBackendConfig(s)).toBeNull(); - expect(saveBackendConfig(s, REMOTE)).toBe('example.com'); - expect(loadBackendConfig(s)).toEqual(REMOTE); - expect(saveBackendConfig(s, LOCAL)).toBe('localhost-3000'); - expect(loadBackendConfig(s)).toEqual(LOCAL); - }); - - it('treats a context missing a plane as no backend rather than guessing one', () => { - const s = store(); - s.createContext('partial', { - endpoint: REMOTE.apiEndpoint, - targets: { api: { endpoint: REMOTE.apiEndpoint }, auth: { endpoint: REMOTE.authEndpoint } } - }); - s.setCurrentContext('partial'); - expect(loadBackendConfig(s)).toBeNull(); - }); -}); diff --git a/agentic/cli/jest.config.js b/agentic/cli/jest.config.js index 8a26efd6d0..b3b5381fb7 100644 --- a/agentic/cli/jest.config.js +++ b/agentic/cli/jest.config.js @@ -2,6 +2,7 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', + setupFilesAfterEnv: ['/jest.setup.js'], transform: { '^.+\\.tsx?$': [ 'ts-jest', diff --git a/agentic/cli/jest.setup.js b/agentic/cli/jest.setup.js new file mode 100644 index 0000000000..e23b1a597a --- /dev/null +++ b/agentic/cli/jest.setup.js @@ -0,0 +1,11 @@ +// Points appstash's default base at a temporary directory for the whole suite, +// so no test can resolve the real home directory when a variable is missing. +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'jest-stash-base-')); +process.env.APPSTASH_BASE_DIR = base; +delete process.env.CONSTRUCTIVE_STASH_DIR; + +afterAll(() => fs.rmSync(base, { recursive: true, force: true })); diff --git a/agentic/cli/package.json b/agentic/cli/package.json index cb3fadce13..916edba9ed 100644 --- a/agentic/cli/package.json +++ b/agentic/cli/package.json @@ -34,9 +34,8 @@ "dependencies": { "@agentic-kit/harness": "workspace:*", "@agentic-kit/pi": "workspace:*", - "@constructive-io/sdk": "workspace:^", + "@agentic-kit/session": "workspace:^", "@earendil-works/pi-coding-agent": "1.4.0", - "appstash": "^0.8.0", "inquirerer": "^4.9.4" }, "keywords": [ diff --git a/agentic/cli/src/account-store.ts b/agentic/cli/src/account-store.ts deleted file mode 100644 index 4364df117c..0000000000 --- a/agentic/cli/src/account-store.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { ConfigStore } from 'appstash'; - - -export interface AccountSession { - userId: string; - email: string; - accessToken: string; - accessTokenExpiresAt?: string; - apiKey?: string; - keyId?: string; - apiKeyExpiresAt?: string; - signedInAt: number; -} - -/** - * Sessions live in the shared Constructive stash, as the credentials of the - * active context (the chosen backend). The store owns the file layout, the - * atomic 0600 writes and the at-rest encoding; this module only maps between - * its `ContextCredentials` and the session shape the CLI passes around. - */ -function currentContextName(store: ConfigStore): string | null { - return store.getCurrentContext()?.name ?? null; -} - -/** The active context; a session is never filed under a backend nobody chose. */ -function ensureContextName(store: ConfigStore): string { - const name = currentContextName(store); - if (!name) throw new Error('No backend chosen — run `agent login` first.'); - return name; -} - -export function loadSession(store: ConfigStore, context?: string): AccountSession | null { - const contextName = context ?? currentContextName(store); - if (!contextName) return null; - const creds = store.getCredentials(contextName); - if (!creds?.token || !creds.userId) return null; - return { - userId: creds.userId, - email: creds.email ?? '', - accessToken: creds.token, - accessTokenExpiresAt: creds.expiresAt, - apiKey: creds.apiKey, - keyId: creds.keyId, - apiKeyExpiresAt: creds.apiKeyExpiresAt, - signedInAt: creds.signedInAt ?? 0 - }; -} - -/** - * `context` names the backend the session belongs to; it does not have to exist - * as a context yet, so a sign-in can be filed before the backend is committed - * and a failed sign-in leaves nothing behind. - */ -export function saveSession(store: ConfigStore, session: AccountSession, context?: string): void { - store.setCredentials(context ?? ensureContextName(store), { - token: session.accessToken, - expiresAt: session.accessTokenExpiresAt, - userId: session.userId, - email: session.email, - apiKey: session.apiKey, - keyId: session.keyId, - apiKeyExpiresAt: session.apiKeyExpiresAt, - signedInAt: session.signedInAt - }); -} - -export function clearSession(store: ConfigStore, context?: string): void { - const contextName = context ?? currentContextName(store); - if (contextName) store.removeCredentials(contextName); -} diff --git a/agentic/cli/src/api-key.ts b/agentic/cli/src/api-key.ts deleted file mode 100644 index 26abab0827..0000000000 --- a/agentic/cli/src/api-key.ts +++ /dev/null @@ -1,133 +0,0 @@ -export const API_KEY_NAME = 'agentic-cli'; -export const API_KEY_ACCESS_LEVEL = 'full_access'; -export const API_KEY_MFA_LEVEL = 'none'; -export const API_KEY_YEARS = 5; - -/** - * Re-mint once the key is within a week of expiry. The mint needs a - * fresh-password step-up window, so in practice the refresh succeeds only right - * after a sign-in; otherwise it surfaces as a re-auth prompt. - */ -export const REMINT_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 7; - -export interface MintedApiKey { - apiKey: string; - keyId: string; - apiKeyExpiresAt?: string; -} - -export interface CreateApiKeyInputShape { - keyName: string; - accessLevel: string; - mfaLevel: string; - expiresIn: { years: number }; -} - -export function buildCreateApiKeyInput({ years }: { years: number }): CreateApiKeyInputShape { - return { - keyName: API_KEY_NAME, - accessLevel: API_KEY_ACCESS_LEVEL, - mfaLevel: API_KEY_MFA_LEVEL, - expiresIn: { years } - }; -} - -interface RawApiKeyRecord { - apiKey?: string | null; - keyId?: string | null; - expiresAt?: string | null; -} - -export function parseMintedKey(record: RawApiKeyRecord | null | undefined): MintedApiKey { - if (!record?.apiKey || !record.keyId) { - throw new Error('createApiKey returned no API key.'); - } - return { - apiKey: record.apiKey, - keyId: record.keyId, - ...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {}) - }; -} - -export type ApiKeyErrorKind = - | 'step-up-required' - | 'disabled' - | 'limit-reached' - | 'not-authenticated' - | 'invalid-access-level' - | 'unknown'; - -const ERROR_CODE_MAP: Record = { - STEP_UP_REQUIRED: 'step-up-required', - API_KEYS_DISABLED: 'disabled', - API_KEY_LIMIT_REACHED: 'limit-reached', - NOT_AUTHENTICATED: 'not-authenticated', - INVALID_ACCESS_LEVEL: 'invalid-access-level' -}; - -export function classifyApiKeyError(err: unknown): ApiKeyErrorKind { - const errors = (err as { errors?: Array<{ message?: string; extensions?: { code?: string } }> })?.errors; - if (Array.isArray(errors)) { - for (const e of errors) { - const code = e.extensions?.code; - if (code && ERROR_CODE_MAP[code]) return ERROR_CODE_MAP[code]; - } - } - const message = err instanceof Error ? err.message : typeof err === 'string' ? err : ''; - for (const code of Object.keys(ERROR_CODE_MAP)) { - if (message.includes(code)) return ERROR_CODE_MAP[code]; - } - return 'unknown'; -} - -export function needsRemint({ - apiKeyExpiresAt, - now, - thresholdMs = REMINT_THRESHOLD_MS -}: { - apiKeyExpiresAt: string | undefined; - now: number; - thresholdMs?: number; -}): boolean { - if (!apiKeyExpiresAt) return false; - const expires = Date.parse(apiKeyExpiresAt); - if (Number.isNaN(expires)) return false; - return expires - now <= thresholdMs; -} - -/** - * Mint-first, revoke-on-success: revoking before minting would destroy a - * still-valid key whenever the mint then fails, leaving no credential at all. - * The one case that needs the old key gone first is the live-key cap - * (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once. - */ -export async function remintApiKey({ - currentKeyId, - revoke, - mint -}: { - currentKeyId: string | undefined; - revoke: (keyId: string) => Promise; - mint: () => Promise; -}): Promise { - const revokeOld = async () => { - if (!currentKeyId) return; - try { - await revoke(currentKeyId); - } catch (err) { - console.warn( - `[agent] failed to revoke superseded API key ${currentKeyId}: ${err instanceof Error ? err.message : String(err)}` - ); - } - }; - - try { - const minted = await mint(); - await revokeOld(); - return minted; - } catch (err) { - if (classifyApiKeyError(err) !== 'limit-reached') throw err; - await revokeOld(); - return mint(); - } -} diff --git a/agentic/cli/src/auth-error.ts b/agentic/cli/src/auth-error.ts deleted file mode 100644 index 7f5114fa2c..0000000000 --- a/agentic/cli/src/auth-error.ts +++ /dev/null @@ -1,107 +0,0 @@ -const NETWORK_ERROR_CODES = new Set([ - 'ECONNREFUSED', - 'ECONNRESET', - 'ENOTFOUND', - 'EAI_AGAIN', - 'EHOSTUNREACH', - 'ENETUNREACH', - 'ETIMEDOUT', - 'UND_ERR_CONNECT_TIMEOUT', - 'UND_ERR_SOCKET' -]); - -function errorCode(err: unknown): string | undefined { - if (!err || typeof err !== 'object') return undefined; - const { code, cause } = err as { code?: unknown; cause?: unknown }; - if (typeof code === 'string') return code; - if (cause && typeof cause === 'object') { - const causeCode = (cause as { code?: unknown }).code; - if (typeof causeCode === 'string') return causeCode; - } - return undefined; -} - -export function isNetworkError(err: unknown): boolean { - const code = errorCode(err); - if (code !== undefined) return NETWORK_ERROR_CODES.has(code); - if (err instanceof AggregateError) return true; - return err instanceof TypeError && /fetch failed/i.test(err.message); -} - -function extractGraphqlMessages(err: unknown): string[] { - const messages: string[] = []; - const codes: string[] = []; - const visited = new Set(); - const visit = (value: unknown): void => { - if (!value || typeof value !== 'object' || visited.has(value)) return; - visited.add(value); - const record = value as Record; - if (typeof record.message === 'string' && record.message.trim() !== '') { - const message = record.message.trim().replace(/^GraphQL Error:\s*/u, ''); - if (message.length > 0) messages.push(message); - } - const extensions = - record.extensions && typeof record.extensions === 'object' - ? (record.extensions as Record) - : undefined; - if (typeof extensions?.code === 'string') codes.push(extensions.code); - if (Array.isArray(record.errors)) record.errors.forEach(visit); - if (record.cause) visit(record.cause); - if (record.extensions) visit(record.extensions); - if (record.detail) visit(record.detail); - if (record.data) visit(record.data); - if (record.response) visit(record.response); - if (record.result) visit(record.result); - if (record.payload) visit(record.payload); - }; - visit(err); - if (messages.length === 0) { - for (const code of codes) { - if (code === 'UNAUTHENTICATED') messages.push('Your session has expired. Sign in again.'); - if (code === 'FORBIDDEN') { - messages.push('The server rejected this request. Check your account permissions.'); - } - } - } - return [...new Set(messages)]; -} - -export function describeAuthError(err: unknown, endpoint: string): string { - if (isNetworkError(err)) { - return `Could not reach the server at ${endpoint}. Check that it is running, or pick a different backend.`; - } - const graphqlMessages = extractGraphqlMessages(err); - if (graphqlMessages.length > 0) return graphqlMessages.join('; '); - const message = err instanceof Error ? err.message : String(err); - if (message.trim() !== '' && message !== '[object Object]') return message; - const name = err instanceof Error ? err.name : typeof err; - return `Authentication failed unexpectedly (${name}).`; -} - -export const AUTH_TIMEOUT_MS = 10_000; - -export function withAuthTimeout( - promise: Promise, - endpoint: string, - ms: number = AUTH_TIMEOUT_MS -): Promise { - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - reject( - new Error( - `The server at ${endpoint} did not respond within ${Math.round(ms / 1000)}s. Check the backend settings and try again.` - ) - ); - }, ms); - promise.then( - value => { - clearTimeout(timer); - resolve(value); - }, - (err: unknown) => { - clearTimeout(timer); - reject(err instanceof Error ? err : new Error(String(err))); - } - ); - }); -} diff --git a/agentic/cli/src/auth.ts b/agentic/cli/src/auth.ts deleted file mode 100644 index a591b86e45..0000000000 --- a/agentic/cli/src/auth.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { auth } from '@constructive-io/sdk'; -import { ConfigStore } from 'appstash'; - -import { AccountSession, clearSession, loadSession, saveSession } from './account-store'; -import { - API_KEY_YEARS, - buildCreateApiKeyInput, - classifyApiKeyError, - MintedApiKey, - needsRemint, - parseMintedKey, - remintApiKey -} from './api-key'; -import { describeAuthError, withAuthTimeout } from './auth-error'; - -type AuthClient = ReturnType; - -interface AuthRecord { - userId?: string; - accessToken?: string; - accessTokenExpiresAt?: string; -} - -export type ApiKeyRefreshStatus = 'ok' | 'reminted' | 'reauth-required' | 'unavailable' | 'signed-out'; - -const SELECT = { - result: { - select: { userId: true, accessToken: true, accessTokenExpiresAt: true } - } -} as const; - -const CREATE_KEY_SELECT = { - result: { select: { apiKey: true, keyId: true, expiresAt: true } } -} as const; - -const REVOKE_KEY_SELECT = { result: true } as const; - -function authedClient(endpoint: string, bearer: string): AuthClient { - return auth.createClient({ - endpoint, - headers: { Authorization: `Bearer ${bearer}` } - }); -} - -async function mint(client: AuthClient): Promise { - const data = (await client.mutation - .createApiKey({ input: buildCreateApiKeyInput({ years: API_KEY_YEARS }) }, { select: CREATE_KEY_SELECT }) - .unwrap()) as { createApiKey?: { result?: MintedApiKey & { expiresAt?: string } } } | undefined; - return parseMintedKey(data?.createApiKey?.result); -} - -async function revoke(client: AuthClient, keyId: string): Promise { - await client.mutation.revokeApiKey({ input: { keyId } }, { select: REVOKE_KEY_SELECT }).unwrap(); -} - -/** - * Ensure the stored session carries a usable, not-about-to-expire API key. - * Never throws: returns a status the caller can surface. A mint/re-mint needs - * the fresh-password step-up window, so it succeeds right after a sign-in and - * degrades to 'reauth-required' when attempted cold. - */ -export async function refreshApiKeyIfNeeded({ - store, - context, - authEndpoint -}: { - store: ConfigStore; - /** Backend context the session is filed under; defaults to the active one. */ - context?: string; - authEndpoint: string; -}): Promise { - const session = loadSession(store, context); - if (!session) return 'signed-out'; - const hasKey = !!session.apiKey; - const due = needsRemint({ - apiKeyExpiresAt: session.apiKeyExpiresAt, - now: Date.now() - }); - if (hasKey && !due) return 'ok'; - - const client = authedClient(authEndpoint, session.accessToken); - try { - const minted = await remintApiKey({ - currentKeyId: session.keyId, - revoke: (keyId) => revoke(client, keyId), - mint: () => mint(client) - }); - saveSession( - store, - { - ...session, - apiKey: minted.apiKey, - keyId: minted.keyId, - apiKeyExpiresAt: minted.apiKeyExpiresAt - }, - context - ); - return 'reminted'; - } catch (err) { - const kind = classifyApiKeyError(err); - if (kind === 'step-up-required' || kind === 'not-authenticated') return 'reauth-required'; - console.warn(`[agent] API key refresh failed (${kind}): ${describeAuthError(err, authEndpoint)}`); - return 'unavailable'; - } -} - -export async function signIn({ - store, - context, - authEndpoint, - email, - password -}: { - store: ConfigStore; - context?: string; - authEndpoint: string; - email: string; - password: string; -}): Promise { - const trimmedEmail = email.trim(); - if (!trimmedEmail || !password) throw new Error('Email and password are required.'); - - const client = auth.createClient({ endpoint: authEndpoint }); - const request = client.mutation - .signIn({ input: { email: trimmedEmail, password } }, { select: SELECT }) - .unwrap(); - - let data: { signIn?: { result?: AuthRecord } } | undefined; - try { - data = (await withAuthTimeout(request, authEndpoint)) as { signIn?: { result?: AuthRecord } } | undefined; - } catch (err) { - throw new Error(describeAuthError(err, authEndpoint)); - } - - const record = data?.signIn?.result; - if (!record?.accessToken || !record.userId) { - throw new Error('Authentication returned no access token (MFA may be required).'); - } - - saveSession( - store, - { - userId: record.userId, - email: trimmedEmail, - accessToken: record.accessToken, - ...(record.accessTokenExpiresAt ? { accessTokenExpiresAt: record.accessTokenExpiresAt } : {}), - signedInAt: Date.now() - }, - context - ); - // Mint the long-lived API key inside the fresh step-up window. Best-effort: a - // mint failure leaves a valid signed-in session that lacks a key until re-auth. - await refreshApiKeyIfNeeded({ store, context, authEndpoint }); - return loadSession(store, context); -} - -export async function signOut({ - store, - context, - authEndpoint -}: { - store: ConfigStore; - /** Backend context the session is filed under; defaults to the active one. */ - context?: string; - authEndpoint: string; -}): Promise { - const session = loadSession(store, context); - if (!session) return false; - if (session.keyId) { - try { - await revoke(authedClient(authEndpoint, session.accessToken), session.keyId); - } catch (err) { - console.warn(`[agent] API key revoke on sign-out failed: ${describeAuthError(err, authEndpoint)}`); - } - } - clearSession(store, context); - return true; -} diff --git a/agentic/cli/src/backend-store.ts b/agentic/cli/src/backend-store.ts deleted file mode 100644 index ce0ca15820..0000000000 --- a/agentic/cli/src/backend-store.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { deriveSubdomainEndpoint } from '@agentic-kit/pi'; -import { ConfigStore } from 'appstash'; - -/** Every Constructive plane the agent talks to, one GraphQL endpoint each. */ -export interface BackendConfig { - apiEndpoint: string; - authEndpoint: string; - modulesEndpoint: string; - agentEndpoint: string; - computeEndpoint: string; -} - -const PLANES = ['api', 'auth', 'modules', 'agent', 'compute'] as const; -type Plane = (typeof PLANES)[number]; -const KEY: Record = { - api: 'apiEndpoint', - auth: 'authEndpoint', - modules: 'modulesEndpoint', - agent: 'agentEndpoint', - compute: 'computeEndpoint' -}; - -/** - * The CLI ships no backend URLs: the user names the api endpoint, and the other - * planes share its host scheme (api. -> auth., modules., ...). - * Throws on anything that is not an absolute URL. - */ -export function backendFromApiEndpoint(apiEndpoint: string): BackendConfig { - const api = apiEndpoint.trim(); - const config = { apiEndpoint: api } as BackendConfig; - for (const plane of PLANES) { - if (plane === 'api') continue; - const endpoint = api ? deriveSubdomainEndpoint(api, plane) : ''; - if (!endpoint) throw new Error(`Invalid API endpoint URL: ${api || '(empty)'}`); - config[KEY[plane]] = endpoint; - } - return config; -} - -/** - * A chosen backend is a named context in the shared store, named after the api - * endpoint's apex (https://api.example.com/graphql -> example.com). Credentials - * hang off the context, so each backend keeps an independent session. - */ -export function contextNameFor(config: BackendConfig): string { - const { host } = new URL(config.apiEndpoint); - const apex = host.includes('.') ? host.slice(host.indexOf('.') + 1) : host; - return apex.toLowerCase().replace(/[^a-z0-9.-]+/g, '-'); -} - -function toBackendConfig(targets: Record | undefined): BackendConfig | null { - const config = {} as BackendConfig; - for (const plane of PLANES) { - const endpoint = targets?.[plane]?.endpoint; - if (!endpoint) return null; - config[KEY[plane]] = endpoint; - } - return config; -} - -/** - * Endpoints of the active context, or null when no backend has been chosen or - * the context lacks a plane: callers must fail then, never pick a default. - */ -export function loadBackendConfig(store: ConfigStore): BackendConfig | null { - const ctx = store.getCurrentContext(); - if (!ctx) return null; - return toBackendConfig(ctx.targets); -} - -/** Persist the endpoints as a context and make it active. */ -export function saveBackendConfig(store: ConfigStore, config: BackendConfig): string { - const name = contextNameFor(config); - const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }])); - store.createContext(name, { endpoint: config.apiEndpoint, targets }); - store.setCurrentContext(name); - return name; -} diff --git a/agentic/cli/src/commands.ts b/agentic/cli/src/commands.ts index 80f080eb49..4bc667ae5f 100644 --- a/agentic/cli/src/commands.ts +++ b/agentic/cli/src/commands.ts @@ -1,13 +1,15 @@ +import { + backendFromEndpoints, + listBackends, + type PreviousKey, + resolveSession, + sessionProblem, + signIn, + signOut, + verifySession +} from '@agentic-kit/session'; import { Inquirerer } from 'inquirerer'; -import { loadSession } from './account-store'; -import { signIn, signOut } from './auth'; -import { - backendFromApiEndpoint, - contextNameFor, - loadBackendConfig, - saveBackendConfig -} from './backend-store'; import { AgentCliConfig, defaultManifest, saveManifestFile } from './config'; import { assembleSkills } from './skills'; @@ -61,11 +63,12 @@ function maskKey(token: string): string { export async function login(config: AgentCliConfig, argv: Record): Promise { if (!process.stdin.isTTY && !(argv.email && argv.password)) { throw new Error( - 'agent login is interactive and needs a terminal. For headless use, set CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN, and CONSTRUCTIVE_API_KEY.' + 'agent login is interactive and needs a terminal. For headless use, set CONSTRUCTIVE_API_ENDPOINT, CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN, and CONSTRUCTIVE_API_KEY.' ); } - const saved = loadBackendConfig(config.store); + const current = listBackends(config.store).find((backend) => backend.current); + const savedEndpoint = current?.status === 'complete' ? current.backend.apiEndpoint : current?.status === 'incomplete' ? current.apiEndpoint : undefined; const prompter = new Inquirerer({ noTty: !process.stdin.isTTY }); try { const answers = await prompter.prompt(argv, [ @@ -73,71 +76,94 @@ export async function login(config: AgentCliConfig, argv: Record { - const backend = loadBackendConfig(config.store); - if (!backend) { + const result = await signOut({ store: config.store, session: resolveSession({ store: config.store }) }); + if (result.kind === 'not-signed-in') { log('not signed in.'); return; } - const wasSignedIn = await signOut({ - store: config.store, - authEndpoint: backend.authEndpoint - }); - if (wasSignedIn) log('signed out — API key revoked and session cleared.'); - else log('not signed in.'); + if (result.kind === 'from-environment') { + log('nothing to sign out of: the session comes from the environment (CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN). Unset them to sign out.'); + return; + } + switch (result.key.kind) { + case 'revoked': + log('signed out — API key revoked and session cleared.'); + break; + case 'absent': + log('signed out — session cleared (it had no API key).'); + break; + case 'failed': + log(`signed out — session cleared, but the API key ${result.key.keyId} could not be revoked (${result.key.reason}); it stays valid until it expires.`); + break; + } } -export function whoami(config: AgentCliConfig): void { - const session = loadSession(config.store); - if (!session) { - log('not signed in — run `agent login`'); +/** The `agent` command that stores a complete backend context. */ +export const REPAIR_HINT = 'Run `agent login` to store a complete backend.'; + +export async function whoami(config: AgentCliConfig): Promise { + const session = resolveSession({ store: config.store }); + if (session.kind !== 'signed-in') { + log(sessionProblem(session, REPAIR_HINT) ?? 'not signed in — run `agent login`'); process.exitCode = 1; return; } - const backend = loadBackendConfig(config.store); - log(`signed in as ${session.email}`); - log(`user id: ${session.userId}`); - log(`backend: ${backend?.apiEndpoint ?? 'unknown'}`); - if (session.apiKey) { - log(`API key: ${maskKey(session.apiKey)} (expires ${session.apiKeyExpiresAt ?? 'unknown'})`); + const { account, backend } = session; + log(`signed in as ${account.email ?? `user ${account.userId}`}${session.source === 'env' ? ' (from the environment)' : ''}`); + log(`user id: ${account.userId}`); + log(`backend: ${backend.apiEndpoint}`); + if (account.key.kind === 'active') { + log(`API key: ${maskKey(account.key.apiKey)} (expires ${account.key.expiresAt ?? 'unknown'})`); } else { log('API key: none — db tools stay signed out. Run `agent login` to mint one.'); } - if (session.accessTokenExpiresAt) log(`access token expires: ${session.accessTokenExpiresAt}`); - log(`context: ${config.store.getCurrentContext()?.name ?? 'none'}`); + if (account.key.kind === 'none' && account.accessTokenExpiresAt) log(`access token expires: ${account.accessTokenExpiresAt}`); + log(`context: ${session.context ?? 'none'}`); + const check = await verifySession(session); + if (check.kind === 'accepted') { + log('credential: accepted by the backend'); + } else if (check.kind === 'rejected') { + log(`credential: rejected — ${check.reason} Run \`agent login\` to sign in again.`); + process.exitCode = 1; + } else { + log(`credential: not checked — ${check.reason}`); + } } export function usage(): void { diff --git a/agentic/cli/src/config.ts b/agentic/cli/src/config.ts index 390b9727cc..1e70dd97cd 100644 --- a/agentic/cli/src/config.ts +++ b/agentic/cli/src/config.ts @@ -1,17 +1,9 @@ import { FetchLike, HarnessDirs, harnessDirs, SkillsManifest } from '@agentic-kit/harness'; -import { ConfigStore, createConfigStore } from 'appstash'; +import { ConfigStore, openStore, STASH_NAME, stashBaseDir } from '@agentic-kit/session'; import * as fs from 'fs'; import * as path from 'path'; export const DEFAULT_SKILLS_REPO = 'constructive-io/constructive-skills'; - -/** - * Directory identity shared with the csdk CLI and the desktop app, so a sign-in - * here is a sign-in there. `agent` is only the tool's own name (env prefixes, - * help text). - */ -export const STASH_NAME = 'constructive'; -export const TOOL_NAME = 'agent'; export const DEFAULT_SKILLS_PIN = 'main'; /** Layer names understood by the assembler. */ @@ -51,12 +43,12 @@ export function defaultManifest(): SkillsManifest { }; } -export function loadConfig(baseDir?: string): AgentCliConfig { - const dirs = harnessDirs('constructive', baseDir); +export function loadConfig(baseDir: string | undefined = stashBaseDir()): AgentCliConfig { + const dirs = harnessDirs(STASH_NAME, baseDir); const agentDir = path.join(dirs.stash.data, 'agent'); const overlayDir = path.join(dirs.stash.config, 'skills-overlay'); const manifestFile = path.join(dirs.stash.config, 'skills-manifest.json'); - const store = createConfigStore(TOOL_NAME, { stashName: STASH_NAME, baseDir }); + const store = openStore(baseDir); fs.mkdirSync(agentDir, { recursive: true }); fs.mkdirSync(overlayDir, { recursive: true }); diff --git a/agentic/cli/src/credentials.ts b/agentic/cli/src/credentials.ts deleted file mode 100644 index d9b4810b28..0000000000 --- a/agentic/cli/src/credentials.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { loadSession } from './account-store'; -import { backendFromApiEndpoint, loadBackendConfig } from './backend-store'; -import { loadConfig } from './config'; - -export type ResolvedAccount = { - userId: string; - accessToken: string; - apiKey?: string; -}; - -export type ResolvedBackendConfig = { - apiEndpoint: string; - modulesEndpoint: string; - agentEndpoint: string; - computeEndpoint: string; -}; - -// Both resolvers run on every tool call and re-read the store, so a login or -// logout mid-session is picked up without a restart. CONSTRUCTIVE_* env vars -// win over the store (the CI/headless path); tokens never enter process.env -// from here. -export function resolveAccount(): ResolvedAccount | null { - const userId = process.env.CONSTRUCTIVE_USER_ID; - const accessToken = process.env.CONSTRUCTIVE_ACCESS_TOKEN; - if (userId && accessToken) { - return { userId, accessToken, apiKey: process.env.CONSTRUCTIVE_API_KEY }; - } - const session = loadSession(loadConfig(process.env.AGENT_HOME).store); - if (!session) return null; - return { userId: session.userId, accessToken: session.accessToken, apiKey: session.apiKey }; -} - -// CONSTRUCTIVE_API_ENDPOINT picks the whole backend: the other planes derive -// from it unless their own CONSTRUCTIVE_*_ENDPOINT is set. A plane override -// without an api endpoint names no backend, so it is an error, never a partial -// config the tools would complete with a guess. -export function resolveBackendConfig(): ResolvedBackendConfig | undefined { - const env = process.env; - const overrides = { - modulesEndpoint: env.CONSTRUCTIVE_MODULES_ENDPOINT, - agentEndpoint: env.CONSTRUCTIVE_AGENT_ENDPOINT, - computeEndpoint: env.CONSTRUCTIVE_COMPUTE_ENDPOINT - }; - const backend = env.CONSTRUCTIVE_API_ENDPOINT - ? backendFromApiEndpoint(env.CONSTRUCTIVE_API_ENDPOINT) - : loadBackendConfig(loadConfig(env.AGENT_HOME).store); - if (!backend) { - const stray = Object.entries(overrides).find(([, value]) => value); - if (stray) throw new Error('CONSTRUCTIVE_API_ENDPOINT is required when any CONSTRUCTIVE_*_ENDPOINT override is set.'); - return undefined; - } - return { - apiEndpoint: backend.apiEndpoint, - modulesEndpoint: overrides.modulesEndpoint || backend.modulesEndpoint, - agentEndpoint: overrides.agentEndpoint || backend.agentEndpoint, - computeEndpoint: overrides.computeEndpoint || backend.computeEndpoint - }; -} diff --git a/agentic/cli/src/db-tools.ts b/agentic/cli/src/db-tools.ts index 0478ee4bd2..e7d1095fe8 100644 --- a/agentic/cli/src/db-tools.ts +++ b/agentic/cli/src/db-tools.ts @@ -1,42 +1,28 @@ import * as fs from 'fs'; import * as path from 'path'; +import { REPAIR_HINT } from './commands'; import { AgentCliConfig } from './config'; const EXTENSION_FILE = 'constructive-db-tools.js'; -/** - * Environment variables that override the stored session at tool-call time. - * Without env vars or a stored session the tools load but report "not signed in". - */ -export const HOST_ENV_VARS = [ - 'CONSTRUCTIVE_USER_ID', - 'CONSTRUCTIVE_ACCESS_TOKEN', - 'CONSTRUCTIVE_API_KEY', - 'CONSTRUCTIVE_API_ENDPOINT', - 'CONSTRUCTIVE_MODULES_ENDPOINT', - 'CONSTRUCTIVE_AGENT_ENDPOINT', - 'CONSTRUCTIVE_COMPUTE_ENDPOINT' -] as const; - // pi's TUI loads extensions from files under /extensions (via jiti), // not from factories, so the db tools are wired by materializing a small // generated entry there. Both entry paths are resolved from THIS package at // assembly time and baked in, because node resolution from the appstash agent // dir would not find them. -function extensionSource(pkgEntry: string, credentialsEntry: string): string { +function extensionSource(pkgEntry: string, sessionEntry: string): string { return `// Generated by @agentic-kit/cli — do not edit (rewritten on every \`agent\` run). // Registers the Constructive typed db tools + confirm gate (@agentic-kit/pi) // with credentials resolved on each call: CONSTRUCTIVE_* env vars first, then -// the \`agent login\` session store. +// the shared session store (@agentic-kit/session). const { createDbTools } = require(${JSON.stringify(pkgEntry)}); -const { resolveAccount, resolveBackendConfig } = require(${JSON.stringify(credentialsEntry)}); +const { sessionToolsHost } = require(${JSON.stringify(sessionEntry)}); -module.exports = createDbTools({ - account: resolveAccount, - backendConfig: resolveBackendConfig, - signInHint: 'Run \`agent login\` to sign in.' -}, { excludeTools: ['add_records', 'create_api_key'] }); +module.exports = createDbTools( + sessionToolsHost({ signInHint: 'Run \`agent login\` to sign in.', repairHint: ${JSON.stringify(REPAIR_HINT)} }), + { excludeTools: ['add_records', 'create_api_key'] } +); `; } @@ -55,10 +41,10 @@ export function materializeDbTools( log('db tools unavailable (@agentic-kit/pi not installed) — continuing without them'); return null; } - const credentialsEntry = require.resolve('./credentials'); + const sessionEntry = require.resolve('@agentic-kit/session'); const dir = path.join(config.agentDir, 'extensions'); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, EXTENSION_FILE); - fs.writeFileSync(file, extensionSource(pkgEntry, credentialsEntry)); + fs.writeFileSync(file, extensionSource(pkgEntry, sessionEntry)); return file; } diff --git a/agentic/cli/src/index.ts b/agentic/cli/src/index.ts index 5a6b5f89f2..4ad30d7003 100644 --- a/agentic/cli/src/index.ts +++ b/agentic/cli/src/index.ts @@ -1,17 +1,17 @@ #!/usr/bin/env node -import { refreshApiKeyIfNeeded } from './auth'; -import { loadBackendConfig } from './backend-store'; -import { init, login, logout, skillsList, skillsUpdate, usage, whoami } from './commands'; +import { keyEndsSoon, resolveSession, sessionProblem } from '@agentic-kit/session'; + +import { init, login, logout, REPAIR_HINT, skillsList, skillsUpdate, usage, whoami } from './commands'; import { loadConfig } from './config'; import { materializeDbTools } from './db-tools'; import { assembleSkills } from './skills'; export { AgentCliConfig, loadConfig } from './config'; -export { HOST_ENV_VARS, materializeDbTools } from './db-tools'; +export { materializeDbTools } from './db-tools'; export { assembleSkills } from './skills'; async function run(args: string[]): Promise { - const config = loadConfig(process.env.AGENT_HOME); + const config = loadConfig(); // pi resolves its agent dir (skills, sessions, auth) from this env var; // point it at the appstash-owned dir before the SDK loads. process.env.PI_CODING_AGENT_DIR ??= config.agentDir; @@ -34,7 +34,7 @@ async function run(args: string[]): Promise { return; } if (first === 'whoami') { - whoami(config); + await whoami(config); return; } if (first === 'skills') { @@ -46,15 +46,12 @@ async function run(args: string[]): Promise { const log = (msg: string) => console.log(`[agent] ${msg}`); await assembleSkills(config, log); materializeDbTools(config, log); - // Fire-and-forget: keep the stored API key fresh (<7 days to expiry re-mints) - // without ever blocking startup. Only an expired login session gets a line. - const backend = loadBackendConfig(config.store); - if (backend) { - void refreshApiKeyIfNeeded({ store: config.store, authEndpoint: backend.authEndpoint }) - .then((status) => { - if (status === 'reauth-required') log('API key expired — run `agent login`'); - }) - .catch(() => {}); + const session = resolveSession({ store: config.store }); + const problem = sessionProblem(session, REPAIR_HINT); + if (problem) log(`warning: ${problem}`); + const key = session.kind === 'signed-in' ? session.account.key : null; + if (key?.kind === 'active' && keyEndsSoon({ expiresAt: key.expiresAt })) { + 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.`); } // pi is ESM-only; tsc's CJS output would downlevel a plain `await import()` // into `require()`, which cannot load it. Indirect the import so it survives diff --git a/agentic/command/README.md b/agentic/command/README.md new file mode 100644 index 0000000000..aad9fa68b8 --- /dev/null +++ b/agentic/command/README.md @@ -0,0 +1,69 @@ +# @agentic-kit/command + +The typed command layer of the Constructive CLI, and the binding of a `HarnessTool` from `@agentic-kit/harness` to a command. A command's input is a zod object; help, `--schema` and `--llms` print JSON Schema made from it, and the layer parses the input with it once. `inquirerer` stays the prompt library: the layer asks for missing input, and for the approval of a change, through its prompts. + +```ts +import { createCli, toCliCommands, toolCommand } from '@agentic-kit/command'; +import { constructiveGateDeps, deleteTableTool, describeSchemaTool } from '@agentic-kit/db-tools'; +import { createConstructiveGatePolicy } from '@agentic-kit/harness'; +import { z } from 'zod'; + +const commands = toCliCommands([ + toolCommand(describeSchemaTool, { name: 'schema show' }), + toolCommand(deleteTableTool, { name: 'table delete', positionals: ['table_name'] }) +], { gate: createConstructiveGatePolicy(constructiveGateDeps()) }); + +createCli({ + name: 'constructive', + version, + globals: z.object({ context: z.string().optional().meta({ description: 'The backend context to use', 'x-carry': true }) }), + commands +}).run(); +``` + +## Five kinds of command + +- **A read** (`effect: 'read'`, `run(input, ctx)`): the layer runs it at once. `--dry-run` and `--yes` mean nothing to it. +- **A change** (`effect: 'write' | 'destructive'`, `plan(input, ctx)` and `apply(input, planned, ctx)`): the layer calls `plan`, then decides from the run alone. `--dry-run` returns `{ applied: false, plan }` with the real run (`--yes`) as the next step. `--yes` or `-y` approves. A terminal shows the plan and asks; a no is `cancelled`, exit 1. Anything else (no terminal, `--no-input`, `CI`) stops with `approval-required`, exit 3, the plan in `error.details.plan` and the same command line with `--yes` as the next step. `apply` runs only after one of those approvals. `plan` returns `{ plan: ConfirmPrompt, needs?: string[], ...state }`: the layer prints only `plan`, and hands the whole value to `apply`, so a change applies exactly what was approved. `needs` are the flags that the run that applies the plan must add when it has no terminal (`--password-stdin` for a password that a terminal would ask for): on a run with no terminal, the layer adds them to the `--yes` step after `--dry-run` and after exit 3. A `plan` that throws stops the run with its error, under `--dry-run` too. +- **A change that runs at once** (`effect: 'write'`, `immediate: true`, `run(input, ctx)`): a change the person makes to their own local session (sign in, sign out, choose a context), or one that only narrows access. It runs as it is, with no `--yes` and no prompt, and refuses `--dry-run` (`dry-run-unsupported`). A CLI keeps the list of these short and fixed. +- **A server** (`stdout: 'reserved'`, `serve(input, ctx)`): it speaks a protocol on stdin and stdout, and its client approves each change made through it, so the layer refuses `--dry-run` (`dry-run-unsupported`) and `--yes` (`invalid-input`). Its results, errors and warnings go to stderr. `effect` is the strongest effect its client can reach. +- **A passthrough** (`passthrough(argv, ctx)`): it keeps its own flags, so it gets every word after the command path, parsed by `parseArgv`, and the layer reads none of them. + +`createCli` checks the kind of every command at start-up: a change with a `run` and no `immediate: true`, or without `plan` and `apply`, is a definition error, and only a write can run at once, so no change skips the approval by accident. + +## The input + +- Each property of the zod object is a flag, in kebab-case, snake_case or camelCase. `--no-` sets a boolean to false. An unknown flag is `unknown-flag`, exit 2, with the nearest flags. +- Values are coerced by the JSON Schema type of the property: string, number, integer, boolean and enum. A list of scalars takes a repeated flag or a JSON array. Anything else takes JSON text or `@path`. `--input ` gives the whole input, and flags override its keys. +- `positionals` name the properties that the arguments fill, in order. When the last one is a list, it takes every argument left. +- Missing required input is asked for on a terminal (an enum as a list, a boolean as a confirm, `x-secret` as a password), and is `missing-input`, exit 2, anywhere else. The layer never reads stdin for a run that cannot prompt. +- The one null rule: `null` for an optional key reads as "not given" where the key's schema does not take null, at any depth. Then zod parses the input once. A failure is `invalid-input`, exit 2: it names the flag (or `--input`, or the argument) and the path in it, the nearest allowed key or enum value, and lists every issue in `error.details.issues`. It never quotes a value. +- `.meta({ 'x-secret': true })` marks a secret: it is never echoed in an error, a next step, `ctx.invocation` or the manifest. `.meta({ 'x-carry': true })` on a global flag makes every next step repeat it. + +## Output and exit codes + +- On a terminal, text with a `Next:` block; otherwise, or with `--json`, one envelope: `{ "ok": true, "data", "meta": { "command", "next", "warnings" } }` or `{ "ok": false, "error": { "code", "message", "cause", "hint", "retryable", "details" }, "meta": { "command", "next" } }`. `--fields a,b.c` keeps only those paths of `data`. +- Exit codes (`ExitCode`): 0 done, 1 failed, 2 usage, 3 approval required, 4 sign in first, 130 interrupted. A `CliError` keeps its own exit code, also across two copies of the package (`isCliError`). +- `--help` and `-h`, ` --schema` (`{ name, summary, effect, positionals, input, output }`), `--llms` and `--llms --json` come from the registry. +- A next step is `{ command, argv, placeholders?, why }`: `ctx.next(words, why)`, `ctx.nextFor(command, input, why)` and `ctx.followUp(flags, { why, drop, command })` build them. + +## Help topics and the reference + +- `topics` in `createCli` are the pages of help that belong to no one command: `{ name, summary, body, section? }`, with a Markdown `body` of paragraphs, lists and code, and no headings. The root help and `--llms` list them, and the manifest carries them whole. A topic name that is also a command or a group name is a definition error. +- Every CLI gets the read command `help`: `help` prints the root help, `help ` the help of a command or a group (the same page `--help` prints), and `help ` a topic. Any other words are `unknown-topic`, exit 2, with the nearest command, group or topic. A CLI cannot define a command named `help`. +- `renderReference(manifest)` turns a manifest into one Markdown reference in the shape of a manual page: the name and synopsis, the description and the notes, the global flags, every command with its usage, flags, examples and notes, every topic as a section of its own, then `EXIT STATUS`, `ENVIRONMENT` and `FILES`, each from the topic whose `section` names it, and `SEE ALSO`. A Markdown-to-roff converter makes a man page of it. + +## Tool commands + +`toolCommand(tool, options)` types one entry by its tool, and `toCliCommands(entries, { gate, failureNext, onUnrenderedCall })` builds every command of a CLI. + +- The tool's zod params are the command input. A friendlier input needs `mapInput`, and what it returns is parsed by the tool's params. +- The command's effect is the tool's one static `effect`. A read tool command runs the tool. A change tool command plans with the gate policy (`callChange`): a `blocked` decision stops with the gate's failure, and an `ask` decision is the plan. `apply` calls the tool with the params of that plan. +- A tool `failure` becomes a `CliError` with the same code, message, hint and `retryable`, and the tool's details plus the failure's `errorId` and `context` (`failureError`). `signed-out`, `step-up-required` and `app-signed-out` exit 4, `invalid-input` exits 2, any other code exits 1. +- A tool's text, summary, description and failure words go to the reader as the tool wrote them: they name no tool and no parameter, and the steps that follow travel as `calls` data. +- The calls a tool suggests become the first next steps, through the first command bound to the tool that can make them (`toInput`, or the same names). `toolCallStep(entries)` writes any call the same way, for a host such as an MCP server. + +## Exports + +- The layer: `createCli`, `renderReference`, `CliError`, `isCliError`, `ExitCode`, `COMMAND_ERROR_CODES`, `flagName`, `decideApproval`, and the types `Cli`, `CliConfig`, `CliIO`, `CliManifest`, `CommandManifest`, `HelpTopic`, `ReferenceSection`, `CommandDefinition`, `ReadCommand`, `ChangeCommand`, `ImmediateCommand`, `ServeCommand`, `PassthroughCommand`, `Planned`, `PlanData`, `Approval`, `CommandContext`, `CommandResult`, `CommandExample`, `CommandErrorCode`, `CliErrorInit`, `Effect`, `InputSchema`, `JSONSchema`, `JSONSchemaType`, `NextStep`, `NextWord`, `StepOptions`, `FollowUpOptions`. +- The tool binding: `toolCommand`, `toCliCommands`, `toCliCommand`, `toolCallStep`, `failureError`, and the types `ToolCommandEntry`, `ToolCommandOptions`, `ToolCommandDeps`, `ToolBinding`, `ToolCallStep`, `FailureNext`. diff --git a/agentic/command/__tests__/approval.test.ts b/agentic/command/__tests__/approval.test.ts new file mode 100644 index 0000000000..9fc31c678f --- /dev/null +++ b/agentic/command/__tests__/approval.test.ts @@ -0,0 +1,21 @@ +import { type Approval, decideApproval } from '../src'; + +type Row = [dryRun: boolean, yes: boolean, interactive: boolean, expected: Approval]; + +// Every combination of the flags and the terminal of a run, for a change the layer has a plan of. +const rows: Row[] = [ + [true, true, true, 'show-plan'], + [true, true, false, 'show-plan'], + [true, false, true, 'show-plan'], + [true, false, false, 'show-plan'], + [false, true, true, 'apply'], + [false, true, false, 'apply'], + [false, false, true, 'ask'], + [false, false, false, 'approval-required'] +]; + +describe('decideApproval', () => { + it.each(rows)('dry-run %s, yes %s, interactive %s: %s', (dryRun, yes, interactive, expected) => { + expect(decideApproval({ dryRun, yes, interactive })).toBe(expected); + }); +}); diff --git a/agentic/command/__tests__/command-process.test.ts b/agentic/command/__tests__/command-process.test.ts new file mode 100644 index 0000000000..9e3b7836b1 --- /dev/null +++ b/agentic/command/__tests__/command-process.test.ts @@ -0,0 +1,144 @@ +import { ChildProcessWithoutNullStreams, spawn } from 'child_process'; +import { join } from 'path'; + +const packageDir = join(__dirname, '..'); +const fixture = join(packageDir, 'test-utils/command-fixture.ts'); + +interface Exit { + code: number | null; + stdout: string; + stderr: string; + ms: number; +} + +interface FixtureOptions { + stdin: 'closed' | 'open'; + /** Stdin and stdout pass for a terminal, so the layer prompts. */ + tty?: boolean; + /** Called with all stderr text so far, for example to type an answer or send a signal. */ + onStderr?: (text: string, child: ChildProcessWithoutNullStreams) => void; +} + +/** Runs the fixture CLI with stdout piped; a child still running after 5 seconds is killed and fails the test. */ +function runFixture(args: string[], { stdin, tty, onStderr }: FixtureOptions): Promise { + return new Promise((resolve, reject) => { + const started = Date.now(); + const child = spawn(process.execPath, ['-r', 'ts-node/register/transpile-only', fixture, ...args], { + cwd: packageDir, + env: { ...process.env, TS_NODE_PROJECT: join(packageDir, 'tsconfig.json'), FIXTURE_TTY: tty ? '1' : '', CI: '' }, + stdio: ['pipe', 'pipe', 'pipe'] + }); + if (stdin === 'closed') child.stdin.end(); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { + stderr += chunk; + onStderr?.(stderr, child); + }); + const timer = setTimeout(() => { + child.kill('SIGKILL'); + reject(new Error(`The fixture did not exit within 5 seconds. stderr: ${stderr}`)); + }, 5000); + child.on('error', reject); + child.on('close', (code) => { + clearTimeout(timer); + child.stdin.destroy(); + resolve({ code, stdout, stderr, ms: Date.now() - started }); + }); + }); +} + +/** Types `keys` once, when stderr first shows `prompt`, then closes stdin unless `keepOpen` is set. */ +const answer = (prompt: string, keys: string, { keepOpen = false } = {}) => { + let typed = false; + return (stderr: string, child: ChildProcessWithoutNullStreams): void => { + if (typed || !stderr.includes(prompt)) return; + typed = true; + if (keepOpen) child.stdin.write(keys); + else child.stdin.end(keys); + }; +}; + +describe('the command layer in a child process', () => { + it.each(['closed', 'open'] as const)('exits 2 with a missing-input envelope when stdin is %s and not a TTY', async (stdin) => { + const exit = await runFixture(['greet'], { stdin }); + expect(exit.code).toBe(2); + expect(JSON.parse(exit.stdout)).toMatchObject({ ok: false, error: { code: 'missing-input', details: { missing: ['--name'] } } }); + expect(exit.ms).toBeLessThan(5000); + }); + + it.each(['closed', 'open'] as const)('exits 3 with the plan, and waits for nothing, when a change has no --yes and stdin is %s', async (stdin) => { + const exit = await runFixture(['approve'], { stdin }); + expect(exit.code).toBe(3); + expect(JSON.parse(exit.stdout)).toMatchObject({ ok: false, error: { code: 'approval-required', details: { plan: { title: 'Change it?' } } } }); + expect(exit.stderr).not.toContain('applied'); + }); + + it('exits 0 with a JSON envelope when all input is given', async () => { + const exit = await runFixture(['greet', 'ann'], { stdin: 'closed' }); + expect(exit.code).toBe(0); + expect(JSON.parse(exit.stdout)).toEqual({ ok: true, data: { greeting: 'Hello, ann' }, meta: { command: 'greet' } }); + }); + + it('aborts the signal and exits 130 on SIGINT', async () => { + const exit = await runFixture(['wait'], { + stdin: 'closed', + onStderr: (stderr, child) => { + if (stderr.includes('ready')) child.kill('SIGINT'); + } + }); + expect(exit.code).toBe(130); + expect(JSON.parse(exit.stdout)).toMatchObject({ ok: false, error: { code: 'interrupted' } }); + }); + + it('waits for the command to settle after SIGINT before it reports the interrupt', async () => { + const exit = await runFixture(['linger', '--format', 'text'], { + stdin: 'closed', + onStderr: (stderr, child) => { + if (stderr === 'ready\n') child.kill('SIGINT'); + } + }); + expect(exit.code).toBe(130); + expect(exit.stderr).toMatch(/^ready\nsettled\nError \(interrupted\)/); + }); + + it.each([ + ['approve', 'Apply this change?'], + ['secret', 'Password'] + ])('cancels "%s" with exit 130 when Ctrl-C is pressed at the prompt', async (command, prompt) => { + const exit = await runFixture([command], { stdin: 'open', tty: true, onStderr: answer(prompt, '\u0003') }); + expect(exit.code).toBe(130); + expect(exit.stdout).toBe(''); + const errors = exit.stderr.split('\n').filter((line) => line.startsWith('Error')); + expect(errors).toEqual(['Error (cancelled): The command was cancelled at a prompt (Ctrl-C). Nothing was changed by this step.']); + expect(exit.stderr).not.toContain('applied'); + }); + + it.each([ + ['approve', 'Ctrl-D', 'Apply this change?', '\u0004'], + ['approve', 'a closed stdin', 'Apply this change?', ''], + ['secret', 'Ctrl-D', 'Password', '\u0004'] + ])('cancels "%s" with exit 1 when %s ends the input at the prompt', async (command, _end, prompt, keys) => { + const exit = await runFixture([command], { stdin: 'open', tty: true, onStderr: answer(prompt, keys, { keepOpen: keys !== '' }) }); + expect(exit.code).toBe(1); + expect(exit.stdout).toBe(''); + const errors = exit.stderr.split('\n').filter((line) => line.startsWith('Error')); + expect(errors).toEqual(['Error (cancelled): The input ended before the prompt got an answer. Nothing was changed by this step.']); + expect(exit.stderr).not.toContain('applied'); + }); + + it('reports a declined approval as cancelled with exit 1, and applies nothing', async () => { + const exit = await runFixture(['approve'], { stdin: 'open', tty: true, onStderr: answer('Apply this change?', 'n\n') }); + expect(exit.code).toBe(1); + expect(exit.stderr).toContain('Error (cancelled): The change was not approved, so nothing was changed.'); + expect(exit.stderr).not.toContain('applied'); + }); + + it('applies the change once the person approves it at the prompt', async () => { + const exit = await runFixture(['approve'], { stdin: 'open', tty: true, onStderr: answer('Apply this change?', 'y\n') }); + expect(exit.code).toBe(0); + expect(exit.stderr).toContain('Change the fixture.'); + expect(exit.stderr).toContain('applied'); + }); +}); diff --git a/agentic/command/__tests__/command.test.ts b/agentic/command/__tests__/command.test.ts new file mode 100644 index 0000000000..d650ac3087 --- /dev/null +++ b/agentic/command/__tests__/command.test.ts @@ -0,0 +1,1625 @@ +import type { ConfirmPrompt } from '@agentic-kit/harness'; +import { execFileSync } from 'child_process'; +import { mkdtempSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join, resolve } from 'path'; +import { PassThrough, Writable } from 'stream'; +import { z } from 'zod'; + +import { + type ChangeCommand, + CliError, + COMMAND_ERROR_CODES, + type CommandContext, + type CommandDefinition, + createCli, + ExitCode, + type HelpTopic, + renderReference +} from '../src'; + +interface Captured { + stream: Writable; + text: () => string; +} + +function capture(onWrite?: (text: string) => void): Captured { + let text = ''; + const stream = new Writable({ + write(chunk, _encoding, callback) { + text += chunk.toString(); + onWrite?.(text); + callback(); + } + }); + return { stream, text: () => text }; +} + +interface RunOptions { + /** stdin and stdout are terminals. */ + tty?: boolean; + /** Text piped into stdin; without it stdin stays open and silent. */ + stdin?: string; + env?: NodeJS.ProcessEnv; + /** In order: when stderr contains the first string, type the second into stdin. */ + answers?: Array<[string, string]>; +} + +const dir = mkdtempSync(join(tmpdir(), 'agentic-command-')); +writeFileSync(join(dir, 'columns.json'), JSON.stringify([{ name: 'id' }])); +writeFileSync(join(dir, 'input.json'), JSON.stringify({ table_name: 'from-file', rowCount: 4 })); + +async function exec(cli: ReturnType, argv: string[], options: RunOptions = {}) { + const stdin = new PassThrough(); + const stdout = capture(); + const answers = [...(options.answers ?? [])]; + const stderr = capture((text) => { + if (answers.length && text.includes(answers[0][0])) { + const [, keys] = answers.shift(); + setImmediate(() => stdin.write(keys)); + } + }); + if (options.tty) { + Object.assign(stdin, { isTTY: true }); + Object.assign(stdout.stream, { isTTY: true }); + } + if (options.stdin !== undefined) stdin.end(options.stdin); + const code = await cli.run(argv, { stdin, stdout: stdout.stream, stderr: stderr.stream, env: options.env ?? {}, cwd: dir }); + return { code, stdout: stdout.text(), stderr: stderr.text(), json: () => JSON.parse(stdout.text()) }; +} + +const seen: Array<{ input: Record; ctx: CommandContext }> = []; +const record = (input: Record, ctx: CommandContext) => { + seen.push({ input, ctx }); + return { data: input }; +}; +const lastInput = () => seen[seen.length - 1].input; + +const planOf = (what: string): ConfirmPrompt => ({ title: `Change ${what}?`, message: `Change ${what}.`, target: { kind: 'workspace', cwd: dir } }); + +const tableAdd: CommandDefinition = { + name: 'table add', + summary: 'Add a table', + effect: 'read', + positionals: ['table_name'], + input: z.object({ + table_name: z.string().describe('Name of the table'), + rowCount: z.number().int().default(0).describe('Rows to seed'), + ratio: z.number().optional(), + kind: z.enum(['plain', 'audit']).optional().describe('Kind of table'), + force: z.boolean().optional().describe('Replace an existing table'), + tags: z.array(z.string()).optional(), + columns: z.array(z.strictObject({ name: z.string() })).optional(), + meta: z.record(z.string(), z.unknown()).optional(), + password: z.string().default('default-secret').meta({ 'x-secret': true, description: 'Database password' }) + }), + examples: [{ command: 'demo table add users --password s3cret-example', description: 'Add users' }], + notes: ['Run demo table list afterwards.'], + run: record +}; + +const applied: string[] = []; +const bumped: string[] = []; + +/** + * A change: its plan names the target, and apply records that it ran. A target named "blocked" cannot be planned, and + * one named "keyed" needs --from-stdin to be applied where no terminal can ask. + */ +const deploy: ChangeCommand }>, unknown, { plan: ConfirmPrompt; target: string; needs?: string[] }> = { + name: 'deploy', + summary: 'Deploy a target', + effect: 'destructive', + positionals: ['target'], + input: z.object({ target: z.string().describe('What to deploy'), from_stdin: z.boolean().optional().describe('Read the key from stdin') }), + plan: ({ target, from_stdin }, ctx) => { + seen.push({ input: { target }, ctx }); + if (target === 'blocked') throw new CliError({ code: 'no-env', message: 'There is nothing to deploy here.', hint: 'Bind the directory first.' }); + return { plan: planOf(target), target, ...(target === 'keyed' && !from_stdin ? { needs: ['--from-stdin'] } : {}) }; + }, + apply: (_input, { target }) => { + applied.push(target); + return { data: { deployed: target } }; + } +}; + +const cli = createCli({ + name: 'demo', + version: '1.2.3', + description: 'Demo CLI.', + globals: z.object({ + context: z.string().default('local').meta({ description: 'Backend to use', 'x-carry': true }), + as: z.string().optional().meta({ description: 'Act as this agent', 'x-carry': true }) + }), + notes: ['Pass --json for machine output.'], + commands: [ + tableAdd, + { + name: 'table list', + summary: 'List tables', + effect: 'read', + run: () => ({ + data: [ + { name: 'users', owner: { id: 1, name: 'ann' }, rows: 3 }, + { name: 'posts', owner: { id: 2, name: 'bob' }, rows: 5 } + ] + }) + }, + { + name: 'status', + summary: 'Show status', + effect: 'read', + run: (_input: Record, ctx: CommandContext) => ({ + data: { ready: true, owner: { id: 1, name: 'ann' } }, + text: 'All good', + next: [ctx.next(['table', 'list'], 'See the tables')], + warnings: ['Low disk'] + }) + }, + { + name: 'setup', + summary: 'Set up', + effect: 'read', + input: z.object({ + kind: z.enum(['plain', 'audit']).describe('Pick a kind'), + confirmed: z.boolean().describe('Continue?') + }), + run: record + }, + { + name: 'login', + summary: 'Sign in', + effect: 'read', + input: z.object({ + email: z.string().describe('Email'), + password: z.string().meta({ 'x-secret': true, description: 'Password' }), + pin: z.number().int().optional().meta({ 'x-secret': true }) + }), + run: (input, ctx) => { + throw new CliError({ + code: 'signed-out', + message: `Sign-in failed for ${input.email} with ${input.password}.`, + next: [ctx.next(['login', '--email', String(input.email), '--password', String(input.password)], 'Sign in again')], + details: { tried: input.password } + }); + } + }, + deploy, + { + name: 'bump', + summary: 'Bump a counter at once', + effect: 'write', + immediate: true, + input: z.object({ by: z.number().int().default(1).describe('How much') }), + run: ({ by }) => { + bumped.push(String(by)); + return { data: { bumped: by } }; + } + }, + { name: 'boom', summary: 'Fail', effect: 'read', hidden: true, run: () => { throw new Error('kaput'); } }, + { + name: 'deny', + summary: 'Fail with a CliError', + effect: 'read', + hidden: true, + run: () => { + throw new CliError({ code: 'signed-out', message: 'You are signed out.', hint: 'Run demo login.', retryable: false, exitCode: ExitCode.signInRequired }); + } + }, + { name: 'server', summary: 'Run the server', effect: 'write', passthrough: async (argv, ctx) => record(argv, ctx) }, + { + name: 'quiet', + summary: 'A passthrough that prints its own output', + effect: 'read', + hidden: true, + passthrough: async (input) => (input.undefined ? undefined : { data: undefined }) + }, + { + name: 'vault', + summary: 'Store secrets', + effect: 'write', + hidden: true, + positionals: ['label'], + input: z.object({ + label: z.string(), + pin: z.number().int().optional().meta({ 'x-secret': true }), + tokens: z.array(z.string()).optional().meta({ 'x-secret': true }), + keys: z.array(z.string().meta({ 'x-secret': true })).optional(), + creds: z.strictObject({ secret: z.string().optional().meta({ 'x-secret': true }), user: z.string().optional() }).optional(), + fail: z.boolean().optional() + }), + plan: (input: Record, ctx: CommandContext) => { + record(input, ctx); + return { plan: planOf('the vault') }; + }, + apply: (input: Record, _planned, ctx: CommandContext) => { + if (input.fail) throw new Error(`vault failed: ${JSON.stringify(input)}`); + return { data: { stored: true }, next: [ctx.next(['vault', String(input.label), '--creds', JSON.stringify(input.creds ?? {})], 'Store it again')] }; + } + }, + { + name: 'ask', + summary: 'Prompt through ctx.prompter', + effect: 'read', + hidden: true, + run: async (_input: Record, ctx: CommandContext) => ({ + data: await ctx.prompter.prompt({}, [{ name: 'who', type: 'text', message: 'Who', required: true }]) + }) + }, + { + name: 'reader', + summary: 'Read a line from stdin and a variable from the environment', + effect: 'read', + hidden: true, + run: async (_input: Record, ctx: CommandContext) => { + let text = ''; + for await (const chunk of ctx.stdin) text += chunk; + return { data: { line: text.split('\n')[0], token: ctx.env.READER_TOKEN } }; + } + }, + { + name: 'pair', + summary: 'Two positionals', + effect: 'read', + hidden: true, + positionals: ['a', 'b'], + input: z.object({ a: z.string().optional(), b: z.string().optional() }), + run: record + }, + { + name: 'field', + summary: 'Optional properties that hosts send as null', + effect: 'read', + hidden: true, + positionals: ['name'], + input: z.object({ + name: z.string(), + is_required: z.boolean().optional(), + label: z.string().default('Untitled'), + default_value: z.union([z.string(), z.null()]).optional(), + note: z.string().nullable().optional(), + rules: z.array(z.strictObject({ kind: z.string(), limit: z.number().int().optional() })).optional() + }), + run: record + }, + { + name: 'policy', + summary: 'JSON input with closed objects', + effect: 'read', + hidden: true, + input: z.object({ + policies: z.array(z.strictObject({ + policy_type: z.enum(['AuthzEntityMembership', 'AuthzDirectOwner']), + permissive: z.boolean().optional(), + data: z.strictObject({ entity_field: z.string().optional(), membership_type: z.number().int().optional() }).optional() + })).optional(), + mode: z.enum(['alpha', 'beta']).optional().meta({ 'x-secret': true }), + vault: z.strictObject({ tier: z.enum(['gold', 'silver']).optional() }).optional().meta({ 'x-secret': true }) + }), + run: record + }, + { + name: 'serve', + summary: 'Speak a protocol on stdout', + effect: 'write', + hidden: true, + stdout: 'reserved', + serve: async (_input: Record, ctx: CommandContext) => { + if (ctx.globals.context === 'nope') throw new CliError({ code: 'context-unknown', message: 'No context is named nope.', exitCode: ExitCode.usage }); + ctx.stdout.write('PROTOCOL\n'); + return { data: { closed: true }, next: [ctx.next(['status'], 'Check')], warnings: ['closed'] }; + } + }, + { + name: 'shape', + summary: 'Every flag kind', + effect: 'read', + hidden: true, + positionals: ['name', 'level', 'paths'], + input: z.object({ + name: z.string().optional(), + level: z.number().int().optional(), + paths: z.array(z.string()).optional(), + count: z.number().int().optional(), + ratio: z.number().optional(), + force: z.boolean().optional(), + quiet: z.boolean().default(true), + kind: z.enum(['plain', 'audit']).optional(), + size: z.literal([1, 2, 3]).optional(), + tags: z.array(z.string()).optional(), + ports: z.array(z.number().int()).optional(), + meta: z.record(z.string(), z.unknown()).optional(), + columns: z.array(z.record(z.string(), z.unknown())).optional(), + anything: z.unknown().optional(), + nullable: z.string().nullable().optional(), + password: z.string().optional().meta({ 'x-secret': true }), + creds: z.object({ secret: z.string().optional().meta({ 'x-secret': true }), user: z.string().optional() }).optional() + }), + run: record + }, + { + name: 'proto', + summary: 'Keys that are also Object.prototype names', + effect: 'read', + hidden: true, + input: z.object({ + constructor: z.string(), + creds: z.strictObject({ toString: z.string(), user: z.string().optional() }).optional() + }), + run: record + } + ] +}); + +beforeEach(() => { + applied.length = 0; + bumped.length = 0; +}); + +describe('command resolution', () => { + it.each([ + [['table', 'add', 'users'], 0, 'table add'], + [['--json', 'table', 'add', 'users'], 0, 'table add'], + [['--yes', 'table', 'add', 'users'], 0, 'table add'], + [['table', 'list', '--format', 'json'], 0, 'table list'] + ])('%j runs the longest matching command', async (argv, code, command) => { + const result = await exec(cli, argv); + expect(result.code).toBe(code); + expect(result.json().meta.command).toBe(command); + }); + + it.each([ + [['tabel', 'add', 'x'], 'demo --help', ['table add']], + [['table', 'bogus'], 'demo table --help', []], + [['stauts'], 'demo --help', ['status']] + ])('%j is unknown-command, exit 2, with the closest names', async (argv, help, suggestions) => { + const result = await exec(cli, argv); + expect(result.code).toBe(ExitCode.usage); + const { error, meta } = result.json(); + expect(error.code).toBe('unknown-command'); + expect(error.details.suggestions).toEqual(suggestions); + expect(meta.next).toEqual([{ command: help, argv: help.split(' '), why: 'List the commands' }]); + }); + + it('prints the help of a group named alone', async () => { + const result = await exec(cli, ['table']); + expect(result.code).toBe(0); + expect(result.stdout).toContain('demo table [flags]'); + expect(result.stdout).toContain('table add'); + expect(result.stdout).toContain('table list'); + expect(result.stdout).not.toContain('status'); + }); +}); + +describe('flags and values', () => { + it.each([ + [['--row-count', '5']], + [['--row_count', '5']], + [['--rowCount', '5']], + [['--row-count=5']] + ])('%j sets the property rowCount', async (flag) => { + const result = await exec(cli, ['table', 'add', 't', ...flag]); + expect(result.code).toBe(0); + expect(lastInput().rowCount).toBe(5); + }); + + it.each(['--table-name', '--table_name', '--tableName'])('%s sets the property table_name', async (flag) => { + const result = await exec(cli, ['table', 'add', flag, 'orders']); + expect(result.code).toBe(0); + expect(lastInput().table_name).toBe('orders'); + }); + + it.each([ + [['--ratio', '0.5'], { ratio: 0.5 }], + [['--ratio', '-2'], { ratio: -2 }], + [['--kind', 'audit'], { kind: 'audit' }], + [['--force'], { force: true }], + [['--no-force'], { force: false }], + [['--force=false'], { force: false }], + [['--force', 'false'], { force: false }], + [['--tags', 'a', '--tags', 'b'], { tags: ['a', 'b'] }], + [['--tags', '["a","b"]'], { tags: ['a', 'b'] }], + [['--columns', '[{"name":"id"}]'], { columns: [{ name: 'id' }] }], + [['--columns', '@columns.json'], { columns: [{ name: 'id' }] }], + [['--meta', '{"a":[1]}'], { meta: { a: [1] } }], + [[], { rowCount: 0, password: 'default-secret' }] + ])('%j is coerced by the schema', async (flags, expected) => { + const result = await exec(cli, ['table', 'add', 't', ...flags]); + expect(result.code).toBe(0); + expect(lastInput()).toMatchObject({ table_name: 't', ...expected }); + }); + + it('does not let a boolean flag swallow the positional after it', async () => { + const result = await exec(cli, ['table', 'add', '--force', 'users']); + expect(result.code).toBe(0); + expect(lastInput()).toMatchObject({ table_name: 'users', force: true }); + }); + + it.each([ + [['--row-count', '1.5'], '--row-count', 'integer'], + [['--row-count', 'abc'], '--row-count', 'integer'], + [['--ratio'], '--ratio', 'needs a value'], + [['--kind', 'bogus'], '--kind', 'plain, audit'], + [['--force=maybe'], '--force', 'true or false'], + [['--columns', '[{}]'], '--columns', 'required key "name"'], + [['--columns', '@missing.json'], '--columns', 'could not read'], + [['--meta', 'not-json'], '--meta', 'not valid JSON'], + [['--row-count', '1', '--row-count', '2'], '--row-count', 'given 2 times'], + [['--row-count', '0x10'], '--row-count', 'decimal'], + [['--row-count', '9007199254740993'], '--row-count', 'safe integer'], + [['--ratio', '0x10'], '--ratio', 'decimal'], + [['--ratio', '9007199254740993'], '--ratio', 'safe integer'], + [['--table-name', 'u'], '--table-name', 'given twice'] + ])('%j is invalid-input, exit 2, naming the flag', async (flags, flag, text) => { + const result = await exec(cli, ['table', 'add', 't', ...flags]); + expect(result.code).toBe(ExitCode.usage); + const { error } = result.json(); + expect(error.code).toBe('invalid-input'); + expect(error.details.flag).toBe(flag); + expect(error.message).toContain(text); + }); + + it.each([ + [['table', 'add', 't', '--tabel-name', 'x'], ['--table-name']], + [['table', 'add', 't', '--rowcount', '1'], ['--row-count']], + [['table', 'add', 't', '--bogus'], []], + [['table', 'add', 't', '-x'], []], + [['table', 'add', 't', '--no-kind'], []], + [['--bogus'], []] + ])('%j is unknown-flag, exit 2, with the closest flags', async (argv, suggestions) => { + const result = await exec(cli, argv); + expect(result.code).toBe(ExitCode.usage); + const { error } = result.json(); + expect(error.code).toBe('unknown-flag'); + expect(error.details.suggestions).toEqual(suggestions); + }); + + it('gives an extra positional unexpected-argument, exit 2', async () => { + const result = await exec(cli, ['table', 'add', 't', 'extra']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error.code).toBe('unexpected-argument'); + }); + + it('gives every argument left to a last positional that is a list', async () => { + const result = await exec(cli, ['shape', 'users', '3', 'a', 'b', 'c']); + expect(result.code).toBe(0); + expect(lastInput()).toMatchObject({ name: 'users', level: 3, paths: ['a', 'b', 'c'] }); + }); +}); + +describe('--input', () => { + it.each([ + [['--input', '{"table_name":"t","rowCount":2}'], undefined, { table_name: 't', rowCount: 2 }], + [['--input', '{"tableName":"t"}'], undefined, { table_name: 't' }], + [['--input', '@input.json'], undefined, { table_name: 'from-file', rowCount: 4 }], + [['--input', '-'], '{"table_name":"piped","kind":"audit"}', { table_name: 'piped', kind: 'audit' }], + [['--input', '{"table_name":"t","rowCount":2}', '--row-count', '9'], undefined, { table_name: 't', rowCount: 9 }], + [['override', '--input', '{"table_name":"t"}'], undefined, { table_name: 'override' }] + ])('%j supplies the whole input, and flags override it', async (flags, stdin, expected) => { + const result = await exec(cli, ['table', 'add', ...flags], { stdin }); + expect(result.code).toBe(0); + expect(lastInput()).toMatchObject(expected); + }); + + it.each([ + [['--input', '{"tabel_name":"t"}'], 'unknown key "tabel_name"'], + [['--input', '[1]'], 'must be a JSON object'], + [['--input', '{"table_name":"t","rowCount":"2"}'], 'at rowCount, expected number'], + [['--input', '{"table_name":"t","rowCount":9007199254740993}'], 'at rowCount, '], + [['--input', '{"table_name":'], 'not valid JSON'] + ])('%j is invalid-input', async (flags, text) => { + const result = await exec(cli, ['table', 'add', ...flags]); + expect(result.code).toBe(ExitCode.usage); + const { error } = result.json(); + expect(error.code).toBe('invalid-input'); + expect(error.message).toContain(text); + }); +}); + +describe('missing input', () => { + it.each([ + [{ tty: false }, [], 'stdin is not a terminal'], + [{ tty: true, env: { CI: '1' } }, [], 'CI'], + [{ tty: true }, ['--no-input'], '--no-input'], + [{ tty: true }, ['--tty', 'false'], '--tty false'], + [{ tty: true }, ['--no-tty'], '--tty false'] + ])('%j %j gives missing-input, exit 2, without waiting on stdin', async (options, flags, reason) => { + const result = await exec(cli, ['login', '--json', ...flags], options); + expect(result.code).toBe(ExitCode.usage); + const { error, meta } = result.json(); + expect(error.code).toBe('missing-input'); + expect(error.details.missing).toEqual(['--email', '--password']); + expect(error.cause).toContain(reason); + expect(meta.next).toEqual([{ command: 'demo login --schema', argv: ['demo', 'login', '--schema'], why: 'See every input property' }]); + }); + + it('prompts with a text prompt when interactive', async () => { + const result = await exec(cli, ['table', 'add', '--json'], { tty: true, answers: [['Name of the table', 'users\n']] }); + expect(result.code).toBe(0); + expect(lastInput().table_name).toBe('users'); + }); + + it('prompts with a list for an enum and a confirm for a boolean', async () => { + const result = await exec(cli, ['setup', '--json'], { + tty: true, + answers: [['audit', '\u001b[B'], ['> audit', '\r'], ['Continue?', 'y\n']] + }); + expect(result.code).toBe(0); + expect(lastInput()).toEqual({ kind: 'audit', confirmed: true }); + }); +}); + +describe('output', () => { + it('prints one success envelope and nothing on stderr in JSON mode', async () => { + const result = await exec(cli, ['status', '--json']); + expect(result.code).toBe(0); + expect(result.json()).toEqual({ + ok: true, + data: { ready: true, owner: { id: 1, name: 'ann' } }, + meta: { command: 'status', next: [{ command: 'demo table list', argv: ['demo', 'table', 'list'], why: 'See the tables' }], warnings: ['Low disk'] } + }); + expect(result.stderr).toBe(''); + }); + + it('prints the text, a Next block on stdout and warnings on stderr in text mode', async () => { + const result = await exec(cli, ['status'], { tty: true }); + expect(result.stdout).toBe('All good\nNext:\n demo table list # See the tables\n'); + expect(result.stderr).toBe('Warning: Low disk\n'); + }); + + it('renders data with the default renderer when the command gives no text', async () => { + const result = await exec(cli, ['table', 'list'], { tty: true }); + expect(result.stdout.trimEnd().split('\n').map((line) => line.split(/ {2,}/))).toEqual([ + ['name', 'owner', 'rows'], + ['users', '{"id":1,"name":"ann"}', '3'], + ['posts', '{"id":2,"name":"bob"}', '5'] + ]); + }); + + it.each([ + [['table', 'list', '--fields', 'name,owner.name'], [{ name: 'users', owner: { name: 'ann' } }, { name: 'posts', owner: { name: 'bob' } }]], + [['status', '--fields', 'owner.id,ready'], { owner: { id: 1 }, ready: true }] + ])('%j keeps only the given paths of data', async (argv, data) => { + const result = await exec(cli, [...argv, '--json']); + expect(result.json().data).toEqual(data); + }); + + it.each([ + [['status', '--fields', 'missing'], ['missing']], + [['table', 'list', '--fields', 'name,nope'], ['nope']], + [['status', '--fields', 'owner.nope,ready'], ['owner.nope']], + [['status', '--fields', 'constructor'], ['constructor']] + ])('%j is invalid-input when a path of a read matches nothing', async (argv, unmatched) => { + const result = await exec(cli, [...argv, '--json']); + expect(result.code).toBe(ExitCode.usage); + const { error } = result.json(); + expect(error.code).toBe('invalid-input'); + expect(error.details.unmatched).toEqual(unmatched); + }); + + it('warns, and keeps the exit code, when a path matches nothing after a change', async () => { + const result = await exec(cli, ['vault', 'l', '--fields', 'stored,nope', '--yes', '--json']); + expect(result.code).toBe(0); + const { ok, data, meta } = result.json(); + expect({ ok, data }).toEqual({ ok: true, data: { stored: true } }); + expect(meta.warnings).toEqual([expect.stringContaining('--fields "nope" matched nothing in the data of "vault"')]); + }); + + it.each([ + [['deny'], ExitCode.signInRequired, { code: 'signed-out', message: 'You are signed out.', hint: 'Run demo login.', retryable: false }], + [['boom'], ExitCode.failure, { code: 'failed', message: 'kaput', hint: 'Rerun with DEBUG=1 to see the stack trace.' }] + ])('%j prints one error envelope with exit %i', async (argv, code, error) => { + const result = await exec(cli, [...argv, '--json']); + expect(result.code).toBe(code); + expect(result.json()).toEqual({ ok: false, error, meta: { command: argv[0] } }); + expect(result.stderr).toBe(''); + }); + + it('includes the stack of an unexpected error only with DEBUG', async () => { + const result = await exec(cli, ['boom', '--json'], { env: { DEBUG: '1' } }); + expect(result.json().error.details.stack).toContain('kaput'); + }); + + it('prints an error on stderr in text mode', async () => { + const result = await exec(cli, ['deny'], { tty: true }); + expect(result.stdout).toBe(''); + expect(result.stderr).toBe('Error (signed-out): You are signed out.\nHint: Run demo login.\n'); + }); + + it('passes the context flags to the command', async () => { + await exec(cli, ['table', 'add', 't', '--dry-run', '--yes', '--cwd', 'sub', '--context', 'prod', '--json']); + const { ctx } = seen[seen.length - 1]; + expect(ctx).toMatchObject({ cliName: 'demo', yes: true, cwd: resolve(dir, 'sub'), format: 'json', interactive: false, globals: { context: 'prod' } }); + }); +}); + +describe('secrets', () => { + it.each([ + [['--email', 'a@b.c', '--password', 'hunter2-flag']], + [['--input', '{"email":"a@b.c","password":"hunter2-json"}']] + ])('%j never echoes an x-secret value in an error or a next command', async (flags) => { + const result = await exec(cli, ['login', ...flags, '--json']); + expect(result.stdout).not.toContain('hunter2'); + const { error, meta } = result.json(); + expect(error.message).toBe('Sign-in failed for a@b.c with ***.'); + expect(meta.next).toEqual([{ + command: 'demo login --email a@b.c --password ***', + argv: ['demo', 'login', '--email', 'a@b.c', '--password', '***'], + why: 'Sign in again' + }]); + expect(error.details).toEqual({ tried: '***' }); + }); + + it('does not quote a secret value that fails coercion', async () => { + const result = await exec(cli, ['login', '--email', 'a', '--password', 'p', '--pin', 'hunter2-pin', '--json']); + expect(result.json().error.code).toBe('invalid-input'); + expect(result.stdout).not.toContain('hunter2'); + }); +}); + +describe('help, --schema and --llms', () => { + it.each([[['--help']], [['-h']], [[]]])('%j prints the root help with the agent block', async (argv) => { + const result = await exec(cli, argv); + expect(result.code).toBe(0); + expect(result.stdout).toContain('Usage:\n demo [flags]'); + expect(result.stdout).toContain('Agents:\n - Pass --json for machine output.'); + expect(result.stdout).toContain('--context '); + expect(result.stdout).toContain('--no-input'); + expect(result.stdout).not.toContain('boom'); + }); + + it('prints the command help with usage, flags, examples and notes', async () => { + const result = await exec(cli, ['table', 'add', '--help']); + expect(result.code).toBe(0); + const help = result.stdout; + expect(help).toContain('demo table add: Add a table\nEffect: read'); + expect(help).toContain('demo table add [flags]'); + expect(help).toMatch(/--table-name +Name of the table \(required, or argument 1\)/); + expect(help).toMatch(/--row-count +Rows to seed \(default: 0\)/); + expect(help).toMatch(/--kind +Kind of table/); + expect(help).toMatch(/--tags \.\.\. +\(repeatable\)/); + expect(help).toContain('demo table add users --password \n Add users'); + expect(help).toContain('Notes:\n - Run demo table list afterwards.'); + expect(help).not.toContain('default-secret'); + expect(help).not.toContain('s3cret-example'); + }); + + it('prints the command schema, made from zod, without secret defaults', async () => { + const result = await exec(cli, ['table', 'add', '--schema']); + const schema = result.json(); + expect(Object.keys(schema)).toEqual(['name', 'summary', 'effect', 'positionals', 'input']); + expect(schema).toMatchObject({ name: 'table add', effect: 'read', positionals: ['table_name'] }); + expect(schema.input.properties.rowCount.default).toBe(0); + expect(schema.input.properties.password).toEqual({ type: 'string', 'x-secret': true, description: 'Database password' }); + const expected = z.toJSONSchema(tableAdd.input, { io: 'input' }) as Record; + delete expected.$schema; + expect({ ...schema.input, properties: { ...schema.input.properties, password: undefined } }).toEqual({ + ...expected, + properties: { ...(expected.properties as object), password: undefined } + }); + }); + + it('prints a Markdown index with --llms', async () => { + const result = await exec(cli, ['--llms']); + expect(result.stdout).toContain('# demo\n'); + expect(result.stdout).toContain('- `demo table add ` (read): Add a table\n'); + expect(result.stdout).toContain('- `demo deploy ` (destructive): Deploy a target\n'); + expect(result.stdout).toContain('## Notes\n\n- Pass --json for machine output.\n'); + expect(result.stdout).not.toContain('boom'); + }); + + it('prints the full manifest with --llms --json', async () => { + const manifest = (await exec(cli, ['--llms', '--json'])).json(); + expect(manifest).toEqual(JSON.parse(JSON.stringify(cli.manifest()))); + expect(manifest.commands.map((command: { name: string }) => command.name)).toEqual(['table add', 'table list', 'status', 'setup', 'login', 'deploy', 'bump', 'server', 'help']); + const add = manifest.commands[0]; + expect(Object.keys(add)).toEqual(['name', 'summary', 'effect', 'positionals', 'input', 'examples', 'notes']); + expect(add.examples).toEqual([{ command: 'demo table add users --password ', description: 'Add users' }]); + expect(add.input.properties.password.default).toBeUndefined(); + expect(manifest.commands[6]).toMatchObject({ name: 'bump', effect: 'write', immediate: true }); + expect(manifest.commands[7]).toMatchObject({ name: 'server', effect: 'write', passthrough: true }); + expect(Object.keys(manifest.globals.properties)).toEqual(expect.arrayContaining(['context', 'json', 'input', 'no_input'])); + }); +}); + +describe('help topics and the help command', () => { + const topics: HelpTopic[] = [ + { name: 'output', summary: 'What a command prints', body: 'Without a terminal, a command prints one JSON envelope.\n\n- `--json` asks for it on a terminal too.' }, + { name: 'exit-codes', summary: 'What each exit code means', body: '- `0`: Done.\n- `2`: Bad input.', section: 'EXIT STATUS' }, + { name: 'environment', summary: 'The variables the CLI reads', body: '- `DEMO_HOME`: where it keeps its files.', section: 'ENVIRONMENT' }, + { name: 'files', summary: 'The files the CLI writes', body: '- `~/.demo/`: the store.', section: 'FILES' } + ]; + const guide = createCli({ + name: 'demo', + version: '1.2.3', + description: 'Demo CLI.', + notes: ['Pass --json for machine output.'], + topics, + commands: [tableAdd, { name: 'table list', summary: 'List tables', effect: 'read', run: () => ({ data: [] }) }, deploy] + }); + + it.each([ + [['help'], ['--help'], { kind: 'cli', name: 'demo' }], + [['help', 'table', 'add'], ['table', 'add', '--help'], { kind: 'command', name: 'table add' }], + [['help', 'table'], ['table', '--help'], { kind: 'group', name: 'table' }] + ])('%j prints the page that %j prints', async (argv, same, page) => { + const expected = (await exec(guide, same)).stdout; + const text = await exec(guide, argv, { tty: true }); + expect(text.code).toBe(0); + expect(text.stdout).toBe(expected); + expect((await exec(guide, argv)).json().data).toEqual({ ...page, text: expected }); + }); + + it('prints a topic: its summary, then its body', async () => { + const result = await exec(guide, ['help', 'output'], { tty: true }); + expect(result.code).toBe(0); + expect(result.stdout).toBe('What a command prints\n\nWithout a terminal, a command prints one JSON envelope.\n\n- `--json` asks for it on a terminal too.\n'); + expect((await exec(guide, ['help', 'output'])).json().data).toEqual({ kind: 'topic', name: 'output', text: result.stdout }); + }); + + it.each([ + [['help', 'outptu'], ['output']], + [['help', 'tabel', 'ad'], ['table add']], + [['help', 'tabel'], ['table']], + [['help', 'nothing', 'like', 'it'], []] + ])('%j is unknown-topic, exit 2, with the nearest command or topic', async (argv, suggestions) => { + const result = await exec(guide, argv); + expect(result.code).toBe(ExitCode.usage); + const { error, meta } = result.json(); + expect(error.code).toBe('unknown-topic'); + expect(error.details.suggestions).toEqual(suggestions); + expect(meta.next).toEqual([{ command: 'demo help', argv: ['demo', 'help'], why: 'List the commands and the help topics' }]); + }); + + it('lists the topics in the root help, in --llms and in the manifest, and help takes words', async () => { + const root = (await exec(guide, ['--help'])).stdout; + expect(root).toMatch(/Help topics:\n {2}output +What a command prints\n/); + expect(root).toContain('Run "demo help " to read one.'); + expect(root).toMatch(/\n {2}help +Show the help of the CLI, a command, a group or a help topic \(read\)\n/); + expect((await exec(guide, ['help', '--help'])).stdout).toContain('demo help [name...] [flags]'); + const llms = (await exec(guide, ['--llms'])).stdout; + expect(llms).toContain('## Help topics\n\n'); + expect(llms).toContain('- `demo help output`: What a command prints\n'); + expect(guide.manifest().topics).toEqual(topics); + }); + + it('renders the manifest as one Markdown reference, with every command and every topic', () => { + const reference = renderReference(guide.manifest()); + expect(reference.startsWith('# demo(1) -- Demo CLI.\n')).toBe(true); + expect(reference.match(/^## .+$/gm)).toEqual([ + '## SYNOPSIS', + '## DESCRIPTION', + '## GLOBAL FLAGS', + '## COMMANDS', + '## OUTPUT', + '## EXIT STATUS', + '## ENVIRONMENT', + '## FILES', + '## SEE ALSO' + ]); + expect(reference.match(/^### .+$/gm)).toEqual(['### table add', '### table list', '### deploy', '### help']); + for (const topic of topics) expect(reference).toContain(topic.body); + expect(reference).toContain('`demo table add [flags]`'); + expect(reference).toMatch(/- `--table-name `: Name of the table \(required, or argument 1\)\n/); + expect(reference).toContain('- `-y, --yes`: Approve the plan of a change without a prompt\n'); + expect(reference).toContain('demo table add users --password '); + expect(reference).toContain('- Pass --json for machine output.\n'); + expect(reference).not.toContain('default-secret'); + expect(reference).not.toContain('s3cret-example'); + }); + + it.each([ + [{ topics: [{ name: 'table', summary: 's', body: 'b' }] }, 'the name of a command or a group'], + [{ topics: [{ name: 'deploy', summary: 's', body: 'b' }] }, 'the name of a command or a group'], + [{ topics: [{ name: 'Exit Codes', summary: 's', body: 'b' }] }, 'invalid name'], + [{ topics: [{ name: 'a', summary: 's', body: 'b' }, { name: 'a', summary: 's', body: 'b' }] }, 'defined twice'], + [{ topics: [{ name: 'a', summary: 's', body: 'Intro.\n\n## Part' }] }, 'no headings'], + [{ commands: [{ name: 'help', summary: 'h', effect: 'read', run: () => ({ data: null }) } as CommandDefinition] }, 'built into the command layer'] + ])('refuses the definition %#', (overrides, text) => { + expect(() => createCli({ name: 'bad', version: '0.0.0', commands: [tableAdd, deploy], ...overrides })).toThrow(text); + }); +}); + +describe('ctx.invocation', () => { + it.each([ + [['table', 'add', 'users', '--row-count', '5', '--json'], 'demo table add users --row-count 5 --json'], + [['--json', 'table', 'add', 'users'], 'demo --json table add users'], + [['table', 'add', "it's here", '--meta', '{"a": 1}', '--tags', '', '--json'], `demo table add 'it'\\''s here' --meta '{"a": 1}' --tags '' --json`], + [['table', 'add', 't', '--password', 'hunter2', '--json'], "demo table add t --password '***' --json"], + [['table', 'add', 't', '--password=hunter2', '--json'], "demo table add t '--password=***' --json"], + [['table', 'add', '--input', '{"table_name":"t","password":"hunter2"}', '--json'], `demo table add --input '{"table_name":"t","password":"***"}' --json`], + [['table', 'add', '--input', '{ "table_name": "t" }', '--json'], `demo table add --input '{ "table_name": "t" }' --json`], + [['server', 'extra', '--port', '5555'], 'demo server extra --port 5555'] + ])('%j is %s', async (argv, invocation) => { + const result = await exec(cli, argv); + expect(result.code).toBe(0); + expect(seen[seen.length - 1].ctx.invocation).toBe(invocation); + }); +}); + +describe('passthrough commands', () => { + it('get every token after the command path, parsed by parseArgv', async () => { + const result = await exec(cli, ['server', 'extra', '--port', '5555', '--help', '-x', '--json']); + expect(result.code).toBe(0); + expect(lastInput()).toEqual({ _: ['extra'], port: 5555, help: true, x: true, json: true }); + expect(result.json().ok).toBe(true); + }); + + it.each([ + [['server', '--format', 'yaml'], { _: [], format: 'yaml' }], + [['server', '--cwd'], { _: [], cwd: true }], + [['server', '--context', 'a', '--context', 'b'], { _: [], context: ['a', 'b'] }], + [['server', '--dry-run'], { _: [], 'dry-run': true }] + ])('%j is not validated by the layer, and has no plan', async (argv, input) => { + const result = await exec(cli, argv); + expect(result.code).toBe(0); + expect(lastInput()).toEqual(input); + }); + + it.each([[['quiet', '--json']], [['quiet', '--undefined', '--json']]])('%j prints nothing when the command returns nothing', async (argv) => { + const result = await exec(cli, argv); + expect(result.code).toBe(0); + expect(result.stdout).toBe(''); + }); +}); + +describe('secrets come from the schema', () => { + it.each([ + [['vault', 'l', '--creds', '{"secret":"NESTED-SECRET-9","user":"u"}'], `demo vault l --creds '{"secret":"***","user":"u"}'`], + [['vault', 'l', '--keys', '["KEY-AAAA-1111","KEY-BBBB-2222"]'], `demo vault l --keys '["***","***"]'`], + [ + ['vault', '--input', '{"label":"l","tokens":["TOKEN-ONE-111"],"pin":4242,"creds":{"secret":"NESTED-SECRET-9"}}'], + `demo vault --input '{"label":"l","tokens":"***","pin":"***","creds":{"secret":"***"}}'` + ] + ])('%j replaces nested, numeric and list secrets in ctx.invocation', async (argv, invocation) => { + const result = await exec(cli, [...argv, '--yes', '--json']); + expect(result.code).toBe(0); + expect(seen[seen.length - 1].ctx.invocation).toBe(`${invocation} --yes --json`); + }); + + it('keeps nested and list secrets out of an error, a plan stop and a next command', async () => { + const failed = await exec(cli, ['vault', 'l', '--creds', '{"secret":"NESTED-SECRET-9"}', '--tokens', 'TOKEN-ONE-111', '--fail', '--yes', '--json']); + expect(failed.json().error.code).toBe('failed'); + expect(failed.stdout).not.toMatch(/NESTED-SECRET-9|TOKEN-ONE-111/); + const stopped = await exec(cli, ['vault', 'l', '--creds', '{"secret":"NESTED-SECRET-9"}', '--json']); + expect(stopped.code).toBe(ExitCode.approvalRequired); + expect(stopped.json().meta.next[0].argv).toEqual(['demo', 'vault', 'l', '--creds', '', '--json', '--yes']); + expect(stopped.stdout).not.toContain('NESTED-SECRET-9'); + const ok = await exec(cli, ['vault', 'l', '--creds', '{"secret":"NESTED-SECRET-9","user":"u"}', '--yes', '--json']); + expect(ok.json().meta.next).toEqual([{ + command: `demo vault l --creds '{"secret":"***","user":"u"}'`, + argv: ['demo', 'vault', 'l', '--creds', '{"secret":"***","user":"u"}'], + why: 'Store it again' + }]); + }); + + it('never uses a short secret as a search pattern, so other text stays intact', async () => { + const result = await exec(cli, ['login', '--email', 'a@b.c', '--password', 'e', '--json']); + expect(result.json().error.message).toBe('Sign-in failed for a@b.c with e.'); + expect(result.json().meta.next[0].argv).toEqual(['demo', 'login', '--email', 'a@b.c', '--password', 'e']); + }); + + const leaky = createCli({ + name: 'x', + version: '1', + commands: [{ + name: 'go', + summary: 'Go', + effect: 'read', + input: z.object({ password: z.string().optional().meta({ 'x-secret': true }) }), + run: ({ password }, ctx) => { + throw new CliError({ code: 'denied', message: `denied ${JSON.stringify({ password })}`, next: [ctx.next(['go', '--password', String(password)], 'Retry')] }); + } + }] + }); + + it.each(['p"a\\ss\nx-long-secret', "it's a long secret"])('redacts the raw, JSON-escaped and shell-quoted forms of %j', async (password) => { + const result = await exec(leaky, ['go', '--input', '-', '--json'], { stdin: JSON.stringify({ password }) }); + const { error, meta } = result.json(); + expect(error.message).toBe('denied {"password":"***"}'); + expect(meta.next).toEqual([{ command: 'x go --password ***', argv: ['x', 'go', '--password', '***'], why: 'Retry' }]); + }); + + it('takes a value that starts with -- after a secret flag and never echoes it', async () => { + const result = await exec(cli, ['login', '--email', 'a@b.c', '--password', '--hunter2-long', '--json']); + expect(result.json().error.code).toBe('signed-out'); + expect(result.stdout).not.toContain('hunter2'); + }); +}); + +describe('a CliError from a second copy of the package', () => { + it('keeps its code, exit code and next', async () => { + let Other: typeof CliError; + jest.isolateModules(() => { + Other = require('../src/types').CliError; + }); + expect(Other).not.toBe(CliError); + const copy = createCli({ + name: 'x', + version: '1', + commands: [{ + name: 'go', + summary: 'Go', + effect: 'read', + run: () => { + throw new Other({ + code: 'approval-required', + message: 'needs approval', + exitCode: ExitCode.approvalRequired, + next: [{ command: 'x go --yes', argv: ['x', 'go', '--yes'], why: 'Approve' }] + }); + } + }] + }); + const result = await exec(copy, ['go', '--json']); + expect(result.code).toBe(ExitCode.approvalRequired); + expect(result.json()).toEqual({ ok: false, error: { code: 'approval-required', message: 'needs approval' }, meta: { command: 'go', next: [{ command: 'x go --yes', argv: ['x', 'go', '--yes'], why: 'Approve' }] } }); + }); +}); + +describe('schemas without one plain type', () => { + const loose = () => createCli({ + name: 'x', + version: '1', + commands: [{ + name: 'loose', + summary: 'Loose', + effect: 'read', + input: z.object({ + default_value: z.union([z.string(), z.null()]).optional().describe('A default'), + level: z.union([z.null(), z.number().int()]).optional(), + mode: z.enum(['a', 'b']).nullable().optional(), + anything: z.unknown().optional(), + either: z.union([z.string(), z.number()]).optional() + }), + run: record + }] + }); + + it('do not stop the CLI at start-up', () => { + expect(loose).not.toThrow(); + }); + + it.each([ + [['--default-value', 'abc'], { default_value: 'abc' }], + [['--level', '3'], { level: 3 }], + [['--mode', 'b'], { mode: 'b' }], + [['--anything', '{"a":[1]}'], { anything: { a: [1] } }], + [['--anything', '@columns.json'], { anything: [{ name: 'id' }] }], + [['--either', '5'], { either: 5 }], + [['--either', '"five"'], { either: 'five' }] + ])('%j reads a nullable scalar as the scalar and any other schema as JSON', async (flags, expected) => { + const result = await exec(loose(), ['loose', ...flags, '--json']); + expect(result.code).toBe(0); + expect(lastInput()).toEqual(expected); + }); +}); + +describe('layer prompts', () => { + it.each([ + ['a text prompt', ['table', 'add', '--json'], { tty: true, answers: [['Name of the table', 'users\n']] }, 0], + ['a list and a confirm', ['setup', '--json'], { tty: true, answers: [['audit', '\u001b[B'], ['> audit', '\r'], ['Continue?', 'y\n']] }, 0], + ['the approval of a change', ['deploy', 'web', '--json'], { tty: true, answers: [['Apply this change?', 'y\n']] }, 0], + ['ctx.prompter without a terminal', ['ask', '--json'], {}, ExitCode.failure] + ] as Array<[string, string[], RunOptions, number]>)('never reset the terminal: %s', async (_name, argv, options, code) => { + const result = await exec(cli, argv, options); + expect(result.code).toBe(code); + expect(result.stderr).not.toContain('\x1bc'); + }); +}); + +describe('ctx.stdin and ctx.env', () => { + it('come from the io given to run()', async () => { + const result = await exec(cli, ['reader', '--json'], { stdin: 'from-stdin\nrest', env: { READER_TOKEN: 'from-env' } }); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ line: 'from-stdin', token: 'from-env' }); + }); +}); + +describe('ctx.next', () => { + const contextOf = async () => { + expect((await exec(cli, ['pair', 'one'])).code).toBe(0); + return seen[seen.length - 1].ctx; + }; + + it('gives the exact words as argv and the same line quoted for POSIX shells', async () => { + const ctx = await contextOf(); + const words = ['api', 'describe', 'Database', '--endpoint', 'https://api.example.com/graphql', 'a=b', 'x@y.z', '-1']; + expect(ctx.next(words, 'Describe it')).toEqual({ + command: 'demo api describe Database --endpoint https://api.example.com/graphql a=b x@y.z -1', + argv: ['demo', ...words], + why: 'Describe it' + }); + }); + + it.each([ + ['a b', "'a b'"], + ["it's", `'it'\\''s'`], + ['"q"', `'"q"'`], + ['a;b', "'a;b'"], + ['$HOME', "'$HOME'"], + ['`id`', "'`id`'"], + ['a\nb', "'a\nb'"], + ['', "''"], + ['a|b&c', "'a|b&c'"], + ['*', "'*'"], + ['~', "'~'"], + ['#c', "'#c'"], + ['a\\b', "'a\\b'"], + ['{a,b}', "'{a,b}'"], + ['é', "'é'"], + ['=name', "'=name'"], + ['', "''"] + ])('quotes %j as one shell word and keeps it as is in argv', async (word, quoted) => { + const ctx = await contextOf(); + const step = ctx.next(['api', 'describe', word], 'Describe it'); + expect(step.command).toBe(`demo api describe ${quoted}`); + expect(step.argv).toEqual(['demo', 'api', 'describe', word]); + expect(step.placeholders).toBeUndefined(); + }); + + it('gives back the same words when a POSIX shell reads the line', async () => { + const ctx = await contextOf(); + const words = ['Database', 'a b', "it's", '"q"', 'a;b', '$HOME', '`echo pwned`', '$(echo pwned)', 'a\nb', '', 'x|y', '*', '~', '#c', 'a\\b', '!', '{a,b}', 'é ✓', '-x', 'a=b', '=x']; + const { command } = ctx.next(words, 'Run it'); + const output = execFileSync('/bin/sh', ['-c', `printf '%s\\0' ${command.slice('demo '.length)}`]).toString('utf8'); + expect(output.split('\0').slice(0, -1)).toEqual(words); + }); + + it('names each placeholder a caller must replace', async () => { + const ctx = await contextOf(); + expect(ctx.next(['context', 'add', { placeholder: 'url' }, '--name', { placeholder: 'name' }], 'Add a context')).toEqual({ + command: 'demo context add --name ', + argv: ['demo', 'context', 'add', '', '--name', ''], + placeholders: ['', ''], + why: 'Add a context' + }); + }); +}); + +describe('ctx.nextFor', () => { + const contextOf = async () => { + expect((await exec(cli, ['pair', 'one'])).code).toBe(0); + return seen[seen.length - 1].ctx; + }; + const hostile = ['a b', "it's", '"q"', 'a;b', '$HOME', '`echo pwned`', '$(echo pwned)', 'a\nb', '', 'x|y', '*', '~', '#c', 'a\\b', '!', '{a,b}', 'é ✓', '=x', '']; + const inputs: Record[] = [ + { name: 'users' }, + { name: 'users', level: 3, paths: ['a', 'b c'], count: 5, ratio: -0.5, force: true, quiet: false, kind: 'audit', size: 2 }, + { name: 'u', level: -2, paths: [], tags: ['x', '--y', '[z', '-w'], ports: [80, -1], meta: { a: [1], b: null }, columns: [{ n: 1 }], anything: 'free text' }, + { name: '-dash', level: 1, paths: ['p'] }, + { name: '--double', force: false, quiet: true }, + { paths: ['only-a-later-positional'], ratio: 1e21, tags: [] }, + { nullable: null, anything: null, meta: {} }, + { nullable: 'set', anything: [1, 'two', { three: 3 }] }, + { name: hostile[0], tags: hostile, paths: hostile, anything: hostile }, + ...hostile.map((word) => ({ name: word, kind: 'plain' })) + ]; + + it.each(inputs.map((input, index) => [index, input] as const))( + 'input %i parses back from its next step, beside the carried flags, and a POSIX shell reads the line as its argv', + async (_index, input) => { + expect((await exec(cli, ['--as', 'bot', '--context', 'staging', 'pair', 'one', '--cwd', 'sub'])).code).toBe(0); + const step = seen[seen.length - 1].ctx.nextFor('shape', input, 'Shape it', { drop: ['--as'] }); + expect(step.argv.slice(0, 6)).toEqual(['demo', '--context', 'staging', '--cwd', 'sub', 'shape']); + expect(step.placeholders).toBeUndefined(); + const result = await exec(cli, [...step.argv.slice(1), '--json']); + expect(result.code).toBe(0); + expect(lastInput()).toEqual({ quiet: true, ...input }); + expect(seen[seen.length - 1].ctx).toMatchObject({ globals: { context: 'staging' }, cwd: resolve(dir, 'sub') }); + expect(seen[seen.length - 1].ctx.globals.as).toBeUndefined(); + const words = execFileSync('/bin/sh', ['-c', `printf '%s\\0' ${step.command.slice('demo '.length)}`]).toString('utf8'); + expect(words.split('\0').slice(0, -1)).toEqual(step.argv.slice(1)); + } + ); + + it('renders positionals as bare words in order, then flags in the spelling the parser reads', async () => { + const ctx = await contextOf(); + expect(ctx.nextFor('shape', { kind: 'audit', name: 'users', level: 3, force: false, tags: ['a', 'b'] }, 'Shape it')).toEqual({ + command: 'demo shape users 3 --kind audit --no-force --tags a --tags b', + argv: ['demo', 'shape', 'users', '3', '--kind', 'audit', '--no-force', '--tags', 'a', '--tags', 'b'], + why: 'Shape it' + }); + }); + + it('turns a placeholder value and every secret into a placeholder word', async () => { + const ctx = await contextOf(); + const step = ctx.nextFor('shape', { name: { placeholder: 'name' }, password: 'hunter2-long', creds: { secret: 'NESTED-SECRET-9', user: 'u' } }, 'Shape it'); + expect(step).toEqual({ + command: 'demo shape --password --creds ', + argv: ['demo', 'shape', '', '--password', '', '--creds', ''], + placeholders: ['', '', ''], + why: 'Shape it' + }); + }); + + it.each([ + ['no such', {}, 'not a command'], + ['shape', { nope: 1 }, '"nope"'], + ['shape', { constructor: 'x' }, '"constructor"'], + ['shape', { count: 'five' }, '--count'] + ])('refuses %j with %j', async (command, input, text) => { + const ctx = await contextOf(); + expect(() => ctx.nextFor(command, input, 'Shape it')).toThrow(text); + }); +}); + +describe('flags that choose the target of a run', () => { + const perRun = ['--json', '--format', 'json', '--yes', '--dry-run', '--fields', 'a', '--input', '{}', '--no-input']; + + it.each([ + [['--context', 'staging', 'pair', 'one', '--cwd', 'sub', ...perRun], ['--context', 'staging', '--cwd', 'sub']], + [['pair', 'one', '--context=staging', ...perRun], ['--context=staging']], + [['pair', 'one', ...perRun], []] + ])('%j gives next and nextFor steps that start with %j', async (argv, carried) => { + expect((await exec(cli, argv)).code).toBe(0); + const { ctx } = seen[seen.length - 1]; + expect(ctx.next(['table', 'list'], 'List them').argv).toEqual(['demo', ...carried, 'table', 'list']); + expect(ctx.nextFor('table add', { table_name: 'users' }, 'Add it')).toMatchObject({ + command: ['demo', ...carried, 'table', 'add', 'users'].join(' '), + argv: ['demo', ...carried, 'table', 'add', 'users'] + }); + expect(ctx.followUp([], { why: 'Again' }).argv).toEqual(['demo', ...argv]); + }); +}); + +describe('null for an optional property', () => { + it.each([ + ['a top-level optional null is absent', ['--input', '{"name":"n","is_required":null}'], { name: 'n', label: 'Untitled' }], + ['a top-level null in another spelling is absent', ['--input', '{"name":"n","isRequired":null}'], { name: 'n', label: 'Untitled' }], + ['a null inside a list item is absent', ['--input', '{"name":"n","rules":[{"kind":"a","limit":null}]}'], { name: 'n', label: 'Untitled', rules: [{ kind: 'a' }] }], + ['a null inside a JSON flag is absent', ['n', '--rules', '[{"kind":"a","limit":null}]'], { name: 'n', label: 'Untitled', rules: [{ kind: 'a' }] }], + ['a property that takes null keeps it', ['--input', '{"name":"n","default_value":null,"note":null}'], { name: 'n', label: 'Untitled', default_value: null, note: null }], + ['a null for a property with a default gets the default', ['--input', '{"name":"n","label":null}'], { name: 'n', label: 'Untitled' }] + ])('%s', async (_case, argv, input) => { + const result = await exec(cli, ['field', ...argv, '--json']); + expect(result.code).toBe(0); + expect(lastInput()).toEqual(input); + }); + + it.each([ + ['a required property', '{"name":null}', 'at name, expected string'], + ['a required key in a list item', '{"name":"n","rules":[{"kind":null}]}', 'at rules[0].kind, expected string'] + ])('%s still refuses null', async (_case, json, message) => { + const result = await exec(cli, ['field', '--input', json, '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error.message).toContain(message); + }); + + it('reads the same way in ctx.nextFor', async () => { + expect((await exec(cli, ['pair', 'one'])).code).toBe(0); + const step = seen[seen.length - 1].ctx.nextFor('field', { name: 'n', is_required: null, rules: [{ kind: 'a', limit: null }], note: null }, 'Add it'); + expect(step.argv).toEqual(['demo', 'field', 'n', '--rules', '[{"kind":"a"}]', '--input', '{"note":null}']); + }); +}); + +describe('a key or a value the schema does not allow', () => { + const schemaStep = { command: 'demo policy --schema', argv: ['demo', 'policy', '--schema'], why: 'See the input schema' }; + + it.each([ + ['at the top level of --input', ['--input', '{"policies":[],"polices":[]}'], 'unknown key "polices"', 'Did you mean "policies"?'], + ['nested in a list', ['--policies', '[{"policy_type":"AuthzEntityMembership","permisive":false}]'], 'at [0], the key "permisive" is not allowed', + 'Did you mean "permissive"? The keys allowed at [0] are policy_type, permissive, data.'], + ['nested in an object', ['--policies', '[{"policy_type":"AuthzDirectOwner","data":{"entity_feild":"owner_id"}}]'], 'at [0].data, the key "entity_feild" is not allowed', + 'Did you mean "entity_field"? The keys allowed at [0].data are entity_field, membership_type.'], + ['an enum value in JSON', ['--policies', '[{"policy_type":"AuthzEntityMembrship"}]'], 'at [0].policy_type, expected one of', 'Did you mean "AuthzEntityMembership"?'], + ['a key with nothing close', ['--policies', '[{"policy_type":"AuthzDirectOwner","foo":1}]'], 'the key "foo" is not allowed', 'The keys allowed at [0] are policy_type, permissive, data.'] + ])('%s names the nearest allowed one and gives the --schema step', async (_case, flags, message, hint) => { + const result = await exec(cli, ['policy', ...flags, '--json']); + expect(result.code).toBe(ExitCode.usage); + const { error, meta } = result.json(); + expect(error.code).toBe('invalid-input'); + expect(error.message).toContain(message); + expect(error.hint).toBe(hint); + expect(meta.next).toEqual([schemaStep]); + }); + + it('names the nearest enum value of a flag', async () => { + const result = await exec(cli, ['table', 'add', 't', '--kind', 'audt', '--json']); + expect(result.json().error.hint).toBe('Did you mean "audit"?'); + expect(result.json().meta.next[0].argv).toEqual(['demo', 'table', 'add', '--schema']); + }); + + it.each([ + [['--mode', 'alhpa'], 'alhpa'], + [['--vault', '{"tier":"gld"}'], 'gld'], + [['--vault', '{"tierr":"gold"}'], 'tierr'] + ])('names nothing from a secret value: %j', async (flags, typed) => { + const result = await exec(cli, ['policy', ...flags, '--json']); + expect(result.json().error.code).toBe('invalid-input'); + expect(result.stdout).not.toContain(typed); + expect(result.stdout).not.toMatch(/Did you mean/); + }); +}); + +describe('a command that serves a protocol', () => { + it.each([ + ['--bogus', ['serve', '--bogus'], 'unknown-flag'], + ['--dry-run', ['serve', '--dry-run'], 'dry-run-unsupported'], + ['--yes', ['serve', '--yes'], 'invalid-input'], + ['-y', ['serve', '-y'], 'invalid-input'], + ['--context nope', ['--context', 'nope', 'serve'], 'context-unknown'] + ])('writes nothing to stdout when %s fails at start-up, in JSON and in text', async (_case, argv, code) => { + const json = await exec(cli, [...argv, '--json']); + expect(json.code).toBe(ExitCode.usage); + expect(json.stdout).toBe(''); + expect(JSON.parse(json.stderr).error.code).toBe(code); + const text = await exec(cli, argv, { tty: true }); + expect(text.code).toBe(ExitCode.usage); + expect(text.stdout).toBe(''); + expect(text.stderr).toContain(`Error (${code})`); + }); + + it('leaves stdout to the command on success, and writes its result to stderr, in JSON and in text', async () => { + const json = await exec(cli, ['serve', '--json']); + expect(json.code).toBe(0); + expect(json.stdout).toBe('PROTOCOL\n'); + expect(JSON.parse(json.stderr)).toMatchObject({ ok: true, data: { closed: true }, meta: { command: 'serve', warnings: ['closed'] } }); + const text = await exec(cli, ['serve'], { tty: true }); + expect(text.code).toBe(0); + expect(text.stdout).toBe('PROTOCOL\n'); + expect(text.stderr).toContain('closed: true\nNext:\n demo status # Check\n'); + }); +}); + +describe('the error codes of the layer', () => { + it('give each code one sentence, none empty and none repeated', () => { + const sentences = Object.values(COMMAND_ERROR_CODES); + expect(Object.keys(COMMAND_ERROR_CODES)).toEqual(expect.arrayContaining([ + 'unknown-command', 'unknown-flag', 'unexpected-argument', 'missing-input', 'invalid-input', + 'dry-run-unsupported', 'approval-required', 'cancelled', 'interrupted', 'failed' + ])); + for (const sentence of sentences) expect(sentence.trim()).toMatch(/^[A-Z].*\.$/); + expect(new Set(sentences).size).toBe(sentences.length); + }); + + it('let a host type its own codes on a CliError', () => { + type HostCode = 'agent-unusable' | 'unknown-agent'; + const error = new CliError({ code: 'agent-unusable', message: 'The agent cannot be used.' }); + const code: HostCode = error.code; + expect(code).toBe('agent-unusable'); + }); +}); + +describe('-y, the short form of --yes', () => { + it('approves like --yes and takes no value, so the words after it stay arguments', async () => { + expect((await exec(cli, ['pair', '-y', 'one', 'two', '--json'])).code).toBe(0); + const { input, ctx } = seen[seen.length - 1]; + expect(ctx.yes).toBe(true); + expect(input).toEqual({ a: 'one', b: 'two' }); + expect((await exec(cli, ['deploy', '-y', 'web', '--json'])).code).toBe(0); + expect(applied).toEqual(['web']); + }); + + it('shows in help, in the manifest and in --llms', async () => { + expect((await exec(cli, ['--help'])).stdout).toMatch(/-y, --yes +Approve the plan of a change without a prompt/); + expect((await exec(cli, ['--help'])).stdout).toMatch(/-h, --help +Show help/); + expect((await exec(cli, ['--llms', '--json'])).json().globals.properties.yes['x-short']).toBe('y'); + expect((await exec(cli, ['--llms'])).stdout).toContain('`-y` is `--yes`'); + }); + + it.each([ + ['a command', { commands: [{ name: 'x', summary: 'x', effect: 'read', input: z.object({ yes_please: z.boolean().optional().meta({ 'x-short': 'y' }) }), run: (): { data: null } => ({ data: null }) }] }], + ['a global of the CLI', { globals: z.object({ force: z.boolean().optional().meta({ 'x-short': 'f' }) }), commands: [] }] + ])('cannot be declared by %s', (_owner, config) => { + expect(() => createCli({ name: 'bad', version: '0.0.0', ...config } as unknown as Parameters[0])).toThrow('short form'); + }); +}); + +describe('a carried flag given more than once', () => { + it('becomes one placeholder in the step, so the person chooses one value', async () => { + const result = await exec(cli, ['--as', 'a', '--context', 'staging', '--as', 'b', 'pair', 'one', '--json']); + expect(result.code).toBe(ExitCode.usage); + const { error, meta } = result.json(); + expect(error.message).toContain('--as was given 2 times'); + expect(meta.next).toEqual([{ + command: 'demo --as --context staging pair --schema', + argv: ['demo', '--as', '', '--context', 'staging', 'pair', '--schema'], + placeholders: [''], + why: 'See the input schema' + }]); + }); +}); + +describe('a step that leaves out a carried flag', () => { + const run = async (argv: string[]) => { + expect((await exec(cli, argv)).code).toBe(0); + return seen[seen.length - 1].ctx; + }; + + it.each([ + [['--as', 'bot', '--context', 'staging', 'pair', 'one', '--cwd', 'sub'], ['--as'], ['--context', 'staging', '--cwd', 'sub'], ['--as', 'bot', '--context', 'staging', '--cwd', 'sub']], + [['pair', 'one', '--as=bot', '--context=staging'], ['as'], ['--context=staging'], ['--as=bot', '--context=staging']] + ])('%j drops %j from one step, keeps the other carried flags, and keeps it in the next step', async (argv, drop, kept, all) => { + const ctx = await run(argv); + expect(ctx.next(['agent', 'remove', 'bot'], 'Remove it', { drop }).argv).toEqual(['demo', ...kept, 'agent', 'remove', 'bot']); + expect(ctx.nextFor('table add', { table_name: 'users' }, 'Add it', { drop }).argv).toEqual(['demo', ...kept, 'table', 'add', 'users']); + expect(ctx.next(['status'], 'Check').argv).toEqual(['demo', ...all, 'status']); + }); + + it.each([['--bogus'], ['--json'], ['--table-name']])('refuses to drop %s, which is not a carried global flag', async (name) => { + const ctx = await run(['--as', 'bot', 'pair', 'one']); + expect(() => ctx.next(['status'], 'Check', { drop: [name] })).toThrow(`cannot drop ${name}`); + expect(() => ctx.nextFor('status', {}, 'Check', { drop: [name] })).toThrow(`cannot drop ${name}`); + }); +}); + +describe('the steps the layer builds itself', () => { + it.each([ + ['missing-input', ['--context', 'staging', 'login', '--json'], ['login', '--schema']], + ['unknown-flag', ['--context', 'staging', 'table', 'add', 't', '--bogus', '--json'], ['table', 'add', '--help']], + ['unexpected-argument of a command', ['table', 'add', 't', 'extra', '--context=staging', '--json'], ['table', 'add', '--help']], + ['unexpected-argument of a group', ['--context', 'staging', 'table', '--json', '--', 'x'], ['table', '--help']], + ['unknown-command', ['--context', 'staging', 'tabel', 'add', '--json'], ['--help']], + ['unknown-command in a group', ['--context', 'staging', 'table', 'bogus', '--json'], ['table', '--help']], + ['dry-run-unsupported', ['--context', 'staging', 'bump', '--dry-run', '--json'], ['bump', '--help']] + ])('%s carries the target flags of the run', async (code, argv, words) => { + const result = await exec(cli, ['--cwd', 'sub', ...argv]); + const { error, meta } = result.json(); + expect(error.code).toBe(code.split(' ')[0]); + const carried = argv.includes('--context=staging') ? ['--context=staging'] : ['--context', 'staging']; + expect(meta.next[0].argv).toEqual(['demo', '--cwd', 'sub', ...carried, ...words]); + }); +}); + +describe('ctx.followUp', () => { + it.each([ + [['pair', 'one', '--', '-x'], [['--yes']], 'demo pair one --yes -- -x'], + [['pair', 'one', 'two', '--yes', 'false'], [['--yes'], { drop: ['--yes'] }], 'demo pair one two --yes'], + [['pair', 'one', 'two', '--no-yes', '--dry-run', '--json'], [['--yes'], { drop: ['--yes', '--dry-run'] }], 'demo pair one two --json --yes'], + [['--json', 'pair', 'one'], [['--yes'], { command: 'table add' }], 'demo --json table add one --yes'], + [['pair', 'pair', '--json'], [[], { command: 'table add' }], 'demo table add pair --json'] + ])('%j with %j is %s', async (argv, args, command) => { + expect((await exec(cli, argv)).code).toBe(0); + const [flags, options] = args as [string[], { drop?: string[]; command?: string }?]; + const step = seen[seen.length - 1].ctx.followUp(flags, { why: 'Apply it', ...options }); + expect(step).toEqual({ command, argv: command.split(' '), why: 'Apply it' }); + }); + + it('turns each secret into a named placeholder, because an agent must not run ***', async () => { + expect((await exec(cli, ['vault', 'l', '--pin', '4242', '--creds={"secret":"NESTED-SECRET-9"}', '--yes'])).code).toBe(0); + expect(seen[seen.length - 1].ctx.followUp([], { why: 'Apply it' })).toEqual({ + command: 'demo vault l --pin --creds --yes', + argv: ['demo', 'vault', 'l', '--pin', '', '--creds', '', '--yes'], + placeholders: ['', ''], + why: 'Apply it' + }); + }); + + it.each([ + [{ drop: ['--bogus'] }, '--bogus'], + [{ command: 'no such' }, 'no such'] + ])('refuses %j', async (options, text) => { + await exec(cli, ['pair', 'one']); + expect(() => seen[seen.length - 1].ctx.followUp(['--yes'], { why: 'Apply it', ...options })).toThrow(text); + }); +}); + +describe('the approval of a change', () => { + const PLAN = planOf('web'); + const RERUN = { command: 'demo deploy web --json --yes', argv: ['demo', 'deploy', 'web', '--json', '--yes'], why: 'Apply the change once the person approves the plan' }; + + it('stops before the change with exit 3, the plan and the rerun with --yes, when there is no terminal', async () => { + const result = await exec(cli, ['deploy', 'web', '--json']); + expect(result.code).toBe(ExitCode.approvalRequired); + expect(result.json()).toEqual({ + ok: false, + error: { + code: 'approval-required', + message: 'This change needs approval, and prompts are off, so nothing was changed.', + hint: 'Show the plan to the person. When they approve it, run the same command with --yes.', + details: { plan: PLAN } + }, + meta: { command: 'deploy', next: [RERUN] } + }); + expect(applied).toEqual([]); + }); + + it('prints the plan above the error in text format', async () => { + const result = await exec(cli, ['deploy', 'web', '--format', 'text']); + expect(result.code).toBe(ExitCode.approvalRequired); + expect(result.stderr).toMatch(/Directory: [\s\S]*Change web\.\n\nError \(approval-required\)/); + expect(applied).toEqual([]); + }); + + it.each([[['--dry-run']], [['--dry-run', '--yes']], [['--dry-run', '-y']]])('returns the plan for %j, offers the real run, and changes nothing', async (flags) => { + const result = await exec(cli, ['deploy', 'web', ...flags, '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ applied: false, plan: PLAN }); + expect(result.json().meta.next).toEqual([RERUN]); + expect(applied).toEqual([]); + }); + + it('adds the flags its plan needs to the exit-3 step and the dry-run step when there is no terminal, and only then', async () => { + const step = (command: string) => ({ command, argv: command.split(' '), why: RERUN.why }); + expect((await exec(cli, ['deploy', 'keyed', '--json'])).json().meta.next).toEqual([step('demo deploy keyed --json --from-stdin --yes')]); + expect((await exec(cli, ['deploy', 'keyed', '--dry-run', '--json'])).json().meta.next).toEqual([step('demo deploy keyed --json --from-stdin --yes')]); + expect((await exec(cli, ['deploy', 'keyed', '--from-stdin', '--dry-run', '--json'])).json().meta.next).toEqual([step('demo deploy keyed --from-stdin --json --yes')]); + expect((await exec(cli, ['deploy', 'keyed', '--dry-run', '--json'], { tty: true })).json().meta.next).toEqual([step('demo deploy keyed --json --yes')]); + expect(applied).toEqual([]); + }); + + it.each([ + [['--yes', 'false', '--json'], false], + [['--no-yes', '--json'], false], + [['--no-input', '--format', 'json'], true] + ])('does not take %j as approval (terminal: %s)', async (flags, tty) => { + const result = await exec(cli, ['deploy', 'web', ...flags], { tty }); + expect(result.code).toBe(ExitCode.approvalRequired); + expect(applied).toEqual([]); + }); + + it('applies the plan with --yes', async () => { + const result = await exec(cli, ['deploy', 'web', '--yes', '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ deployed: 'web' }); + expect(applied).toEqual(['web']); + }); + + it.each([[['--dry-run']], [['--yes']], [[]]])('stops a change whose plan fails with that failure (%j), and never applies it', async (flags) => { + const result = await exec(cli, ['deploy', 'blocked', ...flags, '--json']); + expect(result.code).toBe(ExitCode.failure); + expect(result.json().error).toEqual({ code: 'no-env', message: 'There is nothing to deploy here.', hint: 'Bind the directory first.' }); + expect(applied).toEqual([]); + }); + + it('shows the plan on a terminal and applies it when the person says yes', async () => { + const result = await exec(cli, ['deploy', 'web', '--json'], { tty: true, answers: [['Apply this change?', 'y\n']] }); + expect(result.code).toBe(0); + expect(result.stderr).toContain('Change web.'); + expect(applied).toEqual(['web']); + }); + + it('fails with cancelled, exit 1, when the person declines', async () => { + const result = await exec(cli, ['deploy', 'web', '--json'], { tty: true, answers: [['Apply this change?', 'n\n']] }); + expect(result.code).toBe(ExitCode.failure); + expect(result.json().error).toEqual({ code: 'cancelled', message: 'The change was not approved, so nothing was changed.' }); + expect(applied).toEqual([]); + }); + + it('labels a change by its effect alone in --schema, the manifest and help', async () => { + expect((await exec(cli, ['deploy', '--schema'])).json()).toMatchObject({ name: 'deploy', effect: 'destructive' }); + expect((await exec(cli, ['deploy', '--help'])).stdout).toContain('Effect: destructive'); + expect((await exec(cli, ['--help'])).stdout).toMatch(/deploy +Deploy a target \(destructive\)/); + expect((await exec(cli, ['--help'])).stdout).toMatch(/server +Run the server \(write, takes its own flags\)/); + }); +}); + +describe('a change that runs at once', () => { + it('runs without --yes and without a terminal, and asks nothing', async () => { + const result = await exec(cli, ['bump', '--by', '2', '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ bumped: 2 }); + expect(bumped).toEqual(['2']); + expect((await exec(cli, ['bump', '--yes', '--json'])).code).toBe(0); + expect(bumped).toEqual(['2', '1']); + }); + + it('refuses --dry-run before it runs, because it has no plan', async () => { + const result = await exec(cli, ['bump', '--dry-run', '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error).toMatchObject({ code: 'dry-run-unsupported', details: { flag: '--dry-run' } }); + expect(result.json().error.message).toContain('makes its change as soon as it runs'); + expect(bumped).toEqual([]); + }); + + it('says it runs at once in help', async () => { + expect((await exec(cli, ['bump', '--help'])).stdout).toContain('Effect: write, at once'); + expect((await exec(cli, ['--help'])).stdout).toMatch(/bump +Bump a counter at once \(write, at once\)/); + }); +}); + +describe('definition errors', () => { + // These rows build definitions that the type refuses on purpose, as an untyped caller could. + const nothing = (): { data: unknown } => ({ data: null }); + const none = async (): Promise => undefined; + const command = (overrides: Record): CommandDefinition => + ({ name: 'x', summary: 'x', effect: 'read', run: nothing, ...overrides }) as unknown as CommandDefinition; + const plan = () => ({ plan: planOf('x') }); + + it.each([ + [[command({}), command({})], 'defined twice'], + [[command({ name: 'a b' })], 'invalid name'], + [[command({ positionals: ['missing'], input: z.object({}) })], 'no such property'], + [[command({ input: z.object({ json: z.boolean().optional() }) })], 'a flag the command layer owns'], + [[command({ input: z.object({ foo_bar: z.string().optional(), fooBar: z.string().optional() }) })], 'is a spelling of both "foo_bar"'], + [[command({ run: undefined, passthrough: none, input: z.object({}) })], 'passthrough'], + [[command({ passthrough: none })], 'passthrough'], + [[command({ effect: 'write' })], 'has plan() and apply() and no run()'], + [[command({ effect: 'destructive', plan, apply: nothing })], 'has plan() and apply() and no run()'], + [[command({ effect: 'read', run: undefined, plan, apply: nothing })], 'is a "read" command'], + [[command({ effect: 'write', run: undefined, plan })], 'has plan() and apply()'], + [[command({ run: undefined, serve: nothing })], "stdout: 'reserved'"], + [[command({ stdout: 'reserved' })], 'reserves stdout'], + [[command({ effect: 'maybe' })], 'Give it "read", "write" or "destructive"'], + [[command({ effect: 'destructive', immediate: true })], 'runs at once (immediate: true)'], + [[command({ effect: 'read', immediate: true })], 'runs at once (immediate: true)'], + [[command({ effect: 'write', immediate: true, run: undefined, plan, apply: nothing })], 'runs at once (immediate: true)'] + ])('rejects %#', (commands, text) => { + expect(() => createCli({ name: 'bad', version: '0.0.0', commands })).toThrow(text); + }); +}); + +describe('object keys that are also Object.prototype names', () => { + it.each([ + [['--constructor', 'c', '--creds', '{"toString":"t","constructor":1}'], 'invalid-input'], + [['--constructor', 'c', '--creds', '{"user":"u"}'], 'invalid-input'], + [[], 'missing-input'] + ])('%j are unknown keys', async (flags, code) => { + const result = await exec(cli, ['proto', ...flags, '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error.code).toBe(code); + }); + + it('never hands a command a __proto__ key, nor sets one on any object', async () => { + const result = await exec(cli, ['proto', '--constructor', 'c', '--creds', '{"toString":"t","__proto__":{"polluted":1}}', '--json']); + expect(result.code).toBe(0); + expect(Object.keys(lastInput().creds as object)).toEqual(['toString']); + expect(({} as Record).polluted).toBeUndefined(); + }); +}); + +describe('output that --schema describes', () => { + const output = z.object({ id: z.string(), rows: z.number().int(), tags: z.array(z.string()), owner: z.object({ name: z.string() }).nullable() }); + const typed = createCli({ + name: 'typed', + version: '1', + commands: [{ name: 'show', summary: 'Show', effect: 'read', output, run: () => ({ data: { id: 'a1', rows: 3, tags: ['x'], owner: null } }) }] + }); + + it('prints the output schema, and the real --json data validates against it', async () => { + const schema = (await exec(typed, ['show', '--schema'])).json().output; + const { data } = (await exec(typed, ['show', '--json'])).json(); + expect(z.fromJSONSchema(schema).safeParse(data).success).toBe(true); + expect(z.fromJSONSchema(schema).safeParse({ ...data, rows: 'three' }).success).toBe(false); + }); +}); + +describe('round trip', () => { + const schema = z.object({ + table_name: z.string().optional(), + rowCount: z.number().int().optional(), + ratio: z.number().optional(), + is_public: z.boolean().optional(), + kind: z.enum(['plain', 'audit']).optional(), + tags: z.array(z.string()).optional(), + ports: z.array(z.number().int()).optional(), + meta: z.record(z.string(), z.unknown()).optional(), + columns: z.array(z.record(z.string(), z.unknown())).optional() + }); + const echo = createCli({ name: 'echo', version: '0.0.0', commands: [{ name: 'echo', summary: 'Echo', effect: 'read', input: schema, run: (input) => ({ data: input }) }] }); + + const inputs: Record[] = [ + { table_name: 'users', rowCount: 3, ratio: 0.25, is_public: true, kind: 'audit', tags: ['a', 'b c'], ports: [80, -1], meta: { nested: { x: [1] } }, columns: [{ name: 'id' }] }, + { table_name: '', rowCount: -7, ratio: -0.5, is_public: false }, + { table_name: 'true', kind: 'plain', tags: ['--not-a-flag', '-1'] }, + { table_name: 'a=b', tags: [], ports: [0] }, + { table_name: 'ünïcødé ✓', ratio: 1e21, columns: [] } + ]; + + const words = (property: string) => property.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().split('_'); + const spellings: Record string> = { + kebab: (property) => words(property).join('-'), + snake: (property) => words(property).join('_'), + camel: (property) => words(property).map((word, index) => (index ? word[0].toUpperCase() + word.slice(1) : word)).join('') + }; + + const argvFor = (input: Record, spell: (property: string) => string): string[] => + Object.entries(input).flatMap(([property, value]) => { + const flag = `--${spell(property)}`; + const pair = (text: string) => (text.startsWith('--') ? [`${flag}=${text}`] : [flag, text]); + if (typeof value === 'boolean') return [value ? flag : `--no-${spell(property)}`]; + if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item !== 'object')) { + return value.flatMap((item) => pair(String(item))); + } + return typeof value === 'object' ? [flag, JSON.stringify(value)] : pair(String(value)); + }); + + it.each(Object.keys(spellings).flatMap((spelling) => inputs.map((input, index) => [spelling, index, input] as const)))( + '%s spelling of input %i parses back to the same object', + async (spelling, _index, input) => { + const result = await exec(echo, ['echo', ...argvFor(input, spellings[spelling]), '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual(input); + } + ); +}); diff --git a/agentic/command/__tests__/tool-command.test.ts b/agentic/command/__tests__/tool-command.test.ts new file mode 100644 index 0000000000..48146ff948 --- /dev/null +++ b/agentic/command/__tests__/tool-command.test.ts @@ -0,0 +1,522 @@ +import { type ConfirmPrompt, defineHarnessTool, type GatePolicy, identifierParam, type ToolFailure } from '@agentic-kit/harness'; +import { mkdtempSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { PassThrough, Writable } from 'stream'; +import { z } from 'zod'; + +import { type CommandDefinition, createCli, toCliCommands, toolCallStep, toolCommand } from '../src'; + +const cwd = mkdtempSync(join(tmpdir(), 'agentic-command-')); +const calls: Array<{ tool: string; params: unknown; cwd: string }> = []; + +const listTool = defineHarnessTool({ + name: 'list_things', + label: 'List things', + description: 'List the things.', + parameters: z.object({ prefix: z.string().optional() }), + effect: 'read', + async execute(params, ctx) { + calls.push({ tool: 'list_things', params, cwd: ctx.cwd }); + return { + content: [{ type: 'text', text: '2 things.' }], + details: { things: ['a', 'b'], message: '2 things.' } + }; + } +}); + +const deleteTool = defineHarnessTool({ + name: 'delete_thing', + label: 'Delete thing', + description: 'Delete a thing.', + parameters: z.object({ thing_name: identifierParam() }), + effect: 'destructive', + async execute(params, ctx) { + calls.push({ tool: 'delete_thing', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: `Deleted ${params.thing_name}` }], details: { deleted: params.thing_name } }; + } +}); + +const createTool = defineHarnessTool({ + name: 'create_thing', + label: 'Create thing', + description: 'Create a thing.', + parameters: z.object({ + thing_name: identifierParam(), + size: z.number().int().min(1).optional(), + note: z.union([z.string(), z.null()]).optional(), + replace: z.boolean().optional() + }), + effect: 'write', + async execute(params, ctx) { + calls.push({ tool: 'create_thing', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: `Created ${params.thing_name}` }], details: { created: params.thing_name } }; + } +}); + +let failure: ToolFailure; +const connectTool = defineHarnessTool({ + name: 'connect_thing', + label: 'Connect thing', + description: 'Connect a thing.', + parameters: z.object({}), + effect: 'read', + async execute() { + return { content: [{ type: 'text', text: failure.message }], details: { connected: false, message: failure.message }, failure }; + } +}); + +const TARGET = { kind: 'account', apiEndpoint: 'http://api.localhost:3000/graphql', account: { userId: 'user-1' } } as const; + +// A read that suggests what to do after it. +const suggestTool = defineHarnessTool({ + name: 'suggest_thing', + label: 'Suggest thing', + description: 'Suggest a thing.', + parameters: z.object({}), + effect: 'read', + async execute() { + return { + content: [{ type: 'text', text: 'Suggested.' }], + details: { suggested: true }, + calls: [ + { tool: 'delete_thing', input: { thing_name: 'old' }, why: 'Delete the old thing' }, + { tool: 'create_thing', input: { size: 2 }, why: 'Make a new one', choose: ['thing_name'] } + ] + }; + } +}); + +const unrendered: Array<{ tool: string; reason: string }> = []; + +let ready = true; +const notReady: ToolFailure = { + code: 'no-env', + message: 'No .env found in the project.', + hint: 'Create a thing first, then retry.' +}; +const prompted: string[] = []; +const gate: GatePolicy = { + isGated: () => true, + resolvePrompt: async (event) => { + prompted.push(event.toolName); + if (!ready) return { kind: 'blocked', failure: notReady }; + const name = String(event.input?.thing_name); + return { + kind: 'ask', + prompt: { + title: 'Change thing?', + message: `Change the thing "${name}".`, + target: TARGET, + preview: { kind: 'policies', tableName: name, policies: ['AuthzDirectOwner'] } + } + }; + } +}; + +const quickInput = z.object({ spec: z.string().describe('name:size') }); + +const cli = createCli({ + name: 'demo', + version: '1.0.0', + commands: toCliCommands([ + toolCommand(listTool, { name: 'thing list' }), + toolCommand(deleteTool, { name: 'thing delete', positionals: ['thing_name'] }), + toolCommand(createTool, { + name: 'thing quick', + input: quickInput, + positionals: ['spec'], + mapInput: ({ spec }: { spec: string }) => { + const [thing_name, size] = spec.split(':'); + return { thing_name, size: Number(size) }; + } + }), + toolCommand(createTool, { + name: 'thing create', + positionals: ['thing_name'], + next: (details, params, ctx) => [ctx.next(['thing', 'delete', params.thing_name], `Undo ${details.created}`)] + }), + toolCommand(connectTool, { name: 'thing connect' }), + toolCommand(suggestTool, { name: 'thing suggest' }) + ], { + gate, + onUnrenderedCall: (call, reason) => unrendered.push({ tool: call.tool, reason }), + // What the CLI passes: the command a person runs for a failure code, built for this run. + failureNext: (failure, ctx) => { + if (failure.code === 'signed-out') return [ctx.next(['login'], 'Sign in')]; + if (failure.code === 'no-env') return [ctx.next(['db', 'create', 'my app'], 'Create a database for this directory')]; + return []; + } + }) +}); + +function capture(onWrite?: (text: string) => void) { + let text = ''; + const stream = new Writable({ + write(chunk, _encoding, callback) { + text += chunk.toString(); + onWrite?.(text); + callback(); + } + }); + return { stream, text: () => text }; +} + +/** `answers`: when stderr contains the first string, type the second into stdin. `tty`: stdin and stdout are terminals. */ +async function run(argv: string[], options: { tty?: boolean; answers?: Array<[string, string]> } = {}) { + const stdin = new PassThrough(); + const stdout = capture(); + const answers = [...(options.answers ?? [])]; + const stderr = capture((text) => { + if (answers.length && text.includes(answers[0][0])) { + const [, keys] = answers.shift(); + setImmediate(() => stdin.write(keys)); + } + }); + if (options.tty) { + Object.assign(stdin, { isTTY: true }); + Object.assign(stdout.stream, { isTTY: true }); + } + const code = await cli.run(argv, { stdin, stdout: stdout.stream, stderr: stderr.stream, env: {}, cwd }); + return { code, stdout: stdout.text(), stderr: stderr.text(), json: () => JSON.parse(stdout.text()) }; +} + +const plan: ConfirmPrompt = { + title: 'Change thing?', + message: 'Change the thing "posts".', + target: TARGET, + preview: { kind: 'policies', tableName: 'posts', policies: ['AuthzDirectOwner'] } +}; + +beforeEach(() => { + calls.length = 0; + prompted.length = 0; + ready = true; +}); + +describe('a read', () => { + it('runs without asking the gate, and returns the details as data', async () => { + const result = await run(['thing', 'list', '--prefix', 'a', '--dry-run']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ things: ['a', 'b'], message: '2 things.' }); + expect(calls).toEqual([{ tool: 'list_things', params: { prefix: 'a' }, cwd }]); + expect(prompted).toEqual([]); + }); + + it('prints the text content of the tool in text format', async () => { + const result = await run(['thing', 'list', '--format', 'text']); + expect(result.code).toBe(0); + expect(result.stdout).toBe('2 things.\n'); + }); +}); + +describe('a change', () => { + it('stops with approval-required and the plan when it is not interactive and has no --yes', async () => { + const result = await run(['thing', 'delete', 'posts']); + expect(result.code).toBe(3); + const { error, meta } = result.json(); + expect(error.code).toBe('approval-required'); + expect(error.details).toEqual({ plan }); + expect(error.hint).toMatch(/plan/); + expect(meta.next).toEqual([{ command: 'demo thing delete posts --yes', argv: ['demo', 'thing', 'delete', 'posts', '--yes'], why: expect.any(String) }]); + expect(calls).toEqual([]); + }); + + it('prints the plan above the approval-required error in text format', async () => { + const result = await run(['thing', 'delete', 'posts', '--format', 'text']); + expect(result.code).toBe(3); + expect(result.stderr).toMatch(/Change the thing "posts"[\s\S]*AuthzDirectOwner[\s\S]*Error \(approval-required\)/); + expect(calls).toEqual([]); + }); + + it('returns the plan for --dry-run, offers the real run, and changes nothing', async () => { + const result = await run(['thing', 'delete', 'posts', '--dry-run', '--yes']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ applied: false, plan }); + expect(result.json().meta.next).toEqual([{ command: 'demo thing delete posts --yes', argv: ['demo', 'thing', 'delete', 'posts', '--yes'], why: expect.any(String) }]); + expect(calls).toEqual([]); + }); + + it.each([[['--dry-run']], [['--yes']], [[]]])('stops a blocked call with the gate\'s failure (%j), and never runs it', async (flags) => { + ready = false; + const result = await run(['thing', 'delete', 'posts', ...flags]); + expect(result.code).toBe(1); + expect(result.json().error).toEqual({ + code: 'no-env', + message: 'No .env found in the project.', + hint: 'Create a thing first, then retry.' + }); + expect(calls).toEqual([]); + }); + + it('runs with --yes', async () => { + const result = await run(['thing', 'delete', 'posts', '--yes']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ deleted: 'posts' }); + expect(calls).toEqual([{ tool: 'delete_thing', params: { thing_name: 'posts' }, cwd }]); + }); + + it('asks the gate for a write, and returns options.next', async () => { + const write = await run(['thing', 'create', 'widgets', '--yes']); + expect(write.json().meta.next).toEqual([{ command: 'demo thing delete widgets', argv: ['demo', 'thing', 'delete', 'widgets'], why: 'Undo widgets' }]); + expect(prompted).toEqual(['create_thing']); + }); +}); + +describe('the interactive confirm', () => { + it('shows the plan and runs when the person approves', async () => { + const result = await run(['thing', 'delete', 'posts', '--json'], { tty: true, answers: [['Apply this change?', 'y\n']] }); + expect(result.code).toBe(0); + expect(result.stderr).toContain('Change the thing "posts".'); + expect(calls).toHaveLength(1); + }); + + it('fails with cancelled when the person declines', async () => { + const result = await run(['thing', 'delete', 'posts', '--json'], { tty: true, answers: [['Apply this change?', 'n\n']] }); + expect(result.code).toBe(1); + expect(result.json().error.code).toBe('cancelled'); + expect(calls).toEqual([]); + }); +}); + +describe('input', () => { + it('fails with invalid-input and names each bad flag when the tool schema, its input, rejects the params', async () => { + const result = await run(['thing', 'create', 'bad\u0001name', '--size', '0', '--yes']); + expect(result.code).toBe(2); + const { error } = result.json(); + expect(error.code).toBe('invalid-input'); + expect(error.details.issues.map((issue: { flag: string }) => issue.flag)).toEqual(['', '--size']); + expect(error.message).toContain(''); + expect(calls).toEqual([]); + expect(prompted).toEqual([]); + }); + + it('builds the params with mapInput from a friendlier input', async () => { + const result = await run(['thing', 'quick', 'widgets:3', '--yes']); + expect(result.code).toBe(0); + expect(calls).toEqual([{ tool: 'create_thing', params: { thing_name: 'widgets', size: 3 }, cwd }]); + }); + + it('validates what mapInput returns with the tool schema', async () => { + const result = await run(['thing', 'quick', 'widgets:none', '--yes']); + expect(result.code).toBe(2); + expect(result.json().error.details.issues.map((issue: { path: string }) => issue.path)).toEqual(['size']); + expect(calls).toEqual([]); + }); + + it('takes a nullable property as a flag and as null in --input', async () => { + await run(['thing', 'create', 'a', '--note', 'hi', '--yes']); + await run(['thing', 'create', '--input', '{"thing_name":"b","note":null}', '--yes']); + expect(calls.map((call) => call.params)).toEqual([{ thing_name: 'a', note: 'hi' }, { thing_name: 'b', note: null }]); + }); +}); + +describe('a call a tool suggests', () => { + it('becomes the first next step of a success, with a placeholder for an input left to choose', async () => { + const { meta } = (await run(['thing', 'suggest'])).json(); + expect(meta.next).toEqual([ + { command: 'demo thing delete old', argv: ['demo', 'thing', 'delete', 'old'], why: 'Delete the old thing' }, + expect.objectContaining({ argv: expect.arrayContaining(['demo', 'thing', 'create', '--size', '2']), placeholders: [expect.any(String)], why: 'Make a new one' }) + ]); + }); + + it('is written with the flags of the command bound to its tool, through the binding', async () => { + const renameTool = defineHarnessTool({ + name: 'rename_thing', + label: 'Rename thing', + description: 'Rename a thing.', + parameters: z.object({ old_name: z.string(), new_name: z.string() }), + effect: 'read', + async execute() { + return { content: [{ type: 'text', text: 'Renamed.' }], details: {}, calls: [{ tool: 'rename_thing', input: { old_name: 'a', new_name: 'b' }, why: 'Again' }] }; + } + }); + const renaming = createCli({ + name: 'demo', + version: '1.0.0', + commands: toCliCommands([ + toolCommand(renameTool, { + name: 'thing rename', + input: z.object({ from: z.string(), to: z.string() }), + positionals: ['from', 'to'], + mapInput: ({ from, to }: { from: string; to: string }) => ({ old_name: from, new_name: to }), + toInput: (params) => ({ from: params.old_name, to: params.new_name }) + }) + ], { gate }) + }); + const stdout = capture(); + await renaming.run(['thing', 'rename', 'x', 'y', '--json'], { stdin: new PassThrough(), stdout: stdout.stream, stderr: capture().stream, env: {}, cwd }); + expect(JSON.parse(stdout.text()).meta.next).toEqual([{ command: 'demo thing rename a b', argv: ['demo', 'thing', 'rename', 'a', 'b'], why: 'Again' }]); + }); +}); + +describe('a tool bound to two commands', () => { + const changeTool = defineHarnessTool({ + name: 'change_thing', + label: 'Change thing', + description: 'Rename or resize a thing.', + parameters: z.object({ thing_name: z.string(), new_name: z.string().optional(), new_size: z.number().optional() }), + effect: 'read', + async execute() { + const calls = [{ tool: 'change_thing', input: { thing_name: 'a', new_size: 2 }, why: 'Resize it' }]; + return { content: [], details: {}, failure: { code: 'conflict', message: 'It does not fit.', calls } }; + } + }); + const cli = createCli({ + name: 'demo', + version: '1.0.0', + commands: toCliCommands([ + toolCommand(changeTool, { + name: 'thing change', + input: z.object({ thing_name: z.string(), new_name: z.string().optional() }), + positionals: ['thing_name'], + mapInput: (input: { thing_name: string; new_name?: string }) => input + }), + toolCommand(changeTool, { + name: 'thing resize', + input: z.object({ thing_name: z.string(), size: z.number() }), + positionals: ['thing_name'], + mapInput: ({ thing_name, size }: { thing_name: string; size: number }) => ({ thing_name, new_size: size }), + toInput: (params) => (params.new_size === undefined ? undefined : { thing_name: params.thing_name, size: params.new_size }) + }) + ], { gate }) + }); + + it('writes a call as a step of the one command that takes its input', async () => { + const stdout = capture(); + await cli.run(['thing', 'change', 'x', '--json'], { stdin: new PassThrough(), stdout: stdout.stream, stderr: capture().stream, env: {}, cwd }); + expect(JSON.parse(stdout.text()).meta.next[0].argv).toEqual(['demo', 'thing', 'resize', 'a', '--size', '2']); + }); +}); + +describe('a tool failure', () => { + it.each([ + ['signed-out', 4], + ['app-signed-out', 4], + ['step-up-required', 4], + ['invalid-input', 2], + ['not-found', 1] + ] as const)('%s exits %i with the tool details', async (code, exitCode) => { + failure = { code, message: 'It failed.', hint: 'Retry.', retryable: true }; + const result = await run(['thing', 'connect']); + expect(result.code).toBe(exitCode); + expect(result.json().error).toEqual({ + code, + message: 'It failed.', + hint: 'Retry.', + retryable: true, + details: { connected: false, message: 'It failed.' } + }); + }); + + it('puts the error id and the backend context next to the tool details', async () => { + failure = { + code: 'query-too-large', + message: 'The query asks for more rows than this backend allows.', + errorId: '0123456789abcdef', + context: { cost: 1010100, limit: 1000000 } + }; + const { error } = (await run(['thing', 'connect'])).json(); + expect(error.details).toEqual({ + connected: false, + message: 'The query asks for more rows than this backend allows.', + errorId: '0123456789abcdef', + context: { cost: 1010100, limit: 1000000 } + }); + }); + + it('gives the next steps the CLI names for a failed call', async () => { + failure = { code: 'signed-out', message: 'No session.' }; + const result = await run(['thing', 'connect']); + expect(result.json().meta.next).toEqual([{ command: 'demo login', argv: ['demo', 'login'], why: 'Sign in' }]); + }); + + it('gives the next steps the CLI names for a blocked call', async () => { + ready = false; + const result = await run(['thing', 'delete', 'posts']); + expect(result.json().meta.next).toEqual([{ command: "demo db create 'my app'", argv: ['demo', 'db', 'create', 'my app'], why: 'Create a database for this directory' }]); + }); + + it('puts the calls a failure suggests first in the next steps, as commands, before the CLI\'s own', async () => { + failure = { + code: 'signed-out', + message: 'Refused.', + calls: [{ tool: 'create_thing', input: { thing_name: 'posts', replace: true }, why: 'Make it again' }] + }; + const { meta } = (await run(['thing', 'connect'])).json(); + expect(meta.next).toEqual([ + { command: 'demo thing create posts --replace', argv: ['demo', 'thing', 'create', 'posts', '--replace'], why: 'Make it again' }, + { command: 'demo login', argv: ['demo', 'login'], why: 'Sign in' } + ]); + }); + + it('gives no step, and does not fail the command, for a call no command can render', async () => { + unrendered.length = 0; + failure = { + code: 'failed', + message: 'Refused.', + calls: [ + { tool: 'unbound_tool', input: {}, why: 'Nothing renders it' }, + { tool: 'create_thing', input: { thing_name: 'posts', colour: 'red' }, why: 'A key the command lacks' } + ] + }; + const result = await run(['thing', 'connect']); + expect(result.json().error.code).toBe('failed'); + expect(result.json().meta.next ?? []).toEqual([]); + expect(unrendered.map((entry) => entry.tool)).toEqual(['unbound_tool', 'create_thing']); + }); +}); + +describe('toolCallStep', () => { + const entries = [ + toolCommand(deleteTool, { name: 'thing delete', positionals: ['thing_name'] }), + toolCommand(createTool, { + name: 'thing quick', + input: quickInput, + positionals: ['spec'], + mapInput: ({ spec }: { spec: string }) => { + const [thing_name, size] = spec.split(':'); + return { thing_name, size: Number(size) }; + } + }), + toolCommand(createTool, { name: 'thing create', positionals: ['thing_name'] }), + toolCommand(connectTool, { name: 'thing connect' }) + ]; + const call = { tool: 'create_thing', input: { thing_name: 'posts', replace: true }, why: 'Make it again' }; + const step = toolCallStep(entries); + // A command that renders the call with the renderer, inside a run, as a host such as the CLI's mcp command does. + const probe: CommandDefinition = { + name: 'probe', + summary: 'Render a call', + effect: 'read', + run: (_input, ctx) => ({ + data: { plain: step(call, ctx), dropped: step(call, ctx, { drop: ['--as'] }), unbound: step({ tool: 'unbound_tool', input: {}, why: 'None' }, ctx) ?? null } + }) + }; + const carrying = createCli({ + name: 'demo', + version: '1.0.0', + globals: z.object({ as: z.string().optional().meta({ description: 'Run as this agent', 'x-carry': true }) }), + commands: [...toCliCommands(entries, { gate }), probe] + }); + const runCarrying = async (argv: string[]) => { + const stdout = capture(); + await carrying.run(argv, { stdin: new PassThrough(), stdout: stdout.stream, stderr: capture().stream, env: {}, cwd }); + return JSON.parse(stdout.text()); + }; + + it('writes a call as the same command the steps of a failure give', async () => { + failure = { code: 'failed', message: 'Refused.', calls: [call] }; + const fromFailure = (await runCarrying(['thing', 'connect', '--as', 'helper'])).meta.next[0]; + const { data } = await runCarrying(['probe', '--as', 'helper']); + expect(data.plain).toEqual(fromFailure); + expect(data.plain.argv).toEqual(['demo', '--as', 'helper', 'thing', 'create', 'posts', '--replace']); + expect(data.unbound).toBeNull(); + }); + + it('passes its step options on, so a carried flag can be left out', async () => { + const { data } = await runCarrying(['probe', '--as', 'helper']); + expect(data.dropped.argv).toEqual(['demo', 'thing', 'create', 'posts', '--replace']); + expect(data.dropped.why).toBe('Make it again'); + }); +}); diff --git a/agentic/command/jest.config.js b/agentic/command/jest.config.js new file mode 100644 index 0000000000..8a26efd6d0 --- /dev/null +++ b/agentic/command/jest.config.js @@ -0,0 +1,21 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + babelConfig: false, + tsconfig: 'tsconfig.json', + }, + ], + }, + transformIgnorePatterns: [`/node_modules/*`], + testRegex: '(/__tests__/.*\\.(test|spec))\\.(jsx?|tsx?)$', + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], + modulePathIgnorePatterns: ['dist/*'], + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, +}; diff --git a/agentic/command/package.json b/agentic/command/package.json new file mode 100644 index 0000000000..f867b841e2 --- /dev/null +++ b/agentic/command/package.json @@ -0,0 +1,42 @@ +{ + "name": "@agentic-kit/command", + "version": "0.1.0", + "author": "Constructive ", + "description": "the typed command layer of the Constructive CLI on zod, with one approval step for every change, and the binding of a HarnessTool to a command", + "main": "index.js", + "module": "esm/index.js", + "types": "index.d.ts", + "homepage": "https://github.com/constructive-io/constructive", + "license": "SEE LICENSE IN LICENSE", + "publishConfig": { + "access": "public", + "directory": "dist" + }, + "repository": { + "type": "git", + "url": "https://github.com/constructive-io/constructive" + }, + "bugs": { + "url": "https://github.com/constructive-io/constructive/issues" + }, + "scripts": { + "clean": "makage clean", + "prepack": "npm run build", + "build": "makage build", + "build:dev": "makage build --dev", + "lint": "eslint . --fix", + "test": "jest", + "test:watch": "jest --watch" + }, + "dependencies": { + "@agentic-kit/harness": "workspace:^", + "inquirerer": "^4.9.4", + "zod": "^4.4.3" + }, + "keywords": [ + "agentic-kit", + "cli", + "tools", + "inquirerer" + ] +} diff --git a/agentic/command/src/approval.ts b/agentic/command/src/approval.ts new file mode 100644 index 0000000000..0ace232fb2 --- /dev/null +++ b/agentic/command/src/approval.ts @@ -0,0 +1,65 @@ +import { type ConfirmPrompt, renderPlan } from '@agentic-kit/harness'; + +import { layerError } from './input'; +import { type ChangeCommand, CliError, type CommandContext, type CommandErrorCode, type CommandResult, ExitCode } from './types'; + +/** What the layer does with a planned change, from the flags and the terminal of the run alone. */ +export type Approval = 'show-plan' | 'apply' | 'ask' | 'approval-required'; + +/** --dry-run shows the plan, --yes approves it, a terminal asks, and anything else stops before the change. */ +export function decideApproval(run: { dryRun: boolean; yes: boolean; interactive: boolean }): Approval { + if (run.dryRun) return 'show-plan'; + if (run.yes) return 'apply'; + return run.interactive ? 'ask' : 'approval-required'; +} + +/** The data of a `--dry-run`: nothing was changed, and this is what would be. */ +export interface PlanData { + applied: false; + plan: ConfirmPrompt; +} + +async function confirmed(ctx: CommandContext, plan: ConfirmPrompt): Promise { + const answers = await ctx.prompter.prompt<{ yes?: boolean }>({}, [ + { type: 'confirm', name: 'yes', message: `${renderPlan(plan)}\n\nApply this change?`, default: false } + ]); + return answers.yes === true; +} + +/** Plans the change, and applies it only when the run approves that plan: the one approval step of every change. */ +export async function runChange( + command: ChangeCommand, + input: Record, + ctx: CommandContext, + dryRun: boolean +): Promise> { + const planned = await command.plan(input, ctx); + const { plan } = planned; + const approve = [...(ctx.interactive ? [] : planned.needs ?? []), '--yes']; + switch (decideApproval({ dryRun, yes: ctx.yes, interactive: ctx.interactive })) { + case 'show-plan': { + const data: PlanData = { applied: false, plan }; + return { + data, + text: renderPlan(plan), + next: [ctx.followUp(approve, { drop: ['dry-run', 'yes'], why: 'Apply the change once the person approves the plan' })] + }; + } + case 'apply': + return command.apply(input, planned, ctx); + case 'ask': + if (await confirmed(ctx, plan)) return command.apply(input, planned, ctx); + throw layerError({ code: 'cancelled', message: 'The change was not approved, so nothing was changed.', exitCode: ExitCode.failure }); + case 'approval-required': + if (ctx.format === 'text') ctx.stderr.write(`${renderPlan(plan)}\n\n`); + // The command wrote the plan, so the error is not the layer's own text: it is searched for secrets like any other. + throw new CliError({ + code: 'approval-required', + message: 'This change needs approval, and prompts are off, so nothing was changed.', + hint: 'Show the plan to the person. When they approve it, run the same command with --yes.', + next: [ctx.followUp(approve, { drop: ['yes'], why: 'Apply the change once the person approves the plan' })], + exitCode: ExitCode.approvalRequired, + details: { plan } + }); + } +} diff --git a/agentic/command/src/cli.ts b/agentic/command/src/cli.ts new file mode 100644 index 0000000000..d661c48334 --- /dev/null +++ b/agentic/command/src/cli.ts @@ -0,0 +1,785 @@ +import { Inquirerer, parseArgv } from 'inquirerer'; +import { resolve as resolvePath } from 'path'; +import { Readable, Writable } from 'stream'; +import { isatty } from 'tty'; +import { z } from 'zod'; + +import { runChange } from './approval'; +import { buildManifest, commandHelp, commandSchema, groupHelp, llmsIndex, rootHelp, type Shown, topicPage } from './help'; +import { + askFor, + buildFlagTable, + closest, + type CommandLine, + commandLine, + type FlagDef, + type FlagTable, + inputWords, + isLayerError, + isPlainObject, + jsonSchemaOf, + kebabCase, + LAYER_FLAGS, + LAYER_INPUT, + layerError, + type LayerFlags, + nearness, + orList, + own, + parseInput, + readInput, + readLayerFlags, + readScope, + redactText, + requestedFormat, + type Scope, + searchPatterns, + splitSecrets, + type StepBuilder, + stepBuilder, + type Token, + tokenize, + usageError +} from './input'; +import { + type ChangeCommand, + type Cli, + type CliConfig, + CliError, + type CliIO, + type CommandContext, + type CommandDefinition, + type CommandErrorCode, + type CommandResult, + type Effect, + ExitCode, + type HelpTopic, + type InputSchema, + isCliError, + type NextStep, + type PassthroughCommand, + type ReadCommand +} from './types'; + +type Format = 'text' | 'json'; + +/** `path` holds the argv indexes of the words that named the group or command. */ +type Resolution = + | { kind: 'root' } + | { kind: 'group'; group: string; path: Set } + | { kind: 'command'; command: CommandDefinition; path: Set } + | { kind: 'unknown'; words: string[] }; + +/** The kinds of command, by what the layer does before it hands over: nothing, the input, or the input and the approval. */ +type Kind = 'read' | 'change' | 'immediate' | 'serve' | 'passthrough'; + +/** After SIGINT, how long the command may take to settle before the interrupt is reported anyway. */ +const SETTLE_LIMIT_MS = 2000; +const COMMAND_NAME = /^[a-z0-9][\w-]*( [a-z0-9][\w-]*)*$/i; +const TOPIC_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/; +/** A Markdown heading outside fenced code. */ +const HEADING = /^ {0,3}#{1,6}(\s|$)/m; +const FENCED = /^ {0,3}```[\s\S]*?^ {0,3}```/gm; + +const HELP_INPUT = z.object({ + name: z.array(z.string()).optional().describe('The words of a command or of a group of commands, or the name of a help topic; none for the help of the CLI') +}); + +const HELP_PAGE = z.object({ + kind: z.enum(['cli', 'group', 'command', 'topic']).describe('What the page is the help of'), + name: z.string().describe('The name of the CLI, the group, the command or the topic'), + text: z.string().describe('The page, as help prints it') +}); + +type HelpPage = z.output; + +/** Throws a plain Error on a definition mistake, as for a command. `taken` holds every command and group name. */ +function checkTopics(topics: HelpTopic[], taken: Set): void { + const names = new Set(); + const sections = new Map(); + for (const topic of topics) { + const owner = `The help topic "${topic.name}"`; + if (!TOPIC_NAME.test(topic.name)) throw new Error(`${owner} has an invalid name. Use lower-case words joined by "-", for example "exit-codes".`); + if (names.has(topic.name)) throw new Error(`${owner} is defined twice. Give each topic a unique name.`); + if (taken.has(topic.name)) throw new Error(`${owner} has the name of a command or a group, so "help ${topic.name}" could not tell them apart. Rename the topic.`); + if (HEADING.test(topic.body.replace(FENCED, ''))) { + throw new Error(`${owner} has a heading in its body, but a topic body has no headings, because the reference makes the topic one section of its own. Use paragraphs and lists.`); + } + if (topic.section && sections.has(topic.section)) { + throw new Error(`${owner} fills the section ${topic.section}, which the topic "${sections.get(topic.section)}" fills too. Give the section to one of them.`); + } + if (topic.section) sections.set(topic.section, topic.name); + names.add(topic.name); + } +} + +const isTerminal = (stream: Readable | Writable): boolean => (stream as { isTTY?: boolean }).isTTY === true; + +const isFunction = (value: unknown): boolean => typeof value === 'function'; + +/** + * The kind of a command, checked against what it defines: a change must have `plan` and `apply` and no `run`, so no + * command can run a change past the layer's approval. Throws a plain Error on a definition mistake. + */ +function kindOf(command: CommandDefinition, owner: string): Kind { + const shape = command as unknown as Record; + const has = (key: string) => isFunction(shape[key]); + const effect = shape.effect; + if (effect !== 'read' && effect !== 'write' && effect !== 'destructive') { + throw new Error(`${owner} has the effect ${JSON.stringify(effect)}. Give it "read", "write" or "destructive".`); + } + if (shape.passthrough !== undefined) { + if (!has('passthrough') || has('run') || has('plan') || has('apply') || has('serve') || shape.input !== undefined || shape.positionals !== undefined) { + throw new Error(`${owner} is a passthrough command, so it has passthrough() alone, and no input schema or positionals. Remove the rest, or remove passthrough.`); + } + return 'passthrough'; + } + if (has('serve')) { + if (shape.stdout !== 'reserved' || has('run') || has('plan') || has('apply')) { + throw new Error(`${owner} serves a protocol, so it has serve() alone and stdout: 'reserved'. Remove run, plan and apply.`); + } + return 'serve'; + } + if (shape.stdout !== undefined) throw new Error(`${owner} reserves stdout, which only a command with serve() does.`); + if (shape.immediate !== undefined) { + if (shape.immediate !== true || effect !== 'write' || !has('run') || has('plan') || has('apply')) { + throw new Error(`${owner} runs at once (immediate: true), so it is a "write" with run() and no plan or apply. Give it a plan instead if it can lose data or widen access.`); + } + return 'immediate'; + } + if (effect === 'read') { + if (!has('run') || has('plan') || has('apply')) throw new Error(`${owner} is a "read" command, so it has run() and no plan or apply.`); + return 'read'; + } + if (!has('plan') || !has('apply') || has('run')) { + throw new Error( + `${owner} has the effect "${effect}", so it has plan() and apply() and no run(): the layer shows the plan, ` + + 'and calls apply only once the run approves it (--yes, or a yes on a terminal). ' + + 'A write the person makes to their own local session, with nothing to approve, is immediate: true with run().' + ); + } + return 'change'; +} + +async function readAll(stream: Readable): Promise { + const chunks: Buffer[] = []; + for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + return Buffer.concat(chunks).toString('utf8'); +} + +/** + * Keeps only the given dot paths of `data`; an array maps over its elements. Each path that matched somewhere is + * added to `matched` (in an empty array every path counts as matched, since no element can disprove it). + */ +function pick(data: unknown, paths: string[], matched: Set, prefix = ''): unknown { + if (Array.isArray(data)) { + if (data.length === 0) paths.forEach((path) => matched.add(prefix + path)); + return data.map((item) => pick(item, paths, matched, prefix)); + } + if (!isPlainObject(data)) return data; + const byHead = new Map(); + for (const path of paths) { + const [head, ...rest] = path.split('.'); + byHead.set(head, [...(byHead.get(head) ?? []), rest.join('.')]); + } + const picked: Array<[string, unknown]> = []; + for (const [head, tails] of byHead) { + if (!Object.hasOwn(data, head)) continue; + if (tails.includes('')) { + picked.push([head, data[head]]); + tails.forEach((tail) => matched.add(prefix + (tail ? `${head}.${tail}` : head))); + } else { + picked.push([head, pick(data[head], tails, matched, `${prefix}${head}.`)]); + } + } + return Object.fromEntries(picked); +} + +function unmatchedFields(unmatched: string[], command: string, data: unknown): { message: string; keys: string } { + const sample = Array.isArray(data) ? data[0] : data; + const keys = isPlainObject(sample) ? Object.keys(sample) : []; + return { + message: `--fields ${orList(unmatched.map((path) => `"${path}"`), 'and')} matched nothing in the data of "${command}".`, + keys: keys.length ? `The data has the keys ${keys.join(', ')}.` : 'The data has no keys to select.' + }; +} + +const cell = (value: unknown): string => + value === null || value === undefined ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value); + +function renderTable(rows: Record[]): string { + const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))]; + const cells = [keys, ...rows.map((row) => keys.map((key) => cell(row[key])))]; + const widths = keys.map((_, index) => Math.max(...cells.map((line) => line[index].length))); + return cells.map((line) => line.map((value, index) => value.padEnd(widths[index])).join(' ').trimEnd()).join('\n'); +} + +function renderData(data: unknown): string { + if (data === null || data === undefined) return ''; + if (Array.isArray(data)) { + if (data.length === 0) return '(none)'; + return data.every(isPlainObject) ? renderTable(data) : data.map(cell).join('\n'); + } + if (isPlainObject(data)) { + return Object.entries(data) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => `${key}: ${cell(value)}`) + .join('\n'); + } + return String(data); +} + +const nextBlock = (next: NextStep[]): string => + ['Next:', ...next.map((step) => (step.why ? ` ${step.command} # ${step.why}` : ` ${step.command}`))].join('\n'); + +/** + * Writes a run's output. `print` and `json` are for what a person asks for (help, --version, --schema, --llms) and + * go to stdout. Results and errors go to `results`: stdout, or stderr for a command whose stdout is reserved. + */ +class Output { + private patterns: string[] = []; + + constructor( + readonly format: Format, + private readonly stdout: Writable, + private readonly stderr: Writable, + private readonly results: Writable, + private readonly debug: boolean, + private readonly command: string | undefined + ) {} + + /** The secrets that text written by the command (not by the layer) is searched for. */ + useSecrets(secrets: string[]): void { + this.patterns = searchPatterns(secrets); + } + + print(text: string): number { + this.stdout.write(text.endsWith('\n') ? text : `${text}\n`); + return ExitCode.ok; + } + + json(value: unknown): number { + return this.print(JSON.stringify(value, null, 2)); + } + + private emit(text: string): void { + this.results.write(text.endsWith('\n') ? text : `${text}\n`); + } + + private emitJson(value: unknown): void { + this.emit(JSON.stringify(value, null, 2)); + } + + /** A --fields path that matches nothing fails a read; after a change it is only a warning, since the change ran. */ + success(result: CommandResult, fields: string[] | undefined, effect: Effect): number { + const matched = new Set(); + const data = fields ? pick(result.data ?? null, fields, matched) : result.data ?? null; + const unmatched = fields?.filter((field) => !matched.has(field)) ?? []; + const warnings = (result.warnings ?? []).map((warning) => this.redact(warning)); + if (unmatched.length) { + const { message, keys } = unmatchedFields(unmatched, this.command, result.data ?? null); + if (effect === 'read') { + return this.error(usageError('invalid-input', message, { hint: keys, details: { flag: '--fields', unmatched } })); + } + warnings.push(`${message} ${keys}`); + } + const next = this.steps(result.next); + if (this.format === 'json') { + this.emitJson({ ok: true, data, meta: { command: this.command, next, warnings: warnings.length ? warnings : undefined } }); + return ExitCode.ok; + } + const body = !fields && result.text !== undefined ? result.text : renderData(data); + if (body) this.emit(body); + if (next) this.emit(nextBlock(next)); + for (const warning of warnings) this.stderr.write(`Warning: ${warning}\n`); + return ExitCode.ok; + } + + error(thrown: unknown): number { + const search = !isLayerError(thrown); + const redact = (text: string): string => (search ? this.redact(text) : text); + const stack = !isCliError(thrown) && this.debug && thrown instanceof Error ? redact(thrown.stack ?? '') : undefined; + const error = isCliError(thrown) + ? thrown + : new CliError({ + code: 'failed', + message: thrown instanceof Error ? thrown.message : String(thrown), + hint: this.debug ? undefined : 'Rerun with DEBUG=1 to see the stack trace.', + details: stack ? { stack } : undefined + }); + const message = redact(error.message); + const cause = error.cause === undefined ? undefined : redact(error.cause); + const hint = error.hint === undefined ? undefined : redact(error.hint); + const next = search ? this.steps(error.next) : error.next; + if (this.format === 'json') { + this.emitJson({ + ok: false, + error: { code: error.code, message, cause, hint, retryable: error.retryable, details: search ? this.redactDeep(error.details) : error.details }, + meta: { command: this.command, next } + }); + return error.exitCode; + } + const lines = [`Error (${error.code}): ${message}`]; + if (cause) lines.push(`Cause: ${cause}`); + if (hint) lines.push(`Hint: ${hint}`); + if (next) lines.push(nextBlock(next)); + if (stack) lines.push(stack); + this.stderr.write(`${lines.join('\n')}\n`); + return error.exitCode; + } + + private steps(next: NextStep[] | undefined): NextStep[] | undefined { + if (!next?.length) return undefined; + return next.map((step) => ({ + command: this.redact(step.command), + argv: step.argv?.map((word) => this.redact(word)), + placeholders: step.placeholders, + why: this.redact(step.why) + })); + } + + private redact(text: string): string { + return redactText(text, this.patterns); + } + + private redactDeep(value: unknown): unknown { + if (typeof value === 'string') return this.redact(value); + if (Array.isArray(value)) return value.map((item) => this.redactDeep(item)); + if (isPlainObject(value)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.redactDeep(item)])); + } + return value; + } +} + +/** Why prompts are off, or undefined when the session is interactive. */ +function promptBlocker(stdinIsTerminal: boolean, stdoutIsTerminal: boolean, layer: LayerFlags, env: NodeJS.ProcessEnv): string | undefined { + if (layer.noInput) return '--no-input was given'; + if (!layer.tty) return '--tty false was given'; + if (env.CI) return 'the CI environment variable is set'; + if (!stdinIsTerminal) return 'stdin is not a terminal'; + if (!stdoutIsTerminal) return 'stdout is not a terminal'; + return undefined; +} + +const helpStep = ({ path, step }: Scope, why: string): NextStep => step([...path, '--help'], why); + +function rejectUnknownFlags(tokens: Token[], table: FlagTable, scope: Scope): void { + const { usage } = scope; + const unknown = tokens.find((token): token is Extract => token.kind === 'unknown'); + if (!unknown) return; + const typed = unknown.flag.replace(/^-+/, ''); + const suggestions = closest(kebabCase(typed) || typed, table.flags.map((def) => def.flag)).map((flag) => `--${flag}`); + throw usageError('unknown-flag', `${unknown.flag} is not a flag of "${usage}".`, { + hint: suggestions.length ? `Did you mean ${orList(suggestions)}?` : `Run "${usage} --help" to list the flags.`, + next: [helpStep(scope, 'List the flags')], + details: { flag: unknown.flag, suggestions } + }); +} + +function rejectPositionals(tokens: Token[], scope: Scope): void { + const { usage } = scope; + const extra = tokens.find((token): token is Extract => token.kind === 'positional'); + if (!extra) return; + throw usageError('unexpected-argument', `"${usage}" takes no arguments, but got "${extra.value}".`, { + hint: `Run "${usage} --help" to list the commands.`, + next: [helpStep(scope, 'List the commands')] + }); +} + +function missingInput(scope: Scope, missing: FlagDef[], blocker: string): CliError { + const { usage } = scope; + const flags = missing.map((def) => `--${def.flag}`); + return usageError('missing-input', `"${usage}" needs ${orList(flags, 'and')}.`, { + cause: `No value was given, and prompts are off because ${blocker}.`, + hint: `Pass ${flags.length === 1 ? 'it as a flag' : 'them as flags'}, or pass the whole input with --input '', --input @file.json or --input - (stdin).`, + next: [scope.step([...scope.path, '--schema'], 'See every input property')], + details: { missing: flags } + }); +} + +/** A command that changes at once has no plan to show, so it has no dry run. */ +function rejectDryRun(layer: LayerFlags, scope: Scope, why: string): void { + if (!layer.dryRun) return; + throw usageError('dry-run-unsupported', `"${scope.usage}" has no dry run: ${why}.`, { + hint: `Run it without --dry-run. Run "${scope.usage} --help" to see what it changes.`, + next: [helpStep(scope, 'See what the command changes')], + details: { flag: '--dry-run' } + }); +} + +/** A command that serves a protocol has no plan of the layer's, so it takes neither --dry-run nor --yes. */ +function rejectApprovalFlags(layer: LayerFlags, scope: Scope): void { + rejectDryRun(layer, scope, 'it serves a protocol, and its client approves each change made through it'); + if (layer.yes) { + throw usageError('invalid-input', `--yes does not apply to "${scope.usage}": it approves nothing here, because its client approves each change made through it.`, { + hint: 'Run it without --yes.', + next: [helpStep(scope, 'See what the command serves')], + details: { flag: '--yes' } + }); + } +} + +/** A usage error of a command that names no next step gets the step every such error has: the command's --schema. */ +function withSchemaStep(error: unknown, scope: Scope): unknown { + if (!isLayerError(error) || error.exitCode !== ExitCode.usage || error.next?.length) return error; + const { code, message, cause, hint, retryable, exitCode, details } = error; + return layerError({ code, message, cause, hint, retryable, exitCode, details, next: [scope.step([...scope.path, '--schema'], 'See the input schema')] }); +} + +/** + * Runs `work` to the end, or until SIGINT: then it aborts the signal, waits up to SETTLE_LIMIT_MS for `work` to + * settle, and fails with `interrupted` whatever `work` did after the abort. + */ +async function untilInterrupted(controller: AbortController, work: () => Promise): Promise { + const onSigint = (): void => controller.abort(); + process.on('SIGINT', onSigint); + try { + const task = work(); + const settled = task.then(() => true, () => true); + const aborted = new Promise((resolve) => controller.signal.addEventListener('abort', () => resolve(false), { once: true })); + if (await Promise.race([settled, aborted])) return await task; + let timer: ReturnType; + const limit = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), SETTLE_LIMIT_MS); + }); + const stopped = await Promise.race([settled, limit]); + clearTimeout(timer); + throw layerError({ + code: 'interrupted', + message: 'The command was interrupted (SIGINT).', + cause: stopped ? undefined : `The command did not stop within ${SETTLE_LIMIT_MS / 1000} s of the interrupt, so it may still be running.`, + exitCode: ExitCode.interrupted + }); + } finally { + process.off('SIGINT', onSigint); + } +} + +const positionalsOf = (command: CommandDefinition): string[] => ('passthrough' in command ? [] : command.positionals ?? []); + +export function createCli(definition: CliConfig): Cli { + const reserved = definition.commands.find((command) => command.name === 'help' || command.name.startsWith('help ')); + if (reserved) { + throw new Error( + `The command "${reserved.name}" uses the name help, which is built into the command layer: it prints the help of the CLI, of a command or a group, and of a help topic. Rename the command.` + ); + } + const byName = new Map(); + const kinds = new Map(); + const groups = new Set(); + const shown = new Map(); + const topics = definition.topics ?? []; + + /** The page `help ` prints: of the CLI, a command, a group or a topic; any other words are unknown-topic. */ + function helpPage(words: string[], next: StepBuilder): HelpPage { + const name = words.join(' '); + if (!words.length) return { kind: 'cli', name: config.name, text: rootHelp(config, rootTable) }; + const command = byName.get(name); + if (command) return { kind: 'command', name, text: commandHelp(config, command, shownOf(command)) }; + if (groups.has(name)) return { kind: 'group', name, text: groupHelp(config, name) }; + const topic = topics.find((item) => item.name === name); + if (topic) return { kind: 'topic', name, text: topicPage(topic) }; + const named = [...config.commands.filter((item) => !item.hidden).map((item) => item.name), ...groups, ...topics.map((item) => item.name)]; + const suggestions = closest(name, named); + throw usageError('unknown-topic', `"${name}" is not a command, a group of commands or a help topic of ${config.name}.`, { + hint: suggestions.length ? `Did you mean ${orList(suggestions.map((item) => `"${item}"`))}?` : `Run "${config.name} help" to list the commands and the help topics.`, + next: [next(['help'], 'List the commands and the help topics')], + details: { suggestions } + }); + } + + const help: ReadCommand = { + name: 'help', + summary: 'Show the help of the CLI, a command, a group or a help topic', + effect: 'read', + positionals: ['name'], + input: HELP_INPUT, + output: HELP_PAGE, + run: ({ name = [] }, ctx) => { + const page = helpPage(name, ctx.next); + return { data: page, text: page.text }; + } + }; + const config: CliConfig = { ...definition, topics, commands: [...definition.commands, help] }; + const globalsJson = config.globals ? jsonSchemaOf(config.globals, 'input') : undefined; + const globalSource = { scope: 'global' as const, schema: config.globals, json: globalsJson }; + const layerSource = { scope: 'layer' as const, schema: LAYER_INPUT, json: LAYER_FLAGS }; + const rootTable = buildFlagTable(`The CLI "${config.name}"`, [globalSource, layerSource]); + + for (const command of config.commands) { + const owner = `The command "${command.name}"`; + if (!COMMAND_NAME.test(command.name)) { + throw new Error(`${owner} has an invalid name. Use words separated by single spaces, for example "table add".`); + } + if (byName.has(command.name)) throw new Error(`${owner} is defined twice. Give each command a unique name.`); + kinds.set(command, kindOf(command, owner)); + const input = 'passthrough' in command ? undefined : command.input; + const inputJson = input ? jsonSchemaOf(input, 'input') : undefined; + for (const name of positionalsOf(command)) { + if (!own(inputJson?.properties, name)) { + throw new Error(`${owner} lists the positional "${name}", but its input schema has no such property. Add the property, or remove the positional.`); + } + } + const output = 'passthrough' in command ? undefined : command.output; + shown.set(command, { + input: inputJson, + output: output ? jsonSchemaOf(output, 'output') : undefined, + table: buildFlagTable(owner, [{ scope: 'input', schema: input, json: inputJson }, globalSource, layerSource]) + }); + byName.set(command.name, command); + const words = command.name.split(' '); + for (let length = 1; length < words.length; length++) groups.add(words.slice(0, length).join(' ')); + } + checkTopics(topics, new Set([...byName.keys(), ...groups])); + + const shownOf = (command: CommandDefinition): Shown => shown.get(command); + const manifest = () => buildManifest(config, globalsJson, shownOf); + + function resolve(argv: string[]): Resolution { + const words: Array<{ value: string; index: number }> = []; + for (const token of tokenize(argv, rootTable)) { + if (token.kind === 'positional') words.push(token); + else if (token.kind !== 'flag') break; + } + const indexes = (length: number) => new Set(words.slice(0, length).map((word) => word.index)); + for (let length = words.length; length > 0; length--) { + const command = byName.get(words.slice(0, length).map((word) => word.value).join(' ')); + if (command) return { kind: 'command', command, path: indexes(length) }; + } + if (words.length === 0) return { kind: 'root' }; + const group = words.map((word) => word.value).join(' '); + return groups.has(group) + ? { kind: 'group', group, path: indexes(words.length) } + : { kind: 'unknown', words: words.map((word) => word.value) }; + } + + function unknownCommand(words: string[], step: StepBuilder): CliError { + let length = 1; + while (length < words.length && groups.has(words.slice(0, length).join(' '))) length++; + const attempted = words.slice(0, length).join(' '); + const group = length > 1 ? words.slice(0, length - 1).join(' ') : undefined; + const suggestions = config.commands + .filter((command) => !command.hidden) + .map((command) => ({ name: command.name, distance: nearness(words.slice(0, command.name.split(' ').length).join(' '), command.name) })) + .filter(({ distance }) => distance !== undefined) + .sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name)) + .slice(0, 3) + .map(({ name }) => name); + const listingPath = group ? group.split(' ') : []; + const listing = [config.name, ...listingPath].join(' '); + return usageError('unknown-command', `"${attempted}" is not a ${config.name} command.`, { + hint: suggestions.length + ? `Did you mean ${orList(suggestions.map((name) => `"${name}"`))}?` + : `Run "${listing} --help" to list the commands.`, + next: [helpStep({ usage: listing, path: listingPath, step }, 'List the commands')], + details: { suggestions } + }); + } + + function showRegistry(resolution: Extract, tokens: Token[], output: Output, cwd: string, step: StepBuilder): number { + const path = resolution.kind === 'group' ? resolution.group.split(' ') : []; + const scope: Scope = { usage: [config.name, ...path].join(' '), path, step }; + rejectUnknownFlags(tokens, rootTable, scope); + rejectPositionals(tokens, scope); + const layer = readLayerFlags(tokens, cwd); + const help = resolution.kind === 'group' ? groupHelp(config, resolution.group) : rootHelp(config, rootTable); + if (layer.help) return output.print(help); + if (layer.version) return output.print(config.version); + if (layer.llms) return layer.format === 'json' ? output.json(manifest()) : output.print(llmsIndex(config, shownOf)); + if (layer.schema) { + const example = config.commands.find((command) => !command.hidden)?.name ?? ''; + throw usageError('invalid-input', '--schema needs a command.', { + hint: `Name the command first, for example "${config.name} ${example} --schema".`, + details: { flag: '--schema' } + }); + } + return output.print(help); + } + + /** The values of the CLI's global flags, parsed by its zod schema; `lenient` keeps what reads for a passthrough command. */ + function readGlobals(tokens: Token[], cwd: string, lenient: boolean): Record { + const values = readScope(tokens, 'global', cwd, lenient); + if (!config.globals) return values; + if (lenient) { + const parsed = config.globals.safeParse(values); + return parsed.success ? parsed.data : values; + } + const labels = new Map(Object.keys(values).map((property) => [property, `--${kebabCase(property)}`])); + return parseInput(config.globals, globalsJson, values, labels, `Run "${config.name} --help" to see the global flags.`); + } + + async function runCommand( + command: CommandDefinition, + tokens: Token[], + rest: string[], + line: CommandLine, + step: StepBuilder, + output: Output, + io: CliIO & { stdout: Writable; stderr: Writable; env: NodeJS.ProcessEnv; cwd: string } + ): Promise { + const kind = kinds.get(command); + const { table, input: inputJson } = shownOf(command); + const usage = `${config.name} ${command.name}`; + const scope: Scope = { usage, path: command.name.split(' '), step }; + // A passthrough command owns its arguments, so the layer reads its own flags there without refusing any. + const lenient = kind === 'passthrough'; + const layer = readLayerFlags(tokens, io.cwd, lenient); + if (!lenient) { + rejectUnknownFlags(tokens, table, scope); + if (layer.help) return output.print(commandHelp(config, command, shownOf(command))); + if (layer.version) return output.print(config.version); + if (layer.llms) return layer.format === 'json' ? output.json(manifest()) : output.print(llmsIndex(config, shownOf)); + if (layer.schema) return output.json(commandSchema(command, shownOf(command))); + if (kind === 'serve') rejectApprovalFlags(layer, scope); + if (kind === 'immediate') rejectDryRun(layer, scope, 'it makes its change as soon as it runs'); + } + + const cwd = layer.cwd ? resolvePath(io.cwd, layer.cwd) : io.cwd; + const stdin = (): Readable => io.stdin ?? process.stdin; + const blocker = promptBlocker(io.stdin ? isTerminal(io.stdin) : isatty(0), isTerminal(io.stdout), layer, io.env); + const interactive = blocker === undefined; + const controller = new AbortController(); + const globals = readGlobals(tokens, cwd, lenient); + let prompter: Inquirerer | undefined; + const ctx: CommandContext = { + cliName: config.name, + invocation: line.invocation, + followUp: (flags, options) => { + if (options.command !== undefined && !byName.has(options.command)) { + throw new Error(`followUp cannot use "${options.command}", because it is not a command of ${config.name}. Name a registered command.`); + } + return line.followUp(flags, options); + }, + next: step, + nextFor: (name, input, why, options) => { + const target = byName.get(name); + if (!target) throw new Error(`nextFor cannot build a step for "${name}", because it is not a command of ${config.name}. Name a registered command.`); + return step([...name.split(' '), ...inputWords(positionalsOf(target), shownOf(target).table, input, `${config.name} ${name}`)], why, options); + }, + cwd, + interactive, + format: output.format, + yes: layer.yes, + globals, + signal: controller.signal, + // A getter, so that process.stdin is only opened when the command reads it. + get stdin(): Readable { + return stdin(); + }, + stdout: io.stdout, + stderr: io.stderr, + env: io.env, + get prompter(): Inquirerer { + // A layer prompt keeps the output of earlier commands on the screen, and a prompt with no answer cancels the command. + prompter ??= new Inquirerer({ + noTty: !interactive, + input: stdin(), + output: io.stderr, + clearScreen: false, + onCancel: (reason) => { + switch (reason) { + case 'interrupt': + return layerError({ + code: 'cancelled', + message: 'The command was cancelled at a prompt (Ctrl-C). Nothing was changed by this step.', + exitCode: ExitCode.interrupted + }); + case 'end-of-input': + return layerError({ + code: 'cancelled', + message: 'The input ended before the prompt got an answer. Nothing was changed by this step.', + exitCode: ExitCode.failure + }); + } + } + }); + return prompter; + } + }; + + /** The input, read from --input, the arguments and the flags, asked for on a terminal, then parsed by zod once. */ + const readValues = async (): Promise> => { + const schema = (command as { input?: InputSchema }).input; + const { values, labels, missing } = await readInput({ + table, + positionals: positionalsOf(command), + tokens, + input: layer.input, + cwd, + scope, + readStdin: () => readAll(stdin()) + }); + if (missing.length && !interactive) throw missingInput(scope, missing, blocker); + const answered = missing.length ? { ...values, ...(await askFor(missing, ctx.prompter, cwd)) } : values; + if (!schema) return answered; + return parseInput(schema, inputJson, answered, labels, `Run "${usage} --schema" to see the input.`); + }; + + const runIt = async (): Promise => { + if (kind === 'passthrough') return (command as PassthroughCommand).passthrough(parseArgv(['', '', ...rest]), ctx); + const input = await readValues(); + output.useSecrets([...splitSecrets(input, inputJson).secrets, ...splitSecrets(globals, globalsJson).secrets]); + switch (kind) { + case 'read': + case 'immediate': + return (command as { run(input: unknown, ctx: CommandContext): Promise }).run(input, ctx); + case 'serve': + return (command as { serve(input: unknown, ctx: CommandContext): Promise }).serve(input, ctx); + case 'change': + return runChange(command as ChangeCommand, input, ctx, layer.dryRun); + } + }; + + try { + const result = await untilInterrupted(controller, runIt); + if (lenient && result?.data === undefined) return ExitCode.ok; + return output.success(result, lenient ? undefined : layer.fields, command.effect); + } finally { + prompter?.close(); + } + } + + async function run(argv: string[] = process.argv.slice(2), io: CliIO = {}): Promise { + const stdout = io.stdout ?? process.stdout; + const stderr = io.stderr ?? process.stderr; + const env = io.env ?? process.env; + const cwd = io.cwd ?? process.cwd(); + const resolution = resolve(argv); + const command = resolution.kind === 'command' ? resolution.command : undefined; + const restIndexes = argv.map((_, index) => index).filter((index) => !('path' in resolution && resolution.path.has(index))); + const rest = restIndexes.map((index) => argv[index]); + const table = command ? shownOf(command).table : rootTable; + const tokens = tokenize(rest, table); + // Every step of this run, the layer's own and the command's, keeps the flags that choose its target (x-carry), + // right after the CLI name, and no flag that only describes this run. + const step = stepBuilder(config.name, argv, tokens, (index) => restIndexes[index], table); + const format = requestedFormat(tokens) ?? (isTerminal(stdout) ? 'text' : 'json'); + const results = command && 'stdout' in command && command.stdout === 'reserved' ? stderr : stdout; + const output = new Output(format, stdout, stderr, results, Boolean(env.DEBUG), command?.name); + try { + switch (resolution.kind) { + case 'unknown': + throw unknownCommand(resolution.words, step); + case 'root': + case 'group': + return showRegistry(resolution, tokens, output, cwd, step); + case 'command': { + const { command: resolved } = resolution; + const path = [...resolution.path].sort((a, b) => a - b); + const { input } = shownOf(resolved); + const line = commandLine(config.name, `${config.name} ${resolved.name}`, argv, path, (index) => restIndexes[index], tokens, positionalsOf(resolved), input, table); + try { + return await runCommand(resolved, tokens, rest, line, step, output, { ...io, stdout, stderr, env, cwd }); + } catch (error) { + throw withSchemaStep(error, { usage: `${config.name} ${resolved.name}`, path: resolved.name.split(' '), step }); + } + } + } + } catch (error) { + return output.error(error); + } + } + + return { run, manifest }; +} diff --git a/agentic/command/src/help.ts b/agentic/command/src/help.ts new file mode 100644 index 0000000000..e731a4e9dd --- /dev/null +++ b/agentic/command/src/help.ts @@ -0,0 +1,334 @@ +import { FlagDef, FlagKind, flagKind, FlagTable, isSecret, kebabCase, LAYER_FLAGS, orList } from './input'; +import type { CliConfig, CliManifest, CommandDefinition, CommandExample, CommandManifest, Effect, HelpTopic, JSONSchema, ReferenceSection } from './types'; + +/** What help and the manifest show of a command: its input and output as JSON Schema, made once from zod. */ +export interface Shown { + input?: JSONSchema; + output?: JSONSchema; + table: FlagTable; +} + +export type ShownOf = (command: CommandDefinition) => Shown; + +/** What help shows of a flag: a FlagDef has it, and so does each property of an input schema in the manifest. */ +type ShownFlag = Pick; + +/** What tells the kinds of command apart, the same on a definition and on its manifest entry. */ +interface KindFacts { + effect: Effect; + passthrough?: unknown; + immediate?: unknown; + stdout?: unknown; +} + +const visible = (config: CliConfig): CommandDefinition[] => config.commands.filter((command) => !command.hidden); + +const positionalsOf = (command: CommandDefinition): string[] => ('passthrough' in command ? [] : command.positionals ?? []); + +const inputFlags = (table: FlagTable): FlagDef[] => table.flags.filter((def) => def.scope === 'input'); + +/** The flags of a JSON Schema object in the manifest, as the flag table of the command would read them. */ +function flagsOfSchema(schema: JSONSchema | undefined): ShownFlag[] { + const required = new Set(schema?.required ?? []); + return Object.entries(schema?.properties ?? {}).map(([property, json]) => ({ + property, + flag: kebabCase(property), + schema: json, + kind: flagKind(json), + required: required.has(property), + secret: isSecret(json) + })); +} + +/** The layer's short forms, from the flags that declare one: "`-y` is `--yes`". */ +const shortForms = (): string[] => + Object.entries(LAYER_FLAGS.properties ?? {}).flatMap(([property, schema]) => + schema['x-short'] ? [`\`-${schema['x-short']}\` is \`--${kebabCase(property)}\``] : []); + +/** What every CLI of this layer tells its agents, after the CLI's own notes. */ +const layerNotes = (name: string): string[] => [ + 'A change (write or destructive) shows its plan with --dry-run, asks on a terminal, and without a terminal stops with exit 3 and the plan until it is run with --yes. ' + + 'A command marked "at once" changes as soon as it runs, and refuses --dry-run; one that takes its own flags, or serves on stdio, has no plan either.', + `Run "${name} --llms" for a command index, and "${name} --schema" for the JSON Schema of a command.` +]; + +function columns(rows: Array<[string, string]>): string[] { + const width = Math.min(Math.max(0, ...rows.map(([left]) => left.length)), 32); + return rows.map(([left, right]) => (right ? ` ${left.padEnd(width)} ${right}` : ` ${left}`)); +} + +function placeholder(kind: FlagKind): string { + switch (kind.kind) { + case 'boolean': + return ''; + case 'scalar': + return ` <${kind.type}>`; + case 'enum': + return ` <${kind.values.map(String).join('|')}>`; + case 'list': + return `${placeholder(kind.item)}...`; + case 'json': + return ' '; + } +} + +/** A list in the last positional takes every argument left. */ +const takesRest = (def: ShownFlag, positionals: readonly string[]): boolean => + def.kind.kind === 'list' && positionals[positionals.length - 1] === def.property; + +function flagRow(def: ShownFlag, positionals: readonly string[]): [string, string] { + const facts: string[] = []; + const argument = positionals.indexOf(def.property); + if (def.required) facts.push('required'); + if (argument >= 0 && takesRest(def, positionals)) facts.push(argument === 0 ? 'or the arguments' : `or arguments ${argument + 1} and on`); + else if (argument >= 0) facts.push(`or argument ${argument + 1}`); + if (def.kind.kind === 'list') facts.push('repeatable'); + if (def.schema.default !== undefined && !def.secret) facts.push(`default: ${JSON.stringify(def.schema.default)}`); + const description = [def.schema.description, facts.length ? `(${facts.join(', ')})` : ''].filter(Boolean).join(' '); + const short = def.schema['x-short']; + return [`${short ? `-${short}, ` : ''}--${def.flag}${placeholder(def.kind)}`, description]; +} + +function argumentsOf(positionals: readonly string[], flags: ShownFlag[]): string { + return positionals + .map((name) => { + const def = flags.find((flag) => flag.property === name); + const word = takesRest(def, positionals) ? `${def.flag}...` : def.flag; + return def.required ? ` <${word}>` : ` [${word}]`; + }) + .join(''); +} + +/** For example `read`, `destructive`, or `write, takes its own flags`. */ +function effectLabel(command: KindFacts): string { + if (command.passthrough) return `${command.effect}, takes its own flags`; + if (command.stdout === 'reserved') return `${command.effect}, serves on stdio`; + if (command.immediate) return `${command.effect}, at once`; + return command.effect; +} + +function commandRows(commands: CommandDefinition[]): string[] { + return columns(commands.map((command) => [command.name, `${command.summary} (${effectLabel(command)})`])); +} + +function redactExample(example: CommandExample, table: FlagTable): CommandExample { + let command = example.command; + for (const [spelling, def] of table.lookup) { + if (!def.secret) continue; + const escaped = spelling.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + command = command.replace(new RegExp(`(--${escaped})(=|\\s+)('[^']*'|"[^"]*"|\\S+)`, 'g'), '$1$2'); + } + return { ...example, command }; +} + +/** A copy of the schema without the default or examples of any secret node. */ +function publicSchema(schema: JSONSchema | undefined): JSONSchema | undefined { + if (!schema) return undefined; + const copy: JSONSchema = { ...schema }; + if (isSecret(schema)) { + delete copy.default; + delete copy.examples; + } + if (schema.properties) { + copy.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => [key, publicSchema(value)])); + } + if (schema.items) copy.items = publicSchema(schema.items); + for (const keyword of ['anyOf', 'oneOf', 'allOf'] as const) { + if (schema[keyword]) copy[keyword] = schema[keyword].map(publicSchema); + } + return copy; +} + +export function rootHelp(config: CliConfig, table: FlagTable): string { + const lines = [`${config.name} ${config.version}`]; + if (config.description) lines.push(config.description); + const notes = [...(config.notes ?? []), ...layerNotes(config.name)]; + lines.push( + '', + 'Usage:', + ` ${config.name} [flags]`, + '', + 'Commands:', + ...commandRows(visible(config)), + '', + 'Global flags:', + ...columns(table.flags.map((def) => flagRow(def, []))) + ); + if (config.topics?.length) { + lines.push('', 'Help topics:', ...columns(config.topics.map((topic) => [topic.name, topic.summary])), '', `Run "${config.name} help " to read one.`); + } + lines.push('', 'Agents:', ...notes.map((note) => ` - ${note}`)); + return `${lines.join('\n')}\n`; +} + +export function groupHelp(config: CliConfig, group: string): string { + const commands = visible(config).filter((command) => command.name.startsWith(`${group} `)); + const lines = [ + 'Usage:', + ` ${config.name} ${group} [flags]`, + '', + 'Commands:', + ...commandRows(commands), + '', + `Run "${config.name} ${group} --help" for the flags of a command.` + ]; + return `${lines.join('\n')}\n`; +} + +export function commandHelp(config: CliConfig, command: CommandDefinition, { table }: Shown): string { + const positionals = positionalsOf(command); + const flags = inputFlags(table); + const otherFlags = table.flags.filter((def) => def.scope !== 'input').map((def) => `--${def.flag}`); + const usage = `${config.name} ${command.name}`; + const lines = [`${usage}: ${command.summary}`, `Effect: ${effectLabel(command)}`]; + if (command.description) lines.push('', command.description); + if ('passthrough' in command) { + lines.push('', 'Usage:', ` ${usage} [its own flags]`, '', `Run "${usage} --help" for its own flags.`); + } else { + lines.push('', 'Usage:', ` ${usage}${argumentsOf(positionals, flags)}${flags.length ? ' [flags]' : ''}`); + } + if (flags.length) lines.push('', 'Flags:', ...columns(flags.map((def) => flagRow(def, positionals)))); + lines.push('', `Global flags: ${otherFlags.join(', ')}. Run "${config.name} --help" for what they do.`); + if (command.examples?.length) { + lines.push('', 'Examples:'); + for (const example of command.examples.map((item) => redactExample(item, table))) { + lines.push(` ${example.command}`); + if (example.description) lines.push(` ${example.description}`); + } + } + if (command.notes?.length) lines.push('', 'Notes:', ...command.notes.map((note) => ` - ${note}`)); + return `${lines.join('\n')}\n`; +} + +export const topicPage = (topic: HelpTopic): string => `${topic.summary}\n\n${topic.body}\n`; + +export function commandSchema(command: CommandDefinition, shown: Shown) { + return { + name: command.name, + summary: command.summary, + effect: command.effect, + positionals: positionalsOf(command), + input: publicSchema(shown.input), + output: shown.output + }; +} + +export function llmsIndex(config: CliConfig, shownOf: ShownOf): string { + const lines = [`# ${config.name}`, '']; + if (config.description) lines.push(config.description, ''); + const passthrough = visible(config).filter((command) => 'passthrough' in command).map((command) => `\`${config.name} ${command.name}\``); + const own = passthrough.length ? ` (but ${orList(passthrough, 'and')}, which take their own flags and print their own output)` : ''; + lines.push( + `Version ${config.version}. Run \`${config.name} --schema\` for the input and output JSON Schema of a command, ` + + `and \`${config.name} --llms --json\` for the full manifest. When stdout is not a terminal, a command${own} prints one JSON envelope: ` + + '`{"ok":true,"data":...}` or `{"ok":false,"error":{"code":...,"message":...}}`. ' + + 'A change stops with exit 3 and its plan in `error.details.plan` until it is run with `--yes`. ' + + `Short forms: ${orList(shortForms(), 'and')}.`, + '', + '## Commands', + '', + ...visible(config).map((command) => + `- \`${config.name} ${command.name}${argumentsOf(positionalsOf(command), inputFlags(shownOf(command).table))}\` (${effectLabel(command)}): ${command.summary}`) + ); + if (config.topics?.length) lines.push('', '## Help topics', '', ...config.topics.map((topic) => `- \`${config.name} help ${topic.name}\`: ${topic.summary}`)); + if (config.notes?.length) lines.push('', '## Notes', '', ...config.notes.map((note) => `- ${note}`)); + return `${lines.join('\n')}\n`; +} + +export function buildManifest(config: CliConfig, globals: JSONSchema | undefined, shownOf: ShownOf): CliManifest { + return { + name: config.name, + version: config.version, + description: config.description, + notes: config.notes ?? [], + globals: publicSchema({ type: 'object', properties: { ...globals?.properties, ...LAYER_FLAGS.properties } }), + commands: visible(config).map((command) => { + const shown = shownOf(command); + return { + name: command.name, + summary: command.summary, + description: command.description, + effect: command.effect, + positionals: positionalsOf(command), + input: publicSchema(shown.input), + output: shown.output, + examples: (command.examples ?? []).map((example) => redactExample(example, shown.table)), + notes: command.notes ?? [], + ...('passthrough' in command ? { passthrough: true as const } : {}), + ...('immediate' in command ? { immediate: true as const } : {}), + ...('serve' in command ? { stdout: 'reserved' as const } : {}) + }; + }), + topics: config.topics ?? [] + }; +} + +/** The sections a reference ends with, in order, each filled by the topic that names it. */ +const REFERENCE_SECTIONS: readonly ReferenceSection[] = ['EXIT STATUS', 'ENVIRONMENT', 'FILES']; + +/** Plain text as Markdown that reads back as the same text: each character Markdown could read as syntax is escaped. */ +const md = (text: string): string => text.replace(/[\\`*_[\]<>#|~&]/g, '\\$&'); + +const sentence = (text: string): string => (/[.!?:]$/.test(text) ? text : `${text}.`); + +const bullets = (items: string[]): string => items.map((item) => `- ${item}`).join('\n'); + +const flagItems = (flags: ShownFlag[], positionals: readonly string[]): string => + bullets(flags.map((def) => flagRow(def, positionals)).map(([left, right]) => (right ? `\`${left}\`: ${md(right)}` : `\`${left}\``))); + +function commandSection(cli: string, command: CommandManifest): string[] { + const usage = `${cli} ${command.name}`; + const flags = flagsOfSchema(command.input); + const blocks = [`### ${command.name}`]; + if (command.passthrough) { + blocks.push(`\`${usage} [its own flags]\``, `${md(sentence(command.summary))} Effect: ${effectLabel(command)}. Run \`${usage} --help\` for its own flags.`); + } else { + blocks.push(`\`${usage}${argumentsOf(command.positionals, flags)}${flags.length ? ' [flags]' : ''}\``, `${md(sentence(command.summary))} Effect: ${effectLabel(command)}.`); + } + if (command.description) blocks.push(md(command.description)); + if (flags.length) blocks.push('Flags:', flagItems(flags, command.positionals)); + if (command.examples.length) { + const lines = command.examples.flatMap((example) => [...(example.description ? [`# ${example.description}`] : []), example.command]); + blocks.push('Examples:', ['```', ...lines, '```'].join('\n')); + } + if (command.notes.length) blocks.push('Notes:', bullets(command.notes.map(md))); + return blocks; +} + +const topicSection = (heading: string, topic: HelpTopic): string[] => [`## ${heading}`, md(sentence(topic.summary)), topic.body]; + +/** + * The manifest as one Markdown reference, in the shape of a manual page: the name, the synopsis, the description, the + * global flags, every command, every topic as a section of its own, then exit status, environment and files (each + * from the topic that fills it), and the commands that print the same facts. A man page is this text through a + * Markdown-to-roff converter. + */ +export function renderReference(manifest: CliManifest): string { + const { name } = manifest; + const description = manifest.description ?? `The ${name} command line`; + const ownSections = manifest.topics.filter((topic) => !topic.section); + const blocks = [ + `# ${name}(1) -- ${md(description)}`, + '## SYNOPSIS', + `\`${name} [flags]\``, + `\`${name} help [ | ]\``, + '## DESCRIPTION', + md(description), + `This reference is for version ${md(manifest.version)}. Notes for agents:`, + bullets([...manifest.notes, ...layerNotes(name)].map(md)), + '## GLOBAL FLAGS', + 'Every command takes these flags, except one that takes its own flags.', + flagItems(flagsOfSchema(manifest.globals), []), + '## COMMANDS', + ...manifest.commands.flatMap((command) => commandSection(name, command)), + ...ownSections.flatMap((topic) => topicSection(topic.name.toUpperCase().replace(/-/g, ' '), topic)), + ...REFERENCE_SECTIONS.flatMap((section) => manifest.topics.filter((topic) => topic.section === section).flatMap((topic) => topicSection(section, topic))), + '## SEE ALSO', + bullets([ + `\`${name} help \` prints a topic, and \`${name} help \` the help of a command.`, + `\`${name} --schema\` prints the input and output JSON Schema of a command.`, + `\`${name} --llms\` prints a command index for agents, and \`${name} --llms --json\` the manifest this reference is made from.` + ]) + ]; + return `${blocks.join('\n\n')}\n`; +} diff --git a/agentic/command/src/index.ts b/agentic/command/src/index.ts new file mode 100644 index 0000000000..c71e05a58c --- /dev/null +++ b/agentic/command/src/index.ts @@ -0,0 +1,47 @@ +export { type Approval, decideApproval, type PlanData } from './approval'; +export { createCli } from './cli'; +export { renderReference } from './help'; +export { flagName } from './input'; +export { + failureError, + type FailureNext, + toCliCommand, + toCliCommands, + type ToolBinding, + type ToolCallStep, + toolCallStep, + toolCommand, + type ToolCommandDeps, + type ToolCommandEntry, + type ToolCommandOptions +} from './tool-command'; +export type { + ChangeCommand, + Cli, + CliConfig, + CliErrorInit, + CliIO, + CliManifest, + CommandContext, + CommandDefinition, + CommandErrorCode, + CommandExample, + CommandManifest, + CommandResult, + Effect, + FollowUpOptions, + HelpTopic, + ImmediateCommand, + InputSchema, + JSONSchema, + JSONSchemaType, + NextStep, + NextWord, + PassthroughCommand, + Planned, + ReadCommand, + ReferenceSection, + ServeCommand, + StepOptions +} from './types'; +export { CliError, COMMAND_ERROR_CODES, ExitCode, isCliError } from './types'; diff --git a/agentic/command/src/input.ts b/agentic/command/src/input.ts new file mode 100644 index 0000000000..691a24998f --- /dev/null +++ b/agentic/command/src/input.ts @@ -0,0 +1,1106 @@ +import { readFileSync } from 'fs'; +import type { Inquirerer, Question, Validation } from 'inquirerer'; +import { resolve as resolvePath } from 'path'; +import { z } from 'zod'; + +import { + CliError, + type CliErrorInit, + type CommandErrorCode, + ExitCode, + type FollowUpOptions, + type InputSchema, + isCliError, + type JSONSchema, + type JSONSchemaType, + type NextStep, + type NextWord, + type StepOptions +} from './types'; + +type ScalarKind = + | { kind: 'boolean' } + | { kind: 'scalar'; type: 'string' | 'number' | 'integer' } + | { kind: 'enum'; values: readonly unknown[] }; + +/** How a property is read from argv: a boolean switch, one scalar, a repeatable scalar, or JSON text / @path. */ +export type FlagKind = ScalarKind | { kind: 'list'; item: ScalarKind } | { kind: 'json' }; + +export type FlagScope = 'layer' | 'global' | 'input'; + +export interface FlagDef { + property: string; + /** Canonical kebab-case spelling, without the leading dashes. */ + flag: string; + /** The property's JSON Schema, as the layer shows it. */ + schema: JSONSchema; + /** The property's own zod schema, which checks one value of it. */ + check: z.ZodType; + kind: FlagKind; + scope: FlagScope; + secret: boolean; + required: boolean; +} + +export interface FlagTable { + flags: FlagDef[]; + /** Every accepted spelling (kebab, snake, camel and the property name) to its flag. */ + lookup: Map; + /** The short forms of the layer's own flags (`-h`, `-y`) to their flag; each takes no value. */ + shorts: Map; +} + +/** `index` is the argv element of the flag; `valueIndex` is the element that holds its value (the same one for --x=v). */ +export type Token = + | { kind: 'flag'; def: FlagDef; value: string | boolean | undefined; index: number; valueIndex?: number } + | { kind: 'unknown'; flag: string } + | { kind: 'positional'; value: string; index: number } + | { kind: 'separator'; index: number }; + +type RawValue = string | boolean | undefined; + +/** The JSON Schema of a zod schema, as the layer reads and prints it. */ +export function jsonSchemaOf(schema: z.ZodType, io: 'input' | 'output'): JSONSchema { + const json = z.toJSONSchema(schema, { io, unrepresentable: 'any' }) as JSONSchema; + delete json.$schema; + return json; +} + +export const LAYER_INPUT = z.object({ + json: z.boolean().optional().describe('Print one JSON envelope on stdout (same as --format json)'), + format: z.enum(['text', 'json']).optional().describe('Output format; the default is text on a terminal, else json'), + fields: z.string().optional().describe('Keep only these comma-separated paths of data, for example id,owner.name'), + input: z.string().optional().describe('The whole input as JSON, @file.json, or - for stdin; flags override its keys'), + dry_run: z.boolean().optional().describe('Show the plan of a change and change nothing'), + yes: z.boolean().optional().meta({ description: 'Approve the plan of a change without a prompt', 'x-short': 'y' }), + no_input: z.boolean().optional().describe('Never prompt; a missing value fails with missing-input'), + tty: z.boolean().optional().describe('Pass false to never prompt (same as --no-input)'), + schema: z.boolean().optional().describe('Print the input and output JSON Schema of the command'), + llms: z.boolean().optional().describe('Print a Markdown command index for agents; with --json, the full manifest'), + cwd: z.string().optional().meta({ description: 'Run as if started in this directory', 'x-carry': true }), + version: z.boolean().optional().describe('Print the version'), + help: z.boolean().optional().meta({ description: 'Show help', 'x-short': 'h' }) +}); + +export const LAYER_FLAGS: JSONSchema = jsonSchemaOf(LAYER_INPUT, 'input'); + +export interface LayerFlags { + /** Set only by --json or --format; the caller picks the default from the terminal. */ + format?: 'text' | 'json'; + fields?: string[]; + input?: string; + dryRun: boolean; + yes: boolean; + noInput: boolean; + tty: boolean; + schema: boolean; + llms: boolean; + cwd?: string; + version: boolean; + help: boolean; +} + +const builtByLayer = new WeakSet(); + +/** An error whose text the layer wrote, so it never holds a secret and is never searched for one. */ +export function layerError(init: CliErrorInit): CliError { + const error = new CliError(init); + builtByLayer.add(error); + return error; +} + +export const isLayerError = (error: unknown): error is CliError => + typeof error === 'object' && error !== null && builtByLayer.has(error); + +export function usageError(code: CommandErrorCode, message: string, extra: Omit = {}): CliError { + return layerError({ code, message, exitCode: ExitCode.usage, ...extra }); +} + +function invalidInput(message: string, hint: string, flag: string, extra: Record = {}): CliError { + return usageError('invalid-input', message, { hint, details: { flag, ...extra } }); +} + +export function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** The value of an own key only, so that `constructor`, `toString` and `__proto__` read as absent. */ +export function own(map: Record | undefined, key: string): T | undefined { + return map !== undefined && Object.hasOwn(map, key) ? map[key] : undefined; +} + +export function orList(items: string[], conjunction = 'or'): string { + return items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} ${conjunction} ${items[items.length - 1]}`; +} + +function words(name: string): string[] { + return name + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .split(/[\s_-]+/) + .filter(Boolean) + .map((word) => word.toLowerCase()); +} + +export function kebabCase(name: string): string { + return words(name).join('-'); +} + +function spellings(property: string): string[] { + const parts = words(property); + const camel = parts[0] + parts.slice(1).map((part) => part[0].toUpperCase() + part.slice(1)).join(''); + return [...new Set([parts.join('-'), parts.join('_'), camel, property])]; +} + +function primaryType(schema: JSONSchema): JSONSchemaType | undefined { + return Array.isArray(schema.type) ? schema.type.find((type) => type !== 'null') : schema.type; +} + +function scalarKind(schema: JSONSchema): ScalarKind | undefined { + if (schema.enum) return { kind: 'enum', values: schema.enum }; + const type = primaryType(schema); + switch (type) { + case 'boolean': + return { kind: 'boolean' }; + case 'string': + case 'number': + case 'integer': + return { kind: 'scalar', type }; + default: + return undefined; + } +} + +/** The scalar branch of `anyOf`/`oneOf` that holds one scalar schema and `null`. */ +function nullableScalar(schema: JSONSchema): ScalarKind | undefined { + const branches = schema.anyOf ?? schema.oneOf; + if (!branches || branches.length !== 2) return undefined; + const others = branches.filter((branch) => branch.type !== 'null'); + return others.length === 1 ? scalarKind(others[0]) : undefined; +} + +/** A nullable scalar reads as the scalar; any schema with no usable type reads as JSON text or @path. */ +export function flagKind(schema: JSONSchema): FlagKind { + const scalar = scalarKind(schema) ?? nullableScalar(schema); + if (scalar) return scalar; + const item = primaryType(schema) === 'array' && schema.items ? scalarKind(schema.items) : undefined; + return item ? { kind: 'list', item } : { kind: 'json' }; +} + +const SCOPE_NAMES: Record = { + layer: 'a flag the command layer owns', + global: 'a global flag of the CLI', + input: 'an input property' +}; + +/** One source of flags: a zod object and its JSON Schema as the layer shows it. */ +export interface FlagSource { + scope: FlagScope; + schema?: InputSchema; + json?: JSONSchema; +} + +/** Throws a plain Error on a definition mistake: these are bugs in the CLI, not in the user's argv. */ +export function buildFlagTable(owner: string, sources: FlagSource[]): FlagTable { + const flags: FlagDef[] = []; + const lookup = new Map(); + const shorts = new Map(); + for (const { scope, schema, json } of sources) { + if (!schema) continue; + if (primaryType(json) !== 'object') { + throw new Error(`${owner}: the ${scope} schema must be a zod object, because each of its properties becomes a flag.`); + } + const required = new Set(json.required ?? []); + for (const [property, propertySchema] of Object.entries(json.properties ?? {})) { + if (words(property).length === 0) { + throw new Error(`${owner}: the property "${property}" has no letters or digits to spell a flag with. Rename it.`); + } + const def: FlagDef = { + property, + flag: kebabCase(property), + schema: propertySchema, + check: schema.shape[property] as z.ZodType, + kind: flagKind(propertySchema), + scope, + secret: isSecret(propertySchema), + required: required.has(property) + }; + for (const spelling of spellings(property)) { + const taken = lookup.get(spelling); + if (taken) { + throw new Error( + `${owner}: --${spelling} is a spelling of both "${taken.property}" (${SCOPE_NAMES[taken.scope]}) ` + + `and "${property}" (${SCOPE_NAMES[scope]}). Rename one of them.` + ); + } + lookup.set(spelling, def); + } + const short = propertySchema['x-short']; + if (short !== undefined) { + if (scope !== 'layer') { + throw new Error( + `${owner}: the property "${property}" declares the short form -${short}, but short forms belong to the command layer ` + + '(-h for --help, -y for --yes), so a command or a CLI global cannot declare one. Remove its x-short.' + ); + } + shorts.set(`-${short}`, def); + } + flags.push(def); + } + } + return { flags, lookup, shorts }; +} + +const NEGATIVE_NUMBER = /^-\d/; + +/** The flag a name (without dashes) spells: an exact spelling, or `no-` plus a boolean flag. */ +function flagNamed(name: string, table: FlagTable): { def: FlagDef; negated: boolean } | undefined { + const def = table.lookup.get(name); + if (def) return { def, negated: false }; + const negated = name.startsWith('no-') ? table.lookup.get(name.slice(3)) : undefined; + return negated?.kind.kind === 'boolean' ? { def: negated, negated: true } : undefined; +} + +const isKnownFlag = (word: string, table: FlagTable): boolean => + word.startsWith('--') && flagNamed(word.slice(2).split('=')[0], table) !== undefined; + +export function tokenize(argv: readonly string[], table: FlagTable): Token[] { + const tokens: Token[] = []; + for (let index = 0; index < argv.length; index++) { + const arg = argv[index]; + if (arg === '--') { + tokens.push({ kind: 'separator', index }); + for (let rest = index + 1; rest < argv.length; rest++) { + tokens.push({ kind: 'positional', value: argv[rest], index: rest }); + } + break; + } + const short = table.shorts.get(arg); + if (short) { + tokens.push({ kind: 'flag', def: short, value: true, index }); + continue; + } + if (!arg.startsWith('--')) { + const isFlag = arg.length > 1 && arg.startsWith('-') && !NEGATIVE_NUMBER.test(arg); + tokens.push(isFlag ? { kind: 'unknown', flag: arg } : { kind: 'positional', value: arg, index }); + continue; + } + const equals = arg.indexOf('='); + const name = equals === -1 ? arg.slice(2) : arg.slice(2, equals); + const inline = equals === -1 ? undefined : arg.slice(equals + 1); + const def = table.lookup.get(name); + const next = argv[index + 1]; + const inlineIndex = inline === undefined ? undefined : index; + if (def?.kind.kind === 'boolean') { + // Only a literal true/false is a boolean's value, so `--yes tasks` keeps `tasks` as a positional. + if (inline === undefined && (next === 'true' || next === 'false')) { + tokens.push({ kind: 'flag', def, value: next, index, valueIndex: index + 1 }); + index++; + } else { + tokens.push({ kind: 'flag', def, value: inline ?? true, index, valueIndex: inlineIndex }); + } + } else if (def) { + // A secret may start with --, so after a secret flag only a known flag or the separator means "no value". + const nextIsValue = next !== undefined && (!next.startsWith('--') || (def.secret && next !== '--' && !isKnownFlag(next, table))); + if (inline === undefined && nextIsValue) { + tokens.push({ kind: 'flag', def, value: next, index, valueIndex: index + 1 }); + index++; + } else { + tokens.push({ kind: 'flag', def, value: inline, index, valueIndex: inlineIndex }); + } + } else { + const negated = inline === undefined ? flagNamed(name, table) : undefined; + tokens.push(negated ? { kind: 'flag', def: negated.def, value: false, index } : { kind: 'unknown', flag: `--${name}` }); + } + } + return tokens; +} + +/** The format asked for by --json or --format, read leniently so that a usage error can still be printed in it. */ +export function requestedFormat(tokens: Token[]): 'text' | 'json' | undefined { + let format: 'text' | 'json' | undefined; + for (const token of tokens) { + if (token.kind !== 'flag' || token.def.scope !== 'layer') continue; + if (token.def.property === 'json' && (token.value === true || token.value === 'true')) return 'json'; + if (token.def.property === 'format' && (token.value === 'text' || token.value === 'json')) format = token.value; + } + return format; +} + +const shown = (secret: boolean, raw: string): string => (secret ? '' : `, got ${JSON.stringify(raw)}`); + +const DECIMAL = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; +const INTEGER_LITERAL = /^-?\d+$/; + +/** `secret` says whether the raw value may be quoted back in an error. */ +function coerceScalar(def: FlagDef, kind: ScalarKind, raw: string, label: string, secret: boolean): unknown { + switch (kind.kind) { + case 'boolean': + if (raw === 'true' || raw === 'false') return raw === 'true'; + throw invalidInput(`${label} takes true or false${shown(secret, raw)}.`, `Pass ${label} alone for true, or --no-${def.flag} for false.`, label); + case 'enum': { + const index = kind.values.findIndex((value) => String(value) === raw); + if (index !== -1) return kind.values[index]; + const near = secret ? [] : closest(raw, kind.values.map(String)); + throw invalidInput( + `${label} must be one of ${kind.values.map(String).join(', ')}${shown(secret, raw)}.`, + near.length ? `Did you mean ${orList(near.map((value) => `"${value}"`))}?` : 'Pass one of the listed values.', + label + ); + } + case 'scalar': { + if (kind.type === 'string') return raw; + const value = Number(raw); + const expected = kind.type === 'integer' ? 'an integer' : 'a number'; + if (!DECIMAL.test(raw) || !Number.isFinite(value) || (kind.type === 'integer' && !Number.isInteger(value))) { + throw invalidInput(`${label} must be ${expected} in decimal notation${shown(secret, raw)}.`, `Pass ${label} as ${expected}, for example 42.`, label); + } + // Past 2^53 an integer silently changes value, so it is refused rather than rounded. + if ((kind.type === 'integer' || INTEGER_LITERAL.test(raw)) && !Number.isSafeInteger(value)) { + throw invalidInput( + `${label} is outside the safe integer range of ±${Number.MAX_SAFE_INTEGER}${shown(secret, raw)}.`, + 'Pass a smaller value, or pass it as a string if the schema takes one.', + label + ); + } + return value; + } + } +} + +function readJsonText(raw: string, label: string, cwd: string): string { + if (!raw.startsWith('@')) return raw; + const file = resolvePath(cwd, raw.slice(1)); + try { + return readFileSync(file, 'utf8'); + } catch (error) { + const reason = (error as NodeJS.ErrnoException).code ?? (error as Error).message; + throw invalidInput(`${label} could not read ${file} (${reason}).`, `Check the path. A relative path is resolved from ${cwd}.`, label); + } +} + +function parseJson(text: string, label: string): unknown { + try { + return JSON.parse(text); + } catch (error) { + // The engine's message can quote the input, and the input may hold a secret, so only the position is kept. + const position = /position (\d+)/.exec((error as Error).message)?.[1]; + throw invalidInput( + `${label} is not valid JSON${position ? ` (the error is at character ${position})` : ''}.`, + `Pass valid JSON, or a file with ${label} @file.json.`, + label + ); + } +} + +/** Turns every raw value given for one flag into a value of its JSON type; zod checks it later. `label` names the flag. */ +export function coerceFlag(def: FlagDef, raws: RawValue[], label: string, cwd: string): unknown { + const { kind } = def; + if (kind.kind !== 'list' && raws.length > 1) { + throw invalidInput(`${label} was given ${raws.length} times, but it takes one value.`, `Pass ${label} once.`, label); + } + if (kind.kind === 'boolean') { + const [raw] = raws; + return typeof raw === 'boolean' ? raw : coerceScalar(def, kind, raw, label, def.secret); + } + if (raws.some((raw) => typeof raw !== 'string')) { + throw invalidInput(`${label} needs a value.`, `Pass it as ${label} or ${label}=.`, label); + } + const values = raws as string[]; + switch (kind.kind) { + case 'scalar': + case 'enum': + return coerceScalar(def, kind, values[0], label, def.secret); + case 'list': { + const secret = def.secret || isSecret(def.schema.items); + return values.flatMap((raw) => { + if (!raw.trimStart().startsWith('[')) return [coerceScalar(def, kind.item, raw, label, secret)]; + const parsed = parseJson(raw, label); + if (!Array.isArray(parsed)) throw invalidInput(`${label} is not valid: a JSON value of it must be an array.`, `Pass ${label} once per item, or one JSON array.`, label); + return parsed; + }); + } + case 'json': + return parseJson(readJsonText(values[0], label, cwd), label); + } +} + +/** `lenient` skips a flag whose value does not read, for a passthrough command that owns its arguments. */ +export function readScope(tokens: Token[], scope: FlagScope, cwd: string, lenient = false): Record { + const grouped = new Map(); + for (const token of tokens) { + if (token.kind !== 'flag' || token.def.scope !== scope) continue; + grouped.set(token.def, [...(grouped.get(token.def) ?? []), token.value]); + } + const values: Record = {}; + for (const [def, raws] of grouped) { + try { + values[def.property] = coerceFlag(def, raws, `--${def.flag}`, cwd); + } catch (error) { + if (!lenient || !isCliError(error)) throw error; + } + } + return values; +} + +export function readLayerFlags(tokens: Token[], cwd: string, lenient = false): LayerFlags { + const values = readScope(tokens, 'layer', cwd, lenient); + return { + format: values.json === true ? 'json' : (values.format as 'text' | 'json' | undefined), + fields: typeof values.fields === 'string' + ? values.fields.split(',').map((field) => field.trim()).filter(Boolean) + : undefined, + input: values.input as string | undefined, + dryRun: values.dry_run === true, + yes: values.yes === true, + noInput: values.no_input === true, + tty: values.tty !== false, + schema: values.schema === true, + llms: values.llms === true, + cwd: values.cwd as string | undefined, + version: values.version === true, + help: values.help === true + }; +} + +/** Whether the schema takes `null`: a "null" type, a null const or enum member, a union branch that does, or no type. */ +function acceptsNull(schema: JSONSchema | undefined): boolean { + if (!isPlainObject(schema)) return true; + if (schema.const !== undefined) return schema.const === null; + if (schema.enum) return schema.enum.includes(null); + const branches = schema.anyOf ?? schema.oneOf; + if (branches) return branches.some(acceptsNull); + if (schema.allOf) return schema.allOf.every(acceptsNull); + if (schema.type === undefined) return true; + return Array.isArray(schema.type) ? schema.type.includes('null') : schema.type === 'null'; +} + +/** + * The one null rule of the layer: a null means "not given" for an optional key whose schema does not take null. + * Hosts with strict function calling and template-built input send every optional key, as null when it is not + * given. A required key, or one whose schema takes null, keeps its null, and zod judges it. + */ +const isAbsentNull = (value: unknown, schema: JSONSchema | undefined, required: boolean): boolean => + value === null && !required && schema !== undefined && !acceptsNull(schema); + +/** `value` with each null that means "not given" removed, in nested objects and list items. */ +function withoutAbsentNulls(value: unknown, schema: JSONSchema | undefined): unknown { + if (!isPlainObject(schema)) return value; + if (Array.isArray(value)) return schema.items ? value.map((item) => withoutAbsentNulls(item, schema.items)) : value; + if (!isPlainObject(value)) return value; + const required = new Set(schema.required ?? []); + const additional = typeof schema.additionalProperties === 'object' ? schema.additionalProperties : undefined; + return Object.fromEntries(Object.entries(value).flatMap(([key, item]): Array<[string, unknown]> => { + const child = own(schema.properties, key) ?? additional; + return isAbsentNull(item, child, required.has(key)) ? [] : [[key, withoutAbsentNulls(item, child)]]; + })); +} + +const pathText = (path: readonly PropertyKey[]): string => + path.reduce((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text ? `${text}.${String(key)}` : String(key)), ''); + +/** The JSON Schema at `path` under `schema`, through properties, items and additionalProperties, and whether a node on the way is secret. */ +function schemaAt(schema: JSONSchema | undefined, path: readonly PropertyKey[]): { node: JSONSchema | undefined; secret: boolean } { + let node = schema; + let secret = isSecret(node); + for (const key of path) { + if (!isPlainObject(node)) return { node: undefined, secret }; + const additional = typeof node.additionalProperties === 'object' ? node.additionalProperties : undefined; + node = typeof key === 'number' ? node.items : own(node.properties, String(key)) ?? additional; + secret ||= isSecret(node); + } + return { node, secret }; +} + +function valueAt(value: unknown, path: readonly PropertyKey[]): unknown { + return path.reduce((at, key) => (isPlainObject(at) || Array.isArray(at) ? (at as Record)[key] : undefined), value); +} + +/** At most this many allowed keys are listed in a hint; a longer list is left to --schema. */ +const MAX_LISTED_KEYS = 10; + +function keyHint(key: string, allowed: string[], at: string): string | undefined { + const near = closest(key, allowed); + const parts = near.length ? [`Did you mean ${orList(near.map((name) => `"${name}"`))}?`] : []; + if (allowed.length && allowed.length <= MAX_LISTED_KEYS) parts.push(`The keys allowed ${at ? `at ${at}` : 'here'} are ${allowed.join(', ')}.`); + return parts.length ? parts.join(' ') : undefined; +} + +/** What is wrong with a value, and, when the layer can tell, what to pass in its place. */ +interface Problem { + /** Where under the value it names, as text. */ + at: string; + message: string; + hint?: string; +} + +/** + * A zod issue in words: where (`display` writes a path as the reader names it), what, and the nearest allowed key or + * enum value when one is close. It never quotes the value, and inside a secret node it names no key and no value at all. + */ +function problemOf(issue: z.core.$ZodIssue, value: unknown, schema: JSONSchema, display: (path: readonly PropertyKey[]) => string): Problem { + const at = display(issue.path); + const { node, secret } = schemaAt(schema, issue.path); + if (secret) return { at, message: 'a value under it does not match its schema' }; + switch (issue.code) { + case 'unrecognized_keys': { + const [key] = issue.keys; + return { at, message: `the key "${key}" is not allowed`, hint: keyHint(key, Object.keys(node?.properties ?? {}), at) }; + } + case 'invalid_type': + if (valueAt(value, issue.path) === undefined) { + return { at: display(issue.path.slice(0, -1)), message: `the required key "${String(issue.path[issue.path.length - 1])}" is missing` }; + } + return { at, message: `expected ${issue.expected}` }; + case 'invalid_value': { + const given = valueAt(value, issue.path); + const near = typeof given === 'string' ? closest(given, issue.values.filter((member): member is string => typeof member === 'string')) : []; + return { + at, + message: `expected one of ${issue.values.map((member) => JSON.stringify(member)).join(', ')}`, + hint: near.length ? `Did you mean ${orList(near.map((member) => `"${member}"`))}?` : undefined + }; + } + default: + return { at, message: issue.message.replace(/\.$/, '').replace(/^\w/, (first) => first.toLowerCase()) }; + } +} + +/** Where a value of the input came from, as an error names it: `--input`, a flag, or an argument. */ +export type InputLabels = Map; + +/** + * The input after the one null rule, parsed by the command's zod schema. A failure is `invalid-input`: it names the + * flag (or --input, or the argument) of the first bad value and where in it, lists every issue in `details.issues`, + * and never quotes a value. + */ +export function parseInput(schema: InputSchema, json: JSONSchema, values: Record, labels: InputLabels, schemaHint: string): Record { + const given = withoutAbsentNulls(values, json) as Record; + const parsed = schema.safeParse(given); + if (parsed.success) return parsed.data; + const issues = parsed.error.issues.map((issue) => { + const property = typeof issue.path[0] === 'string' ? issue.path[0] : undefined; + const label = property ? labels.get(property) ?? `--${kebabCase(property)}` : '--input'; + // A value given in --input is named from the top of the input, one given in a flag from the top of the flag. + const display = label === '--input' ? pathText : (path: readonly PropertyKey[]) => pathText(path.slice(1)); + const { at, message, hint } = problemOf(issue, given, json, display); + return { label, at, message, hint }; + }); + const [first] = issues; + throw invalidInput( + `${first.label} is not valid: ${first.at ? `at ${first.at}, ` : ''}${first.message}.`, + first.hint ?? schemaHint, + first.label, + { issues: issues.map(({ label, at, message }) => ({ flag: label, ...(at ? { path: at } : {}), message })) } + ); +} + +/** The value of one flag, checked by its own zod schema; the error that names it, or undefined when it fits. */ +function checkOne(def: FlagDef, value: unknown): string | undefined { + const given = withoutAbsentNulls(value, def.schema); + const parsed = def.check.safeParse(given); + if (parsed.success) return undefined; + const problem = problemOf(parsed.error.issues[0], given, def.schema, pathText); + return `--${def.flag} is not valid: ${problem.at ? `at ${problem.at}, ` : ''}${problem.message}.`; +} + +export interface InputRequest { + table: FlagTable; + positionals: readonly string[]; + tokens: Token[]; + /** The value of --input. */ + input?: string; + cwd: string; + /** What the input is for: its usage text, its command path, and the run's step builder. */ + scope: Scope; + readStdin(): Promise; +} + +async function readInputObject(request: InputRequest, labels: InputLabels): Promise> { + const label = '--input'; + const schemaHint = `Run "${request.scope.usage} --schema" to see the input properties.`; + const fromStdin = request.input === '-'; + const text = fromStdin ? await request.readStdin() : readJsonText(request.input, label, request.cwd); + if (fromStdin && text.trim() === '') { + throw invalidInput('--input - read nothing from stdin.', 'Pipe a JSON object into the command, or pass the JSON inline with --input \'{...}\'.', label); + } + const parsed = parseJson(text, label); + if (!isPlainObject(parsed)) { + throw invalidInput('--input must be a JSON object.', `Pass an object whose keys are the input properties. ${schemaHint}`, label); + } + const inputProperties = request.table.flags.filter((def) => def.scope === 'input').map((def) => def.property); + const values: Record = {}; + for (const [key, raw] of Object.entries(parsed)) { + const def = request.table.lookup.get(key); + if (!def || def.scope !== 'input') { + const suggestions = closest(key, inputProperties).map((property) => `"${property}"`); + throw invalidInput(`--input has the unknown key "${key}".`, suggestions.length ? `Did you mean ${orList(suggestions)}?` : schemaHint, label); + } + if (Object.hasOwn(values, def.property)) { + throw invalidInput(`--input sets "${def.property}" twice, with two spellings of the key.`, 'Keep one of the keys.', label); + } + values[def.property] = raw; + labels.set(def.property, label); + } + return values; +} + +/** The flag of the argument at `index`: its positional's, or the last one's when that one is a list, which takes the rest. */ +export function positionalAt(names: readonly string[], table: FlagTable, index: number): FlagDef | undefined { + if (index < names.length) return table.lookup.get(names[index]); + const last = names.length ? table.lookup.get(names[names.length - 1]) : undefined; + return last?.kind.kind === 'list' ? last : undefined; +} + +/** + * Merges --input, positionals and flags (in rising priority) into the raw input, with the label of each value, and + * the required flags still missing. Schema defaults are zod's to fill, when it parses the input. + */ +export async function readInput(request: InputRequest): Promise<{ values: Record; labels: InputLabels; missing: FlagDef[] }> { + const { table, tokens, cwd, positionals: names } = request; + const labels: InputLabels = new Map(); + const values = request.input === undefined ? {} : await readInputObject(request, labels); + const given = readScope(tokens, 'input', cwd); + for (const property of Object.keys(given)) labels.set(property, `--${table.lookup.get(property).flag}`); + const positionals = tokens.filter((token): token is Extract => token.kind === 'positional'); + const extra = positionals.find((_token, index) => !positionalAt(names, table, index)); + if (extra) { + const takes = names.length === 0 ? 'no arguments' : `${names.length} argument${names.length === 1 ? '' : 's'} (${names.join(', ')})`; + const { usage, path, step } = request.scope; + throw usageError('unexpected-argument', `"${usage}" takes ${takes}, but got the extra argument "${extra.value}".`, { + hint: `Pass other values as flags. Run "${usage} --help" to list them.`, + next: [step([...path, '--help'], 'List the arguments and flags')] + }); + } + const raws = new Map(); + positionals.forEach((token, index) => { + const def = positionalAt(names, table, index); + raws.set(def, [...(raws.get(def) ?? []), token.value]); + }); + for (const [def, values] of raws) { + if (Object.hasOwn(given, def.property)) { + throw invalidInput(`"${def.property}" was given twice: as argument ${names.indexOf(def.property) + 1} and as --${def.flag}.`, 'Give it once.', `--${def.flag}`); + } + given[def.property] = coerceFlag(def, values, `<${def.flag}>`, cwd); + labels.set(def.property, `<${def.flag}>`); + } + Object.assign(values, given); + const missing = table.flags.filter((def) => def.scope === 'input' && def.required && own(values, def.property) === undefined); + return { values, labels, missing }; +} + +export const REDACTED = '***'; +const MIN_SEARCH_LENGTH = 8; +const SHELL_SAFE = /^[\w@%+=:,./-]+$/; + +// A leading = is quoted too: zsh (the macOS default shell) expands `=name` to the path of a command `name`. +export const shellQuote = (word: string): string => + SHELL_SAFE.test(word) && !word.startsWith('=') ? word : `'${word.replace(/'/g, `'\\''`)}'`; + +/** The CLI name and the words, each shell-quoted where needed, so that a POSIX shell reads every word as one. */ +export const quoteCommand = (cliName: string, words: readonly string[]): string => [cliName, ...words].map(shellQuote).join(' '); + +const wordText = (word: NextWord): string => (typeof word === 'string' ? word : `<${word.placeholder}>`); + +/** A next step: `argv` is exact, `command` is quoted for POSIX shells, and a placeholder stays bare in both. */ +export function nextStep(cliName: string, words: readonly NextWord[], why: string): NextStep { + const argv = [cliName, ...words.map(wordText)]; + const command = [shellQuote(cliName), ...words.map((word) => (typeof word === 'string' ? shellQuote(word) : wordText(word)))].join(' '); + const placeholders = [...new Set(words.filter((word) => typeof word !== 'string').map(wordText))]; + return placeholders.length ? { command, argv, placeholders, why } : { command, argv, why }; +} + +function containsSecret(schema: JSONSchema | undefined): boolean { + if (!isPlainObject(schema)) return false; + if (schema['x-secret'] === true) return true; + const additional = typeof schema.additionalProperties === 'object' ? schema.additionalProperties : undefined; + const children = [...Object.values(schema.properties ?? {}), schema.items, additional, ...(schema.anyOf ?? []), ...(schema.oneOf ?? []), ...(schema.allOf ?? [])]; + return children.some(containsSecret); +} + +/** A node is secret when it is marked, or when it is a union with a secret in any branch (the branch a value took is unknown). */ +export function isSecret(schema: JSONSchema | undefined): boolean { + if (!isPlainObject(schema)) return false; + return schema['x-secret'] === true || [schema.anyOf, schema.oneOf, schema.allOf].some((branches) => branches?.some(containsSecret) ?? false); +} + +function collectLeaves(value: unknown, into: string[]): void { + if (typeof value === 'string') into.push(value); + else if (typeof value === 'number') into.push(String(value)); + else if (Array.isArray(value)) value.forEach((item) => collectLeaves(item, into)); + else if (isPlainObject(value)) Object.values(value).forEach((item) => collectLeaves(item, into)); +} + +export interface SplitSecrets { + /** The value with every x-secret node replaced by ***. */ + redacted: unknown; + /** Every string and number under an x-secret node. */ + secrets: string[]; + found: boolean; +} + +/** The one walk of a value with its schema that decides what is secret. Nothing else adds to `secrets`. */ +export function splitSecrets(value: unknown, schema: JSONSchema | undefined): SplitSecrets { + const secrets: string[] = []; + let found = false; + const walk = (node: unknown, nodeSchema: JSONSchema | undefined): unknown => { + if (node === undefined || !nodeSchema) return node; + if (isSecret(nodeSchema)) { + found = true; + collectLeaves(node, secrets); + return REDACTED; + } + if (Array.isArray(node)) return node.map((item) => walk(item, nodeSchema.items)); + if (!isPlainObject(node)) return node; + const additional = typeof nodeSchema.additionalProperties === 'object' ? nodeSchema.additionalProperties : undefined; + return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, walk(item, own(nodeSchema.properties, key) ?? additional)])); + }; + const redacted = walk(value, schema); + return { redacted, secrets, found }; +} + +/** + * Patterns for text the layer did not write, such as a message a command throws: each secret of 8 or more + * characters, raw, JSON-escaped and shell-quoted, longest first. A shorter secret would match ordinary words. + */ +export function searchPatterns(secrets: string[]): string[] { + const patterns = new Set(); + for (const secret of secrets) { + if (secret.length < MIN_SEARCH_LENGTH) continue; + patterns.add(secret); + patterns.add(JSON.stringify(secret).slice(1, -1)); + patterns.add(shellQuote(secret)); + } + return [...patterns].sort((a, b) => b.length - a.length); +} + +export const redactText = (text: string, patterns: string[]): string => + patterns.reduce((result, pattern) => result.split(pattern).join(REDACTED), text); + +/** JSON text with its secret nodes as ***; text that does not parse is *** whole when the schema holds a secret. */ +function redactJsonText(text: string, schema: JSONSchema | undefined): string { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return containsSecret(schema) ? REDACTED : text; + } + const split = splitSecrets(parsed, schema); + return split.found ? JSON.stringify(split.redacted) : text; +} + +/** One argv word that holds a value of `def`, with its secrets replaced where they sit. */ +function redactWord(word: string, def: FlagDef): string { + if (def.secret) return REDACTED; + switch (def.kind.kind) { + case 'list': + if (word.trimStart().startsWith('[')) return redactJsonText(word, def.schema); + return isSecret(def.schema.items) ? REDACTED : word; + case 'json': + return word.startsWith('@') ? word : redactJsonText(word, def.schema); + default: + return word; + } +} + +/** Builds a next step of one run: the CLI name, the run's carried flags but those named in `drop`, then `words`. */ +export type StepBuilder = (words: readonly NextWord[], why: string, options?: StepOptions) => NextStep; + +/** What a usage error or a hint is about: the text a person typed for it, its command path, and the run's steps. */ +export interface Scope { + usage: string; + path: string[]; + step: StepBuilder; +} + +const isCarried = (def: FlagDef): boolean => def.scope !== 'input' && def.schema['x-carry'] === true; + +/** + * The step builder of one run. It repeats each flag of the run marked x-carry right after the CLI name, in argv + * order, as typed, with a secret value as a placeholder named after its flag; a step leaves out the carried flags + * named in `drop`. `table` is the one the run was parsed with, and `argvIndex` maps a token index back to argv. + */ +export function stepBuilder( + cliName: string, + argv: readonly string[], + tokens: Token[], + argvIndex: (tokenIndex: number) => number, + table: FlagTable +): StepBuilder { + const given = tokens.flatMap((token): Array<{ def: FlagDef; words: NextWord[] }> => { + if (token.kind !== 'flag' || !isCarried(token.def)) return []; + const at = argvIndex(token.index); + const valueAt = token.valueIndex === undefined ? undefined : argvIndex(token.valueIndex); + const secret = typeof token.value === 'string' && redactWord(token.value, token.def) !== token.value; + const placeholder = { placeholder: token.def.flag }; + if (valueAt === undefined) return [{ def: token.def, words: [argv[at]] }]; + if (valueAt === at) return [{ def: token.def, words: secret ? [argv[at].slice(0, argv[at].indexOf('=')), placeholder] : [argv[at]] }]; + return [{ def: token.def, words: [argv[at], secret ? placeholder : argv[valueAt]] }]; + }); + // A one-value flag given twice failed this run; repeating both values would fail the step too, and keeping one + // would choose for the person. The step names the flag once, with a placeholder for the value they choose. + const count = (def: FlagDef): number => given.filter((flag) => flag.def === def).length; + const carried = given.flatMap((flag, index) => { + if (flag.def.kind.kind === 'list' || count(flag.def) === 1) return [flag]; + if (given.findIndex((other) => other.def === flag.def) !== index) return []; + return [{ def: flag.def, words: [flagName(flag.def.property), { placeholder: flag.def.flag }] }]; + }); + return (words, why, { drop = [] } = {}) => { + const dropped = new Set(drop.map((spelling) => { + const named = flagNamed(spelling.replace(/^--/, ''), table); + if (!named || !isCarried(named.def)) { + throw new Error(`A next step cannot drop ${spelling}, because it is not a carried global flag of ${cliName}. Name a global flag marked x-carry, for example --cwd.`); + } + return named.def; + })); + return nextStep(cliName, [...carried.filter(({ def }) => !dropped.has(def)).flatMap((flag) => flag.words), ...words], why); + }; +} + +export interface CommandLine { + invocation: string; + followUp(flags: string[], options: FollowUpOptions): NextStep; +} + +/** + * The command line as given, secrets as *** and words shell-quoted where needed, plus next steps built from it. + * `tokens` come from the argv without the command path, whose argv indexes are `path`; `argvIndex` maps a token + * index back to argv. `input` is the command's input JSON Schema, for the secrets of --input. + */ +export function commandLine( + cliName: string, + usage: string, + argv: readonly string[], + path: readonly number[], + argvIndex: (tokenIndex: number) => number, + tokens: Token[], + positionals: readonly string[], + input: JSONSchema | undefined, + table: FlagTable +): CommandLine { + const words = [...argv]; + const flagWords: Array<{ def: FlagDef; at: number[] }> = []; + // A redacted word, by argv index: the placeholder a follow-up shows, and the flag spelling of an inline `--x=v`. + const secrets = new Map(); + let separator: number | undefined; + let slot = 0; + for (const token of tokens) { + if (token.kind === 'separator') { + separator = argvIndex(token.index); + } else if (token.kind === 'positional') { + const def = positionalAt(positionals, table, slot++); + const at = argvIndex(token.index); + if (!def) continue; + const value = redactWord(token.value, def); + if (value === token.value) continue; + words[at] = value; + secrets.set(at, { placeholder: def.flag }); + } else if (token.kind === 'flag') { + const at = argvIndex(token.index); + const valueAt = token.valueIndex === undefined ? undefined : argvIndex(token.valueIndex); + flagWords.push({ def: token.def, at: valueAt === undefined || valueAt === at ? [at] : [at, valueAt] }); + if (valueAt === undefined || typeof token.value !== 'string') continue; + const isInput = token.def.scope === 'layer' && token.def.property === 'input'; + const keep = isInput && (token.value === '-' || token.value.startsWith('@')); + const value = keep ? token.value : isInput ? redactJsonText(token.value, input) : redactWord(token.value, token.def); + if (value === token.value) continue; + const inline = valueAt === at; + const flagText = inline ? words[at].slice(0, words[at].indexOf('=')) : undefined; + words[valueAt] = inline ? `${flagText}=${value}` : value; + secrets.set(valueAt, { placeholder: token.def.flag, inlineFlag: flagText }); + } + } + // One argv word as a next step shows it: a redacted secret is a placeholder, and an inline `--x=secret` two words. + const stepWords = (index: number): NextWord[] => { + const secret = secrets.get(index); + if (!secret) return [words[index]]; + return secret.inlineFlag ? [secret.inlineFlag, { placeholder: secret.placeholder }] : [{ placeholder: secret.placeholder }]; + }; + return { + invocation: quoteCommand(cliName, words), + followUp(flags, { why, drop = [], command: newPath }) { + const dropped = new Set(drop.map((spelling) => { + const named = flagNamed(spelling.replace(/^--/, ''), table); + if (!named) throw new Error(`followUp cannot drop ${spelling}, because it is not a flag of "${usage}". Name a flag the command accepts.`); + return named.def; + })); + const removed = new Set(flagWords.filter(({ def }) => dropped.has(def)).flatMap(({ at }) => at)); + const end = separator ?? words.length; + const out: NextWord[] = []; + for (let index = 0; index <= words.length; index++) { + if (index === end) out.push(...flags); + if (index === words.length || removed.has(index)) continue; + if (path.includes(index)) { + if (newPath === undefined) out.push(words[index]); + else if (index === path[0]) out.push(...newPath.split(' ')); + continue; + } + out.push(...stepWords(index)); + } + return nextStep(cliName, out, why); + } + }; +} + +/** The flag a person types for an input property, for example `--table-name` for `table_name`. */ +export const flagName = (property: string): string => `--${kebabCase(property)}`; + +const isPlaceholder = (value: unknown): value is { placeholder: string } => + isPlainObject(value) && Object.keys(value).length === 1 && typeof value.placeholder === 'string'; + +/** The one word that carries `value` for `def`, as a positional or after its flag; undefined when no word can. */ +function valueWord(def: FlagDef, value: unknown): string | undefined { + if (value === null && def.kind.kind !== 'json') return undefined; + switch (def.kind.kind) { + case 'boolean': + case 'scalar': + case 'enum': + return String(value); + case 'list': + case 'json': + return JSON.stringify(value); + } +} + +/** A word that the tokenizer reads as a positional, not as a flag. */ +const standsAlone = (word: string): boolean => !(word.startsWith('-') && word !== '-' && !NEGATIVE_NUMBER.test(word)); + +/** A flag and its value; a value that starts with -- is written inline, or the tokenizer would read it as a flag. */ +const flagWordsOf = (def: FlagDef, word: string): string[] => + word.startsWith('--') ? [`${flagName(def.property)}=${word}`] : [flagName(def.property), word]; + +/** + * The words after a command path that make the parser read `input` back: positionals as bare words in their + * declared order while each can stand alone, then flags in the order of `input`. A list is repeated flags unless an + * item would read as JSON (or it is empty), and then one JSON word. A value that no flag can carry (null for a + * scalar flag) goes into one --input word, which the parser reads before the flags. A secret or a + * `{ placeholder }` value becomes a placeholder word. Throws for a key or a value the command's schema refuses. + */ +export function inputWords(positionals: readonly string[], table: FlagTable, input: Record, usage: string): NextWord[] { + const inputs = table.flags.filter((def) => def.scope === 'input'); + const entries: Array<[string, unknown]> = []; + const defs = new Map(); + for (const [key, raw] of Object.entries(input)) { + if (raw === undefined) continue; + const def = inputs.find((candidate) => candidate.property === key); + if (!def) { + throw new Error(`nextFor cannot pass "${key}" to "${usage}", because its input schema has no such property. Known properties: ${inputs.map((known) => known.property).join(', ') || 'none'}.`); + } + if (isPlaceholder(raw)) { + defs.set(key, def); + entries.push([key, raw]); + continue; + } + if (isAbsentNull(raw, def.schema, def.required)) continue; + const value = withoutAbsentNulls(raw, def.schema); + const problem = def.secret ? undefined : checkOne(def, value); + if (problem) throw new Error(`nextFor cannot pass the input to "${usage}": ${problem}`); + defs.set(key, def); + entries.push([key, value]); + } + const placeholderFor = (def: FlagDef, value: unknown): NextWord | undefined => { + if (isPlaceholder(value)) return value; + if (def.secret || ((def.kind.kind === 'json' || def.kind.kind === 'list') && splitSecrets(value, def.schema).found)) { + return { placeholder: def.flag }; + } + return undefined; + }; + + const words: NextWord[] = []; + const asPositional = new Set(); + for (const name of positionals) { + if (!defs.has(name)) break; + const value = entries.find(([key]) => key === name)[1]; + const placeholder = placeholderFor(defs.get(name), value); + const word = placeholder ? undefined : valueWord(defs.get(name), value); + if (!placeholder && (word === undefined || !standsAlone(word))) break; + words.push(placeholder ?? word); + asPositional.add(name); + } + + const inputOnly: Record = {}; + for (const [key, value] of entries) { + if (asPositional.has(key)) continue; + const def = defs.get(key); + const placeholder = placeholderFor(def, value); + if (placeholder) { + words.push(flagName(def.property), placeholder); + } else if (value === null && def.kind.kind !== 'json') { + inputOnly[key] = value; + } else if (def.kind.kind === 'boolean') { + words.push(value ? flagName(def.property) : `--no-${def.flag}`); + } else if (def.kind.kind === 'list') { + const items = value as unknown[]; + const repeated = items.length > 0 && items.every((item) => !String(item).trimStart().startsWith('[')); + words.push(...(repeated ? items.flatMap((item) => flagWordsOf(def, String(item))) : flagWordsOf(def, JSON.stringify(items)))); + } else { + words.push(...flagWordsOf(def, valueWord(def, value))); + } + } + if (Object.keys(inputOnly).length) words.push('--input', JSON.stringify(inputOnly)); + return words; +} + +function questionFor(def: FlagDef, cwd: string): Question { + const base = { name: def.property, message: def.schema.description ?? def.property, required: true }; + switch (def.kind.kind) { + case 'enum': + return { ...base, type: 'list', options: def.kind.values.map((value) => ({ name: String(value), value })) }; + case 'boolean': + return { ...base, type: 'confirm' }; + default: { + const validate = (answer: unknown): Validation => { + if (answer === null || answer === undefined) return { success: true }; + try { + const problem = checkOne(def, typeof answer === 'string' ? coerceFlag(def, [answer], `--${def.flag}`, cwd) : answer); + return problem ? { success: false, reason: problem } : { success: true }; + } catch (error) { + return { success: false, reason: (error as Error).message }; + } + }; + return def.secret ? { ...base, type: 'password', validate } : { ...base, type: 'text', validate }; + } + } +} + +/** Prompts for each missing value with a prompt built from its schema, and types the answers like flags. */ +export async function askFor(missing: FlagDef[], prompter: Inquirerer, cwd: string): Promise> { + const answers = await prompter.prompt>({}, missing.map((def) => questionFor(def, cwd))); + const values: Record = {}; + for (const def of missing) { + const answer = own(answers, def.property); + values[def.property] = typeof answer === 'string' ? coerceFlag(def, [answer], `--${def.flag}`, cwd) : answer; + } + return values; +} + +/** Optimal string alignment distance: inserts, deletes, substitutions, and swaps of two neighbouring characters. */ +function editDistance(left: string, right: string): number { + const rows = Array.from({ length: left.length + 1 }, (_, i) => Array.from({ length: right.length + 1 }, (__, j) => (i === 0 ? j : j === 0 ? i : 0))); + for (let i = 1; i <= left.length; i++) { + for (let j = 1; j <= right.length; j++) { + const cost = left[i - 1] === right[j - 1] ? 0 : 1; + rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && left[i - 1] === right[j - 2] && left[i - 2] === right[j - 1]) rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1); + } + } + return rows[left.length][right.length]; +} + +/** + * The one rule for a suggestion (a flag, a command, a key, an enum value): the edit distance from what was typed, + * when it is at most one edit for every four characters typed, so `foo` allows one edit and `permisive` two. + */ +export function nearness(typed: string, candidate: string): number | undefined { + const distance = editDistance(typed, candidate); + return distance <= Math.floor((typed.length + 1) / 4) ? distance : undefined; +} + +export function closest(input: string, candidates: string[]): string[] { + return candidates + .map((candidate) => ({ candidate, distance: nearness(input, candidate) })) + .filter(({ distance }) => distance !== undefined) + .sort((a, b) => a.distance - b.distance || a.candidate.localeCompare(b.candidate)) + .slice(0, 3) + .map(({ candidate }) => candidate); +} diff --git a/agentic/command/src/tool-command.ts b/agentic/command/src/tool-command.ts new file mode 100644 index 0000000000..6dc28274fa --- /dev/null +++ b/agentic/command/src/tool-command.ts @@ -0,0 +1,322 @@ +import { + type AnyHarnessTool, + callChange, + type GateDecision, + type GatePolicy, + type HarnessTool, + type HarnessToolContent, + type HarnessToolResult, + type ToolCallSuggestion, + type ToolFailure, + type ToolFailureCode +} from '@agentic-kit/harness'; +import { z } from 'zod'; + +import { + type ChangeCommand, + CliError, + type CommandContext, + type CommandExample, + type CommandResult, + ExitCode, + type InputSchema, + type NextStep, + type Planned, + type ReadCommand, + type StepOptions +} from './types'; + +interface ToolCommandBase { + /** Space-separated command path, for example 'table add'. */ + name: string; + /** Default: the tool's label. */ + summary?: string; + /** Default: the tool's description. */ + description?: string; + positionals?: string[]; + examples?: CommandExample[]; + notes?: string[]; + /** Default: the tool's text content. */ + text?(details: TDetails): string; + /** The commands to run after a call that succeeded; build each with `ctx.next`. */ + next?(details: TDetails, params: TParams, ctx: CommandContext): NextStep[]; + /** + * This command's input for a call of its tool that a tool suggests (the inverse of `mapInput`), or undefined when + * this command cannot make that call. Without it, the call's params are the input when this command takes each of + * them as an input property. + */ + toInput?(params: Record): Record | undefined; +} + +/** A command bound to a tool, for writing the calls a tool suggests as next steps. */ +export interface ToolBinding { + /** The command path, for example 'field update'. */ + command: string; + /** Its input properties. */ + properties: ReadonlySet; + toInput?(params: Record): Record | undefined; +} + +/** The command takes the tool's own params as its input, or a friendlier input that `mapInput` turns into them. */ +type ToolCommandInput = + | { input?: never; mapInput?: never } + | { input: TInput; mapInput(input: z.output, ctx: CommandContext): TParams | Promise }; + +export type ToolCommandOptions = ToolCommandBase & ToolCommandInput; + +export interface ToolCommandDeps { + gate: GatePolicy; + /** The next steps of a failed or blocked call, by its failure. */ + failureNext?: FailureNext; + /** Tool name to every command bound to it, in the order a call of the tool is tried on them. */ + bindings?: ReadonlyMap; + /** Told about a suggested call no bound command can make: a bug in a tool or a binding, which a test should fail on. */ + onUnrenderedCall?(call: ToolCallSuggestion, reason: string): void; +} + +/** One tool command, before the CLI is built; `toolCommand` keeps the tool's types for `mapInput`, `text` and `next`. */ +export interface ToolCommandEntry { + tool: AnyHarnessTool; + options: ToolCommandOptions; +} + +/** The tool's params as a command input: a zod object, whose properties become flags. */ +function paramsOf(tool: AnyHarnessTool): InputSchema { + const params = tool.parameters as unknown; + if (params instanceof z.ZodObject) return params; + throw new Error(`The tool "${tool.name}" takes params that are not a zod object, so they cannot be a command's flags. Give the command an input and a mapInput.`); +} + +const inputOf = (options: ToolCommandOptions, tool: AnyHarnessTool): InputSchema => options.input ?? paramsOf(tool); + +const propertiesOf = (schema: InputSchema): string[] => Object.keys(schema.shape); + +const pathText = (path: readonly PropertyKey[]): string => + path.reduce((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text ? `${text}.${String(key)}` : String(key)), ''); + +function parseParams(schema: TSchema, raw: unknown, usage: string, schemaStep: NextStep): z.output { + const parsed = schema.safeParse(raw); + if (parsed.success) return parsed.data; + const issues = parsed.error.issues.map((issue) => ({ path: pathText(issue.path), message: issue.message })); + const listed = issues.map((issue) => `${issue.path || 'the input'}: ${issue.message}`).join('; '); + throw new CliError({ + code: 'invalid-input', + message: `The input of "${usage}" is not valid: ${listed}.`, + hint: `Fix each listed value. Run "${usage} --schema" to see the input.`, + next: [schemaStep], + exitCode: ExitCode.usage, + details: { issues } + }); +} + +type Renderer = Pick; + +/** + * A suggested call as a next step of this CLI, made by the first command bound to its tool that takes its input + * (`toInput`, or the same names), with a placeholder for each input left to choose. A call no command can make gives + * no step, so a run never fails on it; `onUnrenderedCall` hears about it. + */ +function rendered(call: ToolCallSuggestion, ctx: CommandContext, deps: Renderer, options?: StepOptions): NextStep | undefined { + const params = { ...call.input, ...Object.fromEntries((call.choose ?? []).map((name) => [name, { placeholder: name }])) }; + const reasons: string[] = []; + for (const binding of deps.bindings?.get(call.tool) ?? []) { + const input = binding.toInput + ? binding.toInput(params) + : Object.keys(params).every((key) => binding.properties.has(key)) + ? params + : undefined; + if (!input) { + reasons.push(`"${binding.command}" does not take ${Object.keys(params).join(', ') || 'this call'}`); + continue; + } + try { + return ctx.nextFor(binding.command, input, call.why, options); + } catch (error) { + reasons.push(`"${binding.command}": ${error instanceof Error ? error.message : String(error)}`); + } + } + deps.onUnrenderedCall?.(call, reasons.join('; ') || `no command is bound to the tool ${call.tool}`); + return undefined; +} + +const stepsFor = (calls: readonly ToolCallSuggestion[] | undefined, ctx: CommandContext, deps: ToolCommandDeps): NextStep[] => + (calls ?? []).map((call) => rendered(call, ctx, deps)).filter((step): step is NextStep => step !== undefined); + +/** The steps in order, each command once: the first one keeps its reason. */ +function unique(...lists: NextStep[][]): NextStep[] { + const seen = new Set(); + return lists.flat().filter((step) => !seen.has(step.command) && Boolean(seen.add(step.command))); +} + +function textOf(content: HarnessToolContent[]): string | undefined { + const parts = content.flatMap((part) => (part.type === 'text' ? [part.text] : [])); + return parts.length ? parts.join('\n') : undefined; +} + +const FAILURE_EXIT_CODES: Partial> = { + 'signed-out': ExitCode.signInRequired, + 'step-up-required': ExitCode.signInRequired, + 'app-signed-out': ExitCode.signInRequired, + 'invalid-input': ExitCode.usage +}; + +/** The commands that follow a failure in this run: the CLI knows them, the tools do not. */ +export type FailureNext = (failure: ToolFailure, ctx: CommandContext) => NextStep[]; + +// The failure's own record, which a CliError has no field for: the id to +// report for a masked error, and the backend's public context. +function withFailureRecord(failure: ToolFailure, details: unknown): unknown { + const record = { + ...(failure.errorId ? { errorId: failure.errorId } : {}), + ...(failure.context ? { context: failure.context } : {}) + }; + if (Object.keys(record).length === 0) return details; + if (details === undefined) return record; + // Details that are not an object have no place for the keys, so they stay as they are. + return typeof details === 'object' && details !== null && !Array.isArray(details) ? { ...details, ...record } : details; +} + +/** + * A tool's or the gate's failure as the error of the command. Its `details` + * are the given details with the failure's `errorId` and `context`, when it + * has them. `next` are the commands to run after it. + */ +export function failureError(failure: ToolFailure, details?: unknown, next: NextStep[] = []): CliError { + return new CliError({ + code: failure.code, + message: failure.message, + hint: failure.hint, + retryable: failure.retryable, + exitCode: FAILURE_EXIT_CODES[failure.code] ?? ExitCode.failure, + ...(next.length ? { next } : {}), + details: withFailureRecord(failure, details) + }); +} + +/** The plan of a tool change: the gate's plan, and the params `apply` calls the tool with. */ +interface ToolPlanned extends Planned { + params: TParams; +} + +/** + * Binds `tool` to a command. A read runs the tool. A change plans with the gate (a blocked call stops with the gate's + * failure, under --dry-run too), and the layer applies it only once the run approves that plan. + */ +export function toCliCommand( + tool: HarnessTool, + options: ToolCommandOptions, TDetails>, + deps: ToolCommandDeps +): ReadCommand | ChangeCommand { + const input = inputOf(options, tool); + type Params = z.output; + // Without mapInput the input is the tool's own params, which the layer has parsed already. + const paramsFor = async (given: Record, ctx: CommandContext): Promise => { + if (!options.mapInput) return given as unknown as Params; + const usage = `${ctx.cliName} ${options.name}`; + return parseParams(tool.parameters, await options.mapInput(given as z.output, ctx), usage, ctx.next([...options.name.split(' '), '--schema'], 'See every input property')); + }; + // The calls a failure suggests come first, then the CLI's own steps for its code. + const failureNext = (failure: ToolFailure, ctx: CommandContext): NextStep[] => + unique(stepsFor(failure.calls, ctx, deps), deps.failureNext?.(failure, ctx) ?? []); + const finish = (result: HarnessToolResult, params: Params, ctx: CommandContext): CommandResult => { + if (result.failure) throw failureError(result.failure, result.details, failureNext(result.failure, ctx)); + const content = textOf(result.content); + const next = unique(stepsFor(result.calls, ctx, deps), options.next?.(result.details, params, ctx) ?? []); + return { + data: result.details, + text: options.text ? options.text(result.details) : content, + ...(next.length ? { next } : {}) + }; + }; + const shape = { + name: options.name, + summary: options.summary ?? tool.label, + description: options.description ?? tool.description, + input, + positionals: options.positionals, + examples: options.examples, + notes: options.notes + }; + if (tool.effect === 'read') { + const read: ReadCommand = { + ...shape, + effect: 'read', + async run(given, ctx) { + const params = await paramsFor(given, ctx); + return finish(await tool.execute(params, { cwd: ctx.cwd, signal: ctx.signal }), params, ctx); + } + }; + return read; + } + const change: ChangeCommand> = { + ...shape, + effect: tool.effect, + async plan(given, ctx) { + const params = await paramsFor(given, ctx); + const called = await callChange(tool, params as Record, deps.gate, ctx.cwd); + const decision = (called as { decision: GateDecision }).decision; + if (decision.kind === 'blocked') throw failureError(decision.failure, undefined, failureNext(decision.failure, ctx)); + return { plan: decision.prompt, params }; + }, + async apply(_given, { params }, ctx) { + return finish(await tool.execute(params, { cwd: ctx.cwd, signal: ctx.signal }), params, ctx); + } + }; + return change; +} + +/** One entry for `toCliCommands`, typed by its tool. */ +export function toolCommand( + tool: HarnessTool, + options: ToolCommandOptions, TDetails> +): ToolCommandEntry { + return { tool, options }; +} + +// A call of a tool bound to several commands is tried first on one that takes the tool's own params, which can make any call of it. +const inBindingOrder = (entries: readonly ToolCommandEntry[]): ToolCommandEntry[] => + [...entries.filter((entry) => !entry.options.input), ...entries.filter((entry) => entry.options.input)]; + +/** Tool name to every command bound to it, in the order a call of the tool is tried on them. */ +function bindingsOf(entries: readonly ToolCommandEntry[]): Map { + const bindings = new Map(); + for (const { tool, options } of inBindingOrder(entries)) { + bindings.set(tool.name, [ + ...(bindings.get(tool.name) ?? []), + { + command: options.name, + properties: new Set(propertiesOf(inputOf(options, tool))), + ...(options.toInput ? { toInput: options.toInput } : {}) + } + ]); + } + return bindings; +} + +/** A tool call written as a next step of this CLI, or undefined when no command bound to its tool can make it. */ +export type ToolCallStep = (call: ToolCallSuggestion, ctx: CommandContext, options?: StepOptions) => NextStep | undefined; + +/** + * Writes any tool call as a command of this CLI, from the same bindings and by the same rule as the next steps of + * the commands `toCliCommands` builds from `entries`. `options` go on to `ctx.nextFor` (`{ drop: ['--as'] }`). + */ +export function toolCallStep( + entries: readonly ToolCommandEntry[], + deps: { onUnrenderedCall?(call: ToolCallSuggestion, reason: string): void } = {} +): ToolCallStep { + const renderer: Renderer = { bindings: bindingsOf(entries), onUnrenderedCall: deps.onUnrenderedCall }; + return (call, ctx, options) => rendered(call, ctx, renderer, options); +} + +/** Every tool command of a CLI, each of which writes a call any tool of the set suggests as a step of the command bound to that tool. */ +export function toCliCommands( + entries: readonly ToolCommandEntry[], + deps: { + gate: GatePolicy; + failureNext?: FailureNext; + onUnrenderedCall?(call: ToolCallSuggestion, reason: string): void; + } +): Array> { + const bindings = bindingsOf(entries); + return entries.map(({ tool, options }) => toCliCommand(tool, options, { gate: deps.gate, bindings, failureNext: deps.failureNext, onUnrenderedCall: deps.onUnrenderedCall })); +} diff --git a/agentic/command/src/types.ts b/agentic/command/src/types.ts new file mode 100644 index 0000000000..8d4bec6372 --- /dev/null +++ b/agentic/command/src/types.ts @@ -0,0 +1,337 @@ +import type { ConfirmPrompt } from '@agentic-kit/harness'; +import type { Inquirerer } from 'inquirerer'; +import type { Readable, Writable } from 'stream'; +import type { z } from 'zod'; + +export type JSONSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'; + +/** The JSON Schema the layer makes from zod: what it reads flags from and prints in help, --schema and the manifest. */ +export interface JSONSchema { + type?: JSONSchemaType | JSONSchemaType[]; + title?: string; + description?: string; + enum?: readonly unknown[]; + const?: unknown; + default?: unknown; + examples?: unknown[]; + properties?: Record; + required?: readonly string[]; + additionalProperties?: boolean | JSONSchema; + items?: JSONSchema; + anyOf?: JSONSchema[]; + oneOf?: JSONSchema[]; + allOf?: JSONSchema[]; + /** Set with `.meta({ 'x-secret': true })`: the value is never echoed. */ + 'x-secret'?: boolean; + /** On a global flag: the flag chooses the target of a run (a backend, a directory), so next steps repeat it. */ + 'x-carry'?: boolean; + /** The one-letter short form of a flag of the command layer (`-y`); a command or a CLI global cannot declare one. */ + 'x-short'?: string; + [keyword: string]: unknown; +} + +export type Effect = 'read' | 'write' | 'destructive'; + +/** The input of a command: a zod object, strict or not, each property a flag. */ +export type InputSchema = z.ZodObject; + +export interface NextStep { + /** The line quoted for POSIX shells (sh, bash, zsh), for a person to read. fish reads it differently: run `argv`. */ + command: string; + /** The exact words to run, the CLI name first. */ + argv: string[]; + /** The words of `argv` that a caller must replace before running it, for example ``. */ + placeholders?: string[]; + why: string; +} + +/** A word of a next step: a literal word, or a placeholder for the caller to fill (`{ placeholder: 'url' }` is ``). */ +export type NextWord = string | { placeholder: string }; + +export interface StepOptions { + /** Carried global flags (x-carry) to leave out of this one step, in any spelling, for example `--as`. */ + drop?: string[]; +} + +export interface FollowUpOptions { + why: string; + /** Flags to remove, in any spelling and with their values, for example `--dry-run`. */ + drop?: string[]; + /** Another command path to run the same arguments with, for example 'api mutate'. */ + command?: string; +} + +export interface CommandExample { + command: string; + description?: string; +} + +export interface CommandContext { + cliName: string; + /** The command line as given, shell-quoted, with each secret value as ***. For display. */ + invocation: string; + /** + * The current command line as a next step: `flags` inserted before a `--` separator, each flag named in `drop` + * removed, and the command path replaced by `command` when given. Each secret becomes a placeholder. + */ + followUp(flags: string[], options: FollowUpOptions): NextStep; + /** A next step that runs another command: the CLI name, then `words`. It does no redaction, so never pass a secret. */ + next(words: readonly NextWord[], why: string, options?: StepOptions): NextStep; + /** + * A next step that runs the command `command` (a command path of this CLI) with `input` as its input, written with + * that command's flags so the parser reads `input` back. A `{ placeholder }` value and every secret become + * placeholder words. Throws for an unknown command, or a key or a value its input schema refuses. + */ + nextFor(command: string, input: Record, why: string, options?: StepOptions): NextStep; + cwd: string; + /** Prompts are allowed. */ + interactive: boolean; + format: 'text' | 'json'; + /** The run was given --yes: a change it plans is approved without a prompt. */ + yes: boolean; + /** Values of the CLI's own global flags. */ + globals: Record; + /** Use only when `interactive` is true. */ + prompter: Inquirerer; + signal: AbortSignal; + /** The stdin given to `run()` (default: the process's). The layer never reads it for the command. */ + stdin: Readable; + stdout: Writable; + stderr: Writable; + /** The environment given to `run()` (default: the process's). */ + env: NodeJS.ProcessEnv; +} + +export interface CommandResult { + data: TData; + /** Human rendering; a default renderer is used when omitted. */ + text?: string; + next?: NextStep[]; + warnings?: string[]; +} + +interface CommandShape { + /** Space-separated path, for example 'table add'. */ + name: string; + /** One line. */ + summary: string; + description?: string; + /** Each property is a flag. The layer parses the input with it once, so a command gets the parsed value. */ + input?: TSchema; + /** Property names taken from positional args, in order. The last one, when it is a list, takes every argument left. */ + positionals?: string[]; + output?: z.ZodType; + examples?: CommandExample[]; + /** Guidance for agents; shown in help and in the manifest. */ + notes?: string[]; + hidden?: boolean; +} + +/** A command that changes nothing: the layer runs it at once. */ +export interface ReadCommand extends CommandShape { + effect: 'read'; + run(input: z.output, ctx: CommandContext): Promise> | CommandResult; +} + +/** + * What a change will do. `plan` is what a person approves: the layer prints it for --dry-run, puts it in + * `error.details.plan` when the run stops for approval, and shows it before it asks. Any other key is what `apply` + * needs to make exactly that change, and the layer never prints it. + */ +export interface Planned { + plan: ConfirmPrompt; + /** + * Flags the run that applies this plan must add when it has no terminal, for example `--password-stdin` for a + * secret a terminal would ask for. The layer adds them to the step it gives after --dry-run and after exit 3. + */ + needs?: string[]; +} + +/** + * A command that changes something. The layer calls `plan`, then decides: --dry-run returns the plan, --yes + * approves it, a terminal asks, and anything else stops with exit 3. Only then does it call `apply`. + */ +export interface ChangeCommand extends CommandShape { + effect: 'write' | 'destructive'; + plan(input: z.output, ctx: CommandContext): Promise | TPlanned; + apply(input: z.output, planned: TPlanned, ctx: CommandContext): Promise> | CommandResult; +} + +/** + * A change that runs at once, with no plan: one the person makes to their own local session (sign in, sign out, choose + * a context), or one that only narrows what an agent may do. The person typed it, and a script must be able to run it + * as it is, so the layer refuses --dry-run, needs no --yes, and never asks. Only a write can be one, and a CLI keeps the + * list of these short and fixed: every other change has a plan. + */ +export interface ImmediateCommand extends CommandShape { + effect: 'write'; + immediate: true; + run(input: z.output, ctx: CommandContext): Promise> | CommandResult; +} + +/** + * A command that speaks a protocol on its stdin and stdout (an MCP server), whose client approves each change it + * makes, so the layer has no plan to show and refuses --dry-run and --yes. `effect` is the strongest effect its + * client can reach. The layer writes none of its results, errors or warnings on stdout; they go to stderr in the run's + * format. Help, --version, --schema and --llms, which a person asks for, still go to stdout. + */ +export interface ServeCommand extends CommandShape { + effect: Effect; + stdout: 'reserved'; + serve(input: z.output, ctx: CommandContext): Promise>; +} + +/** + * A command that keeps its own flags: `passthrough` gets every word after the command path, parsed by `parseArgv`, and + * the layer reads none of them, --help and --schema included, so it has no plan either. Returning no data prints nothing. + */ +export interface PassthroughCommand { + name: string; + summary: string; + description?: string; + examples?: CommandExample[]; + notes?: string[]; + hidden?: boolean; + effect: Effect; + passthrough(argv: Record, ctx: CommandContext): Promise | undefined>; +} + +export type CommandDefinition = ReadCommand | ChangeCommand | ImmediateCommand | ServeCommand | PassthroughCommand; + +export const ExitCode = { ok: 0, failure: 1, usage: 2, approvalRequired: 3, signInRequired: 4, interrupted: 130 } as const; + +/** + * Every failure code the command layer answers, with one sentence: what it means for the caller, and the kind of + * step that follows. The layer builds its errors only with these codes, so a new one needs its sentence to compile. + */ +export const COMMAND_ERROR_CODES = { + 'unknown-command': 'The words before the flags name no command, so nothing ran: the hint names the nearest command, and the step lists the commands of the group or of the CLI.', + 'unknown-topic': 'The words after help name no command, group or help topic, so nothing ran: the hint names the nearest one, and the step lists them all.', + 'unknown-flag': "A flag the command does not have was given, so nothing ran: the hint names the nearest flag, and the step shows the command's help.", + 'unexpected-argument': "More arguments were given than the command takes, so nothing ran: the step shows the command's help, and other values go in flags.", + 'missing-input': "A required value was not given and no prompt could ask for it, so nothing ran: error.details.missing names the flags, and the step shows the command's --schema.", + 'invalid-input': "A flag, an --input key or a JSON value does not match the command's schema, so nothing ran (for --fields on a read, only the selection of its output failed): the hint names the nearest allowed key or value, and the step shows the command's --schema.", + 'dry-run-unsupported': 'The command has no plan, so it has no dry run and nothing ran: it changes at once (a sign-in, a context, a narrower right), or it serves a protocol whose client approves each change; the step shows its help.', + 'approval-required': 'A change stopped before it was made because the run had no --yes and no terminal to ask on, so nothing changed: error.details.plan holds the plan to show the person, and the step reruns the command with --yes once they approve.', + cancelled: 'A prompt ended without an answer (Ctrl-C exits 130, the end of input exits 1), or the person declined, so the step it guarded changed nothing: run the command again when the person is ready.', + interrupted: "The run got SIGINT, and the layer aborted the command's signal and waited briefly for it to stop, so a change may be partly made: check the state before running the command again.", + failed: 'The command threw an error that is not a CliError, so the message is its own: rerun with DEBUG=1 for the stack in error.details.' +} as const satisfies Record; + +export type CommandErrorCode = keyof typeof COMMAND_ERROR_CODES; + +/** `Code` is the code union of whoever throws the error: the layer's `CommandErrorCode`, or a host's own. */ +export interface CliErrorInit { + code: Code; + message: string; + cause?: string; + hint?: string; + next?: NextStep[]; + retryable?: boolean; + exitCode?: number; + details?: unknown; +} + +// A registered symbol, so that two installed copies of this package recognize each other's errors. +const CLI_ERROR_BRAND = Symbol.for('agentic-kit.CliError'); + +/** True for a CliError from any copy of this package: the brand plus the shape, never `instanceof`. */ +export function isCliError(value: unknown): value is CliError { + if (typeof value !== 'object' || value === null) return false; + const error = value as Record; + return error[CLI_ERROR_BRAND] === true && typeof error.code === 'string' && typeof error.message === 'string' && typeof error.exitCode === 'number'; +} + +export class CliError extends Error { + readonly code: Code; + declare readonly cause?: string; + readonly hint?: string; + readonly next?: NextStep[]; + readonly retryable?: boolean; + readonly exitCode: number; + readonly details?: unknown; + + constructor(init: CliErrorInit) { + super(init.message); + Object.defineProperty(this, CLI_ERROR_BRAND, { value: true }); + this.name = 'CliError'; + this.code = init.code; + this.cause = init.cause; + this.hint = init.hint; + this.next = init.next; + this.retryable = init.retryable; + this.exitCode = init.exitCode ?? ExitCode.failure; + this.details = init.details; + } +} + +/** A section every reference has, which a topic can fill in place of a section of its own. */ +export type ReferenceSection = 'EXIT STATUS' | 'ENVIRONMENT' | 'FILES'; + +/** + * A page of help that is not a command: ` help ` prints it, root help and --llms list it, the manifest + * carries it, and the reference has it as a section. `body` is Markdown (paragraphs, lists and code, no headings), so + * it reads the same on a terminal and in the reference. + */ +export interface HelpTopic { + /** Lower-case words joined by "-", for example "exit-codes"; never the name of a command or of a group. */ + name: string; + /** One line. */ + summary: string; + body: string; + section?: ReferenceSection; +} + +export interface CliConfig { + name: string; + version: string; + description?: string; + commands: CommandDefinition[]; + /** The CLI's own global flags, for example --context. */ + globals?: InputSchema; + /** The agent guidance block of the root help. */ + notes?: string[]; + topics?: HelpTopic[]; +} + +export interface CliIO { + stdin?: Readable; + stdout?: Writable; + stderr?: Writable; + env?: NodeJS.ProcessEnv; + cwd?: string; +} + +export interface CommandManifest { + name: string; + summary: string; + description?: string; + effect: Effect; + positionals: string[]; + input?: JSONSchema; + output?: JSONSchema; + examples: CommandExample[]; + notes: string[]; + /** It keeps its own flags, and has no plan. */ + passthrough?: true; + /** It changes at once, with no plan, and refuses --dry-run. */ + immediate?: true; + /** It speaks a protocol on stdout, and has no plan: its client approves each change. */ + stdout?: 'reserved'; +} + +export interface CliManifest { + name: string; + version: string; + description?: string; + notes: string[]; + /** Flags every command accepts: the layer's own and the CLI's globals. Each property is a kebab-case flag. */ + globals: JSONSchema; + commands: CommandManifest[]; + topics: HelpTopic[]; +} + +export interface Cli { + run(argv?: string[], io?: CliIO): Promise; + manifest(): CliManifest; +} diff --git a/agentic/command/test-utils/command-fixture.ts b/agentic/command/test-utils/command-fixture.ts new file mode 100644 index 0000000000..6746605d70 --- /dev/null +++ b/agentic/command/test-utils/command-fixture.ts @@ -0,0 +1,73 @@ +import { z } from 'zod'; + +import { createCli } from '../src'; + +// With FIXTURE_TTY=1 the piped stdin and stdout pass for a terminal, so the layer prompts; no pty library is needed. +const tty = process.env.FIXTURE_TTY === '1'; +if (tty) { + Object.assign(process.stdin, { isTTY: true }); + Object.assign(process.stdout, { isTTY: true }); +} + +const cli = createCli({ + name: 'fixture', + version: '1.0.0', + commands: [ + { + name: 'greet', + summary: 'Greet someone', + effect: 'read', + positionals: ['name'], + input: z.object({ name: z.string().describe('Who to greet') }), + run: ({ name }) => ({ data: { greeting: `Hello, ${name}` } }) + }, + { + name: 'wait', + summary: 'Wait until interrupted', + effect: 'read', + run: (_input, ctx) => new Promise((resolve) => { + const timer = setInterval(() => undefined, 1000); + ctx.signal.addEventListener('abort', () => { + clearInterval(timer); + resolve({ data: null }); + }); + ctx.stderr.write('ready\n'); + }) + }, + { + name: 'linger', + summary: 'Clean up for a moment after an interrupt', + effect: 'read', + run: (_input, ctx) => new Promise((resolve) => { + const timer = setInterval(() => undefined, 1000); + ctx.signal.addEventListener('abort', () => setTimeout(() => { + clearInterval(timer); + ctx.stderr.write('settled\n'); + resolve({ data: null }); + }, 300)); + ctx.stderr.write('ready\n'); + }) + }, + { + name: 'approve', + summary: 'Change something after the approval of its plan', + effect: 'write', + plan: () => ({ plan: { title: 'Change it?', message: 'Change the fixture.', target: { kind: 'workspace', cwd: process.cwd() } } }), + apply: (_input, _planned, ctx) => { + ctx.stderr.write('applied\n'); + return { data: { applied: true } }; + } + }, + { + name: 'secret', + summary: 'Ask for a secret', + effect: 'read', + input: z.object({ password: z.string().meta({ 'x-secret': true, description: 'Password' }) }), + run: () => ({ data: { signedIn: true } }) + } + ] +}); + +cli.run(process.argv.slice(2), tty ? { stdin: process.stdin } : {}).then((code) => { + process.exitCode = code; +}); diff --git a/agentic/command/tsconfig.esm.json b/agentic/command/tsconfig.esm.json new file mode 100644 index 0000000000..a4afc3821d --- /dev/null +++ b/agentic/command/tsconfig.esm.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "moduleResolution": "bundler", + "module": "es2022", + "outDir": "dist/esm" + } +} diff --git a/agentic/command/tsconfig.json b/agentic/command/tsconfig.json new file mode 100644 index 0000000000..df063b5ee3 --- /dev/null +++ b/agentic/command/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"] +} diff --git a/agentic/mcp/README.md b/agentic/mcp/README.md new file mode 100644 index 0000000000..64bc334874 --- /dev/null +++ b/agentic/mcp/README.md @@ -0,0 +1,63 @@ +# @agentic-kit/mcp + +Serves `HarnessTool`s from `@agentic-kit/harness` as MCP tools on `@modelcontextprotocol/server` 2.x. It's the MCP host beside the command host (`@agentic-kit/command`): a tool's name, description, parameters, effect, gate, failures and follow-up calls all come from the tool object, and the plan text and the gate's decision come from the harness (`renderPlan`, `callChange`). + +```ts +import { constructiveDbTools, constructiveGateDeps } from '@agentic-kit/db-tools'; +import { createConstructiveGatePolicy } from '@agentic-kit/harness'; +import { serveStdio } from '@agentic-kit/mcp'; + +const server = serveStdio({ + name: 'constructive', + version, + tools, // the tools to serve + gate: createConstructiveGatePolicy(constructiveGateDeps()), + cwd: process.cwd(), // the project the tools act on + readOnly: true, // true: only the tools that read; false: the tools that write too + instructions // optional: the host's own guidance, sent after the server's +}); +await server.closed; // the client closed stdin +``` + +`createMcpServerFactory(options)` returns the same servers as a factory, for `createMcpHandler` on HTTP or an in-memory test. + +## Modes and tools + +`readOnly: true` serves the tools whose effect is `read`. `readOnly: false` serves those and the tools whose effect is `write`. A tool whose effect is `destructive` (it can lose data, or delete what the person set up), or whose effect depends on its input, is served in neither mode, so a client cannot call it. + +Each tool is listed under its own name, with its label as `title`, its description, and its zod parameters as the input schema: + +| Effect | `annotations` | `_meta` | +|---|---|---| +| `read` | `{ readOnlyHint: true }` | none | +| `write` | `{ readOnlyHint: false, destructiveHint: true, idempotentHint: false }` | `{ "anthropic/requiresUserInteraction": true }` | + +MCP reads `destructiveHint: false` as "only adds" and `idempotentHint: true` as "a second call changes nothing more". A write may change or replace what exists, and the tool object promises neither, so a write says the MCP defaults out loud. + +## The host approves each write + +Claude Code asks the person before every call of a tool marked with `anthropic/requiresUserInteraction`, in every permission mode and past allow rules. Where no one can answer (a `-p` run, or the `dontAsk` mode) it denies the call. Codex asks before a call of a tool that is not marked read-only in its `writes` approval mode. Annotations are hints that a host may ignore, so for any other host serve `readOnly: true`. + +A write call that reaches the server runs once: + +1. **The plan.** The gate makes the plan of the call. When the call cannot run (no one signed in, no database bound), the gate's failure comes back and nothing changes. +2. **The run.** The tool runs, and its result carries the plan: its own text, then "The plan of this call:" and the rendered plan, and the plan as `plan` in the envelope. + +**Preview.** When the client declares form elicitation, the server shows the plan once and asks "Apply this change?". The preview is optional, not a second approval: the host's own prompt is the approval, so the box starts ticked and accepting the form as shown applies the change. A decline, a closed question or a box the person unticks changes nothing: the result is `cancelled`, says that nothing was changed, and carries the plan. A client without elicitation gets no question. The preview shows the plan as it is when the question is asked. The gate makes the plan again when the answer comes back, and the result carries the plan that ran, so the result is where to read what changed. The preview doesn't decide whether a client may write, because the client sends the answer. + +## Results + +`content` is the tool's content, and `structuredContent` is an envelope: + +- a success: `{ ok: true, data, plan?, calls? }`; +- a failure, with `isError: true`: `{ ok: false, error: { code, message, hint?, retryable?, errorId?, context? }, data?, plan?, calls? }`. + +`plan` is there on every result of a write that got a plan. `calls` are the tool's follow-up calls, with tool names as they are, because the agent calls tools. A thrown tool error becomes `failed` with a fixed sentence that names the tool, and the error id when the server logged one; its text and stack are never shown, since they can carry the server's own words. + +## Instructions + +Every server sends instructions when a client connects. They name the read tools and say to call them first, name the tools that change things, and say that the host asks the person before each call of them. In read-only mode, they say that nothing changes through the server. The `instructions` option is added after them. Keep the whole text under 4,096 characters. + +## stdio + +`serveStdio` keeps stdout for the protocol: from the moment it starts, every other write to `process.stdout`, `console.log` among them, goes to stderr. A child process that inherits file descriptor 1 still writes past that, so a tool must start its child processes with piped output. diff --git a/agentic/mcp/__tests__/fixtures/stdio-server.ts b/agentic/mcp/__tests__/fixtures/stdio-server.ts new file mode 100644 index 0000000000..162c97df5d --- /dev/null +++ b/agentic/mcp/__tests__/fixtures/stdio-server.ts @@ -0,0 +1,33 @@ +import { defineHarnessTool } from '@agentic-kit/harness'; +import { z } from 'zod'; + +import { serveStdio } from '../../src'; + +// A read that writes to stdout the ways a tool or a library might. +const noisyRead = defineHarnessTool({ + name: 'noisy_read', + label: 'Noisy read', + description: 'A read that writes to stdout.', + parameters: z.object({}), + effect: 'read', + async execute() { + console.log('console noise'); + console.info('info noise'); + process.stdout.write('direct noise\n'); + return { content: [{ type: 'text', text: 'read done' }], details: { done: true } }; + } +}); + +const server = serveStdio({ + name: 'fixture', + version: '1.0.0', + tools: [noisyRead], + gate: { + isGated: () => true, + resolvePrompt: async () => ({ kind: 'blocked', failure: { code: 'unsupported', message: 'The fixture changes nothing.' } }) + }, + cwd: process.cwd(), + readOnly: true +}); + +void server.closed.then(() => process.stderr.write('server closed\n')); diff --git a/agentic/mcp/__tests__/server.test.ts b/agentic/mcp/__tests__/server.test.ts new file mode 100644 index 0000000000..d1dc46cb8f --- /dev/null +++ b/agentic/mcp/__tests__/server.test.ts @@ -0,0 +1,390 @@ +import { type ConfirmPrompt, defineHarnessTool, type GatePolicy, strictObject, type ToolFailure } from '@agentic-kit/harness'; +import { Client, InMemoryTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; +import { createMcpHandler } from '@modelcontextprotocol/server'; +import { z } from 'zod'; + +import { createMcpServerFactory } from '../src'; + +const cwd = '/tmp/agentic-mcp-project'; +const runs: Array<{ tool: string; params: unknown; cwd: string }> = []; +const asked: string[] = []; +const state: { database: string; blocked?: ToolFailure } = { database: 'db-1' }; + +const listThings = defineHarnessTool({ + name: 'list_things', + label: 'List things', + description: 'List the things. Call create_thing to add one.', + parameters: z.object({ prefix: z.string().optional() }), + effect: 'read', + async execute(params, ctx) { + runs.push({ tool: 'list_things', params, cwd: ctx.cwd }); + return { + content: [{ type: 'text', text: '2 things' }], + details: { things: ['a', 'b'] }, + calls: [{ tool: 'create_thing', input: {}, why: 'Add a thing', choose: ['thing_name'] }] + }; + } +}); + +const createThing = defineHarnessTool({ + name: 'create_thing', + label: 'Create thing', + description: 'Create a thing.', + parameters: z.object({ thing_name: z.string().describe('Name of the thing') }), + effect: 'write', + async execute(params, ctx) { + runs.push({ tool: 'create_thing', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: `Created ${params.thing_name}` }], details: { created: params.thing_name } }; + } +}); + +const deleteThing = defineHarnessTool({ + name: 'delete_thing', + label: 'Delete thing', + description: 'Delete a thing.', + parameters: z.object({ thing_name: z.string() }), + effect: 'destructive', + async execute(params, ctx) { + runs.push({ tool: 'delete_thing', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: `Deleted ${params.thing_name}` }], details: { deleted: params.thing_name } }; + } +}); + +const failure: ToolFailure = { + code: 'permission-denied', + message: 'This account may not change the thing.', + hint: 'Call explain_access to see who may.', + retryable: false, + errorId: 'err-42', + context: { table: 'things' }, + calls: [{ tool: 'explain_access', input: { table: 'things' }, why: 'See who may change it' }] +}; + +const failThing = defineHarnessTool({ + name: 'fail_thing', + label: 'Fail thing', + description: 'Always fails.', + parameters: z.object({}), + effect: 'read', + async execute() { + return { content: [{ type: 'text', text: `${failure.message} ${failure.hint}` }], details: { success: false }, failure }; + } +}); + +const throwThing = defineHarnessTool({ + name: 'throw_thing', + label: 'Throw thing', + description: 'Always throws.', + parameters: z.object({}), + effect: 'read', + async execute() { + // A thrown client error keeps the server's GraphQL errors, the logged one with its id. + const error = Object.assign(new Error('relation "secret_private.thing" does not exist'), { errors: [{ message: 'Internal error', extensions: { errorId: 'err-123' } }] }); + error.stack = 'Error: relation "secret_private.thing" does not exist\n at fetchWithToken (STACK-MARKER)'; + throw error; + } +}); + +const tools = [listThings, createThing, deleteThing, failThing, throwThing]; + +const planOf = (input: Record | undefined): ConfirmPrompt => ({ + title: 'Change it?', + message: `Change ${JSON.stringify(input)}.`, + target: { + kind: 'database', + database: { name: state.database, id: 'id-1' }, + apiEndpoint: 'http://api.localhost/graphql', + account: { userId: 'user-1' } + } +}); + +const gate: GatePolicy = { + isGated: () => { + throw new Error('The adapter must gate on the tool object, never by name.'); + }, + resolvePrompt: async (event, gateCwd) => { + asked.push(`${event.toolName} in ${gateCwd}`); + return state.blocked ? { kind: 'blocked', failure: state.blocked } : { kind: 'ask', prompt: planOf(event.input) }; + } +}; + +type Elicit = (message: string) => { action: 'accept' | 'decline' | 'cancel'; content?: Record }; + +async function connect(options: { era?: 'legacy' | 'modern'; elicit?: Elicit; readOnly?: boolean; tools?: typeof tools; instructions?: string } = {}) { + const factory = createMcpServerFactory({ + name: 'test-server', + version: '1.0.0', + tools: options.tools ?? tools, + gate, + cwd, + readOnly: options.readOnly === true, + instructions: options.instructions + }); + const client = new Client( + { name: 'test-client', version: '1.0.0' }, + { + capabilities: options.elicit ? { elicitation: { form: {} } } : {}, + ...(options.era === 'modern' ? { versionNegotiation: { mode: { pin: '2026-07-28' as const } } } : {}) + } + ); + if (options.elicit) { + const elicit = options.elicit; + client.setRequestHandler('elicitation/create', async (request) => elicit(request.params.message)); + } + if (options.era === 'modern') { + const handler = createMcpHandler(factory); + await client.connect(new StreamableHTTPClientTransport(new URL('http://test.local/mcp'), { + fetch: (url, init) => handler.fetch(new Request(url, init)) + })); + return { client, close: async () => { await client.close(); await handler.close(); } }; + } + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const server = factory(); + await server.connect(serverTransport); + await client.connect(clientTransport); + return { client, close: async () => { await client.close(); await server.close(); } }; +} + +type Envelope = { + ok: boolean; + data?: any; + plan?: ConfirmPrompt; + error?: { code: string; message: string; hint?: string; retryable?: boolean; errorId?: string; context?: unknown }; + calls?: Array<{ tool: string; input: Record; why: string; choose?: string[] }>; +}; + +const envelope = (result: { structuredContent?: unknown }): Envelope => result.structuredContent as Envelope; +const text = (result: { content?: unknown }): string => + (result.content as Array<{ type: string; text?: string }>).map((part) => part.text ?? '').join('\n'); + +let session: Awaited> | undefined; +const open = async (options?: Parameters[0]) => { + session = await connect(options); + return session.client; +}; + +beforeEach(() => { + runs.length = 0; + asked.length = 0; + state.database = 'db-1'; + state.blocked = undefined; +}); + +afterEach(async () => { + await session?.close(); + session = undefined; +}); + +describe('tools/list', () => { + it('marks each write tool for the host to ask the person on every call, and serves no tool that can be destructive', async () => { + const client = await open(); + const { tools: listed } = await client.listTools(); + const byName = Object.fromEntries(listed.map((tool) => [tool.name, tool])); + expect(Object.keys(byName)).toEqual(['list_things', 'create_thing', 'fail_thing', 'throw_thing']); + expect(byName.list_things).toMatchObject({ title: 'List things', description: 'List the things. Call create_thing to add one.' }); + expect(byName.list_things.annotations).toEqual({ readOnlyHint: true }); + expect(byName.list_things._meta).toBeUndefined(); + expect(byName.create_thing.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: false }); + expect(byName.create_thing._meta).toEqual({ 'anthropic/requiresUserInteraction': true }); + expect((byName.create_thing.inputSchema as any).properties).toEqual({ thing_name: { type: 'string', description: 'Name of the thing' } }); + await expect(client.callTool({ name: 'delete_thing', arguments: { thing_name: 'a' } })).rejects.toThrow(/not found/); + expect(runs).toEqual([]); + }); + + it('serves only the tools whose effect is read when read-only', async () => { + const client = await open({ readOnly: true }); + const { tools: listed } = await client.listTools(); + expect(listed.map((tool) => tool.name)).toEqual(['list_things', 'fail_thing', 'throw_thing']); + }); +}); + +describe('a read', () => { + it('runs without the gate, with the text as content and the details and calls as data', async () => { + const client = await open({ elicit: () => ({ action: 'decline' }) }); + const result = await client.callTool({ name: 'list_things', arguments: { prefix: 'a' } }); + expect(result.isError).toBeFalsy(); + expect(text(result)).toBe('2 things'); + expect(envelope(result)).toEqual({ + ok: true, + data: { things: ['a', 'b'] }, + calls: [{ tool: 'create_thing', input: {}, why: 'Add a thing', choose: ['thing_name'] }] + }); + expect(runs).toEqual([{ tool: 'list_things', params: { prefix: 'a' }, cwd }]); + expect(asked).toEqual([]); + }); +}); + +describe('a change on a connection without elicitation', () => { + it('runs once on the call the host let through, and its result gives what changed and the plan', async () => { + const client = await open(); + const result = await client.callTool({ name: 'create_thing', arguments: { thing_name: 'a' } }); + expect(result.isError).toBeFalsy(); + expect(envelope(result)).toEqual({ ok: true, data: { created: 'a' }, plan: planOf({ thing_name: 'a' }) }); + expect(text(result)).toMatch(/^Created a\n/); + expect(text(result)).toContain('Change {"thing_name":"a"}.'); + expect(text(result)).toContain('Database: "db-1" (ID id-1)'); + expect(runs).toEqual([{ tool: 'create_thing', params: { thing_name: 'a' }, cwd }]); + expect(asked).toEqual([`create_thing in ${cwd}`]); + }); +}); + +describe.each(['legacy', 'modern'] as const)('a change on a %s connection with form elicitation', (era) => { + it('shows the plan once, and applies the change when the person accepts the form as given', async () => { + const messages: string[] = []; + const client = await open({ era, elicit: (message) => (messages.push(message), { action: 'accept', content: {} }) }); + const result = await client.callTool({ name: 'create_thing', arguments: { thing_name: 'a' } }); + expect(envelope(result)).toEqual({ ok: true, data: { created: 'a' }, plan: planOf({ thing_name: 'a' }) }); + expect(messages).toHaveLength(1); + expect(messages[0]).toContain('Change {"thing_name":"a"}.'); + expect(messages[0]).toContain('Database: "db-1" (ID id-1)'); + expect(runs).toEqual([{ tool: 'create_thing', params: { thing_name: 'a' }, cwd }]); + }); + + it.each([ + ['declines', { action: 'decline' as const }], + ['closes the preview', { action: 'cancel' as const }], + ['accepts after unticking the box', { action: 'accept' as const, content: { apply: false } }] + ])('changes nothing when the person %s, and says so with the plan', async (_case, answer) => { + const client = await open({ era, elicit: () => answer }); + const result = await client.callTool({ name: 'create_thing', arguments: { thing_name: 'a' } }); + expect(result.isError).toBe(true); + expect(envelope(result).error).toMatchObject({ code: 'cancelled', message: expect.stringMatching(/nothing was changed/) }); + expect(envelope(result).plan).toEqual(planOf({ thing_name: 'a' })); + expect(text(result)).toContain('Database: "db-1" (ID id-1)'); + expect(runs).toEqual([]); + }); +}); + +describe('a blocked change', () => { + it('stops with the failure and its calls, without asking anyone', async () => { + state.blocked = { code: 'signed-out', message: 'No one is signed in.', hint: 'Sign in.', calls: [{ tool: 'describe_schema', input: {}, why: 'Check the session' }] }; + const messages: string[] = []; + const client = await open({ elicit: (message) => (messages.push(message), { action: 'accept', content: { apply: true } }) }); + const result = await client.callTool({ name: 'create_thing', arguments: { thing_name: 'a' } }); + expect(result.isError).toBe(true); + expect(envelope(result)).toEqual({ + ok: false, + error: { code: 'signed-out', message: 'No one is signed in.', hint: 'Sign in.' }, + calls: [{ tool: 'describe_schema', input: {}, why: 'Check the session' }] + }); + expect(text(result)).toBe('No one is signed in. Sign in.'); + expect(messages).toEqual([]); + expect(runs).toEqual([]); + }); +}); + +describe('a failure', () => { + it('is an error with the failure, the details and the calls as data, and tool names left as they are', async () => { + const client = await open(); + const result = await client.callTool({ name: 'fail_thing', arguments: {} }); + expect(result.isError).toBe(true); + expect(text(result)).toBe('This account may not change the thing. Call explain_access to see who may.'); + expect(envelope(result)).toEqual({ + ok: false, + error: { + code: 'permission-denied', + message: 'This account may not change the thing.', + hint: 'Call explain_access to see who may.', + retryable: false, + errorId: 'err-42', + context: { table: 'things' } + }, + data: { success: false }, + calls: [{ tool: 'explain_access', input: { table: 'things' }, why: 'See who may change it' }] + }); + }); + + it('is failed, with a fixed sentence and the error id, but no text or stack of the error, when the tool throws', async () => { + const client = await open(); + const result = await client.callTool({ name: 'throw_thing', arguments: {} }); + expect(result.isError).toBe(true); + expect(envelope(result).error).toMatchObject({ code: 'failed', message: expect.stringContaining('The tool throw_thing failed'), errorId: 'err-123' }); + expect(envelope(result).error.message).toContain('Error id: err-123'); + expect(JSON.stringify(result)).not.toMatch(/STACK-MARKER|secret_private|does not exist/); + }); +}); + +describe('null for an optional key, as a host with strict function calling sends it', () => { + const findThings = defineHarnessTool({ + name: 'find_things', + label: 'Find things', + description: 'Find things.', + parameters: strictObject('the input of find_things', { prefix: z.string().optional() }), + effect: 'read', + async execute(params, ctx) { + runs.push({ tool: 'find_things', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: 'found' }], details: {} }; + } + }); + const setThing = defineHarnessTool({ + name: 'set_thing', + label: 'Set thing', + description: 'Set a thing.', + parameters: strictObject('the input of set_thing', { + thing_name: z.string(), + note: z.string().optional(), + default_value: z.union([z.string(), z.null()]).optional().describe('null removes the default') + }), + effect: 'write', + async execute(params, ctx) { + runs.push({ tool: 'set_thing', params, cwd: ctx.cwd }); + return { content: [{ type: 'text', text: 'set' }], details: {} }; + } + }); + const nullTools = [findThings, setThing]; + + it('reaches a read tool as not given', async () => { + const client = await open({ tools: nullTools }); + const result = await client.callTool({ name: 'find_things', arguments: { prefix: null } }); + expect(envelope(result).ok).toBe(true); + expect(runs).toHaveLength(1); + expect(runs[0].params).not.toHaveProperty('prefix', null); + }); + + it('reaches a tool whose parameters are a plain zod object as not given, by the same rule', async () => { + const client = await open(); + const result = await client.callTool({ name: 'list_things', arguments: { prefix: null } }); + expect(envelope(result).ok).toBe(true); + expect(runs).toEqual([{ tool: 'list_things', params: {}, cwd }]); + }); + + it('lists each key with its own schema, and no key of the server', async () => { + const client = await open({ tools: nullTools }); + const byName = Object.fromEntries((await client.listTools()).tools.map((tool) => [tool.name, tool.inputSchema as any])); + expect(byName.find_things.properties).toEqual({ prefix: { type: 'string' } }); + expect(byName.set_thing.properties).toEqual({ + thing_name: { type: 'string' }, + note: { type: 'string' }, + default_value: { anyOf: [{ type: 'string' }, { type: 'null' }], description: 'null removes the default' } + }); + expect(byName.set_thing.required).toEqual(['thing_name']); + }); +}); + +describe('server instructions', () => { + it('say to call the read tools first, name the tools that change things and that the host asks the person, and stay under 4,096 characters', async () => { + const client = await open(); + const instructions = client.getInstructions(); + expect(instructions.length).toBeLessThan(4096); + expect(instructions).toMatch(/read tools first/); + expect(instructions).toContain('list_things, fail_thing and throw_thing'); + expect(instructions).toContain('create_thing'); + expect(instructions).toMatch(/asks the person/); + expect(instructions).not.toMatch(/delete_thing/); + }); + + it('say in read-only mode that nothing changes through this server, and name no change tool', async () => { + const client = await open({ readOnly: true }); + const instructions = client.getInstructions(); + expect(instructions).toMatch(/only tools that read/); + expect(instructions).toContain('list_things'); + expect(instructions).not.toContain('create_thing'); + }); + + it.each(['legacy', 'modern'] as const)('end with the host\'s own instructions on a %s connection', async (era) => { + const client = await open({ era, instructions: 'You act as the agent "helper" of the person.' }); + const instructions = client.getInstructions(); + expect(instructions).toMatch(/read tools first/); + expect(instructions.endsWith('\n\nYou act as the agent "helper" of the person.')).toBe(true); + }); +}); diff --git a/agentic/mcp/__tests__/stdio.test.ts b/agentic/mcp/__tests__/stdio.test.ts new file mode 100644 index 0000000000..13a476f9c2 --- /dev/null +++ b/agentic/mcp/__tests__/stdio.test.ts @@ -0,0 +1,62 @@ +import { spawn } from 'child_process'; +import { join } from 'path'; + +const fixture = join(__dirname, 'fixtures', 'stdio-server.ts'); + +const requests = [ + { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'probe', version: '1.0.0' } } }, + { jsonrpc: '2.0', method: 'notifications/initialized' }, + { jsonrpc: '2.0', id: 2, method: 'tools/list' }, + { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'noisy_read', arguments: {} } } +]; + +/** Runs the fixture server, sends the requests one line each, and returns its stdout and stderr once every request has an answer. */ +function exchange(): Promise<{ stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['-r', 'ts-node/register/transpile-only', fixture], { + cwd: join(__dirname, '..'), + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stdout = ''; + let stderr = ''; + const timer = setTimeout(() => { + child.kill(); + reject(new Error(`The fixture did not answer every request. stdout: ${stdout} stderr: ${stderr}`)); + }, 25_000); + child.stdout.on('data', (chunk) => { + stdout += chunk; + const answered = stdout.split('\n').filter(Boolean).flatMap((line) => { + try { + return [JSON.parse(line).id]; + } catch { + return []; + } + }); + if ([1, 2, 3].every((id) => answered.includes(id))) child.stdin.end(); + }); + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); + child.on('error', reject); + child.on('close', () => { + clearTimeout(timer); + resolve({ stdout, stderr }); + }); + for (const request of requests) child.stdin.write(`${JSON.stringify(request)}\n`); + }); +} + +describe('serveStdio', () => { + it('answers initialize, tools/list and a read, writes nothing to stdout but the protocol, and closes with stdin', async () => { + const { stdout, stderr } = await exchange(); + expect(stdout.endsWith('\n')).toBe(true); + const messages = stdout.slice(0, -1).split('\n').map((line) => JSON.parse(line)); + for (const message of messages) expect(message.jsonrpc).toBe('2.0'); + const byId = Object.fromEntries(messages.map((message) => [message.id, message])); + expect(byId[1].result.serverInfo).toMatchObject({ name: 'fixture', version: '1.0.0' }); + expect(byId[2].result.tools.map((tool: { name: string }) => tool.name)).toEqual(['noisy_read']); + expect(byId[3].result.structuredContent).toEqual({ ok: true, data: { done: true } }); + for (const noise of ['console noise', 'info noise', 'direct noise']) expect(stderr).toContain(noise); + expect(stderr).toContain('server closed'); + }, 30_000); +}); diff --git a/agentic/mcp/jest.config.js b/agentic/mcp/jest.config.js new file mode 100644 index 0000000000..8a26efd6d0 --- /dev/null +++ b/agentic/mcp/jest.config.js @@ -0,0 +1,21 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + babelConfig: false, + tsconfig: 'tsconfig.json', + }, + ], + }, + transformIgnorePatterns: [`/node_modules/*`], + testRegex: '(/__tests__/.*\\.(test|spec))\\.(jsx?|tsx?)$', + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], + modulePathIgnorePatterns: ['dist/*'], + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, +}; diff --git a/agentic/mcp/package.json b/agentic/mcp/package.json new file mode 100644 index 0000000000..e925b26769 --- /dev/null +++ b/agentic/mcp/package.json @@ -0,0 +1,44 @@ +{ + "name": "@agentic-kit/mcp", + "version": "0.1.0", + "author": "Constructive ", + "description": "serves HarnessTools as MCP tools: each write is marked for the host to ask the person, and its result carries its plan", + "main": "index.js", + "module": "esm/index.js", + "types": "index.d.ts", + "homepage": "https://github.com/constructive-io/constructive", + "license": "SEE LICENSE IN LICENSE", + "publishConfig": { + "access": "public", + "directory": "dist" + }, + "repository": { + "type": "git", + "url": "https://github.com/constructive-io/constructive" + }, + "bugs": { + "url": "https://github.com/constructive-io/constructive/issues" + }, + "scripts": { + "clean": "makage clean", + "prepack": "npm run build", + "build": "makage build", + "build:dev": "makage build --dev", + "lint": "eslint . --fix", + "test": "jest", + "test:watch": "jest --watch" + }, + "dependencies": { + "@agentic-kit/harness": "workspace:^", + "@modelcontextprotocol/server": "2.4.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@modelcontextprotocol/client": "2.4.0" + }, + "keywords": [ + "agentic-kit", + "mcp", + "tools" + ] +} diff --git a/agentic/mcp/src/index.ts b/agentic/mcp/src/index.ts new file mode 100644 index 0000000000..1d08b71d37 --- /dev/null +++ b/agentic/mcp/src/index.ts @@ -0,0 +1 @@ +export { createMcpServerFactory, type McpStdioServer, type McpToolsOptions, serveStdio } from './server'; diff --git a/agentic/mcp/src/server.ts b/agentic/mcp/src/server.ts new file mode 100644 index 0000000000..bd8384c2b3 --- /dev/null +++ b/agentic/mcp/src/server.ts @@ -0,0 +1,297 @@ +import { + type AnyHarnessTool, + callChange, + type Change, + type ConfirmPrompt, + failureText, + type GatePolicy, + type HarnessToolContent, + type HarnessToolResult, + normalizeToolParams, + renderPlan, + type ToolCallSuggestion, + type ToolFailure +} from '@agentic-kit/harness'; +import { + type CallToolResult, + CLIENT_CAPABILITIES_META_KEY, + type ClientCapabilities, + inputRequired, + type InputRequiredResult, + inputResponse, + McpServer, + type ServerContext, + type ToolAnnotations +} from '@modelcontextprotocol/server'; +import { serveStdio as serveSdkStdio, type StdioServerHandle, StdioServerTransport } from '@modelcontextprotocol/server/stdio'; +import { Writable } from 'stream'; +import { z } from 'zod'; + +export interface McpToolsOptions { + /** The server's name and version, as `initialize` reports them. */ + name: string; + version: string; + tools: readonly AnyHarnessTool[]; + /** Makes the plan of each write call, and stops a call that cannot run. */ + gate: GatePolicy; + /** The project directory the tools act on. */ + cwd: string; + /** + * true serves the tools whose effect is `read`. false serves those and the tools whose effect is `write`, each marked + * for the host to ask the person before every call. A tool whose effect is `destructive` is served in neither mode. + */ + readOnly: boolean; + /** The host's own guidance for the agent (who it acts as, for example), sent after the server's instructions. */ + instructions?: string; +} + +const READ_ANNOTATIONS: ToolAnnotations = { readOnlyHint: true }; +// MCP reads destructiveHint: false as "only adds" and idempotentHint: true as "a second call changes nothing more". A +// write may change or replace what exists (set_access replaces a table's rules), and the tool object promises neither. +const WRITE_ANNOTATIONS: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, idempotentHint: false }; +// Claude Code asks the person before every call of a tool with this key, in every permission mode, and denies the call where no one can answer. +const WRITE_META = { 'anthropic/requiresUserInteraction': true }; + +const isServed = (tool: AnyHarnessTool, readOnly: boolean): boolean => tool.effect === 'read' || (tool.effect === 'write' && !readOnly); + +/** + * The schema the SDK checks a call with: the tool's parameters behind the + * harness's null rule (null for an optional key that does not take null is not + * given). A preprocess step has no JSON Schema of its own, so tools/list shows + * the parameters as they are. + */ +function inputSchemaOf(tool: AnyHarnessTool): z.ZodType, unknown> { + if (tool.parameters._zod.def.type !== 'object') { + throw new Error(`The tool "${tool.name}" takes parameters that are not an object, and an MCP tool's input must be one. Wrap them in z.object().`); + } + const parameters = tool.parameters as z.ZodObject; + return z.preprocess((value) => normalizeToolParams(parameters, value), parameters); +} + +const toolList = (tools: readonly AnyHarnessTool[]): string => { + const names = tools.map((tool) => tool.name); + return names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`; +}; + +/** What the agent reads when it connects: which tools read and which change things, how a change is approved, then the host's own guidance. */ +function serverInstructions(served: readonly AnyHarnessTool[], readOnly: boolean, host: string | undefined): string { + const reads = toolList(served.filter((tool) => tool.effect === 'read')); + const own = readOnly + ? [ + `This server serves only tools that read, so nothing changes through it: ${reads}.`, + 'For a change, tell the person what to change, so that they can make it themselves.' + ] + : [ + `Call the read tools first, to learn the current state before you change anything: ${reads}.`, + `These tools change things: ${toolList(served.filter((tool) => tool.effect === 'write'))}.`, + 'In hosts that support it, the host asks the person to approve each call of them before it runs, so tell the person what a call will change before you make it.', + 'A call the host lets through runs once, and its result says what changed and gives the plan it applied.', + 'Tools that can lose data or delete what the person set up are not served here: the person makes those changes themselves.' + ]; + return [own.join(' '), host].filter(Boolean).join('\n\n'); +} + +/** What a failed call returns as data: the failure without its calls, which sit beside it. */ +type ErrorData = Pick & { code: string }; + +const errorData = (failure: ErrorData): ErrorData => Object.fromEntries( + (['code', 'message', 'hint', 'retryable', 'errorId', 'context'] as const).flatMap((key) => (failure[key] === undefined ? [] : [[key, failure[key]]])) +) as ErrorData; + +const callsData = (calls: ToolCallSuggestion[] | undefined) => (calls?.length ? { calls } : {}); + +const content = (parts: HarnessToolContent[]): CallToolResult['content'] => parts.map((part) => ({ ...part })); + +/** A result of this server: its envelope `{ ok, data?, error?, plan?, calls? }` is always an object. */ +type ToolCallResult = CallToolResult & { structuredContent: Record }; + +function failed(failure: ErrorData & { calls?: ToolCallSuggestion[] }, data?: unknown, parts?: HarnessToolContent[]): ToolCallResult { + return { + content: parts?.length ? content(parts) : [{ type: 'text', text: failureText(failure as ToolFailure) }], + structuredContent: { ok: false, error: errorData(failure), ...(data === undefined ? {} : { data }), ...callsData(failure.calls) }, + isError: true + }; +} + +function toolResult(result: HarnessToolResult): ToolCallResult { + if (result.failure) return failed(result.failure, result.details, result.content); + return { content: content(result.content), structuredContent: { ok: true, data: result.details, ...callsData(result.calls) } }; +} + +/** The id the server logged a GraphQL error under, from the errors a thrown client error keeps. */ +function errorIdOf(error: unknown): string | undefined { + const errors = (error as { errors?: unknown } | null)?.errors; + if (!Array.isArray(errors)) return undefined; + return errors.map((entry) => (entry as { extensions?: { errorId?: unknown } } | null)?.extensions?.errorId).find((id): id is string => typeof id === 'string'); +} + +/** A tool that threw: its text can carry the server's own words, so the result says only which tool failed, with the logged error's id. */ +function thrown(tool: AnyHarnessTool, error: unknown): ToolCallResult { + const errorId = errorIdOf(error); + const again = tool.effect === 'read' ? 'Call it again once' : 'Read the current state before you call it again, since part of the change may have been made'; + const after = errorId ? 'give the error id to the backend operator: it names the logged error' : 'tell the person which tool failed'; + return failed({ + code: 'failed', + message: `The tool ${tool.name} failed with an unexpected error, whose text is not shown.${errorId ? ` Error id: ${errorId}.` : ''}`, + hint: `${again}; if it fails again, ${after}.`, + ...(errorId ? { errorId } : {}) + }); +} + +/** A write's result with the plan it was made from: as text after the tool's own, and as data beside the envelope's. */ +const withPlan = (result: ToolCallResult, plan: ConfirmPrompt): ToolCallResult => ({ + ...result, + content: [...result.content, { type: 'text', text: `The plan of this call:\n${renderPlan(plan)}` }], + structuredContent: { ...result.structuredContent, plan } +}); + +const APPLY = 'apply'; +// The host's own prompt is the approval, so the preview starts ticked and an accepted form applies the change. +const APPLY_FIELD = { type: 'boolean', title: 'Apply this change', default: true } as const; + +type PreviewAnswer = { action: 'accept' | 'decline' | 'cancel'; apply: boolean }; + +const NOT_APPLIED: Record = { + accept: 'The person unticked "Apply this change" when its plan was shown, so nothing was changed.', + decline: 'The person declined the change when its plan was shown, so nothing was changed.', + cancel: 'The plan was closed without an answer, so nothing was changed.' +}; + +function previewQuestion(plan: ConfirmPrompt): InputRequiredResult { + return inputRequired({ + inputRequests: { + [APPLY]: inputRequired.elicit({ + mode: 'form', + message: `${renderPlan(plan)}\n\nApply this change?`, + requestedSchema: { + type: 'object', + properties: { [APPLY]: APPLY_FIELD }, + required: [APPLY] + } + }) + } + }); +} + +function previewAnswer(ctx: ServerContext): PreviewAnswer | null { + const view = inputResponse(ctx.mcpReq.inputResponses, APPLY); + if (view.kind !== 'elicit') return null; + return { action: view.action, apply: view.action === 'accept' && (view.content?.[APPLY] ?? APPLY_FIELD.default) === true }; +} + +/** The client's capabilities for this request: its envelope on the 2026 era, its `initialize` on a 2025-era connection. */ +function clientCapabilities(server: McpServer, ctx: ServerContext): ClientCapabilities | undefined { + const envelope = ctx.mcpReq.envelope as Record | undefined; + return envelope ? (envelope[CLIENT_CAPABILITIES_META_KEY] as ClientCapabilities | undefined) : server.server.getClientCapabilities(); +} + +// A bare `elicitation: {}` is the 2025 form of declaring form mode, as the SDK reads it. +function supportsFormElicitation(capabilities: ClientCapabilities | undefined): boolean { + const elicitation = capabilities?.elicitation as { form?: unknown; url?: unknown } | undefined; + return elicitation !== undefined && (elicitation.form !== undefined || elicitation.url === undefined); +} + +/** + * A read runs. A write runs on the call the host let through, because the host + * is the one that asks the person (WRITE_META). The gate makes its plan first + * and stops a call that cannot run. A client that can show questions is shown + * the plan once, as a preview: a decline there changes nothing. A client that + * cannot gets no question. + */ +function handlerFor(tool: AnyHarnessTool, server: McpServer, options: McpToolsOptions) { + return async (params: Record, ctx: ServerContext): Promise => { + const run = async (): Promise => { + try { + return toolResult(await tool.execute(params, { cwd: options.cwd, signal: ctx.mcpReq.signal })); + } catch (error) { + return thrown(tool, error); + } + }; + let change: Change; + try { + change = await callChange(tool, params, options.gate, options.cwd); + } catch (error) { + return thrown(tool, error); + } + if (change.effect === 'read') return run(); + if (change.decision.kind === 'blocked') return failed(change.decision.failure); + const plan = change.decision.prompt; + if (supportsFormElicitation(clientCapabilities(server, ctx))) { + const answer = previewAnswer(ctx); + if (!answer) return previewQuestion(plan); + if (!answer.apply) { + const hint = 'Do not make this change again unless the person asks for it.'; + return withPlan(failed({ code: 'cancelled', message: NOT_APPLIED[answer.action], hint }), plan); + } + } + return withPlan(await run(), plan); + }; +} + +/** A factory of MCP servers that serve `tools`, one server per connection (or per request on HTTP). */ +export function createMcpServerFactory(options: McpToolsOptions): () => McpServer { + const served = options.tools.filter((tool) => isServed(tool, options.readOnly)); + const schemas = served.map(inputSchemaOf); + const instructions = serverInstructions(served, options.readOnly, options.instructions); + return () => { + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { tools: {} }, instructions }); + served.forEach((tool, index) => { + const write = tool.effect === 'write'; + server.registerTool( + tool.name, + { + title: tool.label, + description: tool.description, + annotations: write ? WRITE_ANNOTATIONS : READ_ANNOTATIONS, + ...(write ? { _meta: WRITE_META } : {}), + inputSchema: schemas[index] + }, + handlerFor(tool, server, options) + ); + }); + return server; + }; +} + +/** + * The process's stdout, for the protocol alone. Every other write to + * `process.stdout` (console.log among them) goes to stderr from here on. A + * child process that inherits file descriptor 1 still writes past this. + */ +function protocolStdout(): Writable { + const stdout = process.stdout; + const write = stdout.write.bind(stdout) as (chunk: unknown, encoding: BufferEncoding, callback: (error?: Error | null) => void) => boolean; + stdout.write = process.stderr.write.bind(process.stderr) as typeof stdout.write; + const protocol = new Writable({ + write(chunk, encoding, callback) { + write(chunk, encoding, callback); + } + }); + stdout.on('error', (error) => protocol.destroy(error)); + return protocol; +} + +/** A server on this process's stdio. `closed` settles when the client closes stdin or `close()` ends the connection. */ +export interface McpStdioServer { + close(): Promise; + closed: Promise; +} + +/** Serves `tools` over this process's stdin and stdout, on both protocol eras. */ +export function serveStdio(options: McpToolsOptions): McpStdioServer { + let ended: () => void; + const closed = new Promise((resolve) => { + ended = resolve; + }); + process.stdin.once('end', () => ended()).once('close', () => ended()); + const handle: StdioServerHandle = serveSdkStdio(createMcpServerFactory(options), { + transport: new StdioServerTransport(process.stdin, protocolStdout()) + }); + return { + close: async () => { + await handle.close(); + ended(); + }, + closed + }; +} diff --git a/agentic/mcp/tsconfig.esm.json b/agentic/mcp/tsconfig.esm.json new file mode 100644 index 0000000000..a4afc3821d --- /dev/null +++ b/agentic/mcp/tsconfig.esm.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "moduleResolution": "bundler", + "module": "es2022", + "outDir": "dist/esm" + } +} diff --git a/agentic/mcp/tsconfig.json b/agentic/mcp/tsconfig.json new file mode 100644 index 0000000000..df063b5ee3 --- /dev/null +++ b/agentic/mcp/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"] +} diff --git a/agentic/session/README.md b/agentic/session/README.md new file mode 100644 index 0000000000..800442a4df --- /dev/null +++ b/agentic/session/README.md @@ -0,0 +1,104 @@ +# @agentic-kit/session + +

+ +

+ +

+ + + + + +

+ +The Constructive sign-in that every binary shares: backend contexts, email and password sign-in, the stored session, agent credentials, and the `CONSTRUCTIVE_*` environment overrides. A sign-in through one binary (the `agent` CLI, the `constructive` CLI, the desktop app) is a sign-in through all of them, because they all read the same [appstash](https://github.com/constructive-io/appstash) store under the stash name `constructive`. The package has no coding-agent SDK and ships no backend URL. + +```bash +npm install @agentic-kit/session +``` + +## The session + +`resolveSession({ context?, env?, store? })` answers "who talks to which backend" once, from the environment and the store together, and returns one of seven states: + +| `kind` | Meaning | +| --- | --- | +| `no-backend` | No context is chosen (`context: null`), or the named one does not exist | +| `incomplete-backend` | The stored context lacks planes (`missing`), for example one another app wrote; no plane is filled in | +| `invalid-override` | An environment variable is missing, empty or wrong; `variable`, `problem` and `fix` say which and what to do | +| `conflict` | A `context` was named, but an environment variable (`variable`) decides the session; drop one of the two | +| `issuer-mismatch` | A session is stored under the context, but it was issued for another backend (`differs` names the planes whose endpoints changed; `issuedFor` is what it was issued for), or it does not record its backend (`issuedFor: null`); it is never used or sent, and a new sign-in replaces it | +| `signed-out` | A usable backend (`source: 'env'` or `'store'`) and no credential for it | +| `signed-in` | The backend, the account and its key, all from one source | + +A credential is only paired with the backend of its own source. Every stored session records the whole backend it was issued for (`issuedFor`, all five endpoints), and it is used only while the context it is filed under names exactly those five endpoints; the compare is exact, so a trailing slash or another letter case is a difference. The session also keeps `authEndpoint`, the field Constructive Desktop reads and writes, so Desktop still sees which auth plane issued it. A session that records only `authEndpoint`, as Desktop writes it, or nothing, cannot show which api, modules, agent and compute endpoints it belongs to: it is never used, and a new sign-in replaces it. Its key can still be revoked, at the recorded `authEndpoint` only, since that is where the token came from. A stored session is used with the endpoints of the context it is filed under, and never with a backend that `CONSTRUCTIVE_API_ENDPOINT` names, unless the override names exactly that context's backend. An environment credential needs the backend from the environment too. `sessionToolsHost({ signInHint, repairHint?, context?, env? })` builds the host of [`@agentic-kit/db-tools`](https://www.npmjs.com/package/@agentic-kit/db-tools) on it. It resolves again on every call, so a sign-in mid-session is picked up. With no backend, `backendConfig()` is undefined and `account()` is null; signed out, `backendConfig()` gives the backend and `account()` is null; for `issuer-mismatch`, `backendConfig()` gives the backend and `account()` throws `sessionProblem`, which names the planes that differ. For `invalid-override`, `conflict` and `incomplete-backend` both getters throw an `Error` with `sessionProblem(session, repairHint)`, the problem and its fix, and a store that cannot be read throws its own error. The db tools turn such a throw into a failure that carries the message. `repairHint` is the binary's command that stores a complete context, for example ``Run `agent login` to store a complete backend.`` + +```ts +import { createConstructiveDbTools } from '@agentic-kit/db-tools'; +import { sessionToolsHost } from '@agentic-kit/session'; + +const tools = createConstructiveDbTools(sessionToolsHost({ signInHint: 'Run `constructive login` to sign in.' })); +``` + +## Signing in and out + +```ts +import { backendFromEndpoints, keyEndsSoon, openStore, resolveSession, signIn, signOut, verifySession } from '@agentic-kit/session'; + +const store = openStore(); +const backend = backendFromEndpoints({ api: 'https://api.example.com/graphql' }); +const { session, apiKey, previousKey } = await signIn({ store, backend, email, password }); + +const resolved = resolveSession({ store }); +if (resolved.kind === 'signed-in') { + await verifySession(resolved); // accepted | rejected | unchecked + if (resolved.account.key.kind === 'active' && keyEndsSoon({ expiresAt: resolved.account.key.expiresAt })) { + // ask the person to sign in again + } +} +const result = await signOut({ store, session: resolved }); +``` + +`signIn` signs in and mints a 30-day API key inside the fresh step-up window before it writes anything. Then it revokes the key of the session it replaces (`previousKey`), ends the password sign-in on the server (the auth `signOut` mutation), and stores the backend, the session and the choice of context, in that order, filed under `context` when the caller passes one. The stored bearer is the key, so no password sign-in session is left behind. The new session records its issuer. A sign-in that ends with no key (none minted, and none of the replaced session kept) throws a `SignInError` and stores nothing. A failed sign-in throws a `SignInError` whose `kind` is `invalid-input`, `invalid-credentials`, `second-factor-required`, `refused` (a locked account, too many attempts, a disabled method; `code` is the server's), `backend-unreachable` or `server-error`, and leaves the store as it was. The mint and the revoke have the same 10 s timeout as the sign-in. + +`signOut({ store, session })` acts on exactly the session `resolveSession` gave, so a CLI's `logout` removes what its `whoami` reported. It revokes the API key at the auth endpoint the credential records (from `issuedFor`, else Desktop's `authEndpoint`), with that credential's own bearer, never at whatever the context names now. It clears the stored session in every state and returns `{ kind: 'cleared', key }`, where `key` says whether the API key was `revoked`, `absent`, or `failed` and why (a session with no recorded issuer sends nothing and says so). It returns `{ kind: 'from-environment' }` for a session from the environment, which leaves the store alone, or `{ kind: 'not-signed-in' }`, and it throws the problem of an `invalid-override` or `conflict` session. + +`verifySession(session)` asks the backend once whether a signed-in session's credential is accepted: `accepted`, `rejected` (HTTP 401 or 403, `UNAUTHENTICATED`, no user, or another user), or `unchecked` when the backend cannot answer. It has the 10 s timeout and classifies by status and code only. Nothing renews a key on its own, because a new key needs a fresh password sign-in: `keyEndsSoon({ expiresAt })` says when a key has ended or ends within 7 days (`SIGN_IN_AGAIN_WITHIN_MS`), so a binary can ask the person to sign in again. None of these throws for a server answer, and the package prints nothing. A message names the server's error codes, never its message text, which may name backend internals. + +## Agents + +An agent is a principal of the signed-in person, with its own key, for a coding agent or a CI job to act as. + +```ts +import { agentSession, createAgent, listAgents, removeAgent, renewAgentKey, resolveSession, sessionToolsHost } from '@agentic-kit/session'; + +const person = resolveSession({ store }); +await createAgent({ store, session: person, password, name: 'helper', allowSchemaChanges: false }); +const host = sessionToolsHost({ signInHint: 'Run `constructive agent add helper` to set it up again.', agent: 'helper' }); +listAgents({ store }); // [{ name: 'helper', state: 'ready', keyExpiresAt, ... }] +await renewAgentKey({ store, session: person, password, name: 'helper' }); // { agent, previousKey } +await removeAgent({ store, session: person, name: 'helper' }); +``` + +- **What it may do.** `createAgent` creates the principal without the person's admin flag (`useAdminOwner: false`, also on every scope call, whose own default is true). By default its org scope masks `manage_database`, so it cannot change the schema; `allowSchemaChanges`, `grantSchemaChanges` and `revokeSchemaChanges` set or clear that mask. `organization` holds it to one organization. A key for a principal needs a recent password sign-in, so `createAgent` and `renewAgentKey` take the person's `password`, sign in afresh (the stored session names the account and the backend), and end that sign-in on the server when done; a wrong password is a `SignInError`. `grantSchemaChanges`, `revokeSchemaChanges` and `removeAgent` go with the person's stored key. +- **Its key.** `createAgent` caps every key of the principal at 30 days (`apiKeyMaxDuration`), then creates one key for it that asks for 30 days. The key is stored in a 0600 file under the person's context (`/agents//.json`), bound to the five endpoints it was issued for, like a person's session. `renewAgentKey` gives the same principal a new 30-day key, so it keeps its grants: it stores the new key, drops the cached token, then revokes the old key, which ends every token minted with it (`previousKey` says whether that worked). +- **Its access tokens.** This package uses the key only to mint access tokens for the principal. The backend accepts the key itself on requests too, so whoever holds it can act as the agent until it ends, `renewAgentKey` replaces it, or `removeAgent` deletes the agent; it stays in its 0600 file. `agentSession` gives the cached access token while more than 30 s of it is left, else it mints a new one and caches it in a 0600 file (`/agents//.json`), written through a temporary file and a rename. There is no lock: a token may be used many times, so processes that mint at once all work, and the cache keeps one of their tokens. The refresh token the backend makes with each mint is never asked for or stored. With `agent`, `sessionToolsHost`'s `account()` is asynchronous and gives that token; requests never carry the key. +- **A refused token.** After the backend refuses the agent's access token as signed out, pass it back once: `agentSession({ store, name, rejectedToken })` drops it from the cache and mints one token from the key, or uses the token another process already minted. It never retries on its own. If the key is refused too, the answer is `set-up-again`. +- **When it stops.** `agentSession` answers `agent-unusable` with `set-up-again` once the key has ended or the backend refuses it (the fix is to renew the key), or the record cannot be read (the fix is to remove and add the agent), and `mint-failed` (retry) when no token could be minted. The person's `signOut` leaves every agent working until its key ends; `listAgents` says which agents those are, and `removeAgent` deletes the principal, which ends its key and every token minted with it at once. +- **A record edited by hand** that no longer parses makes the agent `set-up-again`; `removeAgent` then removes the entry, and the principal is deleted in the app. +- **Managing agents** needs the person's own stored session; an agent, or a credential from the environment, gets `AgentError` `not-a-person`. A refusal for a recent sign-in is `step-up-required`, and the fix is to sign in again. + +## Backends + +`backendFromEndpoints({ api, auth?, modules?, agent?, compute? })` builds a backend. A plane that is not given is derived from the api host only when the host is `api.` (`api.example.com` gives `auth.example.com`). Any other host must give every plane, so a password never goes to a host the caller did not name. It throws an `EndpointError` (`reason`: `not-a-url`, `scheme`, `userinfo` or `not-derivable`) for anything else; only `http` and `https` are accepted, and a user name or password in a URL is refused. + +A backend is a named context in the store, named after the api host without a leading `api.` (`https://api.example.com/graphql` is `example.com`). A context name is the stem of a file in the store, so every function that takes one checks it first with `checkContextName`: 1 to 100 characters, lower-case letters, digits, `.`, `-` and `_`, starting with a letter or a digit, with no `..`. Upper case is refused so that two names never reach one file on a disk that ignores letter case (macOS): `PROD` cannot delete the file of `prod`. A bad name throws `ContextNameError` before any file is touched, and `contextNameFor` only produces names that pass. `listBackends` lists a stored context whose name does not pass, for example one with upper-case letters that another program wrote, as `status: 'invalid-name'` with the `reason`, and goes on with the others; no function acts on it, so it is removed by hand (the file under `/.constructive/config/contexts/`). `listBackends`, `readBackend`, `addBackend`, `selectBackend` and `removeBackend` manage the contexts. No function drops a stored session while its key stays valid: `addBackend` keeps the session of a context when it was issued for exactly the new five endpoints, and otherwise throws `ContextInUseError`, as `removeBackend` does while any session is filed under the context. `signOut` first, which revokes the key; `signIn` replaces a session of another backend itself, after it has revoked that session's key. + +## Environment + +- `CONSTRUCTIVE_STASH_DIR` sets the base directory of the store (`/.constructive/`) in place of the home directory, for tests and isolated runs. Constructive Desktop reads the same variable. An empty value is an error. `stashDirectories(env)` lists every directory the store uses (root, config, cache, data, logs, tmp) from the same resolution as `openStore`, without creating any, so a caller can refuse a path inside the store. +- `CONSTRUCTIVE_USER_ID` and `CONSTRUCTIVE_ACCESS_TOKEN`, with an optional `CONSTRUCTIVE_API_KEY`, give the credential. Any one of them selects the environment as the credential source, so the set must be complete, and `CONSTRUCTIVE_API_ENDPOINT` must name the backend. +- `CONSTRUCTIVE_API_ENDPOINT` picks the backend. `CONSTRUCTIVE_AUTH_ENDPOINT`, `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT` and `CONSTRUCTIVE_COMPUTE_ENDPOINT` give one plane each, and are required for an api host that is not `api.`. A plane variable without `CONSTRUCTIVE_API_ENDPOINT` is an error. + +The store file `/.constructive/config/credentials.json` holds the tokens in plaintext with mode `0600`. diff --git a/agentic/session/__tests__/agent-child.ts b/agentic/session/__tests__/agent-child.ts new file mode 100644 index 0000000000..6a83c2020c --- /dev/null +++ b/agentic/session/__tests__/agent-child.ts @@ -0,0 +1,12 @@ +// A second process for agent.test.ts: resolves one agent session from the +// store in argv[2] and prints what it got. Run with ts-node. +import { openStore } from '../src/account-store'; +import { agentSession } from '../src/agent'; + +(async () => { + const store = openStore(process.argv[2]); + const session = await agentSession({ store, name: process.argv[3], env: {} }); + process.stdout.write(JSON.stringify(session.kind === 'signed-in' ? { kind: session.kind, token: session.account.accessToken } : session)); +})().catch((err) => { + process.stdout.write(JSON.stringify({ kind: 'threw', message: String(err?.message ?? err) })); +}); diff --git a/agentic/session/__tests__/agent.test.ts b/agentic/session/__tests__/agent.test.ts new file mode 100644 index 0000000000..2cd6a86a79 --- /dev/null +++ b/agentic/session/__tests__/agent.test.ts @@ -0,0 +1,526 @@ +import { ConfigStore } from 'appstash'; +import { execFile } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { promisify } from 'util'; + +import { openStore, saveSession } from '../src/account-store'; +import { AgentError, agentSession, createAgent, grantSchemaChanges, listAgents, removeAgent, renewAgentKey, revokeSchemaChanges, SCHEMA_READ_ONLY_MASK } from '../src/agent'; +import { SignInError } from '../src/auth-error'; +import { addBackend, selectBackend } from '../src/backend-store'; +import { resolveSession } from '../src/session'; +import { sessionToolsHost } from '../src/tools-host'; +import { FakePrincipals } from './fake-principals'; + +const run = promisify(execFile); +const DAY_MS = 24 * 3600 * 1000; + +let home: string; +let store: ConfigStore; +let auth: FakePrincipals; + +const person = () => ({ + userId: 'person-1', + email: 'owner@example.com', + accessToken: 'person-access-token', + accessTokenExpiresAt: new Date(Date.now() + 3600_000).toISOString(), + apiKey: 'person-api-key', + keyId: 'person-key-id', + signedInAt: 1, + issuedFor: auth.backend() +}); + +const personSession = () => { + const session = resolveSession({ store, env: {} }); + if (session.kind !== 'signed-in') throw new Error(`expected signed-in, got ${session.kind}`); + return session; +}; + +const agentFile = (name: string) => path.join(home, '.constructive', 'config', 'agents', auth.context(), `${name}.json`); +const readAgent = (name: string) => JSON.parse(fs.readFileSync(agentFile(name), 'utf8')); +const cacheFile = (name: string) => path.join(home, '.constructive', 'cache', 'agents', auth.context(), `${name}.json`); +const readCache = (name: string) => JSON.parse(fs.readFileSync(cacheFile(name), 'utf8')); +const writeCache = (name: string, token: Record) => { + fs.mkdirSync(path.dirname(cacheFile(name)), { recursive: true }); + fs.writeFileSync(cacheFile(name), JSON.stringify(token), { mode: 0o600 }); +}; +/** Make the cached access token of `name` look ended, as after 15 minutes. */ +const expireCache = (name: string) => writeCache(name, { ...readCache(name), accessExpiresAt: new Date(Date.now() - 1000).toISOString() }); +const allFiles = () => (fs.readdirSync(home, { recursive: true }) as string[]).map((f) => path.join(home, f)).filter((f) => fs.statSync(f).isFile()); +const mints = () => auth.calls.filter((call) => call.op === 'mintAccessToken'); + +beforeEach(async () => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'session-agent-')); + store = openStore(home); + auth = new FakePrincipals(); + await auth.start(); + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, person()); +}); + +afterEach(async () => { + await auth.stop(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +const create = (name: string, allowSchemaChanges = false, extra: Record = {}) => + createAgent({ store, session: personSession(), password: 'pw', name, allowSchemaChanges, ...extra }); + +const signedIn = async (name: string) => { + const session = await agentSession({ store, name, env: {} }); + if (session.kind !== 'signed-in') throw new Error(`expected signed-in, got ${JSON.stringify(session)}`); + return session; +}; + +describe('the mint-only agent credential', () => { + it('stores no refresh token for an agent, and never asks the backend for one', async () => { + await create('helper'); + expect(await agentSession({ store, name: 'helper', env: {} })).toMatchObject({ kind: 'signed-in' }); + const stored = allFiles().filter((file) => file.includes(`${path.sep}agents${path.sep}`)); + expect(stored.length).toBeGreaterThan(0); + for (const file of stored) { + const text = fs.readFileSync(file, 'utf8'); + expect(text).not.toMatch(/cnc_live_rt_|refreshToken/); + } + expect(auth.calls.filter((call) => call.op === 'mintAccessToken').map((call) => call.query.includes('refreshToken'))).not.toContain(true); + }); + + it('lets two processes whose cached token expired both mint with the key at once and both succeed, with no lock', async () => { + await create('helper'); + const record = readAgent('helper'); + writeCache('helper', { keyId: record.keyId, accessToken: 'cnc_live_at_spent', accessExpiresAt: new Date(Date.now() - 1000).toISOString() }); + const before = auth.calls.length; + // Each mint is answered only once both have arrived: a lock would hold the second process back, and this would never return. + auth.barrier = { op: 'mintAccessToken', count: 2 }; + const child = run(process.execPath, ['-r', 'ts-node/register/transpile-only', path.join(__dirname, 'agent-child.ts'), home, 'helper'], { + env: { ...process.env, TS_NODE_TRANSPILE_ONLY: 'true' } + }); + const mine = agentSession({ store, name: 'helper', env: {} }); + const [{ stdout }, own] = await Promise.all([child, mine]); + const theirs = JSON.parse(stdout); + + const mints = auth.calls.slice(before).filter((call) => call.op === 'mintAccessToken'); + expect(mints).toHaveLength(2); + for (const call of mints) expect(call).toMatchObject({ bearer: record.apiKey, input: { principalId: record.principalId } }); + expect(own).toMatchObject({ kind: 'signed-in' }); + expect(theirs).toMatchObject({ kind: 'signed-in' }); + const tokens = [own.kind === 'signed-in' ? own.account.accessToken : '', theirs.token]; + for (const token of tokens) expect(auth.live(token)).toBe(true); + expect(tokens).toContain(JSON.parse(fs.readFileSync(cacheFile('helper'), 'utf8')).accessToken); + expect(fs.statSync(cacheFile('helper')).mode & 0o777).toBe(0o600); + expect(fs.readdirSync(path.dirname(cacheFile('helper')))).toEqual(['helper.json']); + }, 30_000); +}); + +describe('createAgent', () => { + it('creates a principal without the admin flag, masks manage_database, caps its keys at 30 days before it makes one, and stores the key beside the session', async () => { + const info = await create('helper'); + + expect(auth.ops()).toEqual(['signIn', 'createPrincipal', 'setPrincipalScope', 'updatePrincipal', 'createApiKey', 'signOut']); + expect(auth.calls[0].input).toEqual({ email: 'owner@example.com', password: 'pw' }); + const fresh = [...auth.signIns.keys()][0]; + expect(auth.calls.slice(1).every((call) => call.bearer === fresh)).toBe(true); + expect(auth.liveSignIns()).toBe(0); + expect(auth.calls[1].input).toEqual({ name: 'helper', useAdminOwner: false }); + const principalId = auth.calls[2].input.principalId; + expect(auth.calls[2].input).toEqual({ principalId, membershipType: 2, allowedMask: SCHEMA_READ_ONLY_MASK, useAdminOwner: false, isActive: true, isReadOnly: false }); + expect(auth.calls[3].input).toEqual({ principalId, apiKeyMaxDuration: { days: 30 } }); + expect(auth.calls[4].input).toEqual({ keyName: 'agent:helper', accessLevel: 'full_access', mfaLevel: 'none', expiresIn: { days: 30 }, principalId }); + + expect(SCHEMA_READ_ONLY_MASK).toHaveLength(64); + expect(SCHEMA_READ_ONLY_MASK.indexOf('0')).toBe(64 - 12); + expect(SCHEMA_READ_ONLY_MASK.replace('0', '')).toBe('1'.repeat(63)); + + expect(info).toMatchObject({ name: 'helper', context: auth.context(), principalId, schemaChanges: false, state: 'ready' }); + if ('keyExpiresAt' in info) expect(Math.abs(Date.parse(info.keyExpiresAt) - (Date.now() + 30 * DAY_MS))).toBeLessThan(60_000); + expect(JSON.stringify(info)).not.toMatch(/cnc_live|person-access-token/); + expect(fs.statSync(agentFile('helper')).mode & 0o777).toBe(0o600); + expect(fs.statSync(path.dirname(agentFile('helper'))).mode & 0o777).toBe(0o700); + expect(readAgent('helper')).toMatchObject({ principalId, ownerId: 'person-1', issuedFor: auth.backend(), schemaChanges: false, apiKey: auth.keys[0].secret, keyId: auth.keys[0].id }); + expect(listAgents({ store })).toEqual([info]); + }); + + it('sets no mask when schema changes are allowed, and holds the agent to the organization it names', async () => { + const info = await create('builder', true, { organization: 'org-1' }); + expect(auth.calls[1].input).toEqual({ name: 'builder', useAdminOwner: false, entityIds: ['org-1'] }); + expect(auth.calls[2].input).toMatchObject({ allowedMask: null, useAdminOwner: false }); + expect(info).toMatchObject({ schemaChanges: true, organization: 'org-1' }); + }); + + it.each<[string, string, string]>([ + ['a principal credential', 'PRINCIPAL_CANNOT_CREATE_PRINCIPAL', 'not-a-person'], + ['an old sign-in', 'STEP_UP_REQUIRED_FRESH_AUTH', 'step-up-required'], + ['an expired sign-in', 'UNAUTHENTICATED', 'sign-in-required'] + ])('refuses %s with a failure that names the sign-in step, and stores nothing', async (_name, code, kind) => { + auth.fail.createPrincipal = { code }; + const error = await create('helper').catch((err) => err); + expect(error).toBeInstanceOf(AgentError); + expect(error.kind).toBe(kind); + expect(error.code).toBe(code); + if (kind !== 'not-a-person') expect(error.message).toContain('Sign in again'); + expect(auth.ops()).toEqual(['signIn', 'createPrincipal', 'signOut']); + expect(auth.liveSignIns()).toBe(0); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); + + it('refuses a wrong password before anything is made', async () => { + const error = await createAgent({ store, session: personSession(), password: 'wrong', name: 'helper', allowSchemaChanges: false }).catch((err) => err); + expect(error).toBeInstanceOf(SignInError); + expect(error.kind).toBe('invalid-credentials'); + expect(auth.ops()).toEqual(['signIn']); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); + + it.each<[string, (a: FakePrincipals) => void, string[]]>([ + ['the key cannot be made', (a) => (a.fail.createApiKey = { code: 'API_KEY_LIMIT_REACHED' }), ['signIn', 'createPrincipal', 'setPrincipalScope', 'updatePrincipal', 'createApiKey', 'deletePrincipal', 'signOut']], + ['the cap is not confirmed', (a) => (a.fail.updatePrincipal = { code: 'NOT_OWNER' }), ['signIn', 'createPrincipal', 'setPrincipalScope', 'updatePrincipal', 'deletePrincipal', 'signOut']] + ])('deletes the principal it made when %s, and says so', async (_name, fault, ops) => { + fault(auth); + const error = await create('helper').catch((err) => err); + expect(error).toBeInstanceOf(AgentError); + expect(error.message).toContain('was deleted again'); + expect(auth.ops()).toEqual(ops); + expect(auth.principals.size).toBe(0); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); + + it('lets one of two adds of one name at the same moment win, and deletes the principal of the other', async () => { + auth.delayMs = 50; + const results = await Promise.allSettled([create('helper'), create('helper')]); + const lost = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected'); + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1); + expect(lost).toHaveLength(1); + expect(lost[0].reason).toMatchObject({ kind: 'name-taken' }); + expect(lost[0].reason.message).toContain('was deleted again'); + expect(auth.principals.size).toBe(1); + expect([...auth.principals.keys()]).toEqual([readAgent('helper').principalId]); + }); + + it('needs a person signed in from the store, and refuses an agent or the environment without a request', async () => { + await create('helper'); + const asAgent = await agentSession({ store, name: 'helper', env: {} }); + const calls = auth.calls.length; + const fromEnv = resolveSession({ store, env: { CONSTRUCTIVE_USER_ID: 'u', CONSTRUCTIVE_ACCESS_TOKEN: 't', CONSTRUCTIVE_API_ENDPOINT: auth.endpoint, CONSTRUCTIVE_AUTH_ENDPOINT: auth.endpoint, CONSTRUCTIVE_MODULES_ENDPOINT: auth.endpoint, CONSTRUCTIVE_AGENT_ENDPOINT: auth.endpoint, CONSTRUCTIVE_COMPUTE_ENDPOINT: auth.endpoint } }); + for (const session of [asAgent, fromEnv]) { + await expect(createAgent({ store, session, password: 'pw', name: 'other', allowSchemaChanges: false })).rejects.toMatchObject({ kind: 'not-a-person' }); + } + const envError = await createAgent({ store, session: fromEnv, password: 'pw', name: 'other', allowSchemaChanges: false }).catch((err) => err); + expect(envError.message).toContain('no stored context to file the agent under'); + expect(auth.calls.length).toBe(calls); + }); + + it('refuses a name that is taken or not valid before any request', async () => { + await create('helper'); + const calls = auth.calls.length; + await expect(create('helper')).rejects.toMatchObject({ kind: 'name-taken' }); + await expect(create('../credentials')).rejects.toMatchObject({ kind: 'invalid-name' }); + await expect(create('Helper')).rejects.toMatchObject({ kind: 'invalid-name' }); + const error = await create('a1.json').catch((err) => err); + expect(error).toMatchObject({ kind: 'invalid-name' }); + expect(error.message).toContain('reads like a file of the store'); + expect(auth.calls.length).toBe(calls); + }); +}); + +describe('agentSession', () => { + it('mints an access token with the agent key on first use, caches it in a 0600 file, and acts as the person', async () => { + await create('helper'); + const record = readAgent('helper'); + const session = await signedIn('helper'); + + expect(mints()).toEqual([expect.objectContaining({ bearer: record.apiKey, input: { principalId: record.principalId, intent: 'agent:helper' } })]); + expect(session).toMatchObject({ + source: 'agent', + context: auth.context(), + account: { userId: 'person-1', key: { kind: 'none' } }, + agent: { name: 'helper', principalId: record.principalId, schemaChanges: false, keyExpiresAt: record.keyExpiresAt } + }); + expect(auth.live(session.account.accessToken)).toBe(true); + expect(readCache('helper')).toEqual({ keyId: record.keyId, accessToken: session.account.accessToken, accessExpiresAt: session.agent.accessExpiresAt }); + expect(fs.statSync(cacheFile('helper')).mode & 0o777).toBe(0o600); + expect(fs.statSync(path.dirname(cacheFile('helper'))).mode & 0o777).toBe(0o700); + }); + + it('uses the cached token while it is fresh, with no request', async () => { + await create('helper'); + const first = await signedIn('helper'); + const calls = auth.calls.length; + expect((await signedIn('helper')).account.accessToken).toBe(first.account.accessToken); + expect(auth.calls.length).toBe(calls); + }); + + it('mints again once the cached token is near its end, and caches the new one', async () => { + await create('helper'); + const first = await signedIn('helper'); + expireCache('helper'); + const second = await signedIn('helper'); + expect(second.account.accessToken).not.toBe(first.account.accessToken); + expect(mints()).toHaveLength(2); + expect(readCache('helper').accessToken).toBe(second.account.accessToken); + }); + + it('never uses a token cached for another key of the name', async () => { + await create('helper'); + writeCache('helper', { keyId: 'an-older-key', accessToken: 'cnc_live_at_old', accessExpiresAt: new Date(Date.now() + 600_000).toISOString() }); + const session = await signedIn('helper'); + expect(session.account.accessToken).not.toBe('cnc_live_at_old'); + expect(mints()).toHaveLength(1); + }); + + it('says to set the agent up again when the backend no longer accepts its key', async () => { + await create('helper'); + auth.keys[0].revoked = true; + const session = await agentSession({ store, name: 'helper', env: {} }); + expect(session).toMatchObject({ kind: 'agent-unusable', agent: 'helper', reason: 'set-up-again' }); + if (session.kind === 'agent-unusable') expect(session.fix).toContain('Renew the key of the agent "helper"'); + expect(fs.existsSync(cacheFile('helper'))).toBe(false); + }); + + it('drops a cached token the backend refused and mints once more from the key, and says to renew when the key is refused too', async () => { + await create('helper'); + const refused = (await signedIn('helper')).account.accessToken; + auth.sessions.find((s) => s.access === refused)!.revoked = true; + + const again = await agentSession({ store, name: 'helper', env: {}, rejectedToken: refused }); + expect(again).toMatchObject({ kind: 'signed-in' }); + const fresh = again.kind === 'signed-in' ? again.account.accessToken : ''; + expect(fresh).not.toBe(refused); + expect(auth.live(fresh)).toBe(true); + expect(mints()).toHaveLength(2); + expect(readCache('helper').accessToken).toBe(fresh); + + // Another process that was refused the same token uses the one already minted. + expect(await agentSession({ store, name: 'helper', env: {}, rejectedToken: refused })).toMatchObject({ kind: 'signed-in', account: { accessToken: fresh } }); + expect(mints()).toHaveLength(2); + + auth.keys[0].revoked = true; + auth.sessions.find((s) => s.access === fresh)!.revoked = true; + const dead = await agentSession({ store, name: 'helper', env: {}, rejectedToken: fresh }); + expect(dead).toMatchObject({ kind: 'agent-unusable', reason: 'set-up-again' }); + expect(mints()).toHaveLength(3); + expect(fs.existsSync(cacheFile('helper'))).toBe(false); + }); + + it('says to set the agent up again, with no request, once its key has ended', async () => { + await create('helper'); + fs.writeFileSync(agentFile('helper'), JSON.stringify({ ...readAgent('helper'), keyExpiresAt: new Date(Date.now() - 1000).toISOString() }), { mode: 0o600 }); + const calls = auth.calls.length; + expect(await agentSession({ store, name: 'helper', env: {} })).toMatchObject({ kind: 'agent-unusable', reason: 'set-up-again', problem: expect.stringContaining('key of the agent "helper" ended') }); + expect(listAgents({ store })[0].state).toBe('set-up-again'); + expect(auth.calls.length).toBe(calls); + }); + + it.each<[string, (a: FakePrincipals) => Promise | void]>([ + ['the backend cannot be reached', (a) => a.stop()], + ['the backend answers HTTP 502', (a) => void (a.fail.mintAccessToken = { status: 502 })] + ])('says to retry when %s, and keeps the key', async (_name, fault) => { + await create('helper'); + const before = readAgent('helper'); + await fault(auth); + const session = await agentSession({ store, name: 'helper', env: {} }); + expect(session).toMatchObject({ kind: 'agent-unusable', reason: 'mint-failed' }); + if (session.kind === 'agent-unusable') expect(session.fix).toContain('Retry'); + expect(readAgent('helper')).toEqual(before); + }); + + it('never uses an agent whose context now names other endpoints, and says which plane differs', async () => { + await create('helper'); + const file = path.join(home, '.constructive', 'config', 'contexts', `${auth.context()}.json`); + const ctx = JSON.parse(fs.readFileSync(file, 'utf8')); + ctx.targets.modules.endpoint = 'http://modules.evil.localhost/graphql'; + fs.writeFileSync(file, JSON.stringify(ctx)); + const calls = auth.calls.length; + const session = await agentSession({ store, name: 'helper', env: {} }); + expect(session).toMatchObject({ kind: 'agent-unusable', reason: 'issuer-mismatch' }); + if (session.kind === 'agent-unusable') expect(session.problem).toContain('modules endpoint'); + expect(auth.calls.length).toBe(calls); + }); + + it('is a conflict when the environment would decide the session', async () => { + await create('helper'); + const env = { CONSTRUCTIVE_USER_ID: 'u', CONSTRUCTIVE_ACCESS_TOKEN: 't' }; + expect(await agentSession({ store, env, name: 'helper' })).toMatchObject({ kind: 'conflict', variable: 'CONSTRUCTIVE_USER_ID' }); + }); + + it.each<[string, string, string]>([ + ['a record that is not valid JSON', '{ "name": "helper", ', 'not valid JSON'], + ['a record without a key', JSON.stringify({ name: 'helper', principalId: 'p', refreshToken: 'r' }), 'lacks the principal, the key or the backend'] + ])('answers set-up-again for %s, names the file, and lists it instead of crashing', async (_name, content, problem) => { + await create('helper'); + fs.writeFileSync(agentFile('helper'), content, { mode: 0o600 }); + const session = await agentSession({ store, name: 'helper', env: {} }); + expect(session).toMatchObject({ kind: 'agent-unusable', reason: 'set-up-again' }); + if (session.kind === 'agent-unusable') { + expect(session.problem).toContain(agentFile('helper')); + expect(session.fix).toContain('Remove the agent'); + } + expect(listAgents({ store })).toEqual([{ name: 'helper', context: auth.context(), state: 'set-up-again', unreadable: true, problem: expect.stringContaining(problem) }]); + await expect(grantSchemaChanges({ store, session: personSession(), name: 'helper' })).rejects.toMatchObject({ kind: 'unreadable-record' }); + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).resolves.toMatchObject({ kind: 'entry-removed', problem: expect.stringContaining('Delete the principal "helper" in the app') }); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); + + it('says an agent that does not exist is not found', async () => { + expect(await agentSession({ store, name: 'nobody', env: {} })).toMatchObject({ kind: 'agent-unusable', reason: 'not-found' }); + }); +}); + +describe('the tools host as an agent', () => { + it('gives a minted agent token as the person, uses a token another process cached, and mints when the cache is near its end', async () => { + await create('helper'); + const host = sessionToolsHost({ signInHint: 'Sign in.', agent: 'helper', env: { CONSTRUCTIVE_STASH_DIR: home } }); + const agent = { name: 'helper', principalId: readAgent('helper').principalId }; + const first = await host.account(); + expect(first).toEqual({ userId: 'person-1', agent, accessToken: readCache('helper').accessToken }); + expect(host.backendConfig()).toMatchObject({ apiEndpoint: auth.endpoint }); + const personal = await sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home } }).account(); + expect(personal).toMatchObject({ userId: 'person-1', email: 'owner@example.com', apiKey: 'person-api-key' }); + expect(personal).not.toHaveProperty('agent'); + + expireCache('helper'); + const elsewhere = await signedIn('helper'); + const minted = mints().length; + expect(await host.account()).toEqual({ userId: 'person-1', agent, accessToken: elsewhere.account.accessToken }); + expect(mints()).toHaveLength(minted); + + expireCache('helper'); + const account = await host.account(); + expect(auth.live(account!.accessToken)).toBe(true); + expect(account!.accessToken).not.toBe(elsewhere.account.accessToken); + expect(account).not.toHaveProperty('apiKey'); + }); + + it('throws the reason from both getters when the agent must be set up again, so a tool reports it', async () => { + await create('helper'); + fs.writeFileSync(agentFile('helper'), JSON.stringify({ ...readAgent('helper'), keyExpiresAt: new Date(Date.now() - 1000).toISOString() }), { mode: 0o600 }); + const host = sessionToolsHost({ signInHint: 'Sign in.', agent: 'helper', env: { CONSTRUCTIVE_STASH_DIR: home } }); + await expect(host.account()).rejects.toThrow('The key of the agent "helper" ended'); + expect(() => host.backendConfig()).toThrow('The key of the agent "helper" ended'); + }); +}); + +describe('schema changes and removal', () => { + it('grants and revokes schema changes with the scope call, and records it', async () => { + await create('helper'); + const principalId = readAgent('helper').principalId; + expect(await grantSchemaChanges({ store, session: personSession(), name: 'helper' })).toMatchObject({ schemaChanges: true }); + expect(auth.calls.at(-1)).toMatchObject({ op: 'setPrincipalScope', bearer: 'person-api-key', input: { principalId, membershipType: 2, allowedMask: null, useAdminOwner: false } }); + expect(await revokeSchemaChanges({ store, session: personSession(), name: 'helper' })).toMatchObject({ schemaChanges: false }); + expect(auth.calls.at(-1)).toMatchObject({ op: 'setPrincipalScope', input: { allowedMask: SCHEMA_READ_ONLY_MASK, useAdminOwner: false } }); + expect(readAgent('helper').schemaChanges).toBe(false); + }); + + it('names the sign-in step when a scope change needs a fresh sign-in', async () => { + await create('helper'); + auth.fail.setPrincipalScope = { code: 'STEP_UP_REQUIRED_MFA' }; + await expect(grantSchemaChanges({ store, session: personSession(), name: 'helper' })).rejects.toMatchObject({ kind: 'step-up-required' }); + expect(readAgent('helper').schemaChanges).toBe(false); + }); + + it('deletes the principal, which ends its key and cached token at once, then the stored entry, and keeps the entry when the delete fails', async () => { + await create('helper'); + const { apiKey } = readAgent('helper'); + const token = (await signedIn('helper')).account.accessToken; + auth.fail.deletePrincipal = { status: 502 }; + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).rejects.toMatchObject({ kind: 'server-error' }); + expect(fs.existsSync(agentFile('helper'))).toBe(true); + + delete auth.fail.deletePrincipal; + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).resolves.toEqual({ kind: 'removed', name: 'helper' }); + expect(auth.live(token)).toBe(false); + expect(auth.keyLive(apiKey)).toBe(false); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + expect(fs.existsSync(cacheFile('helper'))).toBe(false); + expect(auth.principals.size).toBe(0); + expect(listAgents({ store })).toEqual([]); + }); + + it('removes the entry of a principal that is already gone', async () => { + await create('helper'); + auth.fail.deletePrincipal = { code: 'PRINCIPAL_NOT_FOUND' }; + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).resolves.toEqual({ kind: 'already-gone', name: 'helper' }); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); +}); + +describe('renewAgentKey', () => { + it('gives the same principal a new capped 30-day key, keeps its grants, drops the cached token, and ends the old key and its tokens', async () => { + await create('helper'); + await grantSchemaChanges({ store, session: personSession(), name: 'helper' }); + const old = readAgent('helper'); + const scope = auth.scopes.get(`${old.principalId}:2`); + const oldToken = (await signedIn('helper')).account.accessToken; + const before = auth.calls.length; + + const renewal = await renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' }); + + expect(auth.calls.slice(before).map((call) => call.op)).toEqual(['signIn', 'createApiKey', 'revokeApiKey', 'signOut']); + expect(auth.calls.at(-3)!.input).toEqual({ keyName: 'agent:helper', accessLevel: 'full_access', mfaLevel: 'none', expiresIn: { days: 30 }, principalId: old.principalId }); + expect(auth.calls.at(-2)!.input).toEqual({ keyId: old.keyId }); + expect(auth.liveSignIns()).toBe(0); + const renewed = readAgent('helper'); + expect(renewed).toMatchObject({ principalId: old.principalId, schemaChanges: true, createdAt: old.createdAt }); + expect(renewed.keyId).not.toBe(old.keyId); + expect(renewal).toEqual({ agent: expect.objectContaining({ principalId: old.principalId, schemaChanges: true, keyExpiresAt: renewed.keyExpiresAt, state: 'ready' }), previousKey: { kind: 'revoked', keyId: old.keyId } }); + expect(auth.scopes.get(`${old.principalId}:2`)).toEqual(scope); + expect(fs.existsSync(cacheFile('helper'))).toBe(false); + expect(auth.keyLive(old.apiKey)).toBe(false); + expect(auth.live(oldToken)).toBe(false); + + const session = await signedIn('helper'); + expect(mints().at(-1)).toMatchObject({ bearer: renewed.apiKey, input: { principalId: old.principalId } }); + expect(auth.live(session.account.accessToken)).toBe(true); + }); + + it('keeps the old key when no new key can be made', async () => { + await create('helper'); + const old = readAgent('helper'); + auth.fail.createApiKey = { code: 'API_KEY_LIMIT_REACHED' }; + await expect(renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' })).rejects.toMatchObject({ kind: 'refused', code: 'API_KEY_LIMIT_REACHED' }); + expect(readAgent('helper')).toEqual(old); + expect(auth.keyLive(old.apiKey)).toBe(true); + expect(auth.liveSignIns()).toBe(0); + }); +}); + +describe('secrets', () => { + it('keeps the key and every token in 0600 files of the store, and out of every result and error', async () => { + await create('helper'); + await signedIn('helper'); + const agentFiles = allFiles().filter((file) => file.includes(`${path.sep}agents${path.sep}`)); + expect(agentFiles).toHaveLength(2); + for (const file of agentFiles) expect([file, fs.statSync(file).mode & 0o777]).toEqual([file, 0o600]); + auth.fail.setPrincipalScope = { code: 'NOT_OWNER', message: 'violates policy on constructive_memberships_private.org_memberships_sprt' }; + const error = await grantSchemaChanges({ store, session: personSession(), name: 'helper' }).catch((err) => err); + expect(`${error.message} ${JSON.stringify(error)}`).not.toMatch(/cnc_live|person-access-token|person-api-key|person-signin|_private/); + expect(error.message).toContain('NOT_OWNER'); + expect(JSON.stringify(listAgents({ store }))).not.toMatch(/cnc_live/); + auth.keys[0].revoked = true; + expireCache('helper'); + expect(JSON.stringify(await agentSession({ store, name: 'helper', env: {} }))).not.toMatch(/cnc_live/); + }); +}); + +describe('the fake api plane', () => { + const listDatabases = (bearer: string | undefined) => + fetch(auth.endpoint, { + method: 'POST', + headers: { 'content-type': 'application/json', ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, + body: JSON.stringify({ query: 'query ListDatabases { databases(first: 100, orderBy: [CREATED_AT_DESC]) { nodes { id name ownerId createdAt } } }' }) + }).then((r) => r.json()); + + it('lists the databases the test sets for the person and for a live agent token, and refuses any other bearer', async () => { + const db = { id: 'db-1', name: 'hcli-db', ownerId: 'person-1', createdAt: '2026-11-26T00:00:00Z' }; + auth.databases = [db]; + await create('helper'); + const token = (await signedIn('helper')).account.accessToken; + const expected = { data: { databases: { nodes: [db] } } }; + expect(await listDatabases('person-access-token')).toEqual(expected); + expect(await listDatabases(token)).toEqual(expected); + for (const bearer of [undefined, 'not-a-token']) { + expect((await listDatabases(bearer)).errors?.[0]?.extensions?.code).toBe('UNAUTHENTICATED'); + } + expect(auth.ops().filter((op) => op === 'databases')).toHaveLength(4); + }); +}); diff --git a/agentic/cli/__tests__/api-key.test.ts b/agentic/session/__tests__/api-key.test.ts similarity index 66% rename from agentic/cli/__tests__/api-key.test.ts rename to agentic/session/__tests__/api-key.test.ts index 5176387b9f..7c72977176 100644 --- a/agentic/cli/__tests__/api-key.test.ts +++ b/agentic/session/__tests__/api-key.test.ts @@ -2,20 +2,20 @@ import { API_KEY_NAME, buildCreateApiKeyInput, classifyApiKeyError, + keyEndsSoon, MintedApiKey, - needsRemint, parseMintedKey, - REMINT_THRESHOLD_MS, - remintApiKey + remintApiKey, + SIGN_IN_AGAIN_WITHIN_MS } from '../src/api-key'; describe('buildCreateApiKeyInput', () => { it('names the key agentic-cli with full access and no MFA', () => { - expect(buildCreateApiKeyInput({ years: 5 })).toEqual({ + expect(buildCreateApiKeyInput({ days: 30 })).toEqual({ keyName: API_KEY_NAME, accessLevel: 'full_access', mfaLevel: 'none', - expiresIn: { years: 5 } + expiresIn: { days: 30 } }); expect(API_KEY_NAME).toBe('agentic-cli'); }); @@ -43,27 +43,27 @@ describe('classifyApiKeyError', () => { expect(classifyApiKeyError(err)).toBe('step-up-required'); }); - it('falls back to message text and then unknown', () => { - expect(classifyApiKeyError(new Error('boom: API_KEY_LIMIT_REACHED'))).toBe('limit-reached'); - expect(classifyApiKeyError(new Error('NOT_AUTHENTICATED'))).toBe('not-authenticated'); + it('never reads a code out of message text', () => { + expect(classifyApiKeyError(new Error('boom: API_KEY_LIMIT_REACHED'))).toBe('unknown'); + expect(classifyApiKeyError(new Error('NOT_AUTHENTICATED'))).toBe('unknown'); expect(classifyApiKeyError(new Error('nope'))).toBe('unknown'); expect(classifyApiKeyError(undefined)).toBe('unknown'); }); }); -describe('needsRemint', () => { +describe('keyEndsSoon', () => { const now = Date.parse('2026-08-03T00:00:00Z'); it('is false without an expiry or with an unparsable one', () => { - expect(needsRemint({ apiKeyExpiresAt: undefined, now })).toBe(false); - expect(needsRemint({ apiKeyExpiresAt: 'garbage', now })).toBe(false); + expect(keyEndsSoon({ expiresAt: undefined, now })).toBe(false); + expect(keyEndsSoon({ expiresAt: 'garbage', now })).toBe(false); }); - it('is true at or inside the 7-day threshold, false outside', () => { + it('is true at or inside the 7-day window, false outside', () => { const at = (deltaMs: number) => new Date(now + deltaMs).toISOString(); - expect(needsRemint({ apiKeyExpiresAt: at(REMINT_THRESHOLD_MS), now })).toBe(true); - expect(needsRemint({ apiKeyExpiresAt: at(REMINT_THRESHOLD_MS + 1000), now })).toBe(false); - expect(needsRemint({ apiKeyExpiresAt: at(-1000), now })).toBe(true); + expect(keyEndsSoon({ expiresAt: at(SIGN_IN_AGAIN_WITHIN_MS), now })).toBe(true); + expect(keyEndsSoon({ expiresAt: at(SIGN_IN_AGAIN_WITHIN_MS + 1000), now })).toBe(false); + expect(keyEndsSoon({ expiresAt: at(-1000), now })).toBe(true); }); }); @@ -82,7 +82,7 @@ describe('remintApiKey', () => { return minted; } }); - expect(result).toEqual(minted); + expect(result).toEqual({ kind: 'minted', minted, previousKey: { kind: 'revoked', keyId: 'old-id' } }); expect(calls).toEqual(['mint', 'revoke:old-id']); }); @@ -101,26 +101,24 @@ describe('remintApiKey', () => { return minted; } }); - expect(result).toEqual(minted); + expect(result).toEqual({ kind: 'minted', minted, previousKey: { kind: 'revoked', keyId: 'old-id' } }); expect(calls).toEqual(['mint', 'revoke:old-id', 'mint']); }); - it('rethrows non-limit errors without revoking', async () => { + it('keeps the old key on a non-limit error without revoking', async () => { const revoke = jest.fn(); - await expect( - remintApiKey({ - currentKeyId: 'old-id', - revoke, - mint: async () => { - throw { errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] }; - } - }) - ).rejects.toBeDefined(); + const result = await remintApiKey({ + currentKeyId: 'old-id', + revoke, + mint: async () => { + throw { errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] }; + } + }); + expect(result).toMatchObject({ kind: 'failed', previousKey: { kind: 'kept', keyId: 'old-id' } }); expect(revoke).not.toHaveBeenCalled(); }); - it('tolerates a failing revoke', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + it('reports a failing revoke instead of printing it', async () => { const result = await remintApiKey({ currentKeyId: 'old-id', revoke: async () => { @@ -128,8 +126,6 @@ describe('remintApiKey', () => { }, mint: async () => minted }); - expect(result).toEqual(minted); - expect(warn).toHaveBeenCalled(); - warn.mockRestore(); + expect(result).toEqual({ kind: 'minted', minted, previousKey: { kind: 'failed', keyId: 'old-id', reason: 'offline' } }); }); }); diff --git a/agentic/session/__tests__/auth.test.ts b/agentic/session/__tests__/auth.test.ts new file mode 100644 index 0000000000..b19335f9c4 --- /dev/null +++ b/agentic/session/__tests__/auth.test.ts @@ -0,0 +1,383 @@ +import { ConfigStore } from 'appstash'; +import * as fs from 'fs'; +import * as http from 'http'; +import { AddressInfo } from 'net'; +import * as os from 'os'; +import * as path from 'path'; + +import { loadSession, openStore, saveSession } from '../src/account-store'; +import { signIn, signOut, verifySession } from '../src/auth'; +import { SignInError } from '../src/auth-error'; +import { addBackend, BackendConfig, backendFromEndpoints, ContextInUseError, contextNameFor, removeBackend, selectBackend } from '../src/backend-store'; +import { resolveSession } from '../src/session'; + +type Reply = { data?: unknown; errors?: unknown[] } | { status: number } | 'hang'; + +interface Call { + op: 'signIn' | 'signOut' | 'createApiKey' | 'revokeApiKey' | 'currentUser'; + bearer?: string; + variables: any; +} + +/** A GraphQL auth endpoint that answers each operation from `replies` and records every call. */ +class FakeAuth { + calls: Call[] = []; + replies: Partial Reply>> = {}; + private server = http.createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + const { query = '', variables } = JSON.parse(body || '{}'); + const op = (['signIn', 'signOut', 'createApiKey', 'revokeApiKey', 'currentUser'] as const).find((name) => query.includes(name)); + const bearer = req.headers.authorization?.replace(/^Bearer /, ''); + const call: Call = { op, bearer, variables }; + this.calls.push(call); + const reply = this.replies[op]?.(call, this.calls.filter((c) => c.op === op).length) ?? { data: {} }; + if (reply === 'hang') return; + if ('status' in reply) { + res.statusCode = reply.status; + res.end('upstream failed'); + return; + } + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify(reply)); + }); + }); + + endpoint = ''; + + async start(): Promise { + await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve)); + this.endpoint = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/graphql`; + } + + async stop(): Promise { + this.server.closeAllConnections(); + await new Promise((resolve) => this.server.close(resolve)); + } + + backend(): BackendConfig { + const ep = this.endpoint; + return backendFromEndpoints({ api: ep, auth: ep, modules: ep, agent: ep, compute: ep }); + } + + context(): string { + return contextNameFor(this.backend()); + } + + ops(): string[] { + return this.calls.map((call) => call.op); + } +} + +const signedIn = (userId: string, n: number) => ({ + data: { signIn: { result: { userId, accessToken: `access-${userId}-${n}`, accessTokenExpiresAt: '2030-01-01T00:00:00Z', mfaRequired: false } } } +}); +const minted = (n: number) => ({ data: { createApiKey: { result: { apiKey: `key-${n}`, keyId: `kid-${n}`, expiresAt: '2031-01-01T00:00:00Z' } } } }); +const revoked = { data: { revokeApiKey: { result: true } } }; +const failure = (code: string, message = code) => ({ errors: [{ message, extensions: { code } }] }); + +let home: string; +let store: ConfigStore; +let auth: FakeAuth; + +beforeEach(async () => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'session-auth-')); + store = openStore(home); + auth = new FakeAuth(); + await auth.start(); + auth.replies = { + signIn: (_call, n) => signedIn('user-1', n), + createApiKey: (_call, n) => minted(n), + revokeApiKey: () => revoked + }; +}); + +afterEach(async () => { + await auth.stop(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +const login = (password = 'pw', backend = auth.backend()) => signIn({ store, backend, email: ' dev@example.com ', password }); + +async function signInError(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error as SignInError; + } + throw new Error('expected the sign-in to fail'); +} + +describe('signIn', () => { + it('mints a key, then stores the backend, the session and the choice of context', async () => { + const result = await login(); + expect(auth.ops()).toEqual(['signIn', 'createApiKey', 'signOut']); + expect(auth.calls[0].variables.input).toEqual({ email: 'dev@example.com', password: 'pw' }); + expect(auth.calls[1].bearer).toBe('access-user-1-1'); + expect(result).toMatchObject({ context: auth.context(), apiKey: { kind: 'minted' }, previousKey: { kind: 'absent' } }); + expect(loadSession(store)).toMatchObject({ userId: 'user-1', apiKey: 'key-1', keyId: 'kid-1', issuedFor: auth.backend(), authEndpoint: auth.endpoint }); + expect(store.getCurrentContext()?.name).toBe(auth.context()); + }); + + it('ends its sign-in session on the server once the key is made, and stores the key as the bearer', async () => { + await login(); + const signOut = auth.calls.findIndex((call) => call.op === 'signOut'); + expect(signOut).toBeGreaterThan(auth.ops().indexOf('createApiKey')); + expect(auth.calls[signOut].bearer).toBe('access-user-1-1'); + expect(loadSession(store)).toMatchObject({ accessToken: 'key-1', accessTokenExpiresAt: '2031-01-01T00:00:00Z', apiKey: 'key-1' }); + }); + + it('fails, stores nothing, and still ends its sign-in session when no key can be made', async () => { + auth.replies.createApiKey = () => failure('API_KEYS_DISABLED', 'keys are off'); + const error = await signInError(login()); + expect(error).toMatchObject({ kind: 'refused', code: 'API_KEYS_DISABLED' }); + expect(error.message).toContain('API_KEYS_DISABLED'); + expect(auth.calls.filter((call) => call.op === 'signOut').map((call) => call.bearer)).toEqual(['access-user-1-1']); + expect(store.listContexts()).toEqual([]); + expect(loadSession(store, auth.context())).toBeNull(); + }); + + it('asks for a person key that lasts 30 days', async () => { + await login(); + expect(auth.calls[1].op).toBe('createApiKey'); + expect(auth.calls[1].variables.input.expiresIn).toEqual({ days: 30 }); + }); + + it('revokes the key of the session it replaces', async () => { + await login(); + const second = await login(); + expect(auth.ops()).toEqual(['signIn', 'createApiKey', 'signOut', 'signIn', 'createApiKey', 'revokeApiKey', 'signOut']); + expect(auth.calls[5].variables.input).toEqual({ keyId: 'kid-1' }); + expect(second.previousKey).toEqual({ kind: 'revoked', keyId: 'kid-1' }); + expect(loadSession(store)).toMatchObject({ apiKey: 'key-2', keyId: 'kid-2' }); + }); + + it('revokes the replaced key with that key when another account signs in', async () => { + await login(); + auth.replies.signIn = (_call, n) => signedIn('user-2', n); + const second = await login(); + const revoke = auth.calls.find((call) => call.op === 'revokeApiKey'); + expect(revoke).toMatchObject({ bearer: 'key-1', variables: { input: { keyId: 'kid-1' } } }); + expect(second.previousKey).toEqual({ kind: 'revoked', keyId: 'kid-1' }); + }); + + it('frees the key limit by revoking the replaced key, then mints again', async () => { + await login(); + auth.replies.createApiKey = (_call, n) => (n === 2 ? failure('API_KEY_LIMIT_REACHED') : minted(n)); + const second = await login(); + expect(auth.ops().slice(3)).toEqual(['signIn', 'createApiKey', 'revokeApiKey', 'createApiKey', 'signOut']); + expect(second).toMatchObject({ apiKey: { kind: 'minted' }, previousKey: { kind: 'revoked', keyId: 'kid-1' } }); + }); + + it('keeps the replaced key when the same account cannot mint a new one', async () => { + await login(); + auth.replies.createApiKey = () => failure('API_KEYS_DISABLED'); + const second = await login(); + expect(second).toMatchObject({ apiKey: { kind: 'not-minted' }, previousKey: { kind: 'kept', keyId: 'kid-1' } }); + expect(loadSession(store)).toMatchObject({ accessToken: 'key-1', apiKey: 'key-1', keyId: 'kid-1' }); + }); + + it.each<[string, Reply | 'unreachable', string]>([ + ['no record (wrong email or password)', { data: { signIn: { result: null } } }, 'invalid-credentials'], + ['an empty record', { data: { signIn: { result: { userId: null, accessToken: null, mfaRequired: false } } } }, 'invalid-credentials'], + ['a second factor', { data: { signIn: { result: { userId: null, accessToken: null, mfaRequired: true } } } }, 'second-factor-required'], + ['a locked account', failure('ACCOUNT_LOCKED_EXCEED_ATTEMPTS'), 'refused'], + ['an HTTP 502', { status: 502 }, 'server-error'], + ['an HTTP 429', { status: 429 }, 'refused'], + ['a refusal named only in the message text', { errors: [{ message: 'ACCOUNT_LOCKED_EXCEED_ATTEMPTS' }] }, 'server-error'], + ['a masked server error', failure('INTERNAL_SERVER_ERROR', 'An unexpected error occurred'), 'server-error'], + ['a closed port', 'unreachable', 'backend-unreachable'] + ])('tells %s apart', async (_name, reply, kind) => { + let backend = auth.backend(); + if (reply === 'unreachable') { + await auth.stop(); + backend = auth.backend(); + } else { + auth.replies.signIn = () => reply; + } + const error = await signInError(login('pw', backend)); + expect(error).toBeInstanceOf(SignInError); + expect(error.kind).toBe(kind); + expect(error.message).not.toContain('pw'); + expect(store.listContexts()).toEqual([]); + expect(loadSession(store, auth.context())).toBeNull(); + }); + + it('files the session under the context it is given, keeping its name', async () => { + const result = await signIn({ store, backend: auth.backend(), context: 'dev', email: 'dev@example.com', password: 'pw' }); + expect(result.context).toBe('dev'); + expect(store.getCurrentContext()?.name).toBe('dev'); + expect(loadSession(store, 'dev')).toMatchObject({ userId: 'user-1' }); + expect(store.loadContext(auth.context())).toBeNull(); + }); + + it('rejects empty credentials without a network call', async () => { + const error = await signInError(signIn({ store, backend: auth.backend(), email: ' ', password: 'pw' })); + expect(error.kind).toBe('invalid-input'); + expect(auth.calls).toEqual([]); + }); +}); + +describe('a context that holds a session of another backend', () => { + it('is refused by addBackend with the session kept, and is replaced by signIn only after that key is revoked', async () => { + const other = new FakeAuth(); + await other.start(); + try { + selectBackend(store, addBackend(store, other.backend(), 'custom').name); + saveSession(store, { userId: 'user-1', email: 'e', accessToken: 'old-key', apiKey: 'old-key', keyId: 'kid-old', signedInAt: 1, issuedFor: other.backend() }, 'custom'); + expect(() => addBackend(store, auth.backend(), 'custom')).toThrow(ContextInUseError); + expect(() => removeBackend(store, 'custom')).toThrow(ContextInUseError); + expect(loadSession(store, 'custom')).toMatchObject({ keyId: 'kid-old', issuedFor: other.backend() }); + expect(store.loadContext('custom')?.targets.api.endpoint).toBe(other.endpoint); + + const result = await signIn({ store, backend: auth.backend(), context: 'custom', email: 'dev@example.com', password: 'pw' }); + expect(result.previousKey).toEqual({ kind: 'revoked', keyId: 'kid-old' }); + expect(other.calls).toEqual([expect.objectContaining({ op: 'revokeApiKey', bearer: 'old-key' })]); + expect(loadSession(store, 'custom')).toMatchObject({ apiKey: 'key-1', issuedFor: auth.backend() }); + } finally { + await other.stop(); + } + }); +}); + +describe('the server error text', () => { + const leak = 'permission denied for table constructive_auth_private.sessions'; + + it('never reaches a message: a sign-in failure and a failed revoke name the code only', async () => { + auth.replies.signIn = () => failure('SOME_SERVER_CODE', leak); + const error = await signInError(login()); + expect(error.message).toContain('SOME_SERVER_CODE'); + expect(error.message).not.toContain('constructive_auth_private'); + + auth.replies.revokeApiKey = () => failure('NOT_OWNER', leak); + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, { userId: 'user-1', email: 'e', accessToken: 'k', apiKey: 'k', keyId: 'kid-1', signedInAt: 1, issuedFor: auth.backend() }); + const out = await signOut({ store, session: resolveSession({ store, env: {} }) }); + expect(out).toMatchObject({ kind: 'cleared', key: { kind: 'failed', reason: expect.stringContaining('NOT_OWNER') } }); + expect(JSON.stringify(out)).not.toContain('constructive_auth_private'); + }); +}); + +describe('signOut', () => { + const session = () => ({ userId: 'user-1', email: 'dev@example.com', accessToken: 'token', apiKey: 'k', keyId: 'kid-1', signedInAt: 1, issuedFor: auth.backend() }); + const out = (env: NodeJS.ProcessEnv = {}) => signOut({ store, session: resolveSession({ store, env }) }); + + it('revokes the key at its issuer and clears the session', async () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, session()); + await expect(out()).resolves.toEqual({ kind: 'cleared', context: auth.context(), key: { kind: 'revoked', keyId: 'kid-1' } }); + expect(auth.calls[0]).toMatchObject({ op: 'revokeApiKey', bearer: 'k' }); + expect(store.getCredentials(auth.context())).toBeNull(); + }); + + it('clears the session and says why when the revoke fails', async () => { + auth.replies.revokeApiKey = () => failure('FORBIDDEN', 'not yours'); + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, session()); + const warn = jest.spyOn(console, 'warn'); + const result = await out(); + expect(result).toMatchObject({ kind: 'cleared', key: { kind: 'failed', keyId: 'kid-1', reason: expect.stringContaining('FORBIDDEN') } }); + expect(store.getCredentials(auth.context())).toBeNull(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('revokes at the issuer the credential records, never at the auth plane the context names now', async () => { + const other = new FakeAuth(); + await other.start(); + try { + selectBackend(store, addBackend(store, other.backend(), 'custom').name); + saveSession(store, session(), 'custom'); + expect(resolveSession({ store, env: {} })).toMatchObject({ kind: 'issuer-mismatch', issuedFor: auth.backend() }); + await expect(out()).resolves.toEqual({ kind: 'cleared', context: 'custom', key: { kind: 'revoked', keyId: 'kid-1' } }); + expect(auth.calls).toEqual([expect.objectContaining({ op: 'revokeApiKey', bearer: 'k' })]); + expect(other.calls).toEqual([]); + } finally { + await other.stop(); + } + }); + + it('sends nothing for a credential with no recorded issuer, clears it, and says the key was not revoked', async () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, { ...session(), issuedFor: undefined }); + const result = await out(); + expect(result).toMatchObject({ kind: 'cleared', key: { kind: 'failed', keyId: 'kid-1', reason: expect.stringContaining('did not record the auth endpoint that issued it') } }); + expect(store.getCredentials(auth.context())).toBeNull(); + expect(auth.calls).toEqual([]); + }); + + it('clears the session of a context that lacks a plane, revoking at its issuer', async () => { + store.createContext('partial', { endpoint: auth.endpoint, targets: { api: { endpoint: auth.endpoint } } }); + store.setCurrentContext('partial'); + saveSession(store, session()); + await expect(out()).resolves.toEqual({ kind: 'cleared', context: 'partial', key: { kind: 'revoked', keyId: 'kid-1' } }); + expect(store.getCredentials('partial')).toBeNull(); + }); + + it('reports a session with no key as cleared with the key absent', async () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, { ...session(), apiKey: undefined, keyId: undefined }); + await expect(out()).resolves.toEqual({ kind: 'cleared', context: auth.context(), key: { kind: 'absent' } }); + }); + + it('is not-signed-in when nothing is stored', async () => { + await expect(out()).resolves.toEqual({ kind: 'not-signed-in', context: null }); + expect(auth.calls).toEqual([]); + }); + + it('removes nothing for a session from the environment, and leaves the stored one alone', async () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, session()); + const env = { CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: 'https://api.example.com/graphql' }; + await expect(out(env)).resolves.toEqual({ kind: 'from-environment' }); + expect(store.getCredentials(auth.context())).not.toBeNull(); + expect(auth.calls).toEqual([]); + }); +}); + +describe('verifySession', () => { + const signedIn = () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, { userId: 'user-1', email: 'e', accessToken: 'token', apiKey: 'key', keyId: 'kid', signedInAt: 1, issuedFor: auth.backend() }); + const session = resolveSession({ store, env: {} }); + if (session.kind !== 'signed-in') throw new Error(`expected signed-in, got ${session.kind}`); + return session; + }; + + it.each<[string, Reply | 'unreachable', string]>([ + ['the credential works', { data: { currentUser: { id: 'user-1' } } }, 'accepted'], + ['the server rejects it', failure('UNAUTHENTICATED', 'expired'), 'rejected'], + ['the server answers HTTP 401', { status: 401 }, 'rejected'], + ['the server sees no user', { data: { currentUser: null } }, 'rejected'], + ['the credential belongs to someone else', { data: { currentUser: { id: 'user-2' } } }, 'rejected'], + ['the server fails', { status: 502 }, 'unchecked'], + ['the server has another error', failure('INTERNAL_SERVER_ERROR', 'boom'), 'unchecked'], + ['the backend is down', 'unreachable', 'unchecked'] + ])('says %s', async (_name, reply, kind) => { + const session = signedIn(); + if (reply === 'unreachable') await auth.stop(); + else auth.replies.currentUser = () => reply; + const check = await verifySession(session); + expect(check.kind).toBe(kind); + if (reply !== 'unreachable') expect(auth.calls.at(-1)).toMatchObject({ op: 'currentUser', bearer: 'key' }); + }); +}); + +describe('timeouts', () => { + it('gives the key mint and the key revoke the sign-in timeout', async () => { + auth.replies.createApiKey = () => 'hang'; + const signingIn = login(); + + const other = openStore(fs.mkdtempSync(path.join(home, 'other-'))); + selectBackend(other, addBackend(other, auth.backend()).name); + saveSession(other, { userId: 'u', email: 'e', accessToken: 't', keyId: 'kid', apiKey: 'k', signedInAt: 1, issuedFor: auth.backend() }); + auth.replies.revokeApiKey = () => 'hang'; + const signingOut = signOut({ store: other, session: resolveSession({ store: other, env: {} }) }); + + const [result, out] = await Promise.all([signInError(signingIn), signingOut]); + expect(result).toMatchObject({ kind: 'backend-unreachable', message: expect.stringContaining('did not respond') }); + expect(loadSession(store, auth.context())).toBeNull(); + expect(out).toMatchObject({ kind: 'cleared', key: { kind: 'failed', reason: expect.stringContaining('did not respond') } }); + }, 20_000); +}); diff --git a/agentic/session/__tests__/fake-principals.ts b/agentic/session/__tests__/fake-principals.ts new file mode 100644 index 0000000000..aef0c37ae0 --- /dev/null +++ b/agentic/session/__tests__/fake-principals.ts @@ -0,0 +1,246 @@ +import * as http from 'http'; +import { AddressInfo } from 'net'; + +import { BackendConfig, backendFromEndpoints, contextNameFor } from '../src/backend-store'; + +export interface PrincipalCall { + op: string; + bearer?: string; + input: any; + query: string; +} + +interface Key { + id: string; + secret: string; + principalId: string; + expiresAt: number; + revoked: boolean; +} + +interface Session { + id: string; + principalId: string; + /** The key the token was minted with; revoking the key ends it. */ + keyId?: string; + access: string; + accessExpiresAt: number; + refresh: string; + revoked: boolean; +} + +const DAY_MS = 24 * 3600 * 1000; +const intervalMs = (interval: any): number => + ((interval?.years ?? 0) * 365 + (interval?.days ?? 0)) * DAY_MS + (interval?.seconds ?? 0) * 1000; + +/** + * An auth plane that keeps the person's password sign-ins, principals, their + * keys and their token sessions the way the backend does: a key needs a live + * password sign-in (a fresh one) and is clamped to the principal's cap + * (`updatePrincipal`'s `apiKeyMaxDuration`) and to 365 days; a mint with that + * key gives a 15-minute access token and a refresh token, which it answers + * whether asked for or not; revoking a key ends the tokens minted with it, and + * deleting a principal ends its keys and tokens at once. + */ +export class FakePrincipals { + calls: PrincipalCall[] = []; + principals = new Map(); + scopes = new Map(); + keys: Key[] = []; + sessions: Session[] = []; + /** Answer an op with a GraphQL error code (or an HTTP status) instead of its normal behavior. */ + fail: Record = {}; + /** Delay before each answer. */ + delayMs = 0; + /** Hold every answer of `op` until `count` requests of it have arrived, so a test can prove they were in flight together. */ + barrier: { op: string; count: number } | null = null; + /** What the api plane's `databases` query lists; `ownerId` is whatever the test sets. */ + databases: Array<{ id: string; name: string; ownerId: string; createdAt: string }> = []; + /** The person's bearers the api plane accepts, beside every live agent access token. */ + personBearers = new Set(['person-access-token', 'person-api-key']); + /** The person's password, and each sign-in token with whether its session is still live. */ + password = 'pw'; + signIns = new Map(); + private n = 0; + private waiting: Array<() => void> = []; + + private server = http.createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', async () => { + const { query = '', variables } = JSON.parse(body || '{}'); + const op = (query.match(/\b(signIn|signOut|createPrincipal|setPrincipalScope|updatePrincipal|createApiKey|revokeApiKey|mintAccessToken|deletePrincipal|currentUser|databases)\b/) ?? [])[1] ?? 'other'; + const bearer = req.headers.authorization?.replace(/^Bearer /, ''); + const input = variables?.input ?? {}; + this.calls.push({ op, bearer, input, query }); + if (this.delayMs) await new Promise((resolve) => setTimeout(resolve, this.delayMs)); + if (this.barrier?.op === op) await this.arrive(this.barrier.count); + const failure = this.fail[op]; + if (failure === 'hang') return; + if (failure && 'status' in failure) { + res.statusCode = failure.status; + res.end('upstream failed'); + return; + } + const refused = this.refuses(op, bearer, input); + const code = failure && 'code' in failure ? failure.code : refused; + const message = failure && 'code' in failure ? (failure.message ?? code) : code; + const answer = code ? { errors: [{ message, extensions: { code } }] } : { data: this.handle(op, input, bearer) }; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify(answer)); + }); + }); + + endpoint = ''; + + private arrive(count: number): Promise { + return new Promise((resolve) => { + this.waiting.push(resolve); + if (this.waiting.length >= count) for (const release of this.waiting.splice(0)) release(); + }); + } + + private id(prefix: string): string { + this.n += 1; + return `${prefix}-${this.n}`; + } + + private liveKey(secret: string | undefined): Key | undefined { + const key = this.keys.find((k) => k.secret === secret); + return key && !key.revoked && key.expiresAt > Date.now() && this.principals.has(key.principalId) ? key : undefined; + } + + /** The error code the backend answers for a credential it does not accept here, if any. */ + private refuses(op: string, bearer: string | undefined, input: any): string | undefined { + const fresh = !!bearer && this.signIns.get(bearer) === true; + const person = fresh || (!!bearer && this.personBearers.has(bearer)); + if (op === 'databases') return person || (bearer && this.live(bearer)) ? undefined : 'UNAUTHENTICATED'; + if (op === 'signOut') return fresh ? undefined : 'UNAUTHENTICATED'; + if (op === 'createApiKey') return fresh ? undefined : person ? 'STEP_UP_REQUIRED_FRESH_AUTH' : 'UNAUTHENTICATED'; + if (['createPrincipal', 'setPrincipalScope', 'updatePrincipal', 'deletePrincipal', 'revokeApiKey'].includes(op)) return person ? undefined : 'UNAUTHENTICATED'; + if (op === 'mintAccessToken') { + if (person) return undefined; + const key = this.liveKey(bearer); + if (!key) return 'UNAUTHENTICATED'; + return key.principalId === input.principalId ? undefined : 'PRINCIPAL_NOT_FOUND'; + } + return undefined; + } + + private handle(op: string, input: any, bearer?: string): unknown { + switch (op) { + case 'signIn': { + if (input.password !== this.password) return { signIn: { result: null } }; + const token = this.id('person-signin'); + this.signIns.set(token, true); + return { signIn: { result: { userId: 'person-1', accessToken: token, accessTokenExpiresAt: new Date(Date.now() + 3600_000).toISOString(), mfaRequired: false } } }; + } + case 'signOut': + this.signIns.set(bearer, false); + return { signOut: { clientMutationId: null } }; + case 'revokeApiKey': { + const key = this.keys.find((k) => k.id === input.keyId); + if (key) key.revoked = true; + for (const s of this.sessions) if (key && s.keyId === key.id) s.revoked = true; + return { revokeApiKey: { result: !!key } }; + } + case 'createPrincipal': { + const id = this.id('principal-user'); + this.principals.set(id, { name: input.name, useAdminOwner: input.useAdminOwner, entityIds: input.entityIds }); + return { createPrincipal: { result: id } }; + } + case 'setPrincipalScope': + this.scopes.set(`${input.principalId}:${input.membershipType}`, input); + return { setPrincipalScope: { result: true } }; + case 'updatePrincipal': { + const principal = this.principals.get(input.principalId); + if (!principal) return { updatePrincipal: { result: false } }; + if (input.apiKeyMaxDuration) principal.apiKeyMaxDurationMs = intervalMs(input.apiKeyMaxDuration); + return { updatePrincipal: { result: true } }; + } + case 'createApiKey': { + const cap = this.principals.get(input.principalId)?.apiKeyMaxDurationMs ?? Infinity; + const ms = Math.min(input.expiresIn ? intervalMs(input.expiresIn) : 90 * DAY_MS, 365 * DAY_MS, cap); + const key: Key = { id: this.id('key'), secret: this.id('cnc_live_sk_fake'), principalId: input.principalId, expiresAt: Date.now() + ms, revoked: false }; + this.keys.push(key); + return { createApiKey: { result: { apiKey: key.secret, keyId: key.id, expiresAt: new Date(key.expiresAt).toISOString() } } }; + } + case 'mintAccessToken': { + const ttl = input.accessTtl?.seconds ?? 900; + const session: Session = { + id: this.id('session'), + principalId: input.principalId, + keyId: this.liveKey(bearer)?.id, + access: this.id('cnc_live_at_fake'), + accessExpiresAt: Date.now() + ttl * 1000, + refresh: this.id('cnc_live_rt_fake'), + revoked: false + }; + this.sessions.push(session); + return { + mintAccessToken: { + result: { + accessToken: session.access, + refreshToken: session.refresh, + sessionId: session.id, + principalUserId: session.principalId, + accessExpiresAt: new Date(session.accessExpiresAt).toISOString(), + refreshExpiresAt: new Date(Date.now() + 30 * DAY_MS).toISOString() + } + } + }; + } + case 'deletePrincipal': + if (!this.principals.delete(input.principalId)) return null; + for (const s of this.sessions) if (s.principalId === input.principalId) s.revoked = true; + for (const k of this.keys) if (k.principalId === input.principalId) k.revoked = true; + return { deletePrincipal: { result: true } }; + case 'databases': + return { databases: { nodes: this.databases } }; + case 'currentUser': + return { currentUser: bearer && this.live(bearer) ? { id: 'person-1' } : null }; + default: + return {}; + } + } + + /** Whether an access token would be accepted now. */ + live(access: string): boolean { + const s = this.sessions.find((x) => x.access === access); + return !!s && !s.revoked && s.accessExpiresAt > Date.now() && this.principals.has(s.principalId); + } + + /** How many password sign-in sessions are still live. */ + liveSignIns(): number { + return [...this.signIns.values()].filter(Boolean).length; + } + + /** Whether a principal's key would be accepted now. */ + keyLive(secret: string): boolean { + return !!this.liveKey(secret); + } + + async start(): Promise { + await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve)); + this.endpoint = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/graphql`; + } + + async stop(): Promise { + for (const release of this.waiting.splice(0)) release(); + this.server.closeAllConnections(); + await new Promise((resolve) => this.server.close(resolve)); + } + + backend(): BackendConfig { + const ep = this.endpoint; + return backendFromEndpoints({ api: ep, auth: ep, modules: ep, agent: ep, compute: ep }); + } + + context(): string { + return contextNameFor(this.backend()); + } + + ops(): string[] { + return this.calls.map((call) => call.op); + } +} diff --git a/agentic/session/__tests__/session.test.ts b/agentic/session/__tests__/session.test.ts new file mode 100644 index 0000000000..5167dfb6ed --- /dev/null +++ b/agentic/session/__tests__/session.test.ts @@ -0,0 +1,484 @@ +import { ConfigStore } from 'appstash'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { checkContextName, ContextNameError, openStore, saveSession, stashBaseDir } from '../src/account-store'; +import { + addBackend, + BackendConfig, + backendFromEndpoints, + ContextInUseError, + contextNameFor, + listBackends, + readBackend, + removeBackend, + selectBackend +} from '../src/backend-store'; +import { resolveSession } from '../src/session'; +import { sessionToolsHost } from '../src/tools-host'; + +const LOCAL = backendFromEndpoints({ api: 'http://api.localhost/graphql' }); +const REMOTE = backendFromEndpoints({ api: 'https://api.example.com/graphql' }); +const OTHER = 'https://api.other-backend.example/graphql'; + +let home: string; +let store: ConfigStore; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'session-resolve-')); + store = openStore(home); +}); + +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +const stored = { + userId: 'stored-user', + email: 'dev@example.com', + accessToken: 'stored-token', + apiKey: 'stored-key', + keyId: 'stored-key-id', + signedInAt: 1 +}; + +function signInStored(config: BackendConfig = REMOTE): string { + const { name } = addBackend(store, config); + selectBackend(store, name); + saveSession(store, { ...stored, issuedFor: config }); + return name; +} + +const resolve = (env: NodeJS.ProcessEnv = {}, context?: string) => resolveSession({ env, store, context }); + +describe('backendFromEndpoints', () => { + it.each([ + ['https://api.example.com/graphql', 'https://auth.example.com/graphql'], + ['http://api.localhost/graphql', 'http://auth.localhost/graphql'], + ['http://api.localhost:3000/graphql', 'http://auth.localhost:3000/graphql'], + ['https://api.example.co.uk/graphql', 'https://auth.example.co.uk/graphql'] + ])('derives the planes of %s', (api, auth) => { + expect(backendFromEndpoints({ api }).authEndpoint).toBe(auth); + }); + + it.each([ + ['https://example.com/graphql', 'not-derivable'], + ['https://constructive.example.com/graphql', 'not-derivable'], + ['https://api-demo.example.com/graphql', 'not-derivable'], + ['http://localhost:3000/graphql', 'not-derivable'], + ['https://api/graphql', 'not-derivable'], + ['https://[::1]:3000/graphql', 'not-derivable'], + ['http://127.0.0.1:3000/graphql', 'not-derivable'], + ['https://user:pw@api.example.com/graphql', 'userinfo'], + ['ftp://api.example.com/x', 'scheme'], + ['api.example.com/graphql', 'not-a-url'], + ['', 'not-a-url'] + ])('refuses %s (%s) and says how to give every plane', (api, reason) => { + let error: any; + try { + backendFromEndpoints({ api }); + } catch (caught) { + error = caught; + } + expect(error?.reason).toBe(reason); + expect(error.message).not.toContain('pw@'); + if (reason === 'not-derivable') expect(error.message).toContain('every plane'); + }); + + it('takes every plane explicitly when the api host cannot derive them', () => { + const ep = 'http://127.0.0.1:3000/graphql'; + expect(backendFromEndpoints({ api: ep, auth: ep, modules: ep, agent: ep, compute: ep })).toEqual({ + apiEndpoint: ep, authEndpoint: ep, modulesEndpoint: ep, agentEndpoint: ep, computeEndpoint: ep + }); + expect(() => backendFromEndpoints({ api: ep, auth: 'https://user:pw@auth.example.com/graphql', modules: ep, agent: ep, compute: ep })) + .toThrow(expect.objectContaining({ reason: 'userinfo' })); + }); +}); + +describe('resolveSession from the store', () => { + it('is no-backend when none is chosen or the named context is unknown', () => { + expect(resolve()).toEqual({ kind: 'no-backend', context: null }); + signInStored(); + expect(resolve({}, 'nowhere.test')).toEqual({ kind: 'no-backend', context: 'nowhere.test' }); + }); + + it('pairs the stored session with the endpoints of its own context', () => { + signInStored(); + expect(resolve()).toMatchObject({ + kind: 'signed-in', + source: 'store', + context: 'example.com', + backend: REMOTE, + account: { userId: 'stored-user', accessToken: 'stored-token', key: { kind: 'active', apiKey: 'stored-key', keyId: 'stored-key-id' } } + }); + }); + + it('reads the context it is given, not the active one', () => { + signInStored(); + selectBackend(store, addBackend(store, LOCAL).name); + expect(resolve()).toMatchObject({ kind: 'signed-out', context: 'localhost' }); + expect(resolve({}, 'example.com')).toMatchObject({ kind: 'signed-in', context: 'example.com', backend: REMOTE }); + }); + + it('is signed-out for a complete context with no session', () => { + selectBackend(store, addBackend(store, LOCAL).name); + expect(resolve()).toEqual({ kind: 'signed-out', source: 'store', context: 'localhost', backend: LOCAL }); + }); + + it('names the missing planes of a context another app wrote, and never fills them in', () => { + signInStored(LOCAL); + const four = LOCAL; + store.createContext('localnet', { + endpoint: four.apiEndpoint, + targets: { api: { endpoint: four.apiEndpoint }, auth: { endpoint: four.authEndpoint }, modules: { endpoint: four.modulesEndpoint }, agent: { endpoint: four.agentEndpoint } } + }); + store.setCurrentContext('localnet'); + saveSession(store, stored); + + expect(resolve()).toEqual({ kind: 'incomplete-backend', context: 'localnet', missing: ['compute'], apiEndpoint: LOCAL.apiEndpoint }); + expect(listBackends(store)).toContainEqual({ name: 'localnet', current: true, status: 'incomplete', missing: ['compute'], apiEndpoint: LOCAL.apiEndpoint }); + }); +}); + +describe('resolveSession with environment overrides', () => { + it('never sends the stored token to a backend that CONSTRUCTIVE_API_ENDPOINT names', () => { + signInStored(); + expect(resolve({ CONSTRUCTIVE_API_ENDPOINT: OTHER })).toEqual({ + kind: 'signed-out', + source: 'env', + context: null, + backend: backendFromEndpoints({ api: OTHER }) + }); + expect(resolve({ CONSTRUCTIVE_MODULES_ENDPOINT: 'https://modules.other.example/graphql', CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint })) + .toMatchObject({ kind: 'signed-out', source: 'env' }); + }); + + it('keeps the stored session when the override names the backend of its context', () => { + signInStored(); + expect(resolve({ CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint })).toMatchObject({ kind: 'signed-in', source: 'store', context: 'example.com' }); + }); + + it('uses a complete credential override with the backend it names', () => { + signInStored(); + const env = { CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: OTHER }; + expect(resolve(env)).toMatchObject({ + kind: 'signed-in', + source: 'env', + context: null, + backend: { apiEndpoint: OTHER }, + account: { userId: 'env-user', accessToken: 'env-token', key: { kind: 'none' } } + }); + }); + + it.each([ + [{ CONSTRUCTIVE_API_KEY: 'k' }, 'CONSTRUCTIVE_USER_ID'], + [{ CONSTRUCTIVE_ACCESS_TOKEN: 't' }, 'CONSTRUCTIVE_USER_ID'], + [{ CONSTRUCTIVE_USER_ID: 'u' }, 'CONSTRUCTIVE_ACCESS_TOKEN'], + [{ CONSTRUCTIVE_USER_ID: 'u', CONSTRUCTIVE_ACCESS_TOKEN: 't' }, 'CONSTRUCTIVE_API_ENDPOINT'], + [{ CONSTRUCTIVE_MODULES_ENDPOINT: 'https://modules.example.com/graphql' }, 'CONSTRUCTIVE_API_ENDPOINT'], + [{ CONSTRUCTIVE_API_ENDPOINT: 'https://example.com/graphql' }, 'CONSTRUCTIVE_API_ENDPOINT'], + [{ CONSTRUCTIVE_API_ENDPOINT: '' }, 'CONSTRUCTIVE_API_ENDPOINT'], + [{ CONSTRUCTIVE_STASH_DIR: '' }, 'CONSTRUCTIVE_STASH_DIR'] + ])('makes the incomplete or wrong override %j invalid-override, naming %s', (env: NodeJS.ProcessEnv, variable) => { + signInStored(); + const session = resolveSession({ env, ...(env.CONSTRUCTIVE_STASH_DIR === undefined ? { store } : {}) }); + expect(session).toMatchObject({ kind: 'invalid-override', variable }); + if (session.kind === 'invalid-override') expect(session.fix).toBeTruthy(); + }); + + it('takes every plane from the environment for a host that cannot derive them', () => { + const ep = 'http://127.0.0.1:3000/graphql'; + const env = { + CONSTRUCTIVE_API_ENDPOINT: ep, + CONSTRUCTIVE_AUTH_ENDPOINT: ep, + CONSTRUCTIVE_MODULES_ENDPOINT: ep, + CONSTRUCTIVE_AGENT_ENDPOINT: ep, + CONSTRUCTIVE_COMPUTE_ENDPOINT: ep + }; + expect(resolve(env)).toMatchObject({ kind: 'signed-out', source: 'env', backend: { authEndpoint: ep, computeEndpoint: ep } }); + }); +}); + +describe('the stash directory', () => { + it('refuses an empty CONSTRUCTIVE_STASH_DIR instead of opening the real store', () => { + expect(() => stashBaseDir({ CONSTRUCTIVE_STASH_DIR: '' })).toThrow('CONSTRUCTIVE_STASH_DIR'); + expect(stashBaseDir({})).toBeUndefined(); + }); +}); + +describe('addBackend', () => { + it('keeps the session of a context when the endpoints are equal, and refuses to replace them while it is filed there', () => { + signInStored(backendFromEndpoints({ api: 'http://api.example.com/graphql' })); + expect(addBackend(store, backendFromEndpoints({ api: 'http://api.example.com/graphql' }))).toEqual({ name: 'example.com' }); + expect(() => addBackend(store, REMOTE)).toThrow(ContextInUseError); + expect(store.getCredentials('example.com')).not.toBeNull(); + }); +}); + +describe('sessionToolsHost', () => { + const read = (get: () => unknown): unknown => { + try { + return get(); + } catch (err) { + return { threw: (err as Error).message }; + } + }; + + const desktopContext = () => { + store.createContext('localnet', { + endpoint: LOCAL.apiEndpoint, + targets: { api: { endpoint: LOCAL.apiEndpoint }, auth: { endpoint: LOCAL.authEndpoint }, modules: { endpoint: LOCAL.modulesEndpoint }, agent: { endpoint: LOCAL.agentEndpoint } } + }); + store.setCurrentContext('localnet'); + saveSession(store, stored); + }; + + const hostConfig = (backend: BackendConfig) => ({ + apiEndpoint: backend.apiEndpoint, modulesEndpoint: backend.modulesEndpoint, agentEndpoint: backend.agentEndpoint, computeEndpoint: backend.computeEndpoint + }); + + it.each<[string, () => NodeJS.ProcessEnv, unknown, unknown]>([ + ['no-backend', () => ({}), null, undefined], + ['signed-out (store)', () => (selectBackend(store, addBackend(store, LOCAL).name), {}), null, hostConfig(LOCAL)], + ['signed-out (env backend)', () => (signInStored(), { CONSTRUCTIVE_API_ENDPOINT: OTHER }), null, hostConfig(backendFromEndpoints({ api: OTHER }))], + ['signed-in', () => (signInStored(), {}), { userId: 'stored-user', email: 'dev@example.com', accessToken: 'stored-token', apiKey: 'stored-key' }, hostConfig(REMOTE)], + [ + 'signed-in (environment, no email)', + () => ({ CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: OTHER }), + { userId: 'env-user', accessToken: 'env-token' }, + hostConfig(backendFromEndpoints({ api: OTHER })) + ], + [ + 'invalid-override (credential without an api endpoint)', + () => ({ CONSTRUCTIVE_USER_ID: 'u', CONSTRUCTIVE_ACCESS_TOKEN: 'secret-token' }), + { threw: expect.stringContaining('CONSTRUCTIVE_API_ENDPOINT') }, + { threw: expect.stringContaining('CONSTRUCTIVE_API_ENDPOINT') } + ], + [ + 'invalid-override (plane variable alone)', + () => ({ CONSTRUCTIVE_MODULES_ENDPOINT: 'https://modules.example.com/graphql' }), + { threw: expect.stringContaining('Set CONSTRUCTIVE_API_ENDPOINT') }, + { threw: expect.stringContaining('Set CONSTRUCTIVE_API_ENDPOINT') } + ], + [ + 'issuer-mismatch (a recorded foreign issuer)', + () => (signInStored(), saveSession(store, { ...stored, issuedFor: backendFromEndpoints({ api: 'http://api.a.localhost/graphql' }) }), {}), + { threw: expect.stringMatching(/"example\.com" was issued for another backend: the api endpoint is https:\/\/api\.example\.com\/graphql, but the session was issued for http:\/\/api\.a\.localhost\/graphql.*sign-in replaces it/) }, + hostConfig(REMOTE) + ], + [ + 'issuer-mismatch (no issuer recorded)', + () => (signInStored(), saveSession(store, stored), {}), + { threw: expect.stringMatching(/"example\.com" does not record the backend it was issued for.*sign-in replaces it/) }, + hostConfig(REMOTE) + ], + [ + 'incomplete-backend', + () => (desktopContext(), {}), + { threw: expect.stringMatching(/"localnet" lacks the compute endpoint.*Run `agent login`/) }, + { threw: expect.stringMatching(/"localnet" lacks the compute endpoint.*Run `agent login`/) } + ] + ])('%s: gives the account and the backend, nothing, or the cause as a throw', (_kind, setup, account, backend) => { + const env = { ...setup(), CONSTRUCTIVE_STASH_DIR: home }; + const host = sessionToolsHost({ signInHint: 'Sign in.', repairHint: 'Run `agent login` to store a complete backend.', env }); + expect(read(() => host.account())).toEqual(account); + expect(read(() => host.backendConfig())).toEqual(backend); + expect(JSON.stringify(read(() => host.account()))).not.toContain('secret-token'); + }); + + it('throws a store that cannot be read, with its own message', () => { + fs.mkdirSync(path.join(home, '.constructive', 'config'), { recursive: true }); + fs.writeFileSync(path.join(home, '.constructive', 'config', 'settings.json'), '{ not json'); + const host = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home } }); + expect(() => host.account()).toThrow(); + expect(() => host.backendConfig()).toThrow(); + }); + + it('throws an empty CONSTRUCTIVE_STASH_DIR as the cause', () => { + const host = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: '' } }); + expect(() => host.account()).toThrow('CONSTRUCTIVE_STASH_DIR is set but empty'); + }); + + it('gives the account and the endpoints of one resolution', () => { + signInStored(); + const host = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home } }); + expect(host.account()).toEqual({ userId: 'stored-user', email: 'dev@example.com', accessToken: 'stored-token', apiKey: 'stored-key' }); + expect(host.backendConfig()).toEqual({ + apiEndpoint: REMOTE.apiEndpoint, modulesEndpoint: REMOTE.modulesEndpoint, agentEndpoint: REMOTE.agentEndpoint, computeEndpoint: REMOTE.computeEndpoint + }); + + const elsewhere = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home, CONSTRUCTIVE_API_ENDPOINT: OTHER } }); + expect(elsewhere.account()).toBeNull(); + expect(elsewhere.backendConfig()).toMatchObject({ apiEndpoint: OTHER }); + }); +}); + +describe('context names', () => { + const configDir = () => path.join(home, '.constructive', 'config'); + const snapshot = () => { + const files = fs.readdirSync(home, { recursive: true }) as string[]; + return Object.fromEntries(files.map((f) => path.join(home, f)).filter((f) => fs.statSync(f).isFile()).map((f) => [f, fs.readFileSync(f, 'utf8')])); + }; + + it.each(['../settings', '../credentials', '../../../victim', 'a/b', 'a\\b', '', '.hidden', '-flag', 'a..b', 'x'.repeat(101), 'naïve', 'a b'])( + 'refuses %j in every function that takes a name, before any file operation', + (bad) => { + signInStored(); + fs.writeFileSync(path.join(home, 'victim.json'), '{"keep":true}'); + const before = snapshot(); + const calls: Array<[string, () => unknown]> = [ + ['addBackend', () => addBackend(store, REMOTE, bad)], + ['selectBackend', () => selectBackend(store, bad)], + ['removeBackend', () => removeBackend(store, bad)], + ['readBackend', () => readBackend(store, bad)], + ['saveSession', () => saveSession(store, stored, bad)], + ['resolveSession', () => resolveSession({ store, env: {}, context: bad })] + ]; + for (const [name, call] of calls) { + let error: unknown; + try { + call(); + } catch (caught) { + error = caught; + } + expect([name, error]).toEqual([name, expect.any(ContextNameError)]); + expect((error as Error).message).toContain('letters, digits'); + } + expect(snapshot()).toEqual(before); + expect(fs.existsSync(path.join(configDir(), 'credentials.json'))).toBe(true); + } + ); + + it.each([ + 'https://api.example.com/graphql', + 'http://api.localhost:3000/graphql', + 'http://127.0.0.1:3000/graphql', + 'https://[::1]:8443/graphql', + 'https://api.xn--bcher-kva.example/graphql', + 'http://localhost/graphql', + `https://api.${'a'.repeat(60)}.${'b'.repeat(60)}.example/graphql` + ])('names the backend of %s with a name that passes the check', (api) => { + const ep = api; + const name = contextNameFor(backendFromEndpoints({ api, auth: ep, modules: ep, agent: ep, compute: ep })); + expect(checkContextName(name)).toBe(name); + }); +}); + +describe('the issuer of a stored session', () => { + const A = backendFromEndpoints({ api: 'http://api.a.localhost/graphql' }); + const B = backendFromEndpoints({ api: 'http://api.b.localhost/graphql' }); + + it('uses a stored session only when it was issued for the backend of its context', () => { + signInStored(B); + expect(resolve()).toMatchObject({ kind: 'signed-in', context: 'b.localhost' }); + + saveSession(store, { ...stored, issuedFor: A }); + expect(resolve()).toEqual({ kind: 'issuer-mismatch', source: 'store', context: 'b.localhost', backend: B, issuedFor: A, differs: ['api', 'auth', 'modules', 'agent', 'compute'] }); + + saveSession(store, stored); + expect(resolve()).toEqual({ kind: 'issuer-mismatch', source: 'store', context: 'b.localhost', backend: B, issuedFor: null, differs: [] }); + const host = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home } }); + expect(() => host.account()).toThrow('does not record the backend it was issued for'); + expect(host.backendConfig()).toMatchObject({ apiEndpoint: B.apiEndpoint }); + }); + + it('refuses the suggested repair of a context another app wrote while a session issued elsewhere is filed there', () => { + store.createContext('custom', { + endpoint: B.apiEndpoint, + targets: { api: { endpoint: B.apiEndpoint }, auth: { endpoint: B.authEndpoint }, modules: { endpoint: B.modulesEndpoint }, agent: { endpoint: B.agentEndpoint } } + }); + store.setCurrentContext('custom'); + saveSession(store, { ...stored, issuedFor: A }); + expect(resolve()).toMatchObject({ kind: 'incomplete-backend', context: 'custom', missing: ['compute'] }); + + expect(() => addBackend(store, B, 'custom')).toThrow('Sign out of "custom" first'); + expect(resolve()).toMatchObject({ kind: 'incomplete-backend', context: 'custom', missing: ['compute'] }); + }); + + it('keeps a session through the repair when it was issued for exactly the new backend', () => { + store.createContext('custom', { endpoint: B.apiEndpoint, targets: { api: { endpoint: B.apiEndpoint }, auth: { endpoint: B.authEndpoint } } }); + store.setCurrentContext('custom'); + saveSession(store, { ...stored, issuedFor: B }); + expect(addBackend(store, B, 'custom')).toEqual({ name: 'custom' }); + expect(resolve()).toMatchObject({ kind: 'signed-in', context: 'custom' }); + }); +}); + +describe('a named context and the environment', () => { + it.each<[string, NodeJS.ProcessEnv, string]>([ + ['a credential', { CONSTRUCTIVE_USER_ID: 'env-user', CONSTRUCTIVE_ACCESS_TOKEN: 'env-token', CONSTRUCTIVE_API_ENDPOINT: OTHER }, 'CONSTRUCTIVE_USER_ID'], + ['an endpoint for another backend', { CONSTRUCTIVE_API_ENDPOINT: OTHER }, 'CONSTRUCTIVE_API_ENDPOINT'] + ])('is a conflict when %s in the environment would decide the session', (_name, env, variable) => { + signInStored(); + selectBackend(store, addBackend(store, LOCAL).name); + const session = resolve(env, 'example.com'); + expect(session).toMatchObject({ kind: 'conflict', context: 'example.com', variable }); + if (session.kind === 'conflict') { + expect(session.problem).toContain('"example.com"'); + expect(session.fix).toContain(variable); + } + expect(resolve(env)).toMatchObject({ source: 'env' }); + }); + + it('is no conflict when the environment names the backend of the named context', () => { + signInStored(); + expect(resolve({ CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint }, 'example.com')).toMatchObject({ kind: 'signed-in', source: 'store', context: 'example.com' }); + }); +}); + +describe('a stored session is bound to the whole backend it was issued for', () => { + const EVIL = 'http://api.evil.localhost/graphql'; + const rewrite = (name: string, change: (targets: Record) => void) => { + const file = path.join(home, '.constructive', 'config', 'contexts', `${name}.json`); + const ctx = JSON.parse(fs.readFileSync(file, 'utf8')); + change(ctx.targets); + fs.writeFileSync(file, JSON.stringify(ctx)); + }; + + it.each<[string, (t: Record) => void, string[]]>([ + ['the api plane names another host, the auth plane unchanged', (t) => (t.api.endpoint = EVIL), ['api']], + ['the modules plane names another host', (t) => (t.modules.endpoint = EVIL.replace('api.', 'modules.')), ['modules']], + ['the auth plane has a trailing slash', (t) => (t.auth.endpoint += '/'), ['auth']], + ['two planes change', (t) => ((t.agent.endpoint = EVIL), (t.compute.endpoint = EVIL)), ['agent', 'compute']] + ])('does not use the session when %s, and says which plane differs', (_name, change, differs) => { + const name = signInStored(); + rewrite(name, change); + const session = resolve(); + expect(session).toMatchObject({ kind: 'issuer-mismatch', context: name, issuedFor: REMOTE, differs }); + const host = sessionToolsHost({ signInHint: 'Sign in.', env: { CONSTRUCTIVE_STASH_DIR: home } }); + expect(() => host.account()).toThrow(`${differs[0]} endpoint`); + }); + + it('treats a session that records only the auth endpoint as unproven, and never uses it', () => { + const name = signInStored(); + store.setCredentials(name, { token: 'stored-token', userId: 'stored-user', email: 'e', apiKey: 'stored-key', keyId: 'k', signedInAt: 1, authEndpoint: REMOTE.authEndpoint } as never); + expect(resolve()).toMatchObject({ kind: 'issuer-mismatch', issuedFor: null, differs: [] }); + }); + + it('still writes the auth endpoint where Desktop reads it', () => { + const name = signInStored(); + expect(store.getCredentials(name)).toMatchObject({ authEndpoint: REMOTE.authEndpoint, issuedFor: REMOTE }); + }); +}); + +describe('stored context names', () => { + it('lists a stored context whose name is not valid as unusable, and keeps listing the others', () => { + signInStored(); + const dir = path.join(home, '.constructive', 'config', 'contexts'); + fs.writeFileSync(path.join(dir, 'odd.json'), JSON.stringify({ name: '../credentials', endpoint: LOCAL.apiEndpoint, targets: {} })); + const rows = listBackends(store); + expect(rows).toContainEqual(expect.objectContaining({ name: 'example.com', status: 'complete' })); + expect(rows).toContainEqual({ name: '../credentials', current: false, status: 'invalid-name', reason: expect.stringContaining('not a valid context name') }); + }); + + it.each(['PROD', 'Prod', 'example.COM'])('refuses the upper-case name %s, so it can never reach the lower-case file on a case-insensitive disk', (name) => { + selectBackend(store, addBackend(store, REMOTE, 'prod').name); + saveSession(store, { ...stored, issuedFor: REMOTE }, 'prod'); + expect(() => removeBackend(store, name)).toThrow(ContextNameError); + expect(() => readBackend(store, name)).toThrow(ContextNameError); + expect(() => addBackend(store, REMOTE, name)).toThrow(ContextNameError); + expect(store.loadContext('prod')).not.toBeNull(); + expect(store.getCredentials('prod')).not.toBeNull(); + }); +}); diff --git a/agentic/session/__tests__/stores.test.ts b/agentic/session/__tests__/stores.test.ts new file mode 100644 index 0000000000..013f39bc6d --- /dev/null +++ b/agentic/session/__tests__/stores.test.ts @@ -0,0 +1,212 @@ +import { ConfigStore } from 'appstash'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { AccountSession, clearSession, loadSession, openStore, saveSession, stashDirectories } from '../src/account-store'; +import { + addBackend, + backendFromEndpoints, + ContextInUseError, + listBackends, + readBackend, + removeBackend, + selectBackend +} from '../src/backend-store'; + +const LOCAL = backendFromEndpoints({ api: 'http://api.localhost:3000/graphql' }); +const REMOTE = backendFromEndpoints({ api: 'https://api.example.com/graphql' }); + +let home: string; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'session-store-')); +}); + +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +const session: AccountSession = { + userId: 'user-1', + email: 'dev@example.com', + accessToken: 'access-token', + accessTokenExpiresAt: '2026-08-04T00:00:00Z', + apiKey: 'cnc_live_sk_abc', + keyId: 'key-1', + apiKeyExpiresAt: '2031-08-03T00:00:00Z', + signedInAt: 1754000000000 +}; + +const configDir = (base: string) => path.join(base, '.constructive', 'config'); + +const use = (s: ConfigStore, config = LOCAL) => selectBackend(s, addBackend(s, config).name); +const current = (s: ConfigStore) => { + const name = s.getCurrentContext()?.name; + const stored = name ? readBackend(s, name) : null; + return stored?.status === 'complete' ? stored.backend : null; +}; + +const store = (): ConfigStore => { + const s = openStore(home); + if (!s.getCurrentContext()) use(s); + return s; +}; +const bareStore = (): ConfigStore => openStore(home); + +describe('openStore', () => { + let prevEnv: NodeJS.ProcessEnv; + let fakeHome: string; + let stashDir: string; + + beforeEach(() => { + prevEnv = { ...process.env }; + fakeHome = path.join(home, 'home'); + stashDir = path.join(home, 'stash'); + fs.mkdirSync(fakeHome); + process.env.APPSTASH_BASE_DIR = fakeHome; + delete process.env.CONSTRUCTIVE_STASH_DIR; + }); + + afterEach(() => { + process.env = prevEnv; + }); + + const inside = (file: string, dirs: string[]) => dirs.some((dir) => !path.relative(dir, file).startsWith('..') && !path.isAbsolute(path.relative(dir, file))); + + it.each<[string, () => NodeJS.ProcessEnv, () => string]>([ + ['the default base (APPSTASH_BASE_DIR, as jest cannot move the home directory)', () => ({ APPSTASH_BASE_DIR: fakeHome }), () => fakeHome], + ['CONSTRUCTIVE_STASH_DIR', () => ({ CONSTRUCTIVE_STASH_DIR: stashDir }), () => stashDir] + ])('names the directories of the store under %s, without creating any, and the store writes inside them', (_where, env, base) => { + Object.assign(process.env, env()); + const dirs = stashDirectories(process.env); + expect(dirs).toEqual(expect.arrayContaining([path.join(base(), '.constructive'), path.join(base(), '.constructive', 'config')])); + expect(fs.existsSync(path.join(base(), '.constructive'))).toBe(false); + + const s = openStore(); + use(s); + saveSession(s, session); + const written = (fs.readdirSync(base(), { recursive: true }) as string[]).map((f) => path.join(base(), f)).filter((f) => fs.statSync(f).isFile()); + expect(written.length).toBeGreaterThan(0); + for (const file of written) expect([file, inside(file, dirs)]).toEqual([file, true]); + }); + + it('refuses an empty CONSTRUCTIVE_STASH_DIR like openStore does', () => { + expect(() => stashDirectories({ CONSTRUCTIVE_STASH_DIR: '' })).toThrow('CONSTRUCTIVE_STASH_DIR is set but empty'); + }); + + it('writes every file under CONSTRUCTIVE_STASH_DIR and nothing under the default base', () => { + process.env.CONSTRUCTIVE_STASH_DIR = stashDir; + const s = openStore(); + use(s); + saveSession(s, session); + + expect(fs.readdirSync(fakeHome)).toEqual([]); + const written = (fs.readdirSync(stashDir, { recursive: true }) as string[]).filter((f) => fs.statSync(path.join(stashDir, f)).isFile()); + expect(written.sort()).toEqual([path.join('.constructive', 'config', 'contexts', 'localhost-3000.json'), path.join('.constructive', 'config', 'credentials.json'), path.join('.constructive', 'config', 'settings.json')]); + expect(loadSession(openStore(stashDir))).toEqual(session); + }); + + it('shares the constructive stash rather than a tool-specific directory', () => { + const s = openStore(home); + use(s); + saveSession(s, session); + expect(fs.existsSync(path.join(configDir(home), 'credentials.json'))).toBe(true); + }); +}); + +describe('account-store', () => { + it('round-trips a session through the shared store', () => { + const s = store(); + saveSession(s, session); + expect(loadSession(s)).toEqual(session); + }); + + it('files the session under the active backend context, keeping backends independent', () => { + const s = store(); + use(s, REMOTE); + saveSession(s, { ...session, issuedFor: REMOTE }); + use(s, LOCAL); + expect(loadSession(s)).toBeNull(); + use(s, REMOTE); + expect(loadSession(s)).toEqual({ ...session, issuedFor: REMOTE, authEndpoint: REMOTE.authEndpoint }); + }); + + it('refuses to file a session before a backend is chosen', () => { + const s = bareStore(); + expect(() => saveSession(s, session)).toThrow('No backend chosen'); + expect(s.getCurrentContext()).toBeNull(); + }); + + it('writes credentials with mode 0600', () => { + const s = store(); + saveSession(s, session); + expect(fs.statSync(path.join(configDir(home), 'credentials.json')).mode & 0o777).toBe(0o600); + }); + + it('returns null when nothing is stored', () => { + expect(loadSession(store())).toBeNull(); + }); + + it('clearSession removes the credentials and tolerates a signed-out store', () => { + const s = store(); + saveSession(s, session); + clearSession(s); + expect(loadSession(s)).toBeNull(); + expect(() => clearSession(s)).not.toThrow(); + }); +}); + +describe('backend-store', () => { + it('derives all five planes from the api endpoint the user names', () => { + expect(REMOTE).toEqual({ + apiEndpoint: 'https://api.example.com/graphql', + authEndpoint: 'https://auth.example.com/graphql', + modulesEndpoint: 'https://modules.example.com/graphql', + agentEndpoint: 'https://agent.example.com/graphql', + computeEndpoint: 'https://compute.example.com/graphql' + }); + expect(() => backendFromEndpoints({ api: 'not a url' })).toThrow('is not an absolute URL'); + }); + + it('round-trips all five planes and returns null before one is chosen', () => { + const s = bareStore(); + expect(current(s)).toBeNull(); + expect(addBackend(s, REMOTE).name).toBe('example.com'); + expect(current(s)).toBeNull(); + selectBackend(s, 'example.com'); + expect(current(s)).toEqual(REMOTE); + use(s, LOCAL); + expect(current(s)).toEqual(LOCAL); + }); + + it('treats a context missing a plane as no backend rather than guessing one', () => { + const s = store(); + s.createContext('partial', { + endpoint: REMOTE.apiEndpoint, + targets: { api: { endpoint: REMOTE.apiEndpoint }, auth: { endpoint: REMOTE.authEndpoint } } + }); + s.setCurrentContext('partial'); + expect(current(s)).toBeNull(); + expect(listBackends(s)).toContainEqual({ name: 'partial', current: true, status: 'incomplete', missing: ['modules', 'agent', 'compute'], apiEndpoint: REMOTE.apiEndpoint }); + }); + + it('lists, selects and removes backends, and refuses to remove one while a session is filed under it', () => { + const s = bareStore(); + use(s, REMOTE); + saveSession(s, session); + use(s, LOCAL); + expect(listBackends(s).sort((a, b) => a.name.localeCompare(b.name))).toEqual([ + { name: 'example.com', current: false, status: 'complete', backend: REMOTE }, + { name: 'localhost-3000', current: true, status: 'complete', backend: LOCAL } + ]); + expect(() => selectBackend(s, 'missing')).toThrow('No backend context named "missing"'); + + expect(() => removeBackend(s, 'example.com')).toThrow(ContextInUseError); + expect(s.getCredentials('example.com')).not.toBeNull(); + s.removeCredentials('example.com'); + expect(removeBackend(s, 'example.com')).toBe(true); + expect(listBackends(s).map((b) => b.name)).toEqual(['localhost-3000']); + expect(removeBackend(s, 'example.com')).toBe(false); + }); +}); diff --git a/agentic/session/jest.config.js b/agentic/session/jest.config.js new file mode 100644 index 0000000000..b3b5381fb7 --- /dev/null +++ b/agentic/session/jest.config.js @@ -0,0 +1,22 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + setupFilesAfterEnv: ['/jest.setup.js'], + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + babelConfig: false, + tsconfig: 'tsconfig.json', + }, + ], + }, + transformIgnorePatterns: [`/node_modules/*`], + testRegex: '(/__tests__/.*\\.(test|spec))\\.(jsx?|tsx?)$', + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], + modulePathIgnorePatterns: ['dist/*'], + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, +}; diff --git a/agentic/session/jest.setup.js b/agentic/session/jest.setup.js new file mode 100644 index 0000000000..e23b1a597a --- /dev/null +++ b/agentic/session/jest.setup.js @@ -0,0 +1,11 @@ +// Points appstash's default base at a temporary directory for the whole suite, +// so no test can resolve the real home directory when a variable is missing. +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'jest-stash-base-')); +process.env.APPSTASH_BASE_DIR = base; +delete process.env.CONSTRUCTIVE_STASH_DIR; + +afterAll(() => fs.rmSync(base, { recursive: true, force: true })); diff --git a/agentic/session/package.json b/agentic/session/package.json new file mode 100644 index 0000000000..528365093b --- /dev/null +++ b/agentic/session/package.json @@ -0,0 +1,43 @@ +{ + "name": "@agentic-kit/session", + "version": "0.1.0", + "author": "Constructive ", + "description": "the shared Constructive sign-in: backend contexts, email and password sign-in, the stored session, agent credentials and the CONSTRUCTIVE_* environment overrides, for every binary", + "main": "index.js", + "module": "esm/index.js", + "types": "index.d.ts", + "homepage": "https://github.com/constructive-io/constructive", + "license": "SEE LICENSE IN LICENSE", + "publishConfig": { + "access": "public", + "directory": "dist" + }, + "repository": { + "type": "git", + "url": "https://github.com/constructive-io/constructive" + }, + "bugs": { + "url": "https://github.com/constructive-io/constructive/issues" + }, + "scripts": { + "clean": "makage clean", + "prepack": "npm run build", + "build": "makage build", + "build:dev": "makage build --dev", + "lint": "eslint . --fix", + "test": "jest", + "test:watch": "jest --watch" + }, + "dependencies": { + "@agentic-kit/db-tools": "workspace:^", + "@constructive-io/fetch": "^1.2.0", + "@constructive-io/sdk": "workspace:^", + "appstash": "^0.8.0" + }, + "keywords": [ + "agentic-kit", + "constructive", + "auth", + "session" + ] +} diff --git a/agentic/session/src/account-store.ts b/agentic/session/src/account-store.ts new file mode 100644 index 0000000000..3eb050ccb6 --- /dev/null +++ b/agentic/session/src/account-store.ts @@ -0,0 +1,164 @@ +import { appstash, ConfigStore, createConfigStore } from 'appstash'; + +import type { BackendConfig } from './backend-store'; + +/** + * Directory identity shared by every Constructive binary and the desktop app, + * so a sign-in through one is a sign-in through all of them. + */ +export const STASH_NAME = 'constructive'; + +/** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */ +export const STASH_DIR_ENV = 'CONSTRUCTIVE_STASH_DIR'; + +/** An empty value is an error: treating it as unset would open the real store under the home directory. */ +export function stashBaseDir(env: NodeJS.ProcessEnv = process.env): string | undefined { + const dir = env[STASH_DIR_ENV]; + if (dir === '') { + throw new Error(`${STASH_DIR_ENV} is set but empty, so it names no directory. Set it to a directory, or unset it to use the store under the home directory.`); + } + return dir; +} + +const STORE_DIRS = new WeakMap(); + +export function openStore(baseDir: string | undefined = stashBaseDir()): ConfigStore { + const store = createConfigStore(STASH_NAME, { stashName: STASH_NAME, baseDir }); + const { config, cache } = appstash(STASH_NAME, { baseDir }); + STORE_DIRS.set(store, { config, cache }); + return store; +} + +/** + * The directories of a store `openStore` opened: `config` holds files beside + * the credentials, `cache` files that may be deleted at any time. + */ +export function storeDirs(store: ConfigStore): { config: string; cache: string } { + const dirs = STORE_DIRS.get(store); + if (!dirs) throw new Error('This store was not opened with openStore, so its directory is unknown. Open it with openStore().'); + return dirs; +} + +/** + * Every directory the store `openStore` opens uses (root, config, cache, data, + * logs, tmp), from the same appstash resolution, so a caller can refuse a path + * inside the store. Creates nothing. + */ +export function stashDirectories(env: NodeJS.ProcessEnv = process.env): string[] { + const dirs = appstash(STASH_NAME, { baseDir: stashBaseDir(env) }); + return [...new Set([dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, dirs.tmp])]; +} + +const CONTEXT_NAME = /^[a-z0-9][a-z0-9._-]{0,99}$/; + +/** A context name that cannot name a file in the store's contexts directory. */ +export class ContextNameError extends Error { + constructor(readonly value: string) { + super( + `"${value.length > 120 ? `${value.slice(0, 120)}…` : value}" is not a valid context name. ` + + 'A context name has 1 to 100 characters: lower-case letters, digits, ".", "-" and "_", starting with a letter or a digit, with no "..".' + ); + this.name = 'ContextNameError'; + } +} + +/** + * A context name is the stem of a file in the store, so it is checked before + * any read or write: no separator, no `..`, no leading dot, and lower case + * only, so two names never reach one file on a disk that ignores letter case. + */ +export function checkContextName(name: string): string { + if (typeof name !== 'string' || !CONTEXT_NAME.test(name) || name.includes('..')) throw new ContextNameError(String(name)); + return name; +} + +export interface AccountSession { + userId: string; + email: string; + accessToken: string; + accessTokenExpiresAt?: string; + apiKey?: string; + keyId?: string; + apiKeyExpiresAt?: string; + signedInAt: number; + /** The whole backend the session was issued for. Absent for a session stored before it was recorded, or by another app. */ + issuedFor?: BackendConfig; + /** The auth endpoint that issued the session, the field Desktop reads and writes. Written from `issuedFor` when it is known. */ + authEndpoint?: string; +} + +const BACKEND_KEYS = ['apiEndpoint', 'authEndpoint', 'modulesEndpoint', 'agentEndpoint', 'computeEndpoint'] as const; + +/** `value` as a complete backend, or undefined when it lacks an endpoint. */ +export function issuedForOf(value: unknown): BackendConfig | undefined { + if (!value || typeof value !== 'object') return undefined; + const record = value as Record; + if (!BACKEND_KEYS.every((key) => typeof record[key] === 'string' && record[key] !== '')) return undefined; + return Object.fromEntries(BACKEND_KEYS.map((key) => [key, record[key]])) as unknown as BackendConfig; +} + +type StoredCredentials = Parameters[1] & { authEndpoint?: string; issuedFor?: BackendConfig }; + +/** + * Sessions live in the shared Constructive stash, as the credentials of a + * backend context. The store owns the file layout, the atomic 0600 writes and + * the at-rest encoding; this module only maps between its `ContextCredentials` + * and the session shape callers pass around. + */ +export function currentContextName(store: ConfigStore): string | null { + const name = store.loadSettings().currentContext; + if (!name) return null; + return store.loadContext(checkContextName(name)) ? name : null; +} + +/** The active context; a session is never filed under a backend nobody chose. */ +function ensureContextName(store: ConfigStore): string { + const name = currentContextName(store); + if (!name) throw new Error('No backend chosen: select a backend before saving a session.'); + return name; +} + +export function loadSession(store: ConfigStore, context?: string): AccountSession | null { + const contextName = context === undefined ? currentContextName(store) : checkContextName(context); + if (!contextName) return null; + const creds = store.getCredentials(contextName) as StoredCredentials | null; + if (!creds?.token || !creds.userId) return null; + return { + userId: creds.userId, + email: creds.email ?? '', + accessToken: creds.token, + accessTokenExpiresAt: creds.expiresAt, + apiKey: creds.apiKey, + keyId: creds.keyId, + apiKeyExpiresAt: creds.apiKeyExpiresAt, + signedInAt: creds.signedInAt ?? 0, + ...(issuedForOf(creds.issuedFor) ? { issuedFor: issuedForOf(creds.issuedFor) } : {}), + ...(typeof creds.authEndpoint === 'string' && creds.authEndpoint ? { authEndpoint: creds.authEndpoint } : {}) + }; +} + +/** + * `context` names the backend the session belongs to; it does not have to exist + * as a context yet, so a sign-in can be filed before the backend is committed + * and a failed sign-in leaves nothing behind. + */ +export function saveSession(store: ConfigStore, session: AccountSession, context?: string): void { + const credentials: StoredCredentials = { + token: session.accessToken, + expiresAt: session.accessTokenExpiresAt, + userId: session.userId, + email: session.email, + apiKey: session.apiKey, + keyId: session.keyId, + apiKeyExpiresAt: session.apiKeyExpiresAt, + signedInAt: session.signedInAt, + ...(session.issuedFor ? { issuedFor: session.issuedFor } : {}), + ...(session.issuedFor || session.authEndpoint ? { authEndpoint: session.issuedFor?.authEndpoint ?? session.authEndpoint } : {}) + }; + store.setCredentials(context === undefined ? ensureContextName(store) : checkContextName(context), credentials); +} + +export function clearSession(store: ConfigStore, context?: string): void { + const contextName = context === undefined ? currentContextName(store) : checkContextName(context); + if (contextName) store.removeCredentials(contextName); +} diff --git a/agentic/session/src/agent-store.ts b/agentic/session/src/agent-store.ts new file mode 100644 index 0000000000..055c8574c5 --- /dev/null +++ b/agentic/session/src/agent-store.ts @@ -0,0 +1,211 @@ +import type { ConfigStore } from 'appstash'; +import { randomBytes } from 'crypto'; +import * as fs from 'fs'; +import * as path from 'path'; + +import { checkContextName, ContextNameError, issuedForOf, storeDirs } from './account-store'; +import type { BackendConfig } from './backend-store'; + +/** + * The stored credential of one agent: a principal of the person, filed under + * the person's context, bound to the five endpoints it was issued for, and the + * principal's own API key, which this package uses only to mint access tokens. + * The backend accepts the key itself on requests too, so it is kept in one 0600 + * file per agent. + */ +export interface AgentRecord { + name: string; + context: string; + /** The principal's user id, which every principal call takes. */ + principalId: string; + /** The person's user id: the account id every request names. */ + ownerId: string; + organization?: string; + schemaChanges: boolean; + createdAt: string; + issuedFor: BackendConfig; + apiKey: string; + keyId: string; + keyExpiresAt: string; +} + +/** An access token minted with the agent's key, cached beside it. `keyId` names the key that minted it. */ +export interface CachedToken { + keyId: string; + accessToken: string; + accessExpiresAt: string; +} + +export class AgentNameError extends Error { + constructor( + readonly value: string, + reason = 'An agent name has 1 to 100 characters: lower-case letters, digits, ".", "-" and "_", starting with a letter or a digit, with no "..".' + ) { + super(`"${value.length > 120 ? `${value.slice(0, 120)}…` : value}" is not a valid agent name. ${reason}`); + this.name = 'AgentNameError'; + } +} + +/** + * An agent name is the stem of a file in the store, so it follows the + * context-name rule, and it may not end like the store's own files. + */ +export function checkAgentName(name: string): string { + try { + checkContextName(name); + } catch (err) { + if (err instanceof ContextNameError) throw new AgentNameError(err.value); + throw err; + } + if (name.endsWith('.json')) { + throw new AgentNameError(name, 'It ends in ".json", so it reads like a file of the store (an agent record). Leave out the ending.'); + } + return name; +} + +const agentDir = (store: ConfigStore, context: string) => path.join(storeDirs(store).config, 'agents', checkContextName(context)); +const tokenDir = (store: ConfigStore, context: string) => path.join(storeDirs(store).cache, 'agents', checkContextName(context)); + +export const agentFile = (store: ConfigStore, context: string, name: string) => path.join(agentDir(store, context), `${checkAgentName(name)}.json`); +const tokenFile = (store: ConfigStore, context: string, name: string) => path.join(tokenDir(store, context), `${checkAgentName(name)}.json`); + +function ensureDir(dir: string): void { + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + fs.chmodSync(dir, 0o700); + fs.chmodSync(path.dirname(dir), 0o700); +} + +/** + * Write `content` with mode 0600 through a temporary file, so a reader sees the + * old file or the new one, never half of one. `create` fails with EEXIST when + * the file exists (a hard link never replaces), so of two creates one wins. + */ +function writeAtomic(file: string, content: string, mode: 'create' | 'replace'): void { + ensureDir(path.dirname(file)); + const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`; + const fd = fs.openSync(tmp, 'wx', 0o600); + try { + fs.writeSync(fd, content); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + try { + if (mode === 'create') fs.linkSync(tmp, file); + else fs.renameSync(tmp, file); + } finally { + fs.rmSync(tmp, { force: true }); + } +} + +/** Whether a record file exists under the name, readable or not. */ +export function agentEntryExists(store: ConfigStore, context: string, name: string): boolean { + return fs.existsSync(agentFile(store, context, name)); +} + +/** A record file that does not parse, or lacks what an agent record holds: an edit by hand, since the store writes it atomically. */ +export class AgentRecordUnreadable extends Error { + constructor( + readonly file: string, + problem: string + ) { + super(`The stored record of the agent (${file}) ${problem}, so its credential cannot be used.`); + this.name = 'AgentRecordUnreadable'; + } +} + +const RECORD_TEXT = ['name', 'context', 'principalId', 'ownerId', 'createdAt', 'apiKey', 'keyId', 'keyExpiresAt'] as const; + +function isRecord(value: unknown): value is AgentRecord { + const r = value as Record | null; + return ( + !!r && + typeof r === 'object' && + RECORD_TEXT.every((key) => typeof r[key] === 'string' && r[key] !== '') && + typeof r.schemaChanges === 'boolean' && + !!issuedForOf(r.issuedFor) + ); +} + +export function readAgent(store: ConfigStore, context: string, name: string): AgentRecord | null { + const file = agentFile(store, context, name); + let raw: string; + try { + raw = fs.readFileSync(file, 'utf8'); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw err; + } + let value: unknown; + try { + value = JSON.parse(raw); + } catch (err) { + throw new AgentRecordUnreadable(file, `is not valid JSON (${(err as Error).message})`); + } + if (!isRecord(value)) throw new AgentRecordUnreadable(file, 'lacks the principal, the key or the backend of an agent'); + return value; +} + +/** Store a new agent; throws an error with code EEXIST when an agent of that name is stored already. */ +export function createAgentEntry(store: ConfigStore, record: AgentRecord): void { + writeAtomic(agentFile(store, record.context, record.name), JSON.stringify(record, null, 2), 'create'); +} + +export function writeAgent(store: ConfigStore, record: AgentRecord): void { + writeAtomic(agentFile(store, record.context, record.name), JSON.stringify(record, null, 2), 'replace'); +} + +/** Delete the agent's cached token. */ +export function dropCachedToken(store: ConfigStore, context: string, name: string): void { + fs.rmSync(tokenFile(store, context, name), { force: true }); +} + +/** Delete the agent's record and its cached token. */ +export function deleteAgent(store: ConfigStore, context: string, name: string): void { + fs.rmSync(agentFile(store, context, name), { force: true }); + dropCachedToken(store, context, name); +} + +/** The names of the agents stored under `context`, valid names only, sorted. */ +export function listAgentNames(store: ConfigStore, context: string): string[] { + let files: string[]; + try { + files = fs.readdirSync(agentDir(store, context)); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []; + throw err; + } + return files + .filter((file) => file.endsWith('.json')) + .map((file) => file.slice(0, -'.json'.length)) + .filter((name) => { + try { + checkAgentName(name); + return true; + } catch { + return false; + } + }) + .sort(); +} + +/** The cached token, or null when there is none or it does not parse: a missing cache only costs one more mint. */ +export function readCachedToken(store: ConfigStore, context: string, name: string): CachedToken | null { + let value: Partial; + try { + value = JSON.parse(fs.readFileSync(tokenFile(store, context, name), 'utf8')); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT' || err instanceof SyntaxError) return null; + throw err; + } + return typeof value?.keyId === 'string' && typeof value.accessToken === 'string' && typeof value.accessExpiresAt === 'string' ? (value as CachedToken) : null; +} + +/** + * Cache a minted token. Processes write it without a lock: a token may be used + * many times, so when two write at once, the one renamed last stays, and the + * other process's token still works until it ends. + */ +export function writeCachedToken(store: ConfigStore, context: string, name: string, token: CachedToken): void { + writeAtomic(tokenFile(store, context, name), JSON.stringify(token), 'replace'); +} diff --git a/agentic/session/src/agent.ts b/agentic/session/src/agent.ts new file mode 100644 index 0000000000..f80a7b953a --- /dev/null +++ b/agentic/session/src/agent.ts @@ -0,0 +1,521 @@ +import { auth } from '@constructive-io/sdk'; +import { ConfigStore } from 'appstash'; + +import { currentContextName } from './account-store'; +import { + agentEntryExists, + AgentNameError, + AgentRecord, + AgentRecordUnreadable, + type CachedToken, + checkAgentName, + createAgentEntry, + deleteAgent, + dropCachedToken, + listAgentNames, + readAgent, + readCachedToken, + writeAgent, + writeCachedToken +} from './agent-store'; +import { type KeyRevocation, revokeKey } from './api-key'; +import { endSignIn, passwordSignIn } from './auth'; +import { describeAuthError, errorCodes, isNetworkError, trackedFetch, withAuthTimeout } from './auth-error'; +import { type BackendConfig, differingPlanes, readBackend } from './backend-store'; +import { agentBinding, renewFix, type ResolvedAgentSession, type Session, type SessionAccount } from './session'; + +/** + * The org capability mask of an agent that may not change the schema: every + * capability but `manage_database`. The platform's org capabilities are 64 + * bits wide, `manage_database` is org capability 12, and bit N counts from the + * right. The backend right-pads a shorter mask with zeros, so the mask must be + * the full width; a wider backend would read this one as removing more + * capabilities, never fewer. + */ +const ORG_CAPABILITY_WIDTH = 64; +const MANAGE_DATABASE_BIT = 12; +export const SCHEMA_READ_ONLY_MASK = Array.from({ length: ORG_CAPABILITY_WIDTH }, (_, i) => (i === ORG_CAPABILITY_WIDTH - MANAGE_DATABASE_BIT ? '0' : '1')).join(''); + +/** The org membership type, where the platform's schema capabilities live. */ +const ORG_MEMBERSHIP_TYPE = 2; + +/** How long an agent's key lasts: the cap set on its principal, and what its key asks for. */ +const AGENT_KEY_DAYS = 30; + +/** Mint a new access token once less than this is left of the cached one: covers clock skew and one request. */ +const TOKEN_MARGIN_MS = 30_000; + +export type AgentErrorKind = + | 'invalid-name' + | 'not-a-person' + | 'sign-in-required' + | 'step-up-required' + | 'name-taken' + | 'not-found' + | 'unreadable-record' + | 'refused' + | 'backend-unreachable' + | 'server-error'; + +/** A failed agent operation. `code` is the server's error code when it gave one. No secret is in it. */ +export class AgentError extends Error { + constructor( + readonly kind: AgentErrorKind, + message: string, + readonly code?: string + ) { + super(message); + this.name = 'AgentError'; + } +} + +const SIGN_IN_AGAIN = 'Sign in again with your password, then retry.'; + +/** Classified by facts only: no answer, the HTTP status, then `extensions.code`. */ +function agentFailure(err: unknown, what: string, endpoint: string, status: number | undefined): AgentError { + if (isNetworkError(err)) return new AgentError('backend-unreachable', `${what} failed: ${describeAuthError(err)}`); + if (status !== undefined && (status < 200 || status >= 300)) { + return new AgentError('server-error', `${what} failed: the server at ${endpoint} answered HTTP ${status}. Retry later, or check the backend logs.`, `HTTP_${status}`); + } + const code = errorCodes(err)[0]; + if (!code) return new AgentError('server-error', `${what} failed: ${describeAuthError(err)}. Retry later, or check the backend logs.`); + if (code.startsWith('STEP_UP_REQUIRED')) return new AgentError('step-up-required', `${what} needs a recent sign-in (${code}). ${SIGN_IN_AGAIN}`, code); + if (code === 'UNAUTHENTICATED' || code === 'NOT_AUTHENTICATED') return new AgentError('sign-in-required', `${what} was refused because the sign-in has ended (${code}). ${SIGN_IN_AGAIN}`, code); + if (code.startsWith('PRINCIPAL_CANNOT_') || code === 'PRINCIPAL_REQUIRED') { + return new AgentError('not-a-person', `${what} was refused: only the person, not an agent, may do this (${code}). Run it signed in as yourself.`, code); + } + if (code === 'PRINCIPAL_NOT_FOUND') return new AgentError('not-found', `${what} failed: the backend has no such principal (${code}).`, code); + return new AgentError('refused', `${what} was refused by the server (${code}).`, code); +} + +type AuthClient = ReturnType; + +/** One auth-plane call with the sign-in timeout, its failure classified. */ +async function call(endpoint: string, bearer: string | undefined, what: string, request: (client: AuthClient) => { unwrap(): Promise }): Promise { + const http = trackedFetch(endpoint); + const client = auth.createClient({ endpoint, fetch: http.fetch, ...(bearer ? { headers: { Authorization: `Bearer ${bearer}` } } : {}) }); + try { + return await withAuthTimeout(request(client).unwrap(), endpoint); + } catch (err) { + throw agentFailure(err, what, endpoint, http.status()); + } +} + +/** What a person must hold to manage agents: a stored session of their own, which names the account and the backend. */ +interface SignedInPerson { + kind: 'signed-in'; + source: 'store'; + context: string; + backend: BackendConfig; + account: SessionAccount; +} + +function person(session: Session): SignedInPerson { + if (session.kind !== 'signed-in' || session.source !== 'store') { + const what = + session.kind === 'signed-in' && session.source === 'agent' + ? 'an agent, and only the person may manage agents' + : session.kind === 'signed-in' || session.kind === 'signed-out' + ? 'a credential from the environment, so there is no stored context to file the agent under' + : 'no sign-in'; + throw new AgentError('not-a-person', `Managing agents needs the person signed in, with a session stored by this computer; this session is ${what}. Unset the CONSTRUCTIVE_* credential variables if they are set, sign in as yourself, then retry.`); + } + return session as SignedInPerson; +} + +/** The person's stored bearer (the key, else the token another app stored), for the calls that make no credential. */ +function storedBearer(owner: SignedInPerson): string { + const { key, accessToken, accessTokenExpiresAt } = owner.account; + const expires = key.kind === 'active' ? key.expiresAt : accessTokenExpiresAt; + if (expires && Date.parse(expires) <= Date.now()) throw new AgentError('sign-in-required', `The person's sign-in ended at ${expires}. ${SIGN_IN_AGAIN}`); + return key.kind === 'active' ? key.apiKey : accessToken; +} + +/** + * Run `task` with a new password sign-in of the person, which a key for a + * principal needs, and end that sign-in on the server when it is done, so no + * bearer session is left behind. Throws a `SignInError` when the sign-in fails. + */ +async function withFreshSignIn(owner: SignedInPerson, password: string, task: (bearer: string) => Promise): Promise { + const endpoint = owner.backend.authEndpoint; + if (!owner.account.email) throw new AgentError('sign-in-required', `The stored session records no email to sign in with. ${SIGN_IN_AGAIN}`); + const fresh = await passwordSignIn(endpoint, owner.account.email, password); + try { + if (fresh.userId !== owner.account.userId) { + throw new AgentError('not-a-person', `The password signed in another account than ${owner.account.email}, which is signed in here. Use the password of ${owner.account.email}.`); + } + return await task(fresh.accessToken); + } finally { + await endSignIn(endpoint, fresh.accessToken); + } +} + +/** + * An agent as listed: its facts, or, for a record that cannot be read, the + * reason it cannot be used. An agent that is `ready` keeps working until its + * key ends (`keyExpiresAt`) or it is removed, also after the person signs out. + */ +export type AgentInfo = AgentDetails | { name: string; context: string; state: 'set-up-again'; unreadable: true; problem: string }; + +export interface AgentDetails { + name: string; + context: string; + principalId: string; + schemaChanges: boolean; + organization?: string; + createdAt: string; + keyExpiresAt: string; + /** `set-up-again`: the key has ended. `issuer-mismatch`: the context now names other endpoints. */ + state: 'ready' | 'set-up-again' | 'issuer-mismatch'; +} + +function infoOf(store: ConfigStore, record: AgentRecord): AgentDetails { + const stored = readBackend(store, record.context); + let state: AgentDetails['state'] = 'ready'; + if (stored?.status !== 'complete' || differingPlanes(record.issuedFor, stored.backend).length > 0) state = 'issuer-mismatch'; + else if (Date.parse(record.keyExpiresAt) <= Date.now()) state = 'set-up-again'; + return { + name: record.name, + context: record.context, + principalId: record.principalId, + schemaChanges: record.schemaChanges, + ...(record.organization ? { organization: record.organization } : {}), + createdAt: record.createdAt, + keyExpiresAt: record.keyExpiresAt, + state + }; +} + +/** The stored record of an agent the person manages, or the AgentError that says why there is none. */ +function ownedRecord(store: ConfigStore, context: string, name: string): AgentRecord { + let record: AgentRecord | null; + try { + record = readAgent(store, context, name); + } catch (err) { + if (err instanceof AgentRecordUnreadable) throw new AgentError('unreadable-record', `${err.message} Remove the agent and add it again.`); + throw err; + } + if (!record) throw new AgentError('not-found', `There is no agent named "${name}" under the context "${context}".`); + return record; +} + +const nameTaken = (name: string, context: string) => + new AgentError('name-taken', `There is already an agent named "${name}" under the context "${context}". Pick another name, or remove that agent first.`); + +function checkedName(name: string): string { + try { + return checkAgentName(name); + } catch (err) { + if (err instanceof AgentNameError) throw new AgentError('invalid-name', err.message); + throw err; + } +} + +async function setScope(endpoint: string, bearer: string, principalId: string, schemaChanges: boolean): Promise { + await call(endpoint, bearer, 'Setting what the agent may change', (client) => + client.mutation.setPrincipalScope( + { + input: { + principalId, + membershipType: ORG_MEMBERSHIP_TYPE, + allowedMask: schemaChanges ? null : SCHEMA_READ_ONLY_MASK, + // The scope's own default is true, which would give the agent the person's admin flag back. + useAdminOwner: false, + isActive: true, + isReadOnly: false + } + }, + { select: { result: true } } + ) + ); +} + +/** Cap every key minted for the principal; the backend applies a cap when it mints a key, so this comes first. */ +async function capKeys(endpoint: string, bearer: string, principalId: string): Promise { + // The generated SDK types this input as a table patch; the backend's updatePrincipal takes each setting as its own argument. + const input = { principalId, apiKeyMaxDuration: { days: AGENT_KEY_DAYS } } as unknown as Parameters[0]['input']; + const capped = await call(endpoint, bearer, "Capping the agent's key lifetime", (client) => client.mutation.updatePrincipal({ input }, { select: { result: true } })).then( + (data) => (data as { updatePrincipal?: { result?: boolean } })?.updatePrincipal?.result + ); + if (capped !== true) throw new AgentError('server-error', "Capping the agent's key lifetime failed: the backend did not confirm it. Retry later, or check the backend logs."); +} + +async function createKey(endpoint: string, bearer: string, principalId: string, name: string): Promise<{ apiKey: string; keyId: string; keyExpiresAt: string }> { + const data = await call(endpoint, bearer, 'Creating the key of the agent', (client) => + client.mutation.createApiKey( + { input: { keyName: `agent:${name}`, accessLevel: 'full_access', mfaLevel: 'none', expiresIn: { days: AGENT_KEY_DAYS }, principalId } }, + { select: { result: { select: { apiKey: true, keyId: true, expiresAt: true } } } } + ) + ); + const key = (data as { createApiKey?: { result?: { apiKey?: string; keyId?: string; expiresAt?: string } } })?.createApiKey?.result; + if (!key?.apiKey || !key.keyId || !key.expiresAt) { + throw new AgentError('server-error', 'Creating the key of the agent failed: the backend answered without a key and its end. Retry later, or check the backend logs.'); + } + return { apiKey: key.apiKey, keyId: key.keyId, keyExpiresAt: key.expiresAt }; +} + +/** + * Create an agent of the signed-in person: a principal that does not share the + * person's admin flag, held to `organization` when one is given, that may not + * change the schema unless `allowSchemaChanges`, with every key of it capped at + * 30 days, and one such key, stored under the person's context. This package + * uses the key only to mint access tokens, but the backend accepts the key itself + * on requests too. It signs the person in afresh with `password` + * and ends that sign-in when done. A failure after the principal exists + * deletes it again and says so. + */ +export async function createAgent({ + store, + session, + password, + name, + organization, + allowSchemaChanges +}: { + store: ConfigStore; + session: Session; + password: string; + name: string; + organization?: string; + allowSchemaChanges: boolean; +}): Promise { + const agentName = checkedName(name); + const owner = person(session); + const context = owner.context; + if (agentEntryExists(store, context, agentName)) throw nameTaken(agentName, context); + return withFreshSignIn(owner, password, (bearer) => createWith(store, owner, bearer, agentName, organization, allowSchemaChanges)); +} + +async function createWith(store: ConfigStore, owner: SignedInPerson, bearer: string, agentName: string, organization: string | undefined, allowSchemaChanges: boolean): Promise { + const context = owner.context; + const endpoint = owner.backend.authEndpoint; + const principalId = await call(endpoint, bearer, 'Creating the agent', (client) => + client.mutation.createPrincipal( + { input: { name: agentName, useAdminOwner: false, ...(organization ? { entityIds: [organization] } : {}) } }, + { select: { result: true } } + ) + ).then((data) => (data as { createPrincipal?: { result?: string } })?.createPrincipal?.result); + if (!principalId) throw new AgentError('server-error', 'Creating the agent failed: the backend answered without a principal id. Retry later, or check the backend logs.'); + + try { + await setScope(endpoint, bearer, principalId, allowSchemaChanges); + await capKeys(endpoint, bearer, principalId); + const key = await createKey(endpoint, bearer, principalId, agentName); + const record: AgentRecord = { + name: agentName, + context, + principalId, + ownerId: owner.account.userId, + ...(organization ? { organization } : {}), + schemaChanges: allowSchemaChanges, + createdAt: new Date().toISOString(), + issuedFor: owner.backend, + ...key + }; + try { + createAgentEntry(store, record); + } catch (err) { + // Another add of this name may have finished since the first check. + if ((err as NodeJS.ErrnoException).code === 'EEXIST') throw nameTaken(agentName, context); + throw err; + } + return infoOf(store, record); + } catch (err) { + const cleanup = await call(endpoint, bearer, 'Deleting the half-made agent', (client) => + client.mutation.deletePrincipal({ input: { principalId } }, { select: { result: true } }) + ).then( + () => 'The principal it made was deleted again.', + (cleanupErr: AgentError) => `The principal ${principalId} it made could not be deleted (${cleanupErr.message}); delete it from the app.` + ); + if (err instanceof AgentError) throw new AgentError(err.kind, `${err.message} ${cleanup}`, err.code); + throw err; + } +} + +/** + * The agents filed under `context` (default: the active one). No secret is in + * the result. The person's sign-out leaves each agent working; this is what to + * tell them, and `removeAgent` is what stops one. + */ +export function listAgents({ store, context }: { store: ConfigStore; context?: string }): AgentInfo[] { + const resolved = context ?? currentContextName(store); + if (!resolved) return []; + return listAgentNames(store, resolved).flatMap((name): AgentInfo[] => { + try { + const record = readAgent(store, resolved, name); + return record ? [infoOf(store, record)] : []; + } catch (err) { + if (!(err instanceof AgentRecordUnreadable)) throw err; + return [{ name, context: resolved, state: 'set-up-again', unreadable: true, problem: `${err.message} Remove the agent and add it again.` }]; + } + }); +} + +type Unusable = Extract; + +/** Mint an access token with the agent's key, for its principal. The refresh token the backend makes is never asked for. */ +async function mint(record: AgentRecord): Promise { + const unusable = (reason: Unusable['reason'], problem: string, fix: string): Unusable => ({ kind: 'agent-unusable', context: record.context, agent: record.name, reason, problem, fix }); + let result: { accessToken?: string; accessExpiresAt?: string } | undefined; + try { + const data = await call(record.issuedFor.authEndpoint, record.apiKey, 'Issuing the agent an access token', (client) => + client.mutation.mintAccessToken( + { input: { principalId: record.principalId, intent: `agent:${record.name}` } }, + { select: { result: { select: { accessToken: true, accessExpiresAt: true } } } } + ) + ); + result = (data as { mintAccessToken?: { result?: typeof result } })?.mintAccessToken?.result; + } catch (err) { + if (!(err instanceof AgentError)) throw err; + if (err.kind === 'sign-in-required' || err.kind === 'not-found') { + return unusable('set-up-again', `The backend no longer accepts the key of the agent "${record.name}" (${err.code}): the agent was removed, or its key was revoked or has ended.`, renewFix(record.name)); + } + return unusable('mint-failed', err.message, 'Retry: the key of the agent is unchanged.'); + } + if (!result?.accessToken || !result.accessExpiresAt) { + return unusable('mint-failed', `Issuing the agent "${record.name}" an access token failed: the backend answered without a token.`, 'Retry later, or check the backend logs.'); + } + return { keyId: record.keyId, accessToken: result.accessToken, accessExpiresAt: result.accessExpiresAt }; +} + +/** + * The agent's session for use: the cached access token while more than a + * short margin of it is left, else a new one minted with the agent's key and + * cached. Processes need no lock: a token may be used many times, so two that + * mint at once both work, and the cache keeps one of them. + * + * `rejectedToken` is an access token of this agent that the backend just + * refused as signed out. When it is the cached one, that entry is dropped and + * one token is minted from the key; when another process already cached a new + * one, that one is used. It never retries on its own, so a caller passes it + * once per refusal. + */ +export async function agentSession({ + store, + name, + context, + env = process.env, + rejectedToken +}: { + store: ConfigStore; + name: string; + context?: string; + env?: NodeJS.ProcessEnv; + rejectedToken?: string; +}): Promise { + const bound = agentBinding({ store, context, env, agent: name }); + if (bound.kind !== 'bound') return bound; + const { record } = bound; + let cached = readCachedToken(store, bound.context, record.name); + if (rejectedToken !== undefined && cached?.accessToken === rejectedToken) { + dropCachedToken(store, bound.context, record.name); + cached = null; + } + let token: CachedToken; + if (cached && cached.keyId === record.keyId && Date.parse(cached.accessExpiresAt) - Date.now() > TOKEN_MARGIN_MS) { + token = cached; + } else { + const minted = await mint(record); + if ('kind' in minted) return minted; + writeCachedToken(store, bound.context, record.name, minted); + token = minted; + } + return { + kind: 'signed-in', + source: 'agent', + context: bound.context, + backend: bound.backend, + account: { userId: record.ownerId, accessToken: token.accessToken, accessTokenExpiresAt: token.accessExpiresAt, key: { kind: 'none' } }, + agent: { name: record.name, principalId: record.principalId, schemaChanges: record.schemaChanges, accessExpiresAt: token.accessExpiresAt, keyExpiresAt: record.keyExpiresAt } + }; +} + +/** Change what an agent may do with the schema, on the backend and in its record. */ +async function setSchemaChanges(store: ConfigStore, session: Session, name: string, schemaChanges: boolean): Promise { + const agentName = checkedName(name); + const owner = person(session); + const record = ownedRecord(store, owner.context, agentName); + await setScope(owner.backend.authEndpoint, storedBearer(owner), record.principalId, schemaChanges); + const updated = { ...record, schemaChanges }; + writeAgent(store, updated); + return infoOf(store, updated); +} + +/** Let an agent change the schema: the scope's mask is removed. */ +export const grantSchemaChanges = ({ store, session, name }: { store: ConfigStore; session: Session; name: string }) => setSchemaChanges(store, session, name, true); + +/** Stop an agent changing the schema: `manage_database` is masked out again. */ +export const revokeSchemaChanges = ({ store, session, name }: { store: ConfigStore; session: Session; name: string }) => setSchemaChanges(store, session, name, false); + +/** A renewed agent, and what happened to its old key. */ +export interface AgentRenewal { + agent: AgentInfo; + previousKey: KeyRevocation; +} + +/** + * Give an agent a new 30-day key for the same principal, so it keeps its + * grants: with a new password sign-in of the person (ended when done), the new + * key is stored first, the cached token dropped, then the old key revoked, + * which ends every token minted with it. A failure before the new key is + * stored keeps the old key and the record as they were. + */ +export async function renewAgentKey({ store, session, password, name }: { store: ConfigStore; session: Session; password: string; name: string }): Promise { + const agentName = checkedName(name); + const owner = person(session); + const record = ownedRecord(store, owner.context, agentName); + const endpoint = owner.backend.authEndpoint; + return withFreshSignIn(owner, password, async (bearer) => { + const key = await createKey(endpoint, bearer, record.principalId, agentName); + const renewed: AgentRecord = { ...record, ...key }; + writeAgent(store, renewed); + dropCachedToken(store, owner.context, agentName); + const previousKey = await revokeKey(record.keyId, async (keyId): Promise => { + await call(endpoint, bearer, 'Revoking the old key of the agent', (client) => client.mutation.revokeApiKey({ input: { keyId } }, { select: { result: true } })); + }); + return { agent: infoOf(store, renewed), previousKey }; + }); +} + +/** + * Delete the agent's principal on the backend, which ends its key and every + * token minted with it at once, then its stored entry and cached token. A + * failed delete keeps the entry and throws; a principal the backend no longer + * has is `already-gone`, and its entry is removed. + */ +export type AgentRemoval = + | { kind: 'removed' | 'already-gone'; name: string } + /** The record could not be read, so its principal is unknown: only the entry was removed. */ + | { kind: 'entry-removed'; name: string; problem: string }; + +export async function removeAgent({ store, session, name }: { store: ConfigStore; session: Session; name: string }): Promise { + const agentName = checkedName(name); + const owner = person(session); + let record: AgentRecord; + try { + record = ownedRecord(store, owner.context, agentName); + } catch (err) { + if (!(err instanceof AgentError && err.kind === 'unreadable-record')) throw err; + deleteAgent(store, owner.context, agentName); + return { + kind: 'entry-removed', + name: agentName, + problem: `The stored record of the agent "${agentName}" could not be read, so its principal is unknown and was not deleted. Delete the principal "${agentName}" in the app; its credential works until then.` + }; + } + let kind: 'removed' | 'already-gone' = 'removed'; + try { + const data = await call(owner.backend.authEndpoint, storedBearer(owner), 'Removing the agent', (client) => + client.mutation.deletePrincipal({ input: { principalId: record.principalId } }, { select: { result: true } }) + ); + if (!(data as { deletePrincipal?: unknown })?.deletePrincipal) kind = 'already-gone'; + } catch (err) { + if (!(err instanceof AgentError && err.kind === 'not-found')) { + if (err instanceof AgentError) throw new AgentError(err.kind, `${err.message} The agent is still stored, and its credential still works.`, err.code); + throw err; + } + kind = 'already-gone'; + } + deleteAgent(store, owner.context, agentName); + return { kind, name: agentName }; +} diff --git a/agentic/session/src/api-key.ts b/agentic/session/src/api-key.ts new file mode 100644 index 0000000000..c772ea0f11 --- /dev/null +++ b/agentic/session/src/api-key.ts @@ -0,0 +1,151 @@ +export const API_KEY_NAME = 'agentic-cli'; +export const API_KEY_ACCESS_LEVEL = 'full_access'; +export const API_KEY_MFA_LEVEL = 'none'; +export const API_KEY_DAYS = 30; + +/** + * Ask the person to sign in again once their key is within a week of its end. + * A new key needs a fresh password sign-in, which mints one, so nothing renews + * a key on its own. + */ +export const SIGN_IN_AGAIN_WITHIN_MS = 1000 * 60 * 60 * 24 * 7; + +export interface MintedApiKey { + apiKey: string; + keyId: string; + apiKeyExpiresAt?: string; +} + +export interface CreateApiKeyInputShape { + keyName: string; + accessLevel: string; + mfaLevel: string; + expiresIn: { days: number }; +} + +export function buildCreateApiKeyInput({ days }: { days: number }): CreateApiKeyInputShape { + return { + keyName: API_KEY_NAME, + accessLevel: API_KEY_ACCESS_LEVEL, + mfaLevel: API_KEY_MFA_LEVEL, + expiresIn: { days } + }; +} + +interface RawApiKeyRecord { + apiKey?: string | null; + keyId?: string | null; + expiresAt?: string | null; +} + +export function parseMintedKey(record: RawApiKeyRecord | null | undefined): MintedApiKey { + if (!record?.apiKey || !record.keyId) { + throw new Error('createApiKey returned no API key.'); + } + return { + apiKey: record.apiKey, + keyId: record.keyId, + ...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {}) + }; +} + +export type ApiKeyErrorKind = + | 'step-up-required' + | 'disabled' + | 'limit-reached' + | 'not-authenticated' + | 'invalid-access-level' + | 'unknown'; + +const ERROR_CODE_MAP: Record = { + STEP_UP_REQUIRED: 'step-up-required', + API_KEYS_DISABLED: 'disabled', + API_KEY_LIMIT_REACHED: 'limit-reached', + NOT_AUTHENTICATED: 'not-authenticated', + INVALID_ACCESS_LEVEL: 'invalid-access-level' +}; + +export function classifyApiKeyError(err: unknown): ApiKeyErrorKind { + const errors = (err as { errors?: Array<{ message?: string; extensions?: { code?: string } }> })?.errors; + if (Array.isArray(errors)) { + for (const e of errors) { + const code = e.extensions?.code; + if (code && ERROR_CODE_MAP[code]) return ERROR_CODE_MAP[code]; + } + } + return 'unknown'; +} + +/** Whether a key that ends at `expiresAt` has ended or ends within `withinMs`, so the person should sign in again. */ +export function keyEndsSoon({ + expiresAt, + now = Date.now(), + withinMs = SIGN_IN_AGAIN_WITHIN_MS +}: { + expiresAt: string | undefined; + now?: number; + withinMs?: number; +}): boolean { + if (!expiresAt) return false; + const expires = Date.parse(expiresAt); + if (Number.isNaN(expires)) return false; + return expires - now <= withinMs; +} + +/** What happened to the key a new one replaces. */ +export type KeyRevocation = + | { kind: 'absent' } + | { kind: 'revoked'; keyId: string } + | { kind: 'failed'; keyId: string; reason: string }; + +/** The replaced key after a remint; `kept` means it is still valid because no new key was minted. */ +export type PreviousKey = KeyRevocation | { kind: 'kept'; keyId: string }; + +export type RemintResult = + | { kind: 'minted'; minted: MintedApiKey; previousKey: KeyRevocation } + | { kind: 'failed'; error: unknown; previousKey: PreviousKey }; + +export function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** Revoke `keyId`; never throws. */ +export async function revokeKey(keyId: string | undefined, revoke: (keyId: string) => Promise): Promise { + if (!keyId) return { kind: 'absent' }; + try { + await revoke(keyId); + return { kind: 'revoked', keyId }; + } catch (err) { + return { kind: 'failed', keyId, reason: errorText(err) }; + } +} + +/** + * Mint-first, revoke-on-success: revoking before minting would destroy a + * still-valid key whenever the mint then fails, leaving no credential at all. + * The one case that needs the old key gone first is the live-key cap + * (API_KEY_LIMIT_REACHED): there we revoke, then retry the mint once. + */ +export async function remintApiKey({ + currentKeyId, + revoke, + mint +}: { + currentKeyId: string | undefined; + revoke: (keyId: string) => Promise; + mint: () => Promise; +}): Promise { + try { + const minted = await mint(); + return { kind: 'minted', minted, previousKey: await revokeKey(currentKeyId, revoke) }; + } catch (err) { + const kept: PreviousKey = currentKeyId ? { kind: 'kept', keyId: currentKeyId } : { kind: 'absent' }; + if (classifyApiKeyError(err) !== 'limit-reached' || !currentKeyId) return { kind: 'failed', error: err, previousKey: kept }; + const previousKey = await revokeKey(currentKeyId, revoke); + try { + return { kind: 'minted', minted: await mint(), previousKey }; + } catch (retryErr) { + return { kind: 'failed', error: retryErr, previousKey }; + } + } +} diff --git a/agentic/session/src/auth-error.ts b/agentic/session/src/auth-error.ts new file mode 100644 index 0000000000..2ee92d9e1a --- /dev/null +++ b/agentic/session/src/auth-error.ts @@ -0,0 +1,140 @@ +import { createFetch } from '@constructive-io/fetch'; + +/** The request never got an HTTP answer: refused, reset, no such host, a TLS failure. */ +export class BackendUnreachableError extends Error { + constructor( + endpoint: string, + readonly cause: unknown + ) { + super(`Could not reach the server at ${endpoint}. Check that it is running, or pick a different backend.`); + this.name = 'BackendUnreachableError'; + } +} + +/** A fetch for one endpoint that tags a request with no answer and records the HTTP status of the last answer. */ +export function trackedFetch(endpoint: string): { fetch: typeof fetch; status(): number | undefined } { + const base = createFetch(); + let status: number | undefined; + const tracked = async (input: Parameters[0], init?: Parameters[1]) => { + let response: Response; + try { + response = await base(input, init); + } catch (err) { + throw new BackendUnreachableError(endpoint, err); + } + status = response.status; + return response; + }; + return { fetch: tracked as typeof fetch, status: () => status }; +} + +export function isNetworkError(err: unknown): boolean { + return err instanceof BackendUnreachableError || err instanceof AuthTimeoutError; +} + +/** + * The `extensions.code` of every GraphQL error in a failed call, wherever the + * client nested it. Message text is never read: the server may put backend + * internals in it. + */ +export function errorCodes(err: unknown): string[] { + const codes: string[] = []; + const visited = new Set(); + const visit = (value: unknown): void => { + if (!value || typeof value !== 'object' || visited.has(value)) return; + visited.add(value); + const record = value as Record; + const code = (record.extensions as { code?: unknown } | undefined)?.code; + if (typeof code === 'string') codes.push(code); + if (Array.isArray(record.errors)) record.errors.forEach(visit); + for (const key of ['cause', 'response', 'result', 'payload', 'data']) visit(record[key]); + }; + visit(err); + return [...new Set(codes)]; +} + +/** A failed auth call in our own words: why no answer came, else the server's codes, never its message text. */ +export function describeAuthError(err: unknown): string { + if (isNetworkError(err)) return (err as Error).message; + const codes = errorCodes(err); + return codes.length > 0 ? `the server answered ${codes.join(', ')}` : 'the server answered with no error code'; +} + +export const AUTH_TIMEOUT_MS = 10_000; + +export class AuthTimeoutError extends Error { + constructor(endpoint: string, ms: number) { + super(`The server at ${endpoint} did not respond within ${Math.round(ms / 1000)}s. Check the backend settings and try again.`); + this.name = 'AuthTimeoutError'; + } +} + +export function withAuthTimeout( + promise: Promise, + endpoint: string, + ms: number = AUTH_TIMEOUT_MS +): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new AuthTimeoutError(endpoint, ms)); + }, ms); + promise.then( + value => { + clearTimeout(timer); + resolve(value); + }, + (err: unknown) => { + clearTimeout(timer); + reject(err); + } + ); + }); +} + +export type SignInErrorKind = + | 'invalid-input' + | 'invalid-credentials' + | 'second-factor-required' + | 'refused' + | 'backend-unreachable' + | 'server-error'; + +/** A failed sign-in, by what the caller can do about it. `code` is the server's error code, when it gave one. */ +export class SignInError extends Error { + constructor( + readonly kind: SignInErrorKind, + message: string, + readonly code?: string + ) { + super(message); + this.name = 'SignInError'; + } +} + +/** Codes the auth plane raises to refuse a sign-in that is otherwise well formed. */ +const REFUSAL_CODES = new Set([ + 'ACCOUNT_LOCKED_EXCEED_ATTEMPTS', + 'TOO_MANY_REQUESTS', + 'PASSWORD_SIGN_IN_DISABLED', + 'AUTH_METHOD_NOT_ALLOWED', + 'IDENTIFIER_UNVERIFIED_AMBIGUOUS', + 'CSRF_TOKEN_REQUIRED', + 'INVALID_CSRF_TOKEN' +]); + +/** + * The sign-in request failed before the server said who the user is. Classified + * by facts only: no answer, the HTTP status (`status`), then `extensions.code`; + * never by message text. + */ +export function signInFailure(err: unknown, endpoint: string, status: number | undefined): SignInError { + if (isNetworkError(err)) return new SignInError('backend-unreachable', describeAuthError(err)); + if (status === 429) return new SignInError('refused', `The server at ${endpoint} refused the sign-in: too many requests (HTTP 429). Wait, then retry.`, 'HTTP_429'); + if (status !== undefined && (status < 200 || status >= 300)) { + return new SignInError('server-error', `The server at ${endpoint} answered the sign-in with HTTP ${status}. Retry later, or check the backend logs.`, `HTTP_${status}`); + } + const refusal = errorCodes(err).find((code) => REFUSAL_CODES.has(code)); + if (refusal) return new SignInError('refused', `The server at ${endpoint} refused the sign-in (${refusal}). Wait, then retry, or sign in through the app.`, refusal); + const code = errorCodes(err)[0]; + return new SignInError('server-error', `The server at ${endpoint} failed to answer the sign-in (${describeAuthError(err)}). Retry later, or check the backend logs.`, code); +} diff --git a/agentic/session/src/auth.ts b/agentic/session/src/auth.ts new file mode 100644 index 0000000000..90f2dd86ec --- /dev/null +++ b/agentic/session/src/auth.ts @@ -0,0 +1,273 @@ +import { auth } from '@constructive-io/sdk'; +import { ConfigStore } from 'appstash'; + +import { AccountSession, clearSession, loadSession, saveSession } from './account-store'; +import { API_KEY_DAYS, buildCreateApiKeyInput, KeyRevocation, MintedApiKey, parseMintedKey, PreviousKey, remintApiKey, revokeKey } from './api-key'; +import { describeAuthError, errorCodes, isNetworkError, SignInError, signInFailure, trackedFetch, withAuthTimeout } from './auth-error'; +import { addBackend, BackendConfig, contextNameFor, selectBackend } from './backend-store'; +import { type Session, sessionProblem } from './session'; + +type AuthClient = ReturnType; + +interface AuthRecord { + userId?: string | null; + accessToken?: string | null; + accessTokenExpiresAt?: string | null; + mfaRequired?: boolean | null; +} + +const SELECT = { + result: { + select: { userId: true, accessToken: true, accessTokenExpiresAt: true, mfaRequired: true } + } +} as const; + +const CREATE_KEY_SELECT = { + result: { select: { apiKey: true, keyId: true, expiresAt: true } } +} as const; + +const REVOKE_KEY_SELECT = { result: true } as const; + +const NO_ISSUER = 'The session did not record the auth endpoint that issued it, so its key was not sent anywhere to be revoked; it stays valid until it expires.'; + +/** Talks to one auth endpoint with one bearer; every call has the sign-in timeout. */ +function keyClient(endpoint: string, bearer: string) { + const client: AuthClient = auth.createClient({ endpoint, headers: { Authorization: `Bearer ${bearer}` }, fetch: trackedFetch(endpoint).fetch }); + return { + async mint(): Promise { + const request = client.mutation + .createApiKey({ input: buildCreateApiKeyInput({ days: API_KEY_DAYS }) }, { select: CREATE_KEY_SELECT }) + .unwrap(); + const data = (await withAuthTimeout(request, endpoint)) as { createApiKey?: { result?: MintedApiKey & { expiresAt?: string } } } | undefined; + return parseMintedKey(data?.createApiKey?.result); + }, + async revoke(keyId: string): Promise { + try { + await withAuthTimeout(client.mutation.revokeApiKey({ input: { keyId } }, { select: REVOKE_KEY_SELECT }).unwrap(), endpoint); + } catch (err) { + throw new Error(describeAuthError(err)); + } + } + }; +} + +/** + * Where a stored session's key is revoked: the auth endpoint that issued it. + * A session that records only that endpoint (Desktop's field) still names its + * issuer, so its own token may go back there, though it is never used for + * anything else. + */ +const issuerOf = (session: AccountSession | null | undefined): string | undefined => session?.issuedFor?.authEndpoint ?? session?.authEndpoint; + +/** + * The stored bearer is the key: the password sign-in that made it is ended + * on the server once the key exists, so its token works nowhere. + */ +const withKey = (session: AccountSession, key: MintedApiKey): AccountSession => ({ + ...session, + accessToken: key.apiKey, + accessTokenExpiresAt: key.apiKeyExpiresAt, + apiKey: key.apiKey, + keyId: key.keyId, + apiKeyExpiresAt: key.apiKeyExpiresAt +}); + +/** A person signed in with the password: a bearer session on the server until `endSignIn` ends it. */ +export interface PasswordSignIn { + userId: string; + email: string; + accessToken: string; + accessTokenExpiresAt?: string; +} + +/** One password sign-in at `authEndpoint`, which writes nothing. Throws a `SignInError`. */ +export async function passwordSignIn(authEndpoint: string, email: string, password: string): Promise { + const trimmedEmail = email.trim(); + if (!trimmedEmail || !password) throw new SignInError('invalid-input', 'Email and password are required.'); + const http = trackedFetch(authEndpoint); + const request = auth.createClient({ endpoint: authEndpoint, fetch: http.fetch }).mutation + .signIn({ input: { email: trimmedEmail, password } }, { select: SELECT }) + .unwrap(); + + let record: AuthRecord | null | undefined; + try { + record = ((await withAuthTimeout(request, authEndpoint)) as { signIn?: { result?: AuthRecord | null } } | undefined)?.signIn?.result; + } catch (err) { + throw signInFailure(err, authEndpoint, http.status()); + } + if (record?.mfaRequired) { + throw new SignInError('second-factor-required', `The account ${trimmedEmail} needs a second factor, which this sign-in does not support yet. Sign in through the app.`); + } + if (!record?.accessToken || !record.userId) { + throw new SignInError('invalid-credentials', `The server at ${authEndpoint} rejected the email or the password.`); + } + return { + userId: record.userId, + email: trimmedEmail, + accessToken: record.accessToken, + ...(record.accessTokenExpiresAt ? { accessTokenExpiresAt: record.accessTokenExpiresAt } : {}) + }; +} + +/** + * End a password sign-in's session on the server, so no bearer session is + * left behind. Best effort: if the server cannot be reached, the session ends + * at its own expiry, and the caller's work stands. + */ +export async function endSignIn(authEndpoint: string, accessToken: string): Promise { + const client = auth.createClient({ endpoint: authEndpoint, headers: { Authorization: `Bearer ${accessToken}` }, fetch: trackedFetch(authEndpoint).fetch }); + await withAuthTimeout(client.mutation.signOut({ input: {} }, { select: { clientMutationId: true } }).unwrap(), authEndpoint).catch((): void => undefined); +} + +/** The sign-in worked, but no key could be made, so nothing is stored. */ +function noKeyFailure(err: unknown, authEndpoint: string): SignInError { + const why = `The sign-in to ${authEndpoint} worked, but no API key could be made (${describeAuthError(err)}), so nothing was stored and the sign-in was ended.`; + if (isNetworkError(err)) return new SignInError('backend-unreachable', `${why} Retry the sign-in.`); + const code = errorCodes(err)[0]; + if (code) return new SignInError('refused', `${why} Revoke an API key you no longer use in the app, or check that API keys are on, then sign in again.`, code); + return new SignInError('server-error', `${why} Retry later, or check the backend logs.`); +} + +export interface SignInResult { + session: AccountSession; + context: string; + /** `not-minted`: the session keeps the key of the session it replaced, which is still valid. */ + apiKey: { kind: 'minted' } | { kind: 'not-minted'; reason: string }; + /** The key of the session this sign-in replaced. */ + previousKey: PreviousKey; +} + +/** + * Sign in to `backend` with email and password and mint the person's 30-day + * API key inside the fresh step-up window, all before anything is written. + * Then revoke the key of the session this one replaces, end the password + * sign-in on the server, and store the backend, the session (whose bearer is + * the key), and make the backend active, in that order, so credentials are + * never filed under a context that does not exist. A failed sign-in, or one + * that ends with no key, throws a `SignInError` and leaves the store as it was. + */ +export async function signIn({ + store, + backend, + context = contextNameFor(backend), + email, + password +}: { + store: ConfigStore; + backend: BackendConfig; + /** The context to file the session under. Default: `contextNameFor(backend)`. */ + context?: string; + email: string; + password: string; +}): Promise { + const { authEndpoint } = backend; + const signedIn = await passwordSignIn(authEndpoint, email, password); + const session: AccountSession = { ...signedIn, signedInAt: Date.now(), issuedFor: backend }; + + // The replaced key is revoked with the new token when it belongs to the same + // account on the same auth plane (that also frees a key-limit slot for the + // mint), else with the old session's own bearer at the issuer it records. + const previous = loadSession(store, context); + const previousAuth = issuerOf(previous); + const sameAccount = !!previous && previous.userId === session.userId && previousAuth === authEndpoint; + const result = await remintApiKey({ currentKeyId: sameAccount ? previous.keyId : undefined, ...keyClient(authEndpoint, session.accessToken) }).finally(() => + endSignIn(authEndpoint, session.accessToken) + ); + + let filed: AccountSession; + let previousKey: PreviousKey = result.previousKey; + let apiKey: SignInResult['apiKey']; + if (result.kind === 'minted') { + filed = withKey(session, result.minted); + apiKey = { kind: 'minted' }; + } else if (sameAccount && result.previousKey.kind === 'kept' && previous.apiKey) { + filed = withKey(session, { apiKey: previous.apiKey, keyId: previous.keyId, apiKeyExpiresAt: previous.apiKeyExpiresAt }); + apiKey = { kind: 'not-minted', reason: describeAuthError(result.error) }; + } else { + // A key-limit retry may have revoked the stored key before the second mint failed. + if (sameAccount && result.previousKey.kind === 'revoked') clearSession(store, context); + throw noKeyFailure(result.error, authEndpoint); + } + if (!sameAccount && previous?.keyId) { + previousKey = previousAuth + ? await revokeKey(previous.keyId, keyClient(previousAuth, previous.apiKey ?? previous.accessToken).revoke) + : { kind: 'failed', keyId: previous.keyId, reason: NO_ISSUER }; + } + + // The replaced session's key is handled above, so its record goes before the new backend is stored. + if (previous) clearSession(store, context); + addBackend(store, backend, context); + saveSession(store, filed, context); + selectBackend(store, context); + return { session: filed, context, apiKey, previousKey }; +} + +export type SignOutResult = + | { kind: 'not-signed-in'; context: string | null } + /** The session comes from the environment: nothing is stored to remove. */ + | { kind: 'from-environment' } + | { kind: 'cleared'; context: string; key: KeyRevocation }; + +/** + * Sign out of exactly the session `resolveSession` gave: revoke its API key at + * the auth endpoint that issued it, with its own bearer, and clear what is + * stored under its context. The session is cleared in every state, also when + * the context lacks planes, the issuer is not recorded or the revoke fails; + * the result says what happened to the key. Throws the problem of an + * `invalid-override` or `conflict` session. Prints nothing. + */ +export async function signOut({ store, session }: { store: ConfigStore; session: Session }): Promise { + if (session.kind === 'invalid-override' || session.kind === 'conflict') throw new Error(sessionProblem(session)); + if ((session.kind === 'signed-in' || session.kind === 'signed-out') && session.source === 'env') return { kind: 'from-environment' }; + const context = 'context' in session ? session.context : null; + if (!context || !store.getCredentials(context)) return { kind: 'not-signed-in', context }; + const stored = loadSession(store, context); + let key: KeyRevocation = { kind: 'absent' }; + const issuer = issuerOf(stored); + if (stored?.keyId) { + key = issuer ? await revokeKey(stored.keyId, keyClient(issuer, stored.apiKey ?? stored.accessToken).revoke) : { kind: 'failed', keyId: stored.keyId, reason: NO_ISSUER }; + } + clearSession(store, context); + return { kind: 'cleared', context, key }; +} + +export type CredentialCheck = + | { kind: 'accepted' } + | { kind: 'rejected'; reason: string; code?: string } + | { kind: 'unchecked'; reason: string }; + +/** + * Ask the backend once whether the credential of a signed-in session is + * accepted: `currentUser` at its auth endpoint, with the bearer the tools send + * (the API key, else the access token), within the sign-in timeout. Classified + * by facts only: no answer is `unchecked`; HTTP 401 or 403 is `rejected`; + * another non-2xx status is `unchecked`; `UNAUTHENTICATED` or `FORBIDDEN` is + * `rejected`, another error code `unchecked`; no user, or another user, is + * `rejected`. Never throws. + */ +export async function verifySession(session: Extract): Promise { + const { authEndpoint } = session.backend; + const bearer = session.account.key.kind === 'active' ? session.account.key.apiKey : session.account.accessToken; + const http = trackedFetch(authEndpoint); + const client = auth.createClient({ endpoint: authEndpoint, headers: { Authorization: `Bearer ${bearer}` }, fetch: http.fetch }); + let result: Awaited['execute']>>; + try { + result = await withAuthTimeout(client.query.currentUser({ select: { id: true } }).execute(), authEndpoint); + } catch (err) { + if (isNetworkError(err)) return { kind: 'unchecked', reason: describeAuthError(err) }; + return { kind: 'unchecked', reason: `The server at ${authEndpoint} gave an answer that could not be read (${describeAuthError(err)}).` }; + } + const status = http.status(); + if (status === 401 || status === 403) return { kind: 'rejected', reason: `The server at ${authEndpoint} rejected the credential (HTTP ${status}).`, code: `HTTP_${status}` }; + if (status !== undefined && (status < 200 || status >= 300)) return { kind: 'unchecked', reason: `The server at ${authEndpoint} answered HTTP ${status}.` }; + if (!result.ok) { + const codes = result.errors.map((error) => error.extensions?.code).filter((code): code is string => typeof code === 'string'); + const rejected = codes.find((code) => code === 'UNAUTHENTICATED' || code === 'FORBIDDEN'); + if (rejected) return { kind: 'rejected', reason: `The server at ${authEndpoint} rejected the credential (${rejected}).`, code: rejected }; + return { kind: 'unchecked', reason: `The server at ${authEndpoint} could not check the credential (${codes.join(', ') || 'no error code'}).` }; + } + const id = (result.data as { currentUser?: { id?: string } | null })?.currentUser?.id; + if (!id) return { kind: 'rejected', reason: `The server at ${authEndpoint} does not know the credential: it sees no signed-in user.` }; + if (id !== session.account.userId) return { kind: 'rejected', reason: `The credential belongs to another user than the session (${session.account.userId}).` }; + return { kind: 'accepted' }; +} diff --git a/agentic/session/src/backend-store.ts b/agentic/session/src/backend-store.ts new file mode 100644 index 0000000000..a9e92791ec --- /dev/null +++ b/agentic/session/src/backend-store.ts @@ -0,0 +1,221 @@ +import { deriveSubdomainEndpoint } from '@agentic-kit/db-tools'; +import { ConfigStore } from 'appstash'; + +import { checkContextName, ContextNameError, currentContextName, loadSession } from './account-store'; + +/** Every Constructive plane a binary talks to, one GraphQL endpoint each. */ +export interface BackendConfig { + apiEndpoint: string; + authEndpoint: string; + modulesEndpoint: string; + agentEndpoint: string; + computeEndpoint: string; +} + +export const PLANES = ['api', 'auth', 'modules', 'agent', 'compute'] as const; +export type Plane = (typeof PLANES)[number]; + +const KEY: Record = { + api: 'apiEndpoint', + auth: 'authEndpoint', + modules: 'modulesEndpoint', + agent: 'agentEndpoint', + compute: 'computeEndpoint' +}; + +export function planeEndpoint(config: BackendConfig, plane: Plane): string { + return config[KEY[plane]]; +} + +/** The planes whose endpoints differ, compared exactly (no case or slash folding). */ +export function differingPlanes(a: BackendConfig, b: BackendConfig): Plane[] { + return PLANES.filter((plane) => planeEndpoint(a, plane) !== planeEndpoint(b, plane)); +} + +/** + * A stored context: complete, lacking planes (a context another app wrote; + * planes are never filled in), or stored under a name that is not a valid + * context name (`reason`), which no function will act on. + */ +export type BackendContext = + | { name: string; current: boolean; status: 'complete'; backend: BackendConfig } + | { name: string; current: boolean; status: 'incomplete'; missing: Plane[]; apiEndpoint?: string } + | { name: string; current: boolean; status: 'invalid-name'; reason: string }; + +export type EndpointProblem = 'not-a-url' | 'scheme' | 'userinfo' | 'not-derivable'; + +/** An endpoint that cannot name a backend. The message never shows userinfo. */ +export class EndpointError extends Error { + constructor( + readonly reason: EndpointProblem, + readonly plane: Plane, + message: string + ) { + super(message); + this.name = 'EndpointError'; + } +} + +function shown(endpoint: string): string { + try { + const url = new URL(endpoint); + url.username = ''; + url.password = ''; + return url.toString(); + } catch { + return endpoint.replace(/\/\/[^/@]*@/, '//'); + } +} + +function checkedEndpoint(plane: Plane, raw: string): string { + const endpoint = raw.trim(); + let url: URL; + try { + url = new URL(endpoint); + } catch { + throw new EndpointError('not-a-url', plane, `The ${plane} endpoint "${shown(endpoint) || '(empty)'}" is not an absolute URL. Pass one such as https://${plane}.example.com/graphql.`); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new EndpointError('scheme', plane, `The ${plane} endpoint ${shown(endpoint)} uses ${url.protocol}, but only http and https are supported. Pass an http or https URL.`); + } + if (url.username || url.password) { + throw new EndpointError('userinfo', plane, `The ${plane} endpoint ${shown(endpoint)} has a user name or password in it, which would go to every plane. Remove it; sign in with email and password instead.`); + } + return endpoint; +} + +/** + * The planes share the api endpoint's host scheme only when the host is + * `api.` (api.example.com -> auth.example.com). Any other host would send + * the password to a host the user never named, so it must give every plane. + */ +function derivedEndpoint(api: string, plane: Plane): string { + const labels = new URL(api).hostname.split('.'); + if (labels[0] !== 'api' || labels.length < 2 || labels.some((label) => label === '')) { + throw new EndpointError( + 'not-derivable', + plane, + `Cannot derive the ${plane} endpoint from ${shown(api)}: the other planes are derived only from a host that starts with "api.". Give every plane endpoint explicitly (auth, modules, agent and compute).` + ); + } + return deriveSubdomainEndpoint(api, plane); +} + +/** + * The backend that `api` names. A plane given explicitly is used as is; a + * missing one is derived from an `api.` host. Throws `EndpointError`. + */ +export function backendFromEndpoints(endpoints: { api: string } & Partial, string>>): BackendConfig { + const api = checkedEndpoint('api', endpoints.api ?? ''); + const config = { apiEndpoint: api } as BackendConfig; + for (const plane of PLANES) { + if (plane === 'api') continue; + const given = endpoints[plane]; + config[KEY[plane]] = given !== undefined ? checkedEndpoint(plane, given) : derivedEndpoint(api, plane); + } + return config; +} + +/** + * A backend is a named context in the shared store, named after the api + * endpoint's host without a leading `api.` (https://api.example.com/graphql -> + * example.com), a port joined by a dash (example.com-8443). Credentials hang + * off the context, so each backend keeps an independent session. + */ +export function contextNameFor(config: BackendConfig): string { + const { host, hostname } = new URL(config.apiEndpoint); + const labels = hostname.split('.'); + const raw = labels[0] === 'api' && labels.length >= 2 ? host.slice('api.'.length) : host; + const name = raw + .toLowerCase() + .replace(/[^a-z0-9.-]+/g, '-') + .replace(/\.{2,}/g, '.') + .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '') + .slice(0, 100) + .replace(/[^a-z0-9]+$/, ''); + return checkContextName(name || 'backend'); +} + +type Targets = Record | undefined; + +/** A stored context under a valid name: complete or lacking planes. */ +export type NamedBackendContext = Exclude; + +function fromTargets(name: string, current: boolean, targets: Targets): NamedBackendContext { + const missing = PLANES.filter((plane) => !targets?.[plane]?.endpoint); + if (missing.length > 0) { + const apiEndpoint = targets?.api?.endpoint; + return { name, current, status: 'incomplete', missing, ...(apiEndpoint ? { apiEndpoint } : {}) }; + } + const backend = {} as BackendConfig; + for (const plane of PLANES) backend[KEY[plane]] = targets[plane].endpoint; + return { name, current, status: 'complete', backend }; +} + +/** One stored context, or null when there is none with that name. */ +export function readBackend(store: ConfigStore, name: string): NamedBackendContext | null { + const ctx = store.loadContext(checkContextName(name)); + return ctx ? fromTargets(name, name === currentContextName(store), ctx.targets) : null; +} + +/** Every stored context. One with a name that does not pass the check is listed as `invalid-name` and stops nothing. */ +export function listBackends(store: ConfigStore): BackendContext[] { + const current = store.loadSettings().currentContext; + return store.listContexts().map((ctx) => { + const name = String(ctx.name); + try { + checkContextName(name); + } catch (err) { + if (!(err instanceof ContextNameError)) throw err; + return { name, current: name === current, status: 'invalid-name', reason: err.message }; + } + return fromTargets(name, name === current, ctx.targets); + }); +} + +/** Storing other endpoints under the context, or removing it, would drop the session filed there while its API key stays valid. */ +export class ContextInUseError extends Error { + constructor( + readonly context: string, + readonly action: 'store' | 'remove' + ) { + super( + action === 'store' + ? `The context "${context}" holds a session that was not issued for these endpoints, so storing them would drop it while its API key stays valid. Sign out of "${context}" first, which revokes that key, or store the backend under another name.` + : `The context "${context}" holds a session, so removing it would drop the session while its API key stays valid. Sign out of "${context}" first, which revokes that key.` + ); + this.name = 'ContextInUseError'; + } +} + +/** + * Store the endpoints as a context (default name: `contextNameFor`), keeping + * its current choice and the session filed under that name, which must have + * been issued for exactly these five endpoints. Throws `ContextInUseError` + * when it was not, or cannot be shown to be: sign out of that context first. + */ +export function addBackend(store: ConfigStore, config: BackendConfig, name: string = contextNameFor(config)): { name: string } { + checkContextName(name); + if (store.getCredentials(name)) { + const issuedFor = loadSession(store, name)?.issuedFor; + if (!issuedFor || differingPlanes(issuedFor, config).length > 0) throw new ContextInUseError(name, 'store'); + } + const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }])); + store.createContext(name, { endpoint: config.apiEndpoint, targets }); + return { name }; +} + +export function selectBackend(store: ConfigStore, name: string): void { + if (!store.setCurrentContext(checkContextName(name))) { + const known = store.listContexts().map((ctx) => ctx.name); + throw new Error( + `No backend context named "${name}". Known contexts: ${known.join(', ') || '(none)'}. Add the backend first.` + ); + } +} + +/** Delete a context. Throws `ContextInUseError` while a session is filed under it: `signOut` first, which revokes its key. */ +export function removeBackend(store: ConfigStore, name: string): boolean { + if (store.getCredentials(checkContextName(name))) throw new ContextInUseError(name, 'remove'); + return store.deleteContext(name); +} diff --git a/agentic/session/src/index.ts b/agentic/session/src/index.ts new file mode 100644 index 0000000000..e091f0305e --- /dev/null +++ b/agentic/session/src/index.ts @@ -0,0 +1,63 @@ +export { + type AccountSession, + checkContextName, + ContextNameError, + openStore, + saveSession, + STASH_DIR_ENV, + STASH_NAME, + stashBaseDir, + stashDirectories +} from './account-store'; +export { + type AgentDetails, + AgentError, + type AgentErrorKind, + type AgentInfo, + type AgentRemoval, + type AgentRenewal, + agentSession, + createAgent, + grantSchemaChanges, + listAgents, + removeAgent, + renewAgentKey, + revokeSchemaChanges, + SCHEMA_READ_ONLY_MASK +} from './agent'; +export { checkAgentName } from './agent-store'; +export { keyEndsSoon, type KeyRevocation, type PreviousKey, SIGN_IN_AGAIN_WITHIN_MS } from './api-key'; +export { type CredentialCheck, signIn, type SignInResult, signOut, type SignOutResult, verifySession } from './auth'; +export { SignInError, type SignInErrorKind } from './auth-error'; +export { + addBackend, + type BackendConfig, + type BackendContext, + backendFromEndpoints, + ContextInUseError, + contextNameFor, + EndpointError, + type EndpointProblem, + listBackends, + type Plane, + PLANES, + readBackend, + removeBackend, + selectBackend +} from './backend-store'; +export { + type AgentIdentity, + type AgentUnusableReason, + hostAccount, + OVERRIDE_ENV_VARS, + type PersonSession, + type ResolvedAgentSession, + resolveSession, + type Session, + type SessionAccount, + type SessionKey, + sessionProblem, + type SessionSource +} from './session'; +export { sessionToolsHost } from './tools-host'; +export type { ConfigStore } from 'appstash'; diff --git a/agentic/session/src/session.ts b/agentic/session/src/session.ts new file mode 100644 index 0000000000..a4820dfa95 --- /dev/null +++ b/agentic/session/src/session.ts @@ -0,0 +1,383 @@ +import type { HostAccount, HostBackendConfig } from '@agentic-kit/db-tools'; +import { ConfigStore } from 'appstash'; + +import { checkContextName, currentContextName, loadSession, openStore, STASH_DIR_ENV, stashBaseDir } from './account-store'; +import { type AgentRecord, AgentRecordUnreadable, checkAgentName, readAgent } from './agent-store'; +import { BackendConfig, backendFromEndpoints, differingPlanes, EndpointError, Plane, planeEndpoint, PLANES, readBackend } from './backend-store'; + +export type SessionSource = 'env' | 'store'; + +export type SessionKey = + | { kind: 'none' } + | { kind: 'active'; apiKey: string; keyId?: string; expiresAt?: string }; + +export interface SessionAccount { + userId: string; + /** Known for a stored session only. */ + email?: string; + accessToken: string; + accessTokenExpiresAt?: string; + key: SessionKey; +} + +/** + * The one answer to "who talks to which backend". A credential is only ever + * paired with the backend of its own source: a stored session with the + * endpoints of the context it is filed under, an environment credential with + * the endpoints the environment names. + */ +/** The states every resolution can answer: no backend, an incomplete one, or a wrong environment. */ +type CommonState = + /** No context is chosen (`context: null`), or the named one does not exist. */ + | { kind: 'no-backend'; context: string | null } + /** A stored context lacks planes, for example one another app wrote. */ + | { kind: 'incomplete-backend'; context: string; missing: Plane[]; apiEndpoint?: string } + /** An environment variable is missing, empty or wrong; `fix` says what to set. */ + | { kind: 'invalid-override'; variable: string; problem: string; fix: string } + /** A context or an agent was named, but the environment variable `variable` decides the session; one of the two must go. */ + | { kind: 'conflict'; context: string; variable: string; problem: string; fix: string }; + +/** A person's session: what `resolveSession` answers without `agent`. */ +export type PersonSession = + | CommonState + /** + * A session is stored under the context, but it was issued for another + * backend: `differs` names the planes whose endpoints are not the ones it + * was issued for (`issuedFor`), or the session does not record the backend + * it was issued for (`issuedFor: null`, `differs: []`). It is never used or + * sent; a new sign-in replaces it. + */ + | { kind: 'issuer-mismatch'; source: 'store'; context: string; backend: BackendConfig; issuedFor: BackendConfig | null; differs: Plane[] } + | { kind: 'signed-out'; source: SessionSource; context: string | null; backend: BackendConfig } + | { kind: 'signed-in'; source: SessionSource; context: string | null; backend: BackendConfig; account: SessionAccount }; + +/** The named agent cannot act; `fix` says how to recover. */ +type AgentUnusable = { kind: 'agent-unusable'; context: string | null; agent: string; reason: AgentUnusableReason; problem: string; fix: string }; + +/** An agent's session that can be used or says why not: what `agentSession` answers. */ +export type ResolvedAgentSession = + | CommonState + /** + * An agent of the person acts: an access token minted with the agent's key, + * filed under the person's context and bound to the endpoints it was issued + * for. `account.userId` is the person's id, which the backend requires. + */ + | { kind: 'signed-in'; source: 'agent'; context: string; backend: BackendConfig; account: SessionAccount; agent: AgentIdentity } + | AgentUnusable; + +/** Any resolution, for a caller that handles both (`sessionProblem`, the tools host). */ +export type Session = PersonSession | ResolvedAgentSession; + +export interface AgentIdentity { + name: string; + principalId: string; + schemaChanges: boolean; + /** When the access token in this session ends. */ + accessExpiresAt: string; + /** When the agent's key ends; after that the agent must be set up again. */ + keyExpiresAt: string; +} + +/** + * `set-up-again`: the agent's key has ended, the backend refused it, or its + * record cannot be read; only the person can add the agent again. + * `mint-failed`: no token could be minted (no answer, or a server error); the + * key is unchanged, so a retry is safe. + */ +export type AgentUnusableReason = 'not-found' | 'issuer-mismatch' | 'set-up-again' | 'mint-failed'; + +const CREDENTIAL_VARS = ['CONSTRUCTIVE_USER_ID', 'CONSTRUCTIVE_ACCESS_TOKEN', 'CONSTRUCTIVE_API_KEY'] as const; +const REQUIRED_CREDENTIAL_VARS = ['CONSTRUCTIVE_USER_ID', 'CONSTRUCTIVE_ACCESS_TOKEN'] as const; + +const endpointVar = (plane: Plane) => `CONSTRUCTIVE_${plane.toUpperCase()}_ENDPOINT`; +const ENDPOINT_VARS = PLANES.map(endpointVar); + +/** Every environment variable `resolveSession` reads, besides `CONSTRUCTIVE_STASH_DIR`. */ +export const OVERRIDE_ENV_VARS = [...CREDENTIAL_VARS, ...ENDPOINT_VARS] as readonly string[]; + +const isSet = (env: NodeJS.ProcessEnv, name: string) => env[name] !== undefined; + +type EnvBackend = { kind: 'none' } | { kind: 'backend'; backend: BackendConfig } | Extract; + +function envBackend(env: NodeJS.ProcessEnv): EnvBackend { + const empty = ENDPOINT_VARS.find((name) => env[name] === ''); + if (empty) return { kind: 'invalid-override', variable: empty, problem: `${empty} is set but empty.`, fix: `Set ${empty} to an http or https URL, or unset it.` }; + const api = env.CONSTRUCTIVE_API_ENDPOINT; + if (api === undefined) { + const stray = ENDPOINT_VARS.find((name) => isSet(env, name)); + if (!stray) return { kind: 'none' }; + return { + kind: 'invalid-override', + variable: 'CONSTRUCTIVE_API_ENDPOINT', + problem: `${stray} is set, but CONSTRUCTIVE_API_ENDPOINT is not, so the environment names no backend.`, + fix: `Set CONSTRUCTIVE_API_ENDPOINT to the api endpoint of the backend ${stray} belongs to, or unset ${stray}.` + }; + } + const given = Object.fromEntries( + PLANES.filter((plane) => plane !== 'api' && isSet(env, endpointVar(plane))).map((plane) => [plane, env[endpointVar(plane)]]) + ); + try { + return { kind: 'backend', backend: backendFromEndpoints({ api, ...given }) }; + } catch (err) { + if (!(err instanceof EndpointError)) throw err; + const variable = endpointVar(err.plane); + const fix = + err.reason === 'not-derivable' + ? `Set every plane explicitly: ${ENDPOINT_VARS.filter((name) => !isSet(env, name)).join(', ')}.` + : `Set ${variable} to an http or https URL with no user name or password.`; + return { kind: 'invalid-override', variable: err.reason === 'not-derivable' ? 'CONSTRUCTIVE_API_ENDPOINT' : variable, problem: err.message, fix }; + } +} + +type EnvAccount = { kind: 'none' } | { kind: 'account'; account: SessionAccount } | Extract; + +function envAccount(env: NodeJS.ProcessEnv): EnvAccount { + const set = CREDENTIAL_VARS.filter((name) => isSet(env, name)); + if (set.length === 0) return { kind: 'none' }; + const missing = REQUIRED_CREDENTIAL_VARS.find((name) => !env[name]); + if (missing || env.CONSTRUCTIVE_API_KEY === '') { + const variable = missing ?? 'CONSTRUCTIVE_API_KEY'; + return { + kind: 'invalid-override', + variable, + problem: `${set.join(' and ')} ${set.length > 1 ? 'are' : 'is'} set, so the credential comes from the environment, but ${variable} is ${isSet(env, variable) ? 'empty' : 'not set'}.`, + fix: `Set CONSTRUCTIVE_USER_ID and CONSTRUCTIVE_ACCESS_TOKEN (and optionally CONSTRUCTIVE_API_KEY), or unset all three to use the stored session.` + }; + } + const apiKey = env.CONSTRUCTIVE_API_KEY; + return { + kind: 'account', + account: { + userId: env.CONSTRUCTIVE_USER_ID, + accessToken: env.CONSTRUCTIVE_ACCESS_TOKEN, + key: apiKey ? { kind: 'active', apiKey } : { kind: 'none' } + } + }; +} + +const sameBackend = (a: BackendConfig, b: BackendConfig) => differingPlanes(a, b).length === 0; + +/** The stored side: the context `named` (default: the active one), with the session filed under it. */ +function storedSession(store: ConfigStore, named: string | undefined): PersonSession { + const context = named ?? currentContextName(store); + const stored = context ? readBackend(store, context) : null; + if (!stored) return { kind: 'no-backend', context: context ?? null }; + if (stored.status === 'incomplete') { + return { kind: 'incomplete-backend', context, missing: stored.missing, ...(stored.apiEndpoint ? { apiEndpoint: stored.apiEndpoint } : {}) }; + } + const session = loadSession(store, context); + if (!session) return { kind: 'signed-out', source: 'store', context, backend: stored.backend }; + const differs = session.issuedFor ? differingPlanes(session.issuedFor, stored.backend) : []; + if (!session.issuedFor || differs.length > 0) { + return { kind: 'issuer-mismatch', source: 'store', context, backend: stored.backend, issuedFor: session.issuedFor ?? null, differs }; + } + const key: SessionKey = session.apiKey + ? { kind: 'active', apiKey: session.apiKey, ...(session.keyId ? { keyId: session.keyId } : {}), ...(session.apiKeyExpiresAt ? { expiresAt: session.apiKeyExpiresAt } : {}) } + : { kind: 'none' }; + return { + kind: 'signed-in', + source: 'store', + context, + backend: stored.backend, + account: { + userId: session.userId, + ...(session.email ? { email: session.email } : {}), + accessToken: session.accessToken, + ...(session.accessTokenExpiresAt ? { accessTokenExpiresAt: session.accessTokenExpiresAt } : {}), + key + } + }; +} + +interface ResolveOptions { + context?: string; + env?: NodeJS.ProcessEnv; + store?: ConfigStore; +} + +type InvalidOverride = Extract; + +/** The store to read and the environment's backend and credential, or the environment variable that is wrong. */ +function prepare({ + context, + env, + store +}: ResolveOptions & { env: NodeJS.ProcessEnv }): { store: ConfigStore; backend: Exclude; account: Exclude } | InvalidOverride { + if (context !== undefined) checkContextName(context); + let opened = store; + if (!opened) { + try { + opened = openStore(stashBaseDir(env)); + } catch (err) { + if (env[STASH_DIR_ENV] !== '') throw err; + return { kind: 'invalid-override', variable: STASH_DIR_ENV, problem: (err as Error).message, fix: `Set ${STASH_DIR_ENV} to a directory, or unset it.` }; + } + } + const backend = envBackend(env); + if (backend.kind === 'invalid-override') return backend; + const account = envAccount(env); + if (account.kind === 'invalid-override') return account; + return { store: opened, backend, account }; +} + +/** + * The person's session, resolved once from the environment and the store together. + * + * - Any credential variable selects the environment as the credential source; + * it needs CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN and the backend + * from CONSTRUCTIVE_API_ENDPOINT. + * - An endpoint override alone gives that backend `signed-out`, unless it names + * exactly the backend of the stored context, whose session then applies. + * - Otherwise the stored context `context` (default: the active one) and the + * session filed under it, used only when the context's auth endpoint issued it. + * - A `context` named while the environment decides the session is `conflict`. + * + * Returns `invalid-override` or `conflict` rather than throwing for a wrong + * environment. Throws `ContextNameError` for a `context` that is not a valid name. + */ +export function resolveSession({ context, env = process.env, store }: ResolveOptions = {}): PersonSession { + const prepared = prepare({ context, env, store }); + if ('kind' in prepared) return prepared; + const { store: opened, backend, account } = prepared; + + if (account.kind === 'account') { + if (backend.kind === 'none') { + return { + kind: 'invalid-override', + variable: 'CONSTRUCTIVE_API_ENDPOINT', + problem: 'The credential comes from the environment, but CONSTRUCTIVE_API_ENDPOINT is not set, so it names no backend to send it to.', + fix: 'Set CONSTRUCTIVE_API_ENDPOINT to the api endpoint the credential belongs to.' + }; + } + if (context !== undefined) return conflict(context, CREDENTIAL_VARS.find((name) => isSet(env, name)), backend.backend, 'credential'); + return { kind: 'signed-in', source: 'env', context: null, backend: backend.backend, account: account.account }; + } + + const stored = storedSession(opened, context); + if (backend.kind === 'none') return stored; + const storedBackend = stored.kind === 'signed-in' || stored.kind === 'signed-out' || stored.kind === 'issuer-mismatch' ? stored.backend : null; + if (storedBackend && sameBackend(storedBackend, backend.backend)) return stored; + if (context !== undefined) return conflict(context, 'CONSTRUCTIVE_API_ENDPOINT', backend.backend, 'backend'); + return { kind: 'signed-out', source: 'env', context: null, backend: backend.backend }; +} + +function agentConflict(context: string, agent: string, variable: string): Extract { + return { + kind: 'conflict', + context, + variable, + problem: `The agent "${agent}" was named, but ${variable} is set, so the environment would decide the session, not the agent.`, + fix: `Name no agent to use the environment, or unset ${variable} and the other CONSTRUCTIVE_* credential and endpoint variables to act as the agent.` + }; +} + +export const agentFix = (agent: string) => `Remove the agent "${agent}" and add it again, which needs the person signed in.`; + +/** The fix for an agent whose key has ended or was refused: a new key keeps its principal and grants. */ +export const renewFix = (agent: string) => `Renew the key of the agent "${agent}", which needs the person's password; if the agent was removed in the app, add it again.`; + +/** An agent whose record and key can be used, bound to the context's backend; it carries no access token yet. */ +export type AgentBinding = Exclude | { kind: 'bound'; context: string; backend: BackendConfig; record: AgentRecord }; + +/** + * The stored agent `agent` under the context `context` (default: the active + * one), checked against the context's endpoints and its key's end, with no + * request. With any CONSTRUCTIVE_* credential or endpoint variable set, it is + * `conflict`: the environment would decide the session, not the agent. + */ +export function agentBinding({ agent, context: named, env = process.env, store }: ResolveOptions & { agent: string }): AgentBinding { + checkAgentName(agent); + const prepared = prepare({ context: named, env, store }); + if ('kind' in prepared) return prepared; + const opened = prepared.store; + const variable = OVERRIDE_ENV_VARS.find((name) => isSet(env, name)); + if (variable) return agentConflict(named ?? currentContextName(opened) ?? '', agent, variable); + + const context = named ?? currentContextName(opened); + const stored = context ? readBackend(opened, context) : null; + if (!stored) return { kind: 'no-backend', context: context ?? null }; + if (stored.status === 'incomplete') { + return { kind: 'incomplete-backend', context, missing: stored.missing, ...(stored.apiEndpoint ? { apiEndpoint: stored.apiEndpoint } : {}) }; + } + const unusable = (reason: AgentUnusableReason, problem: string, fix = agentFix(agent)): AgentUnusable => ({ kind: 'agent-unusable', context, agent, reason, problem, fix }); + let record: AgentRecord | null; + try { + record = readAgent(opened, context, agent); + } catch (err) { + if (err instanceof AgentRecordUnreadable) return unusable('set-up-again', err.message.replace('of the agent', `of the agent "${agent}"`)); + throw err; + } + if (!record) { + return unusable('not-found', `There is no agent named "${agent}" under the context "${context}".`, `Add the agent first, or name one that exists.`); + } + const differs = differingPlanes(record.issuedFor, stored.backend); + if (differs.length > 0) { + const changes = differs.map((plane) => `the ${plane} endpoint is ${planeEndpoint(stored.backend, plane)}, but the agent was set up for ${planeEndpoint(record.issuedFor, plane)}`); + return unusable('issuer-mismatch', `The agent "${agent}" was set up for another backend: ${changes.join('; ')}. Its credential is not used or sent anywhere.`); + } + if (Date.parse(record.keyExpiresAt) <= Date.now()) { + return unusable('set-up-again', `The key of the agent "${agent}" ended at ${record.keyExpiresAt}.`, renewFix(agent)); + } + return { kind: 'bound', context, backend: stored.backend, record }; +} + +function conflict(context: string, variable: string, backend: BackendConfig, what: 'credential' | 'backend'): Extract { + const unset = what === 'credential' ? 'CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN and CONSTRUCTIVE_API_KEY' : 'CONSTRUCTIVE_API_ENDPOINT and the other CONSTRUCTIVE_*_ENDPOINT variables'; + return { + kind: 'conflict', + context, + variable, + problem: `The context "${context}" was named, but ${variable} is set, so the environment decides the session: the ${what} for ${backend.apiEndpoint}, not the context.`, + fix: `Name no context to use the environment, or unset ${unset} to use the context.` + }; +} + +/** The tools' account for a signed-in session: an agent's names the agent, so a plan says who makes the change. */ +export function hostAccount(session: Extract): HostAccount { + const { account } = session; + return { + userId: account.userId, + ...(account.email ? { email: account.email } : {}), + ...(session.source === 'agent' ? { agent: { name: session.agent.name, principalId: session.agent.principalId } } : {}), + accessToken: account.accessToken, + ...(account.key.kind === 'active' ? { apiKey: account.key.apiKey } : {}) + }; +} + +export function hostBackendConfig(backend: BackendConfig): HostBackendConfig { + return { + apiEndpoint: backend.apiEndpoint, + modulesEndpoint: backend.modulesEndpoint, + agentEndpoint: backend.agentEndpoint, + computeEndpoint: backend.computeEndpoint + }; +} + +const planeList = (missing: readonly Plane[]) => `${missing.join(', ')} endpoint${missing.length > 1 ? 's' : ''}`; + +/** + * Why a session cannot be used, in one or two sentences with the fix, or null + * for a session that is only absent or signed out. `repairHint` names the + * command of the binary that stores a complete context. No secret is in it. + */ +export function sessionProblem(session: Session, repairHint = 'Store the context again with every endpoint.'): string | null { + switch (session.kind) { + case 'incomplete-backend': + return `The backend context "${session.context}" lacks the ${planeList(session.missing)}, so it cannot be used; no endpoint is filled in on its own. ${repairHint}`; + case 'invalid-override': + case 'conflict': + case 'agent-unusable': + return `${session.problem} ${session.fix}`; + case 'issuer-mismatch': { + const where = `The session stored under "${session.context}"`; + if (!session.issuedFor) { + return `${where} does not record the backend it was issued for, so it is not used or sent anywhere: it may not come from ${session.backend.authEndpoint}. A new sign-in replaces it.`; + } + const { issuedFor } = session; + const changes = session.differs.map((plane) => `the ${plane} endpoint is ${planeEndpoint(session.backend, plane)}, but the session was issued for ${planeEndpoint(issuedFor, plane)}`); + return `${where} was issued for another backend: ${changes.join('; ')}. It is not used or sent anywhere. A new sign-in replaces it.`; + } + default: + return null; + } +} diff --git a/agentic/session/src/tools-host.ts b/agentic/session/src/tools-host.ts new file mode 100644 index 0000000000..172bfcb4fa --- /dev/null +++ b/agentic/session/src/tools-host.ts @@ -0,0 +1,68 @@ +import type { ToolsHost } from '@agentic-kit/db-tools'; + +import { openStore, stashBaseDir } from './account-store'; +import { agentSession } from './agent'; +import { agentBinding, hostAccount, hostBackendConfig, type PersonSession, resolveSession, sessionProblem } from './session'; + +/** + * The `configureHost` input of `@agentic-kit/db-tools`. Each call resolves the + * session again, so a sign-in mid-session, or an agent token another process + * minted, is picked up without a restart, and each answer comes from one + * resolution. Absence is null (no account) or undefined (no backend). A + * session that cannot be used, and a store that cannot be read, throw their + * cause from both getters, so the tools report it whichever they read first. + * A stored session another backend issued throws from `account()` only, since + * the backend itself is usable. + * + * With `agent`, the host acts as that agent of the person: `account()` is + * asynchronous, and gives an access token minted with the agent's key when the + * cached one is near its end. + */ +export function sessionToolsHost({ + signInHint, + repairHint, + context, + env, + agent +}: { + signInHint: string; + /** The command that stores a complete context, for the `incomplete-backend` message. */ + repairHint?: string; + context?: string; + env?: NodeJS.ProcessEnv; + agent?: string; +}): ToolsHost { + const person = (): PersonSession => { + const session = resolveSession({ context, env }); + const problem = session.kind === 'issuer-mismatch' ? null : sessionProblem(session, repairHint); + if (problem) throw new Error(problem); + return session; + }; + const agentAccount = async () => { + const stash = env ?? process.env; + const session = await agentSession({ store: openStore(stashBaseDir(stash)), name: agent, context, env: stash }); + const problem = sessionProblem(session, repairHint); + if (problem) throw new Error(problem); + return session.kind === 'signed-in' ? hostAccount(session) : null; + }; + return { + account() { + if (agent !== undefined) return agentAccount(); + const session = person(); + if (session.kind === 'issuer-mismatch') throw new Error(sessionProblem(session)); + return session.kind === 'signed-in' ? hostAccount(session) : null; + }, + backendConfig() { + if (agent !== undefined) { + const bound = agentBinding({ context, env, agent }); + if (bound.kind === 'bound') return hostBackendConfig(bound.backend); + const problem = sessionProblem(bound, repairHint); + if (problem) throw new Error(problem); + return undefined; + } + const session = person(); + return session.kind === 'signed-in' || session.kind === 'signed-out' || session.kind === 'issuer-mismatch' ? hostBackendConfig(session.backend) : undefined; + }, + signInHint + }; +} diff --git a/agentic/session/tsconfig.esm.json b/agentic/session/tsconfig.esm.json new file mode 100644 index 0000000000..a4afc3821d --- /dev/null +++ b/agentic/session/tsconfig.esm.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "moduleResolution": "bundler", + "module": "es2022", + "outDir": "dist/esm" + } +} diff --git a/agentic/session/tsconfig.json b/agentic/session/tsconfig.json new file mode 100644 index 0000000000..df063b5ee3 --- /dev/null +++ b/agentic/session/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c246c48200..5c3abac143 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -186,20 +186,30 @@ importers: '@agentic-kit/pi': specifier: workspace:* version: link:../pi/dist - '@constructive-io/sdk': + '@agentic-kit/session': specifier: workspace:^ - version: link:../../sdk/constructive-sdk/dist + version: link:../session/dist '@earendil-works/pi-coding-agent': specifier: 1.4.0 version: 1.4.0(@aws-sdk/credential-provider-node@3.972.89)(@smithy/signature-v4@5.7.4)(ws@8.21.3)(zod@4.4.3) - appstash: - specifier: ^0.8.0 - version: 0.8.0 inquirerer: specifier: ^4.9.4 version: 4.9.4 publishDirectory: dist + agentic/command: + dependencies: + '@agentic-kit/harness': + specifier: workspace:^ + version: link:../harness/dist + inquirerer: + specifier: ^4.9.4 + version: 4.9.4 + zod: + specifier: ^4.4.3 + version: 4.4.3 + publishDirectory: dist + agentic/db-tools: dependencies: 12factor-env: @@ -291,6 +301,23 @@ importers: version: 8.18.1 publishDirectory: dist + agentic/mcp: + dependencies: + '@agentic-kit/harness': + specifier: workspace:^ + version: link:../harness/dist + '@modelcontextprotocol/server': + specifier: 2.4.0 + version: 2.4.0 + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@modelcontextprotocol/client': + specifier: 2.4.0 + version: 2.4.0 + publishDirectory: dist + agentic/metering: publishDirectory: dist @@ -414,6 +441,22 @@ importers: version: link:../run-log/dist publishDirectory: dist + agentic/session: + dependencies: + '@agentic-kit/db-tools': + specifier: workspace:^ + version: link:../db-tools/dist + '@constructive-io/fetch': + specifier: ^1.2.0 + version: 1.2.0 + '@constructive-io/sdk': + specifier: workspace:^ + version: link:../../sdk/constructive-sdk/dist + appstash: + specifier: ^0.8.0 + version: 0.8.0 + publishDirectory: dist + examples/codegen-integration: dependencies: '@0no-co/graphql.web': @@ -5544,6 +5587,18 @@ packages: '@levischuck/tiny-cbor@0.2.11': resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==} + '@modelcontextprotocol/client@2.4.0': + resolution: {integrity: sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==} + engines: {node: '>=20'} + + '@modelcontextprotocol/core@2.4.0': + resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==} + engines: {node: '>=20'} + + '@modelcontextprotocol/server@2.4.0': + resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==} + engines: {node: '>=20'} + '@n1ru4l/push-pull-async-iterable-iterator@3.2.0': resolution: {integrity: sha512-3fkKj25kEjsfObL6IlKPAlHYPq/oYwUkkQ03zsTTiDjD7vg/RxjdiLeCydqtxHZP0JgsXL3D/X5oAkMGzuUp/Q==} engines: {node: '>=12'} @@ -8039,6 +8094,14 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + execa@5.0.0: resolution: {integrity: sha512-ov6w/2LCiuyO4RLYGdpFGjkcs0wMTgGE8PrkTHikeUy5iJekXyPIKUjifk5CsE0pt7sMCrMZ3YNqoCj6idQOnQ==} engines: {node: '>=10'} @@ -9026,6 +9089,9 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true + jose@6.2.18: + resolution: {integrity: sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -9983,6 +10049,10 @@ packages: resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} engines: {node: '>= 6'} + pkce-challenge@5.0.2: + resolution: {integrity: sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA==} + engines: {node: '>=16.20.0'} + pkg-dir@4.2.0: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} @@ -13321,6 +13391,25 @@ snapshots: '@levischuck/tiny-cbor@0.2.11': {} + '@modelcontextprotocol/client@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.1 + jose: 6.2.18 + pkce-challenge: 5.0.2 + zod: 4.4.3 + + '@modelcontextprotocol/core@2.4.0': + dependencies: + zod: 4.4.3 + + '@modelcontextprotocol/server@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + zod: 4.4.3 + '@n1ru4l/push-pull-async-iterable-iterator@3.2.0': {} '@napi-rs/wasm-runtime@0.2.4': @@ -15760,6 +15849,12 @@ snapshots: events@3.3.0: {} + eventsource-parser@3.1.1: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.1 + execa@5.0.0: dependencies: cross-spawn: 7.0.6 @@ -17289,6 +17384,8 @@ snapshots: jiti@2.7.0: {} + jose@6.2.18: {} + js-tokens@4.0.0: {} js-yaml@3.14.2: @@ -18417,6 +18514,8 @@ snapshots: pirates@4.0.7: {} + pkce-challenge@5.0.2: {} + pkg-dir@4.2.0: dependencies: find-up: 4.1.0